Bear Limak examines a social network. Its main functionality is that two members can become friends (then they can talk with each other and share funny pictures).
There are n members, numbered 1 through n. m pairs of members are friends. Of course, a member can't be a friend with themselves.
Let A-B denote that members A and B are friends. Limak thinks that a network is reasonable if and only if the following condition is satisfied: For every three distinct members (X, Y, Z), if X-Y and Y-Z then also X-Z.
For example: if Alan and Bob are friends, and Bob and Ciri are friends, then Alan and Ciri should be friends as well.
Can you help Limak and check if the network is reasonable? Print "YES" or "NO" accordingly, without the quotes.
Input
The first line of the input contain two integers n and m (3 ≤ n ≤ 150 000, ) — the number of members and the number of pairs of members that are friends.
The i-th of the next m lines contains two distinct integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi). Members ai and bi are friends with each other. No pair of members will appear more than once in the input.
Output
If the given network is reasonable, print "YES" in a single line (without the quotes). Otherwise, print "NO" in a single line (without the quotes).
Examples
Input
4 3
1 3
3 4
1 4
Output
YES
Input
4 4
3 1
2 3
3 4
1 2
Output
NO
Input
10 4
4 3
5 10
8 9
1 2
Output
YES
Input
3 2
1 2
2 3
Output
NO
Note
The drawings below show the situation in the first sample (on the left) and in the second sample (on the right). Each edge represents two members that are friends. The answer is "NO" in the second sample because members (2, 3) are friends and members (3, 4) are friends, while members (2, 4) are not.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to read input: n,m, then m edges. Determine if the graph is "reasonable": For any three distinct vertices X,Y,Z, if X-Y and Y-Z are edges, then X-Z must also be an edge. This is exactly the property that every connected component is a clique (complete graph). Actually, it's stronger: The condition only needs to hold for any three distinct vertices, but it is equivalent to the graph being a disjoint union of cliques. Let's reason:
Condition: For all distinct X,Y,Z, if edges (X,Y) and (Y,Z) exist, then edge (X,Z) must exist.
If the graph is a disjoint union of cliques, then within each clique, all pairs are edges. Across different components, there are no edges. Check condition: If X-Y and Y-Z exist, then Y is neighbor to both X and Z, meaning X and Z are in the same component as Y (since edges exist). In a disjoint union of cliques, if X and Y are in same component and Y and Z are in same component, then X and Z are in same component and there must be edge because component is clique. So condition holds. Conversely, suppose condition holds. Consider any connected component (by edges). For any two vertices X and Z in same component, there is a path. We need to show that X and Z are directly connected. But is it true that if condition holds, each component is a clique? Let's see: For any two vertices X and Z that have a common neighbor Y, condition forces edge X-Z. But what if they are at distance 2 but not sharing a common neighbor? Actually, distance 2 means there exists a path of length 2: X - Y - Z. That's exactly common neighbor Y. So if any two vertices are at distance exactly 2, they must be directly connected. But what about vertices at distance >2? Suppose X and Z are in same component but the shortest path length is 3: X-A-B-Z. Then X and A are adjacent, A and B are adjacent, so by condition (X, A, B) => X and B must be adjacent. Then we have X-B edge, and B-Z edge, so then X and Z are at distance 2 (via B) => must be adjacent. So by induction, all vertices in same connected component become directly connected. Thus each component becomes a clique. More formally, the condition implies that the graph is a disjoint union of cliques. So problem reduces to: Check if each connected component is a complete graph.
Given constraints: n up to 150,000, m up to 150,000? Actually, it says m (some condition, but image shows something? Actually input spec: "3 ≤ n ≤ 150 000, " might indicate something like m up to something? Usually m can be up to 150k or maybe 300k? But we can handle up to O(n + m). We'll read edges, build adjacency list. Then we need to check for each component: if the number of edges in the component equals n_c * (n_c - 1) / 2, where n_c is the number of vertices in that component. But careful: The edges we have are given; they might be only the edges in that component. So we need to compute for each component the number of vertices and number of edges that lie inside that component. Since there are no edges across components? Actually graph may not be disjoint union of cliques initially, but we just need to check if it is a disjoint union of cliques, i.e., each component is complete. So we compute connected components (undirected) based on given edges. Then for each component, check that every pair of vertices is directly connected. That is, total edges in that component should equal (size * (size - 1)) / 2.
But caution: If the graph is not a disjoint union of cliques, it might still have edges across components? Actually by definition of connected components, there are no edges between different components because components are defined by connectivity. So edges only within components. So computing component size and counting edges per component works.
Thus algorithm:
Use adjacency list representation.
Use BFS/DFS to find connected components (since n up to 150k, m up to maybe 150k, recursion depth might be big, so iterative DFS or BFS).
While traversing each component, collect the set of vertices (or just count size) and also count number of edges in that component. But careful: When counting edges for a component, we could double count if we sum adjacency lists of vertices within component, but each edge appears twice in adjacency lists (once per endpoint). So we can count edges by summing degree of vertices in component and divide by 2. However, degree of a vertex is number of incident edges, all of which are within its component (since no cross edges). So total edges in component = (sum of degrees of vertices in component) / 2.
Thus we can compute:
For each component, size = number of vertices visited.
total_degree_sum = sum of degrees of those vertices.
required edges = size * (size - 1) / 2.
Check if total_degree_sum / 2 == required_edges.
But careful: The degree sum must be even, obviously. But we can do this check.
Alternatively, we could iterate over all edges and assign component ID to each endpoint, then count edges per component by incrementing a counter when both endpoints belong to that component. That might be simpler: First find component labels for all vertices via union-find or DFS. Then for each edge, if component of u == component of v, increment edge count for that component. Finally, for each component, if edge count != size*(size-1)/2, answer NO.
Given constraints up to 150k, both approaches fine.
We'll implement DFS using stack to avoid recursion depth issues.
Edge cases: n=3, m=2 example output NO because component size 3 has only 2 edges, not 3.
Third example: 10 4, edges are (4,3),(5,10),(8,9),(1,2). So components: {4,3} size 2 edges 1 => complete (size 2 requires 1 edge, ok). {5,10} size 2 edges 1 ok. {8,9} size2 edges1 ok. {1,2} size2 edges1 ok. Others isolated vertices? Actually there are vertices 6,7 possibly isolated? They are alone. For a component of size 1, required edges 0, that's fine. So YES.
Thus algorithm will handle isolated vertices as components of size 1.
So answer is YES if for every component, edges_in_component == size*(size-1)/2.
Complexities: O(n+m).
Implementation steps:
Read n,m.
Build adjacency list: list of neighbors for each vertex (1-indexed). Also store list of edges (pairs) maybe.
Initialize visited array false.
For each vertex not visited, start BFS/DFS:
Use stack: push vertex, mark visited, initialize component list.
While stack not empty: pop, add to component list.
For each neighbor, if not visited, push and mark visited.
But careful: while exploring, we need to collect vertices. We'll keep a vector to store vertices in component.
After BFS, compute size = component.size().
Compute sum_degree = sum of degree[vertex] for vertices in component. We have degree array computed from adjacency list length.
edges_in_component = sum_degree // 2.
required = size * (size - 1) // 2.
If edges_in_component != required: print NO and exit.
If loop finishes, print YES.
Edge cases: Ensure we handle large ints: size up to 150k, size*(size-1)/2 up to ~11e9, fits in 64-bit. So use long long (int64_t) for required.
Alternatively, compute sum_degree as int (since m up to maybe 150k, sum_degree <= 2*m, so it's fine in int). But required may exceed int range, use long long.
Check constraints: m could be up to min(150000, n*(n-1)/2)? It says maybe indicating something like m ≤ 150000? Typically for n up to 150k, m could be up to 150k. So sum_degree <= 2m <= 300k, which fits in int. However if graph is complete, m = n(n-1)/2, which for n=150k is huge (~1.1e10) but likely m is limited by input size? Actually input constraints may limit m to be ≤ 150000? The problem statement: "3 ≤ n ≤ 150 000, " I suspect they intended m to be up to something, but the image might be missing. Typically in such problems, m ≤ 150000 as well. So we assume m ≤ 150000. However if n=150k and m could be huge, our algorithm still fine as degree sums would be large but still fit in long long. We'll use 64-bit to be safe.
But note: If m is huge (like O(n^2)), building adjacency list might be memory heavy; but constraints likely keep m moderate. Usually Codeforces problem (Bear and Social Network) had n up to 150k, m up to 150k. So we'll go with that.
Now implement:
Pseudo:
int n, m;
vector<vector> adj(n+1);
vector deg(n+1, 0);
vector<pair<int,int>> edges(m); // maybe not needed
Read edges:
for i in range(m):
int a,b;
cin>>a>>b;
adj[a].push_back(b);
adj[b].push_back(a);
deg[a]++; deg[b]++;
// also edges.push_back({a,b}) maybe not needed
vector visited(n+1, false);
for v from 1 to n:
if not visited[v]:
// BFS/DFS
stack st;
st.push(v);
visited[v]=true;
vector comp; // vertices in component
while (!st.empty()) {
int u = st.top(); st.pop();
comp.push_back(u);
for (int w : adj[u]) {
if (!visited[w]) {
visited[w]=true;
st.push(w);
}
}
}
long long size = comp.size();
long long sum_deg = 0;
for (int u : comp) {
sum_deg += deg[u];
}
long long edges_in_comp = sum_deg / 2;
long long required = size * (size - 1) / 2;
if (edges_in_comp != required) {
cout << "NO" << endl;
return 0;
}
cout << "YES" << endl;
That's it.
But one subtlety: The condition for reasonableness is: for every three distinct members (X,Y,Z), if X-Y and Y-Z then also X-Z. This is exactly the condition that the graph is a disjoint union of cliques. But is there any nuance with isolated vertices? Yes, isolated vertices are trivially okay. The condition involves triples; if one of them is isolated, there's no edge, so condition holds vacuously. So fine.
Thus solution works.
Double-check: In second sample: n=4,m=4 edges: (3,1),(2,3),(3,4),(1,2). Graph: all vertices connected? Let's see: component includes all 4 vertices? There is path: 2-3-4 and 2-1-3, so it's one component. Size=4. sum_deg: deg[1]=2, deg[2]=2, deg[3]=3, deg[4]=1? Wait edges: (3,1): deg1=1, deg3=1; (2,3): deg2=1, deg3 becomes2; (3,4): deg3=3, deg4=1; (1,2): deg1=2, deg2=2. So sum_deg = 2+2+3+1 = 8. edges_in_comp = 4. required = 4*3/2=6. 4 != 6 -> NO. Good.
We should also consider alternative edge-case: If the graph is a clique but with extra isolated vertices, fine. So our method works.
But wait: Could there be a scenario where the graph is not a disjoint union of cliques yet satisfies condition? Let's try a counterexample: consider a 4-cycle: vertices 1-2-3-4-1, edges (1,2),(2,3),(3,4),(4,1). Check condition: pick X=1,Y=2,Z=3 => edges (1,2) and (2,3) exist, so edge (1,3) must exist, but it doesn't. So fails. What about a star: center connected to leaves, no leaf-leaf edges. Pick leaf1, center, leaf2 => edges leaf1-center and center-leaf2 exist, so leaf1-leaf2 must be edge, but not. Fails. So indeed only cliques satisfy.
One nuance: The condition only requires that if X-Y and Y-Z then X-Z. It does not require symmetry? But friendship is symmetric (undirected). So it's undirected. So fine.
Thus solution correct.
We'll implement.
Edge case: The graph could have multiple components. In counting edges per component, we must ensure we count only edges within component. Using sum_deg works because degrees only count edges to neighbors, which are all in the same component? Actually if a vertex belongs to a component, all its neighbors are in that component because any neighbor is connected, so yes they are in same component. So fine.
But what about if there is an edge between two vertices that are in different components? That would merge them into one component. So after DFS, there are no cross-component edges.
Implementation using DFS iterative.
Potential improvement: Use union-find to label components and then count edges per component. But DFS is simpler.
Let's write code:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, m;
cin >> n >> m;
vector<vector<int>> adj(n+1);
vector<int> deg(n+1, 0);
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
++deg[a];
++deg[b];
}
vector<bool> vis(n+1, false);
for (int v = 1; v <= n; ++v) {
if (!vis[v]) {
// DFS
stack<int> st;
st.push(v);
vis[v] = true;
vector<int> comp;
while (!st.empty()) {
int u = st.top();
st.pop();
comp.push_back(u);
for (int w : adj[u]) {
if (!vis[w]) {
vis[w] = true;
st.push(w);
}
}
}
long long sz = comp.size();
long long sum_deg = 0;
for (int u : comp) {
sum_deg += deg[u];
}
long long edges = sum_deg / 2;
long long need = sz * (sz - 1) / 2;
if (edges != need) {
cout << "NO\n";
return 0;
}
}
}
cout << "YES\n";
return 0;
}
Check with examples.
But there's a subtle bug: When we use DFS, we push neighbors and mark visited immediately before pushing to stack to avoid duplicate pushes. That's correct.
Also note: The sum_deg/2 might not be integer if sum_deg is odd, but sum_deg must be even because sum of degrees is even (handshaking lemma). But if graph is inconsistent? No, it's consistent. But even if it's odd due to bug, integer division would floor, causing mismatch. So we can assert or not worry.
Edge-case: Isolated vertices (size 1): need = 0, sum_deg = 0, edges = 0 => OK.
Thus answer.
We should also consider scenario where there are multiple edges? Input says no pair appears more than once, so fine.
Thus final answer.
Now for formatting: In the problem statement, they have sample input and output. We'll produce just the code.
But we must also note the possibility that using int for size and deg sum may cause overflow when computing need. We used long long.
Alternatively, we can compute need as long long.
Now complexity: O(n+m). n=150k, m=150k => fine.
One could also use BFS with queue.
Now about the image: The problem statement includes an image but we don't need it.
So final answer.
But wait: Is there any hidden nuance about the condition "for every three distinct members (X, Y, Z)"? It might also require that if there is any two edges X-Y and Y-Z, then X-Z must exist. That's exactly the "friendship graph is transitive", i.e., it's an equivalence relation (reflexive? not required because no self-friend, but for transitivity to hold we need that if ab and bc then ac, but reflexivity is not required, but it's symmetric because friendship is symmetric). In equivalence relations, each equivalence class is a set where all pairs are related. However, reflexivity is not required, but since for any member X, not necessarily XX, but within an equivalence class, we don't have self loops. So it's like a complete graph without self-loops. So disjoint union of cliques.
Thus condition is exactly that graph is a disjoint union of cliques.
Now check again with a component of size 2: There are two vertices, edge exists. For any triple distinct members, can't pick three distinct members within this component because only two members. So condition vacuously true. So a single edge is allowed. Good.
Thus algorithm is correct.
Now we can output code.
But wait: There is another nuance: What if the graph is not a disjoint union of cliques but still satisfies condition? Let's try some weird graphs: Suppose we have a triangle with an extra vertex attached to one vertex? Actually consider component: vertices A,B,C,D where edges: A-B, A-C, A-D, and also B-C, C-D, but not B-D. Check condition: For triple (B,A,C): edges B-A and A-C => need B-C (exists). Good. (B,A,D): edges B-A and A-D => need B-D (does not exist). So condition fails. So any missing edge within the neighborhood of a vertex causes failure. So it seems it forces complete. So we are good.
I will now produce final answer in required format.
But the platform might expect "YES"/"NO" case-sensitive.
Now produce code.
But I recall that there is an alternative condition: The graph is "cluster graph" or "union of cliques". So yes.
Thus solution.
Now we write final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, m;
cin >> n >> m;
vector<vector<int>> adj(n + 1);
vector<int> deg(n + 1, 0);
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
++deg[a];
++deg[b];
}
vector<bool> visited(n + 1, false);
for (int v = 1; v <= n; ++v) {
if (!visited[v]) {
// collect all vertices of the component
stack<int> st;
st.push(v);
visited[v] = true;
vector<int> component;
while (!st.empty()) {
int u = st.top();
st.pop();
component.push_back(u);
for (int w : adj[u]) {
if (!visited[w]) {
visited[w] = true;
st.push(w);
}
}
}
long long sz = component.size();
long long sum_deg = 0;
for (int u : component) {
sum_deg += deg[u];
}
long long edges = sum_deg / 2; // actual edges inside component
long long need = sz * (sz - 1) / 2; // edges needed for a clique
if (edges != need) {
cout << "NO\n";
return 0;
}
}
}
cout << "YES\n";
return 0;