There are n people, each alone at first. You get a list of commands: some join two people's groups, others ask whether two people are in the same group.
What to build
Use union-find. For a command 1 a b, unite a and b. For a command 2 a b, print YES if find(a) == find(b) and NO otherwise.
Requirements
- Use find with path compression and unite by size
- Print one answer per question, in order
Input
The first line has n and q. Each of the next q lines has t a b: t = 1 means unite, t = 2 means ask.
Output
For each question (t = 2), YES or NO, one per line.
Constraints
1 ≤ n, q ≤ 100,000.
Example
Input:
5 6
1 1 2
1 3 4
2 1 2
2 1 3
1 2 3
2 1 4
Output:
YES
NO
YES
Why it works
Two people are in the same group exactly when their roots match. With path compression and union by size, every command takes almost constant time, so the whole job is nearly O(q).
Examples
5 6 1 1 2 1 3 4 2 1 2 2 1 3 1 2 3 2 1 4
YES NO YES
3 2 2 1 2 2 3 3
NO YES
Hints
Hint 1
parent[i] = i and sz[i] = 1 at the start.
Hint 2
find: if (parent[x] != x) parent[x] = find(parent[x]); return parent[x];
Hint 3
unite: find both roots, return if equal, attach the smaller under the larger and add the sizes.
Solution
Show one correct solution (try it yourself first)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
vector<int> parent, sz;
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
void unite(int a, int b) {
a = find(a);
b = find(b);
if (a == b) return;
if (sz[a] < sz[b]) swap(a, b);
parent[b] = a;
sz[a] += sz[b];
}
int main() {
int n, q;
cin >> n >> q;
parent.resize(n + 1);
sz.assign(n + 1, 1);
for (int i = 0; i <= n; i++) parent[i] = i;
while (q--) {
int t, a, b;
cin >> t >> a >> b;
if (t == 1) unite(a, b);
else cout << (find(a) == find(b) ? "YES" : "NO") << "\n";
}
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step