zoukankan      html  css  js  c++  java
  • 【并查集入门专题1】F

    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. 

    InputThe 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.
    OutputFor 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
    模板题一道 就当回顾。本来答应自己不写水题的,但是是师父出的,得给点面子吧,虽然师父也觉得没意思~
    #include<stdio.h>
    #include<string.h>
    #define N 1100
    
    int n,m;
    int f[N],u[N],v[N];
    
    int find(int u)
    {
        if(f[u]==u)
            return u;
        else
        {
            f[u] = find(f[u]);
            return f[u];
        }
    }
    
    void merge(int x,int y)
    {
        int t1,t2;
        t1 = find(x);
        t2 = find(y);
        if(t1!=t2)
            f[t1] = t2;
        return;
    }
    
    int main()
    {
        int t,i,j,count;
        scanf("%d",&t);
        while(t --)
        {
            scanf("%d%d",&n,&m);
            for(i = 1; i <= n; i ++)
                f[i] = i;
            for(i = 1; i <= m; i ++)
                scanf("%d%d",&u[i],&v[i]);
            for(i = 1; i <= m; i ++)
                merge(u[i],v[i]);
            count = 0;
            for(i = 1; i <= n; i ++)
                if(f[i]==i)
                    count ++;
            printf("%d
    ",count);
        }
        return 0;
    }
  • 相关阅读:
    hg下拉和上传代码
    PC下ubuntu查找PC串口并加入用户组
    pyserial安装
    profile, bashrc, source, setup.*sh
    另一篇xtion、kinect选择比较(openni下)
    OpenCV、PCL;Xtion、kinect;OpenNI、kinect for windows SDK比较
    ROS安装环境配置及多版本的切换
    ubuntu安装软件或upgrade出现 You might want to run 'apt-get -f install' to correct these
    树莓派静态IP配置
    android之MP3播放器(1)
  • 原文地址:https://www.cnblogs.com/hellocheng/p/7367729.html
Copyright © 2011-2022 走看看