How Many Tables

本文介绍了一个生日派对上朋友分桌的问题,朋友们不想与陌生人同桌。通过并查集数据结构,我们可以高效地解决这个问题。文章详细解析了如何应用并查集的find和union操作来判断朋友之间的关系,并最终确定所需的最少餐桌数量。实例展示了如何处理输入数据,并给出了完整的C语言代码实现。
摘要由CSDN通过智能技术生成

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.这个问题的一个重要规则是,如果我告诉你A认识B,B认识C,那就说明A、B、C认识,所以可以留在一张桌子上。

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.举个例子:如果我告诉你A认识B,B认识C,D认识E,那么A、B、C可以留在一张桌子上,D、E必须留在另一张桌子上。所以Ignatius至少需要2张桌子

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.输入 ;输入以整数T(1<=T<=25)开始,表示测试用例的数量。然后T测试用例随之而来。每个测试用例以两个整数N和M(1<=N,M<=1000)开始。n表示朋友的数量,朋友从1到n标记。然后M行跟随。每行由两个整数A和B组成(A!=B),也就是说朋友A和朋友B认识。两个案例之间会有一个空白行。

Output
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.输出 ;对于每个测试用例,只需输出Ignatius至少需要多少个表。请勿打印任何空白。

#include<stdio.h>
int sum,f[1005];   || 定义sum为需要桌子的最大数量,定义f为主人和他的朋友组成的集合。 
int find(int x)   || 定义x为根节点,也就是发起这个活动的主人。
    if(f[x]!=x)
        f[x]=find(f[x]);
    return f[x];  || 在这个集合中找到主人。
}
void  make(int x,int y)  || 定义两人x,y。
{
    int f1=find(x);  
    int f2=find(y);  || 定义集合中两人为x,y。
    if(f1!=f2)  || 若两人认识
    {
        f[f1]=f2;    || 则放在一块儿,也就是做在一个桌子上。
        sum--;      ||因为有认识的人,所以最少须要的桌子要减1}
}
int main()
{
    int n,m,i,t;  || 定义有n个人,m层关系,i为人的序号,t为测试关系
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d %d",&n,&m);
        sum=n;      || 若开始时全部的人都不认识,则需桌子数为n
        for(i=1;i<=n;i++)   || 这里从i开始循环,循环的是数组中的人,每次加一
            f[i]=i;  || 这里是数组f[i]的根节点为i,也就是这个桌子上的人认识i。
        for(i=1;i<=m;i++)  || 这里循环的是桌子数,各查找各个桌子上有无互相认识的人,意思是查重。
        {
            int a,b;
            scanf("%d %d",&a,&b);
            make(a,b);  ||  a,b有关系,则他们坐在一起。
        } 
        printf("%d\n",sum);  || 输出所需要的桌子数量。
    }
    return 0;

这个问题是并查集的应用。 find操作 【函数在并查集s中查找并返回包含元素x的树的根。】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值