畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 39593 Accepted Submission(s): 21009
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
1 0 2 998Huge input, scanf is recommended.HintHint并查集的详细分析:http://blog.csdn.net/wuxiushu/article/details/49615311
#include<stdio.h> #include<math.h> #include<string.h> #include<iostream> #include<algorithm> const int MAX = 1010; using namespace std; int pre[MAX],visit[MAX]; int find(int x) ///寻找根节点 { int r = x; while(r != pre[r]) { r = pre[r]; } int i = x,j; while(pre[i] != r) { j = pre[i]; pre[i] = r; i = j; } return r; } void join(int x,int y) ///判断是否是相同的根节点 { int fx = find(x); int fy = find(y); if(fx != fy) { pre[fy] = fx; } } int main() { int n,m,a,b; while(scanf("%d%d",&n,&m)&&n) { memset(visit,0,sizeof(visit)); for(int i = 1; i <= n; i ++) ///初始化 pre[i] = i; for(int i = 1; i <= m; i ++) { scanf("%d%d",&a,&b); join(a,b); } for(int i = 1; i <= n; i ++) visit[find(i)] = 1; int sum = 0; for(int i = 1; i <= n; i ++) if(visit[i]) ++ sum; printf("%d\n",sum - 1); } }