• (专题赛)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 }
  • 相关阅读:
    oracle rank() 排名函数
    oracle rank over partition by
    oracle over函数
    oracle extract函数
    mybatis的<choose>和<when>、<otherwise>标签
    python字符串操作实方法大合集
    GO安全并发之无锁原子操作
    设计模式(Design Patterns)Java版
    Linux内核参数调优
    TCP协议解析
  • 原文地址:https://www.cnblogs.com/awsent/p/4267058.html
Copyright © 2020-2023  润新知