简单的并查集的应用,统计和 0 联通的点的个数,约等于模板题。。。。。。手残没有判断两个点的根节点是否相等。。。。。贡献了五个WA......
1 #include <iostream> 2 #include <cstdlib> 3 #include <cstdio> 4 5 using namespace std; 6 7 int stu[30010],num[30010]; 8 9 int find(int x) 10 { 11 return stu[x] == x ? x : stu[x] = find(stu[x]); 12 } 13 14 void merge(int a,int b) 15 { 16 int fa = find(a); 17 int fb = find(b); 18 if(fa != fb) 19 { 20 stu[fb] = fa; 21 num[fa] += num[fb]; 22 } 23 } 24 25 int main() 26 { 27 int n,m,s; 28 29 int i,a,b; 30 31 while(cin>>n>>m && (n||m)) 32 { 33 for(i = 0;i <= n; ++i) 34 { 35 stu[i] = i; 36 num[i] = 1; 37 } 38 for(i = 0;i < m; ++i) 39 { 40 cin>>s; 41 if(s > 0) 42 cin>>a; 43 while(--s) 44 { 45 cin>>b; 46 merge(a,b); 47 } 48 } 49 50 cout<<num[find(0)]<<endl; 51 } 52 return 0; 53 }