• hdu 1213 How Many Tables (并查集)


    Problem Description
    Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.

    One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.

    For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
     
    Input
    The input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.
     
    Output
    For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.
     
    Sample Input
    2 5 3 1 2 2 3 4 5 5 1 2 5
     
    Sample Output
    2 4
     

     并查集水模版题~

    代码如下:

     1 #include<stdio.h>
     2 #include<string.h>
     3 #include<ctype.h>
     4 #include<math.h>
     5 
     6 int f[1100],n,m,k,sum;
     7 void init ()
     8 {
     9     int i;
    10     for(i=1;i<=n;i++){
    11         f[i]=i;
    12     }
    13     return ;
    14 }
    15 int getf(int v)
    16 {
    17     if(f[v]==v){
    18         return v;
    19     }else {
    20         f[v]=getf(f[v]);
    21         return f[v];
    22     }
    23 }
    24 void marge (int v,int u)
    25 {
    26     int t1,t2;
    27     t1=getf(v);
    28     t2=getf(u);
    29     if(t1!=t2){
    30         f[t2]=t1;
    31     }
    32     return ;
    33 }
    34 int main ()
    35 {
    36     int i,x,y,j;
    37     int t;
    38     scanf("%d",&t);
    39     for(j=0;j<t;j++){
    40         memset(f,0,sizeof(f));
    41         sum=0;
    42         scanf("%d%d",&n,&m);
    43         init();
    44         for(i=1;i<=m;i++){
    45             scanf("%d %d",&x,&y);
    46             marge(x,y);
    47         }
    48         for(i=1;i<=n;i++){
    49             if(f[i]==i)
    50                 sum++;
    51         }
    52         printf("%d
    ",sum);
    53     }
    54 }
  • 相关阅读:
    梯度下降法-4.向量化和数据标准化
    梯度下降法-3.实现线性回归中的梯度下降法
    梯度下降法-2.线性回归中的梯度下降法
    梯度下降法-1.原理及简单实现
    线性回归算法-5.更多思考
    TCP/IP协议
    TFTP 服务器
    python3 系统编程进程
    python3 私有化 属性property
    python3 面向对象
  • 原文地址:https://www.cnblogs.com/lanaiwanqi/p/6734636.html
Copyright © 2020-2023  润新知