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 }
  • 相关阅读:
    WCF服务自我寄宿 Windows服务
    客户端调用 WCF 的几种方式
    SQL Server 2005 数据库 可疑状态
    mysql server 自动断开的问题
    mysql数据表简单拷贝及重命名
    Mac提示App已损坏 你应该将它移到废纸篓的解决方案
    Mac系统下安装Tomcat,以及终端出现No such file or directory的错误提示解决方案
    md1
    转-SourceTree注册atlassian账号SIGUP按钮灰色无法注册的问题
    mysql my.cnf优化
  • 原文地址:https://www.cnblogs.com/lanaiwanqi/p/6734636.html
Copyright © 2011-2022 走看看