题目链接:
注意:从1开始循环,一定要循环到n啊(<=n)
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 5 const int maxn = 1010; 6 int ufs[maxn]; 7 8 void Init(int n) { 9 for(int i = 1;i <= n;i++) { 10 ufs[i] = i; 11 } 12 } 13 14 int FindRoot(int x) { 15 return ufs[x] == x ? x : ufs[x] = FindRoot(ufs[x]); 16 } 17 18 bool Merge(int x,int y) { 19 int a = FindRoot(x); 20 int b = FindRoot(y); 21 if(a == b) 22 return false; 23 else 24 { 25 ufs[b] = a; 26 return true; 27 } 28 } 29 30 int main() { 31 int n,m; 32 int t; 33 scanf("%d",&t); 34 while(t--) { 35 scanf("%d%d",&n,&m); 36 Init(n); 37 int x,y; 38 while(m--) { 39 scanf("%d%d",&x,&y); 40 if(Merge(x,y)) 41 n--; 42 } 43 printf("%d ",n); 44 } 45 return 0; 46 }