zoukankan      html  css  js  c++  java
  • 【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
    ", m, x);
    66     }
    67 
    68     return 0;
    69 }
  • 相关阅读:
    IE下的异步JS测试
    使用P3P实现 跨域共享Cookie
    DataRow的泛型扩展方法
    我的Exec方法
    原创:截取HttpResponse输出流
    SWT/JFACE 第五天,常用组件
    导入数据库:DMP
    JAVA常见错误收集
    swtjface学习第二天
    项目管理过程之项目团队
  • 原文地址:https://www.cnblogs.com/bombe1013/p/3699818.html
Copyright © 2011-2022 走看看