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;
    }
  • 相关阅读:
    从FxCop归纳出来的一些规范建议
    UML用例建模的慨念和应用
    Android 截屏脚本
    悲剧的账户绑定与通讯录丢失实录
    文件分享功能实现
    Java字符串与整数之间的互相转换
    关于大的Bitmap保存问题
    将程序关联成Android系统默认打开程序
    关于Android应用多语言支持实现
    关于通过getWidth与getHeight获取bitmap​的尺寸与其实际尺寸不符合问题
  • 原文地址:https://www.cnblogs.com/hellocheng/p/7367729.html
Copyright © 2011-2022 走看看