【算法】Friends

描述

There are some people traveling together. Some of them are friends. The friend relation is transitive, that is, if A and B are friends, B and C are friends, then A and C will become friends too.

These people are planning to book some rooms in the hotel. But every one of them doesn’t want to live with strangers, that is, if A and D are not friends, they can’t live in the same room.

Given the information about these people, can you determine how many rooms they have to book at least? You can assume that the rooms are large enough.

输入

The first line of the input is the number of test cases, and then some test cases followed.

The first line of each test case contain two integers N and M, indicating the number of people and the number of the relationship between them. Each line of the following M lines contain two numbers A and B (1 ≤ A ≤ N , 1 ≤ B ≤ N , A ≠ B), indicating that A and B are friends.

You can assume 1 ≤ N ≤ 100, 0 ≤ M ≤ N * (N-1) / 2. All the people are numbered from 1 to N.

输出

Output one line for each test case, indicating the minimum number of rooms they have to book.

样例输入

3
5 3
1 2
2 3
4 5
5 4
1 2
2 3
3 4
4 5
10 0

样例输出

2
1
10

分析:并查集的简单运用,复习。
代码:
#include<bits/stdc++.h>
using namespace std;
int f[101];
int findit(int x)
{
return f[x]==x?x:f[x]=findit(f[x]);
}
void Union(int x,int y)
{
int fx=findit(x);
int fy=findit(y);
if (fx!=fy)
{
f[fy]=fx;
}
}
int main()
{
int T,N,M,A,B,ans;
cin>>T;
while(T–)
{
ans=0;
cin>>N>>M;
for (int i=1;i<=N;i++)
f[i]=i;
for (int i=0;i<M;i++)
{
cin>>A>>B;
Union(A,B);
}
for (int i=1;i<=N;i++)
{
if (f[i]==i)
ans++;
}
cout<<ans<<endl;
}
return 0;
}

发布了40 篇原创文章 · 获赞 0 · 访问量 673

猜你喜欢

转载自blog.csdn.net/Skynamer/article/details/103652120