HDU 1232 - 畅通工程
传送门
思路
并查集。
睡前一水
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#define MP(a, b) make_pair(a, b)
using namespace std;
const int MAXN = 1000 + 5;
const int INF = 0x3f3f3f3f;
int pa[MAXN];
int Find(int x)
{
return pa[x] == x ? x : pa[x] = Find(pa[x]);
}
int main()
{
//freopen("input.txt", "r", stdin);
int nc, nr, i, j, a, b;
while (scanf("%d", &nc), nc)
{
for (i = 1; i <= nc; i++)
pa[i] = i;
int cnt = -1;
scanf("%d", &nr);
for (i = 0; i < nr; i++)
{
scanf("%d%d", &a, &b);
int x = Find(a), y = Find(b);
if (x != y)
pa[x] = y;
}
for (i = 1; i <= nc; i++)
if (pa[i] == i) cnt++;
printf("%d\n", cnt);
}
return 0;
}