HDOJ1232 并查集

 1 /* 呀 博客园支持C代码了 */
2 # include <stdio.h>
3
4 # define MAXN 1002
5
6 int father[MAXN];
7 int N, M, i, x, y, cnt;
8
9 int main()
10 {
11 while (1)
12 {
13 scanf("%d%d", &N, &M);
14 if (N == 0) break;
15 cnt = 0;
16 for (i = 1; i <= N; ++i)
17 father[i] = i;
18 while (M--)
19 {
20 scanf("%d%d", &x, &y);
21 while (x != father[x]) x = father[x];
22 while (y != father[y]) y = father[y];
23 if (x != y)
24 {
25 ++cnt;
26 father[y] = x;
27 }
28 }
29 printf("%d\n", N-1-cnt);
30 }
31
32 return 0;
33 }

posted on 2012-03-18 16:55  getgoing  阅读(204)  评论(0编辑  收藏  举报

导航