基础并查集,统计有多少个根节点即可。我这里用set
#include <bits/stdc++.h> using namespace std; int fa[10000]; int Find(int x) { if (x == fa[x]) return x; return fa[x] = Find(fa[x]); } void Union(int x, int y) { int fx = Find(x); int fy = Find(y); // printf("%d %d %d ", fa[fy], fy, fx); if (fx != fy) fa[fy] = fx; } int main() { int t; while (~scanf("%d", &t)) { while (t--) { fill(fa, fa + 10000, 0); int n, m; scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) fa[i] = i; for (int i = 1; i <= m; i++) { int a, b; scanf("%d %d", &a, &b); Union(a, b); } set<int> s; for (int i = 1; i <= n; i++) s.insert(Find(i)); printf("%d ", s.size()); } } return 0; }