• 杭电 2120 Ice_cream's world I (并查集求环数)


    Description

    ice_cream's world is a rich country, it has many fertile lands. Today, the queen of ice_cream wants award land to diligent ACMers. So there are some watchtowers are set up, and wall between watchtowers be build, in order to partition the ice_cream’s world. But how many ACMers at most can be awarded by the queen is a big problem. One wall-surrounded land must be given to only one ACMer and no walls are crossed, if you can help the queen solve this problem, you will be get a land.

    Input

    In the case, first two integers N, M (N<=1000, M<=10000) is represent the number of watchtower and the number of wall. The watchtower numbered from 0 to N-1. Next following M lines, every line contain two integers A, B mean between A and B has a wall(A and B are distinct). Terminate by end of file.

    Output

    Output the maximum number of ACMers who will be awarded. 
    One answer one line.

    Sample Input

    8 10
    0 1
    1 2
    1 3
    2 4
    3 4
    0 5
    5 6
    6 7
    3 6
    4 7

    Sample Output

    3



    大意:有n个碉堡,m种关系每个关系表示两个碉堡连在一起,问一共有多少环。
    父结点相等就有一个环。

     1 #include<cstdio>
     2 int n,m,fa[1005],i,a,b,sum;
     3 int find(int a)
     4 {
     5     int r=a;
     6     while(r != fa[r])
     7     {
     8         r=fa[r];
     9     }
    10     int i=a,j;
    11     while(i != r)
    12     {
    13         j=fa[i];
    14         fa[i]=r;
    15         i=j;
    16     }
    17     return r;
    18 }
    19 void f1(int x,int y)
    20 {
    21     int nx,ny;
    22     nx=find(x);
    23     ny=find(y);
    24     if(nx != ny)
    25     {
    26         fa[nx]=ny;
    27     }
    28     else
    29     {
    30         sum++;
    31     }
    32 }
    33 int main()
    34 {
    35     while(scanf("%d %d",&n,&m)!=EOF)
    36     {
    37         sum=0;
    38         for(i = 0 ; i < n ; i++)
    39         {
    40             fa[i]=i;
    41         }
    42         for(i = 0 ; i < m ; i++)
    43         {
    44             scanf("%d %d",&a,&b);
    45             f1(a,b);
    46         }
    47         printf("%d
    ",sum);
    48     }
    49 } 
    
    
    
     
    ——将来的你会感谢现在努力的自己。
  • 相关阅读:
    单例模式简介
    WebSocket简介
    向数据库中插入非空字段并赋初值
    MD5加(解)密代码实现
    DES字符串加(解)密代码实现
    常见状态码
    13.Roman to Integer&#160;
    14.Longest Common Prefix
    20.Valid Parentheses
    26.Remove Duplicates from Sorted Array
  • 原文地址:https://www.cnblogs.com/yexiaozi/p/5727113.html
Copyright © 2020-2023  润新知