某人要办一个派对。他请来他的朋友,他需要准备桌子。而坐在同一桌的人必须相互认识。给T组数据,每组数据给定总人数n及朋友关系对数m,接下去给出朋友关系。注意,如果A认识B,B认识C,则A、B、C相互认识,可以坐在同一桌。
并查集呗。第一次做并查集的题目,把我坑惨了,一开始只写了找根节点的函数,然后发现需要考虑成环的情况,于是修改,还是WA,然后又想到要考虑比如1 2、1 3之后3 3重置的情况,于是又改,继续WA。一道题坑了几个小时,想不出其他情况了,于是百度,终于发现没有写合并的函数,添加后直接AC,根本不需要考虑那么多情况的。果然刚开始写不熟悉啊,要多刷题,嗯!
代码中find_root(int x)部分的代码受了群里某大神的影响,把找根节点和路径压缩用一行代码解决了,大赞。
# include <cstdio>
# include <cstring>
# include <iostream>
using namespace std;
const int MAXN = 1010 ;
int fa[MAXN] ;
bool hv[MAXN] ;
int find_root(int x) {
return (x == fa[x])? x : fa[x] = find_root(fa[x]);
}
void Union(int x , int y) {
int root_x , root_y ;
root_x = find_root(x) ;
root_y = find_root(y) ;
if (root_x != root_y) {
if (root_x > root_y) {
fa[root_x] = root_y ;
hv[root_x] = 0 ;
}
else {
fa[root_y] = root_x ;
hv[root_y] = 0 ;
}
}
}
int main() {
//freopen("in.txt" , "r" , stdin) ;
int T ;
cin >> T ;
while (T--) {
memset(fa , 0 , sizeof(fa));
memset(hv , 0 , sizeof(hv));
int n , m ;
cin >> n >> m ;
for (int i = 1 ; i <= n ; i ++) {
fa[i] = i ;
hv[i] = 1 ;
}
while (m--) {
int x , y ;
cin >> x >> y ;
Union(x , y) ;
}
int table = 0 ;
for (int i = 0 ; i <= n ; i ++) {
if (hv[i]) table ++ ;
}
cout << table <<endl ;
}
return 0;
}