2019-01-29

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
问题链接:https://vjudge.net/contest/279641#problem/G
问题简述:把相互认识的人分成一堆,求有多少堆
问题分析:找到每个人最初认识的人
程序说明:并查集
AC通过的C++程序如下:

include<iostream>

using namespace std;
int find(int x[],int i)
{
if (x[i] != i)
return find(x,x[i]);
return x[i];
}
void set(int x[], int y,int z)
{
int a = find(x,y), b = find(x,z);
if (a != b)
x[b] = a;
else return;
}
int main()
{
int t, n, m, f[1005], a, b, s;
cin >> t;
while (t--)
{
s = 0;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
f[i] = i;
}
for (int i = 1; i <= m; i++)
{
cin >> a >> b;
set(f,a, b);
}
for (int i = 1; i <= n; i++)
{
find(f,i);
if (find(f,i) == i)
s++;
}
cout << s<< endl;
}
return 0;
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,160评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,469评论 0 23
  • 自从认识了安化黑茶,我就天天喝茶,忽然有一天我的身体慢慢的就有所改变,不像以前那样老是感冒了。
    袁雪利阅读 1,209评论 0 0
  • 每天看二宝,就像在打仗,身心疲惫,我也想陪大宝写作业,也想陪她读书,陪她一起写日记,没看过娃的人不知道,有心无力,...
    李凝萱妈妈阅读 921评论 0 0
  • 三年级第四单元习作:
    睿子格格阅读 2,523评论 0 0