解题思路:和畅通工程类似,问最后还剩下几个不连通的区域。
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 15086 Accepted Submission(s): 7364
#include<stdio.h> int pre[1005]; int find(int root) { return root == pre[root] ? root : pre[root] = find(pre[root]); } void unionroot(int root1,int root2) { int x,y; x=find(root1); y=find(root2); if(x!=y); pre[x]=y; } int main() { int i,ncase,n,m,tmp,root1,root2,x,y; scanf("%d",&ncase); while(ncase--) { tmp=0; scanf("%d %d",&n,&m); for(i=1;i<=n;i++) pre[i]=i; while(m--) { scanf("%d %d",&root1,&root2); x=find(root1); y=find(root2); unionroot(x,y); } for(i=1;i<=n;i++) { if(pre[i]==i) tmp++; } printf("%d\n",tmp); } }
原文:http://www.cnblogs.com/wuyuewoniu/p/4200268.html