首页 > 代码库 > 【HDOJ】3560 Graph’s Cycle Component

【HDOJ】3560 Graph’s Cycle Component

并查集的路径压缩。

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 #define MAXNUM 100005
 5 
 6 int deg[MAXNUM], bin[MAXNUM];
 7 char isCycle[MAXNUM];
 8 
 9 int find(int x) {
10     int r = x;
11     int i = x, j;
12 
13     while (r != bin[r])
14         r = bin[r];
15 
16     while (i != r) {
17         j = bin[i];
18         bin[i] = r;
19         i = j;
20     }
21 
22     return r;
23 }
24 
25 void merge(int x, int y) {
26     int fx;
27     int fy;
28 
29     fx = find(x);
30     fy = find(y);
31     if (fx != fy)
32         bin[fx] = fy;
33 }
34 
35 int main() {
36     int n, m;
37     int i, x, y;
38 
39     while (scanf("%d %d", &n, &m)!=EOF && (n||m)) {
40         for (i=0; i<n; ++i)
41             bin[i] = i;
42         memset(isCycle, 0, sizeof(isCycle));
43         memset(deg, 0, sizeof(deg));
44         while (m--) {
45             scanf("%d %d", &x, &y);
46             deg[x]++;
47             deg[y]++;
48             merge(x, y);
49         }
50         m = 0;
51         for (i=0; i<n; ++i) {
52             x = find(i);
53             if (isCycle[x] == 0) {
54                 ++m;
55                 isCycle[x] = 1;
56             }
57         }
58         for (i=0; i<n; ++i)
59             if (deg[i] != 2)
60                 isCycle[bin[i]] = 0;
61         x = 0;
62         for (i=0; i<n; ++i)
63             if (isCycle[i])
64                 ++x;
65         printf("%d %d\n", m, x);
66     }
67 
68     return 0;
69 }