Acwing
Topic description
ideas
if(find(a) == find(b)) continue;
siz[find(b)] += siz[find(a)];//在根节点上加上另一个树节点的古树
p[find(a)] = find(b);
Think of a connected block as a set, and open an
siz
array to record the number of nodes of the two connected blocks. The two connected blocks are merged, that is, the twosiz
arrays can be added, but they must be added to the parent node. Note that the order is First add the root node, update the parent node, and ifa,b
it is in the same connected block, there is no need to insert the operation, directlycontinue
code 1
#include <bits/stdc++.h>
using namespace std ;
const int N = 100010;
int n, m;
int siz[N], p[N];
int find (int x) {
if(p[x] != x) {
p[x] = find(p[x]);
}
return p[x];
}
int main () {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
p[i] = i;
siz[i] = 1;
}
char op[5];
while (m --) {
cin >> op;
int a, b;
if(op[0] == 'C') {
cin >> a >> b;
if(find(a) == find(b)) continue;
siz[find(b)] += siz[find(a)];//在根节点上加上另一个树节点的古树
p[find(a)] = find(b);
} else if(op[1] == '1') {
cin >> a >> b;
if(find(a) == find(b)) {
puts("Yes");
} else {
puts("No");
}
} else {
cin >> a;
cout << siz[find(a)] << endl;
}
}
return 0;
}