zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    Django之Admin
    反射功能:***attr
    python单例模式
    三元表达式,推导式,生成器表达式
    jquery的each()
    Django篇之F,Q
    Django的思维导图
    Models_Class 有choice,如何显示其中文
    Java并发机制(1)--线程状态与方法(转)
    Java并发机制(2)--synchronized与Lock
  • 原文地址:https://www.cnblogs.com/TonyNeal/p/hdu1213.html
Copyright © 2011-2022 走看看