How Many Tables

How Many Tables
题目链接:
http://acm.hust.edu.cn/vjudge/contest/123393#problem/C

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.

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个人参加晚宴;
完全不认识的两个人不能被分配在同一餐桌;
认识具有传递性:A认识B B认识C,那么A和C也认识.

题解:
很明显的并查集模版题.
将认识两个人合并到同一集合;
最后统计有多少个不同的集合即可;

注意:部分编译器不允许变量名与关键字冲突;故注意next和rank这些关键字,以免CE.

#include<bits/stdc++.h>
using namespace std;
int t,n,m,a1,a2,res;
int f[1001];//-1 代表为根节点 
int find_root(int x)//找x的根节点
{
	if(f[x]==-1)	return x;//如果为-1,则这就是根节点 
	else	return find_root(f[x]);//不然就递归找根节点 
} 
void union_set(int a,int b)//合并两个元素 
{
	int fa=find_root(a);//先找各自的根节点 
	int fb=find_root(b);
	if(fa!=fb||(fa==-1&&fb==-1))//如果根节点不一样或根节点都是本身,就合并起来 
	{
		f[fa]=fb;
	}
}
int main()
{
	cin>>t;//t组数据 
	while(t--)//循环t次 
	{
		res=0;//每次都初始化为0 
		memset(f,-1,sizeof(f));//把所有根节点都为本身 
		cin>>n>>m;
		for(int i=1;i<=m;i++)
		{
			cin>>a1>>a2;
			union_set(a1,a2);//合并 
		}
		for(int i=1;i<=n;i++)	if(f[i]==-1)	res++;//加上所有根节点 
		cout<<res<<endl;//根节点个数就是桌子个数 
	}
	return 0;
}
全部评论

相关推荐

牛客737698141号:他们可以看到在线简历的。。。估计不合适直接就拒了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务