• [HDU 1213] How Many Tables


    How Many Tables

    Time Limit: 2000/1000 MS (Java/Others)    

    Memory Limit: 65536/32768 K (Java/Others)

    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 <bits/stdc++.h>
     2 using namespace std;
     3 int pre[1001],r[1001],t,n,m;
     4 int findset(int x) {
     5     int r=x;
     6     while(pre[r]!=r) r=pre[r];
     7     int i=x,j;
     8     while(i!=r) {
     9         j=pre[i];
    10         pre[i]=r;
    11         i=j;
    12     }
    13     return r;
    14 }
    15 void join(int a,int b) {
    16     int f1=findset(a),f2=findset(b);
    17     if(r[f1]<=r[f2]) {
    18         pre[f1]=f2;
    19         if(r[f1]==r[f2]) r[f2]++;
    20     }
    21     else pre[f2]=f1;
    22 }
    23 int main() {
    24     scanf("%d",&t);
    25     while(t--) {
    26         scanf("%d%d",&n,&m);
    27         for (int i=1;i<=n;++i) pre[i]=i,r[i]=1;
    28         while(m--) {
    29             int a,b;
    30             scanf("%d%d",&a,&b);
    31             join(a,b);
    32         }
    33         int cnt=0;
    34         for (int i=1;i<=n;++i) if(i==pre[i]) cnt++;
    35         printf("%d
    ",cnt);
    36     }
    37     return 0;
    38 }
    View Code
    这篇文章由TonyFang发布。 所有解释权归TonyFang所有。 Mailto: tony-fang@map-le.net
  • 相关阅读:
    Cisco 路由器硬件信息(各种序列号)查询命令
    解析黑客利用交换机漏洞攻击的常用手段
    所有windows操作系统键盘操作
    [转载]UC黑话解释Cisco统一通信江湖黑话解释
    常用照片尺寸和纸张尺寸参考
    Word中如何選擇從向文字
    python基础数据类型元组(tuple)
    promiseAll 使用
    js JavaScript 封装异步函数并被调用
    promise 学习2
  • 原文地址:https://www.cnblogs.com/TonyNeal/p/hdu1213.html
Copyright © 2020-2023  润新知