码迷,mamicode.com
首页 > 其他好文 > 详细

【HDOJ】3560 Graph’s Cycle Component

时间:2014-04-29 17:22:46      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   io   

并查集的路径压缩。

mamicode.com,码迷
 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 }
mamicode.com,码迷

 

【HDOJ】3560 Graph’s Cycle Component,码迷,mamicode.com

【HDOJ】3560 Graph’s Cycle Component

标签:style   blog   http   java   color   io   

原文地址:http://www.cnblogs.com/bombe1013/p/3699818.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!