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 }
  • 相关阅读:
    emWin 界面切换注意事项
    emWin 工程之汉字显示
    emWin 使用 GUIBuilder 放置标题 TEXT 注意
    【转】系统调用和驱动程序中相应函数的参数对应关系
    主机 & 虚拟机 & 开发板 相互通信
    电脑通过网口连接开发板
    【转】ARM交叉编译工具链
    【转】vi 写完文件保存时才发现是 readonly
    【转】ubuntu 12.04下如何开启 NFS 服务 & 设置
    安装完打开 eclipse 提示 JVM 版本较低
  • 原文地址:https://www.cnblogs.com/lanaiwanqi/p/6734636.html
Copyright © 2011-2022 走看看