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 }
  • 相关阅读:
    Linux下串口编程入门
    arm-linux-gdb+gdbserver环境搭建以及远程调试
    google jib容器打包工具
    docker入门——构建镜像
    Docker搭建MySQL服务
    docker基本操作
    Docker 使用指南—— 基本操作
    使用docker Maven插件本地构建docker镜像并发布到远程服务器
    10张图带你深入理解Docker容器和镜像
    springboot+Jib+Maven+Idea+Docker 实践
  • 原文地址:https://www.cnblogs.com/awsent/p/4267058.html
Copyright © 2011-2022 走看看