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;
    }
  • 相关阅读:
    app移动测试 (自动化遍历方法和技巧)(转载大佬)
    使用Jmeter录制脚本并调试
    整理token,session ,cookies 和正则表达式整理
    ·接口测试核心:URL&HTTP协议详解
    性能测试基本概念 聚合报告指标分析
    数据分析技能点梳理
    数据分析整体知识点架构(转载)
    数据分析职业前景规划
    数据分析三年建议指导(书籍等)
    系统吞吐量(TPS)、用户并发量、性能测试概念和公式 (转载)
  • 原文地址:https://www.cnblogs.com/hellocheng/p/7367729.html
Copyright © 2011-2022 走看看