数据结构:并查集
- 题目描述
- 参考代码
题目描述
输入样例
5 5
C 1 2
Q1 1 2
Q2 1
C 2 5
Q2 5
输出样例
Yes
2
3
参考代码
#include <iostream>using namespace std;const int N = 100010;int n, m;
int p[N], sz[N];int find(int x) // 返回x的祖宗节点 + 路径压缩
{if (p[x] != x) p[x] = find(p[x]);return p[x];
}int main()
{scanf("%d%d", &n, &m);for (int i = 1; i <= n; i++) {p[i] = i;sz[i] = 1;}while (m--){char op[2];int a, b;scanf("%s", op);if (op[0] == 'C') {scanf("%d%d", &a, &b);if (find(a) == find(b)) continue;sz[find(b)] += sz[find(a)];p[find(a)] = find(b);}else if (op[1] == '1'){scanf("%d%d", &a, &b);if (find(a) == find(b)) puts("Yes");else puts("No");}else{scanf("%d", &a);printf("%d\n", sz[find(a)]);}}return 0;
}