畅通工程
畅通工程
Time Limit : 4000/2000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 4 Accepted Submission(s) : 2
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
#include<stdio.h>
int father[1005],depth[1005];
void init()
{
int i;
for(i = 1; i < 1005;i ++)
{
father[i] = i;
depth[i] = 0;
}
}
int find(int x)
{
if(x==father[x])
return x;
else
return father[x] = find(father[x]); //优化树的高度;
}
void unit(int x,int y)
{
x = find(x);
y = find(y);
if(x==y)
return ;
if(depth[x]<depth[y]) //注意树的优化,防止高度过高而超时;
{
father[x] = father[y];
}
else
{
if(depth[x]>depth[y])
father[y] = father[x];
else
{
father[x] = father[y];
depth[y]++;
}
}
}
int main()
{
int n,m,a,b,j,gr;
while(~scanf("%d%d",&n,&m)&&n!=0)
{
gr = 0;
init();
while(m--)
{
scanf("%d%d",&a,&b);
unit(a,b);
}
for(j = 1;j <= n;j ++)
{
if(j==father[j])
gr++;
}
printf("%d\n",gr-1);
}
return 0;
}