畅通工程
Time Limit : 4000/2000ms (Java/Other)Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 0Accepted Submission(s) : 0
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
Input
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
Output
Sample Input
4 2 1 3 4 3 3 3 1 2 1 3 2 3 5 2 1 2 3 5 999 0 0
Sample Output
1 0 2 998
Hint
Huge input, scanf is recommended.
属于并查集的入门题,和 1856很像 注意最后算集合数目的技巧
#include <iostream> #define N 100005 using namespace std; int MAX,num; struct node { int parent; int rank; }elem[N]; void init() // 初始化 { int i; for(i=0;i<N;i++) { elem[i].parent=i; elem[i].rank=1; } } int find(int x) { int root,temp; temp=x; while(elem[x].parent!=x) // 找到根节点 { x=elem[x].parent; } root=x; x=temp; while(elem[x].parent!=x) // 压缩路径,路劲上的点直接指向 根节点 { temp=elem[x].parent; elem[x].parent=root; x=temp; } return root; } void uni(int a,int b) // 合并 { int x,y; x=find(a); y=find(b); if(elem[x].rank>=elem[y].rank) { elem[y].parent=elem[x].parent; elem[x].rank+=elem[y].rank; if(MAX<elem[x].rank) MAX=elem[x].rank; } else { elem[x].parent=elem[y].parent; elem[y].rank+=elem[x].rank; if(MAX<elem[y].rank) MAX=elem[y].rank; } } int main() { int n,m,a,b,x,y; while (scanf("%d",&n),n) { num=0; init(); scanf("%d",&m); while (m--) { scanf("%d%d",&a,&b); x=find(a); y=find(b); if(x!=y) uni(a,b); } //以下是计算集合的数量 集合的数量实际上就是根节点的个数,当elem[i].parent==i的时候,i就是根节点 // 所以要修的路的条数就是 num-1 for(int i=1;i<=n;i++) { if(elem[i].parent==i) num++; } printf("%d/n",num-1); } return 0; }