zoukankan      html  css  js  c++  java
  • (专题赛)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 
     3 
     4 
     5 int pre[1000];
     6 
     7 
     8 
     9 int find(int x)
    10 
    11 {
    12 
    13 int r=x;
    14 
    15 while(pre[r]!=r)
    16 
    17 r=pre[r];
    18 
    19 int i=x,j;
    20 
    21 while(i!=r)
    22 
    23 {
    24 
    25 j=pre[i];
    26 
    27 pre[i]=r;
    28 
    29 i=j;
    30 
    31 }
    32 
    33 return r;
    34 
    35 }
    36 
    37 
    38 
    39 int main()
    40 
    41 {
    42 
    43 int t,n,m,a,b,f1,f2,i,total;
    44 
    45 scanf("%d",&t);
    46 
    47 while(t--)
    48 
    49 {
    50 
    51 scanf("%d",&n);
    52 
    53 total=n;//在最初有n个集合
    54 
    55 for(i=1;i<=n;i++)
    56 
    57 {pre[i]=i;}
    58 
    59 scanf("%d",&m);
    60 
    61 while(m--)
    62 
    63 {
    64 
    65 scanf("%d %d",&a,&b);
    66 
    67 f1=find(a);
    68 
    69 f2=find(b);
    70 
    71 if(f1!=f2)
    72 
    73 {
    74 
    75 pre[f2]=f1;
    76 
    77 total--;
    78 
    79 }
    80 
    81 }
    82 
    83 printf("%d
    ",total);
    84 
    85 }
    86 
    87 return 0;
    88 
    89 }
  • 相关阅读:
    avalon随笔
    ms-attr-data-real-gold="{{page_data[0].gold}}" 属性付真
    jQuery 快捷操作
    jQuery 属性操作
    jQuery 表单域选中选择器
    jQuery 层次选择器
    jQuery 基本选择器
    jQuery 基本使用
    jQuery 引入多个库文件冲突
    BOM window对象方法
  • 原文地址:https://www.cnblogs.com/awsent/p/4267058.html
Copyright © 2011-2022 走看看