标签:
***并查集模板题
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<queue> #include<algorithm> using namespace std; typedef long long LL; #define N 1010 #define INF 0x3f3f3f3f int father[N]; int Find(int x) { while(x!=father[x]) x=father[x]; return x; } int main() { int T, n, m, a, b, x, y, p, ans, k; scanf("%d", &T); while(T--) { scanf("%d%d", &n, &m); for(int i = 0; i <= n; i++) father[i] = i; for(int i = 1; i <= m; i++) { scanf("%d%d", &a, &b); x = Find(a); y = Find(b); if(x != y) father[x] = y; } p = Find(1); ans = 1; for(int i = 1; i <= n; i++) { k = Find(i); if(k != p) { ans++; father[k] = p; } } printf("%d\n", ans); } return 0; }
标签:
原文地址:http://www.cnblogs.com/9968jie/p/5726724.html