hdoj How Many Tables【并查集】
2015-07-29 20:46
330 查看
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 withstrangers.
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 from1 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
Author
Ignatius.L代码:
#include<cstdio>
#include<algorithm>
using namespace std;
int pre[1010];
int find(int n)
{
int r=n;
if(r!=pre[r])
return pre[r]=find(pre[r]);
return r;
}
int main()
{
int n,m,t,x,y,ans,i,j;
scanf("%d",&t);
while(t--)
{
ans=0;
scanf("%d %d",&n,&m);
for(i=1;i<=n;i++)
pre[i]=i;
for(i=0;i<m;i++)
{
scanf("%d %d",&x,&y);
x=find(x);y=find(y);
if(x!=y)
pre[x]=y;
}
for(i=1;i<=n;i++)
if(pre[i]==i)
ans++;
printf("%d\n",ans);
}
return 0;
}
相关文章推荐
- linux权限控制机制
- Spark开发环境的配置
- 制作svg动画
- SQL VIEW 使用语法
- 设置android屏幕全屏
- HALCON算子函数——Chapter 11 : Morphology
- 2015多校第一场1008 hdu 5295 Unstable
- 60. Permutation Sequence
- [题解+总结]20150729
- SDWebImage使用,图片加载和缓存
- Jsoup读取东方财富网站数据实例
- loadrunner解决用户名、密码不同问题
- 【bzoj3679】 数字之积 数位dp
- shell编程入门
- jquery常用技巧及常用方法列表集合
- java eclipse 监视选择指定变量
- 黑马程序员———单例设计模式-懒汉式关于线程安全以及要点
- HALCON算子函数——Chapter 9 : Matching
- LeetCode || Sum Root to Leaf Numbers
- linux之例行性工作排程:crontab学习