版权声明:假装有个原创声明……虽然少许博文不属于完全原创,但也是自己辛辛苦苦总结的,转载请注明出处,感谢! https://blog.csdn.net/m0_37454852/article/details/88430960
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;
//用了并查集和集合来解决,时间复杂度O(N)
const int MAX = 10010, INF = 1<<30;
int N, K, Q;
int father[MAX];
set<int> S;//集合用来统计集合的个数和集合中元素的个数
int cnt = 0;
int findFather(int a)
{
int aF = a;
while(aF != father[aF]) aF = father[aF];
while(a != aF)
{
int temp = father[a];
father[a] = aF;
a = temp;
}
return aF;
}
int main()
{
for(int i=0; i<MAX; i++) father[i] = i;
scanf("%d", &N);
for(int i=0; i<N; i++)
{
scanf("%d", &K);
int F, X;
if(K) scanf("%d", &F);
S.insert(F);
for(int j=1; j<K; j++)
{
scanf("%d", &X);
if(X == father[X]) father[X] = F;
else
{
int xF = findFather(X);
father[xF] = F;
}
S.insert(X);
}
}
for(set<int>::iterator it = S.begin(); it != S.end(); it++)//先查询一遍,利用路径优化,让每个集合只有一个根节点
{
findFather(*it);
}
for(set<int>::iterator it = S.begin(); it != S.end(); it++)
{
if(father[*it] == *it) cnt++;//查询根节点个数,即集合个数(树的个数)
}
printf("%d %d\n", cnt, S.size());//集合大小即元素个数(鸟的个数)
scanf("%d", &Q);
for(int i=0; i<Q; i++)
{
int a, b;
scanf("%d %d", &a, &b);
if(father[a] != father[b]) printf("No\n");//不在同一个集合
else printf("Yes\n");//在同一个集合
}
return 0;
}