HDU-1213-How Many Tables
Background
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
题意
- 先输入一个T,代表有T组测试数据
- 每组测试数据先输入一组N和M,分别代表有N个人(1-N标号)
- 以及接下来有M条表示A和B是朋友的输入
- 认识(直接或间接是朋友)的人必须坐在一张桌子上,不认识的人不能坐在一张桌子上
- 对每组测试数据输出需要多少张桌子
题解
- 这题还是一个并查集的基础板子题,套用模板输入输出即可
- 是朋友的代表在同一个集合内
- 每次输入A和B是朋友都用baba函数使它们进入同一集合,各自的祖先拜把子
- 然后遍历所有人,用flag数组对每个人的祖先用1做标记
- 相当于每一个集合里面有一个人是祖先,这个人也在所有人里面,那么就可以有下面这个步骤
- 最后遍历所有人,遇到一个flag为1的就sum++(注意对于每组测试数据sum要初始化为0)
- 输出sum值就行啦~
涉及知识点
- 并查集 算法
- 对于并查集的算法-详见链接博客介绍并查集
AC代码
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=1010;
int father[maxn];
int n=1010;
void init()
{
for(int i=1;i<=n;i++)
{
father[i]=i;
}
}
int find(int x)
{
return x==father[x]?x:father[x]=find(father[x]);
}
void baba(int x,int y)
{
int fx=find(x);
int fy=find(y);
father[fx]=fy;
}
int main()
{
int T,n,m,x,y,flag[1010];
scanf("%d",&T);
getchar();
for(int i=0;i<T;i++)
{
init();
scanf("%d %d",&n,&m);
memset(flag,0,sizeof(flag));
for(int j=0;j<m;j++)
{
scanf("%d %d",&x,&y);
baba(x,y);
}
for(int j=1;j<=n;j++)
{
flag[find(j)]=1;
}
int sum=0;
for(int j=1;j<=n;j++)
{
if(flag[j]==1) sum++;
}
printf("%d\n",sum);
}
return 0;
}