kuangbin 并查集 - HDU - 1213 How Many Tables(并查集简单题)
小明今天请吃饭. 他邀请了很多朋友。现在该吃饭了。小明想知道她至少需要多少张桌子。但是不是所有的人都互相认识,所有的人都不想和陌生人坐在一起。
但是如果A认识B, B认识C,那A, B, C就假装认识,所以他们就可以在一张桌子上吃饭。
如果A知道B, B知道C, D知道E,那么A、B、C可以留在一起,而D、E必须在另一张桌子吃饭。至少需要两张桌子。
Input
输入以一个整数T(1<=T<=25)开始,它表示测试用例的数量。然后是测试用例。每个测试用例都以两个整数N和M开始(1<=N,M<=1000)。N表示朋友的数量,从1到N标记朋友,之后的M行,每一行由两个整数A和B(A!=B)组成,这意味着朋友A和朋友B相互认识。两种情况之间会有一条空行。
Output
对于每个测试用例,只需输出至少需要多少张桌子。不要打印任何空格。
Sample Input
2
5 3
1 2
2 3
4 5
5 1
2 5
Sample Output
2
4
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define ll long long
//#define int ll
#define INF 0x3f3f3f3f
using namespace std;
int read()
{
int w = 1, s = 0;
char ch = getchar();
while (ch < '0' || ch>'9') { if (ch == '-') w = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { s = s * 10 + ch - '0'; ch = getchar(); }
return s * w;
//最大公约数
}int gcd(int x,int y) {
if(x<y) swap(x,y);//很多人会遗忘,大数在前小数在后
//递归终止条件千万不要漏了,辗转相除法
return x % y ? gcd(y, x % y) : y;
}
int lcm(int x,int y)//计算x和y的最小公倍数
{
return x * y / gcd(x, y);//使用公式
}
//------------------------ 以上是我常用模板与刷题几乎无关 ------------------------//
const int N = 1010;
int p[N];
int find(int x)//返回x的祖宗节点+路径压缩
{
if (p[x] != x)//如果当前节点x不是根节点的话,就会往上走一层。
p[x] = find(p[x]);//就返回父节点的祖宗节点
return p[x];
}
int main()
{
int t;
cin>>t;
while(t--)
{
int n = read(), m = read();
for(int i = 1; i <= n; ++i)
p[i] = i;
while(m--) {
int a = read(), b = read();
if (find(a) != find(b))
p[find(a)] = find(b);
}
int cnt = 0;
for(int i = 1; i <= n; ++i)
if(p[i] == i)
++cnt;
printf("%d\n", cnt);
}
return 0;
}