hdu1232
畅通工程
0x00 Tags
并查集
0x01 题目简介
统计总的根节点个数ans,然后减1就是结果
0x02 代码
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1010;
int root[maxn];
void Init()
{
for (int i = 1; i < maxn; i++)
{
root[i] = i;
}
}
/*
未优化的查找
int Find(int x)
{
//return x == root[x] ? x : Find(root[x]);
while (x != root[x])
{
x = root[x];
}
return x;
}
*/
int Find(int x)
{
//return x == root[x] ? x : Find(root[x]);
int r = x;
while (r != root[r])
{
r = root[r];
}
int i = x, j;
while (i != r)
{
j = root[i];
root[i] = r;
i = j;
}
return r;
}
void Union(int x, int y)
{
x = Find(x);
y = Find(y);
if (x != y) root[x] = y;
}
int main()
{
int n, m;
while (scanf("%d", &n) != EOF)
{
if (n == 0) break;
Init();
int s, t;
scanf("%d", &m);
for (int i = 1; i <= m; i++)
{
scanf("%d%d", &s, &t);
Union(s, t);
}
// 找出连通分量的个数
int num = 0;
for (int i = 1; i <= n; i++)
{
if (root[i] == i)
num++;
}
printf("%d
", num - 1);
}
return 0;
}