并查集—— How Many Tables

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

根据题意,需要在一组人数的集合(总人数),开始时让每个人构成一个单元素的集合,然后按一定顺序将属于同一组的人所在的集合合并,其间要反复查找一个元素在哪个集合中。此类问题用到并查集;
并查集
在一些有N个元素的集合应用问题中,我们通常是在开始时让每个元素构成一个单元素的集合,然后按一定顺序将属于同一组的元素所在的集合合并,其间要反复查找一个元素在哪个集合中。这一类问题近几年来反复出现在信息学的国际国内赛题中,其特点是看似并不复杂,但数据量极大,若用正常的数据结构来描述的话,往往在空间上过大,计算机无法承受;即使在空间上勉强通过,运行的时间复杂度也极高,根本就不可能在比赛规定的运行时间(1~3秒)内计算出试题需要的结果,只能用并查集来描述。并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets)的合并及查询问题。常常在使用中以森林来表示。

  1. 初始化

把每个点所在集合初始化为其自身。
通常来说,这个步骤在每次使用该数据结构时只需要执行一次,无论何种实现方式,时间复杂度均为O(N)。

  1. 查找

查找元素所在的集合,即根节点。

  1. 合并

将两个元素所在的集合合并为一个集合。
通常来说,合并之前,应先判断两个元素是否属于同一集合,这可用上面的“查找”操作实现。

这个是找出至少需要的桌子的数量;
这个从总人数方面分析,人数的总和就为一个集合,构成朋友的为每一个子集即
他们为一个桌的人;
其实,每个桌子的人数应该是不限的。``

#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
int a[1005],b[1005];
void xset(int n)  //初始化,将自己定义为根;
{
    int i;
    for(i=1;i<=n;i++)
        a[i]=i;
}
int findshu(int x)  //这个函数用来找到自己所属的集合,返回的是自己所属集合的名称
{
    while(x!=a[x])
        x=a[x];
    return x;
}
void judge(int x,int y)  //此函数用来合并两个朋友的所属集合,使它们在一个集合里面
{
    int i=findshu(x);
    int j=findshu(y);
    if(i!=j)
        a[i]=j;
}
int main()
{
    int t,n,m,i,x,y;
    scanf("%d",&t);
    while(t--)
    {
        int j=0;
        memset(b,0,sizeof(b));
        scanf("%d%d",&n,&m);
        xset(n);
        for(i=1;i<=m;i++)
        {
            scanf("%d%d",&x,&y);
            judge(x,y);
        }
        for(i=1;i<=n;i++)
        {
            if(b[findshu(a[i])]++==0)  //a[i]是第i个人的集合名称,findshu( )是用来找到a[i]的所属集合
                j++;    //在同一个集合中的人共用一张桌子,一个集合只被计数一次
        }
        cout<<j<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43516113/article/details/86525284