本文共 2503 字,大约阅读时间需要 8 分钟。
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 27651 Accepted Submission(s): 13726
1 #include2 using namespace std; 3 int pre[1010]; 4 int t[1010]; 5 int find(int x) 6 { 7 int r=x; 8 while(pre[r]!=r) 9 r=pre[r];10 int i=x,j;11 while(pre[r]!=r)12 {13 j=pre[r];14 pre[r]=r;15 i=j;16 }17 return r;18 }19 void join(int x,int y)20 {21 int fx=find(x),fy=find(y);22 if(fx!=fy)23 pre[fy]=fx;24 }25 int main()26 {27 int N,M,a,b,i,ans,n,m;28 while(scanf("%d",&N)!=EOF)29 {30 while(N--)31 {32 scanf("%d%d",&a,&b);33 for(i=1;i<=a;i++)34 pre[i]=i;35 for(i=1;i<=b;i++)36 {37 scanf("%d%d",&n,&m);38 join(n,m);39 }40 memset(t,0,sizeof(t));41 for(i=1;i<=a;i++)42 t[find(i)]=1;43 for(ans=0,i=1;i<=a;i++)44 if(t[i])45 ans++;46 printf("%d\n",ans);47 }48 }49 return 0;50 }
转载地址:http://lnjta.baihongyu.com/