zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    AOP从静态代理到动态代理 Emit实现
    云计算仿真工具CloudSim介绍和使用
    SSH框架中配置log4j的方法
    SSH常见面试题
    第一章
    shell 生成目录的树状视图、生成文件及子目录的汇总信息
    shell拼写检查,利用Linux字典
    SHELL:多文件的重命名和移动
    sort
    tr1
  • 原文地址:https://www.cnblogs.com/lanaiwanqi/p/6734636.html
Copyright © 2011-2022 走看看