HDU 1232 并查集
畅通工程
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 54406 Accepted Submission(s): 29032
注意:两个城市之间可以有多条道路相通,也就是说
3 3
1 2
1 2
2 1
这种输入也是合法的
当N为0时,输入结束,该用例不被处理。
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <algorithm>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
int pre[1005];
int find(int i)
{
if (i != pre[i])
pre[i] = find(pre[i]); //递归实现路径压缩
return pre[i];
}
void mix(int x, int y)
{
int x1 = find(x), y1 = find(y); //将两个集合合并
if (x1 != y1)
pre[y1] = x1;
}
int main()
{
int n, m;
int a, b;
while(scanf("%d%d",&n,&m)&&n)
{
for (int i = 1; i <= n; i++)
pre[i] = i;
for (int i = 0; i < m; i++)
{
scanf("%d%d", &a, &b);
mix(a, b);
}
int v[1005]={0};
for (int i = 1; i <= n; i++)
v[find(i)] = 1;
int sum = 0;
for (int i = 1; i <= n; i++)
{
if (v[i])
sum++;
}
printf("%d\n", sum - 1);
}
return 0;
}