• [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
  • 相关阅读:
    CopyOnWriteArrayList 写时复制思想
    CAS中ABA问题的解决
    彻底解决Chrome“请停用以开发者模式运行的扩展程序”提示(亲测整合)
    解决软件安装无法自定义文件夹,自动安装在C盘 (Windows系统)
    IDEA降低注解检测级别
    大白话带你认识JVM(转)
    Windows 与 Linux (CentOS7) 之间的文件共享
    Dubbo、Zookeeper 以及 Tomcat 启动的相关问题
    创建 maven 项目的时候遇到的问题
    MyBatis 项目的 jar 包导入与源码导入
  • 原文地址:https://www.cnblogs.com/TonyNeal/p/hdu1213.html
Copyright © 2020-2023  润新知