#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;
}
PAT (Advanced Level) Practice A1118 Birds in Forest (25 分)(C++)(甲级)(并查集、set)
最新推荐文章于 2021-05-30 14:15:43 发布
本文介绍了一种使用并查集和集合进行数据结构操作的方法,实现对元素的快速查找和集合统计,时间复杂度为O(N)。通过路径压缩优化,确保每个集合只有一个根节点,便于统计集合数量及元素总数。
C++甲级(并查集、set)&spm=1001.2101.3001.5002&articleId=88430960&d=1&t=3&u=9e15ea651cd34e0daba673034b86a553)
416

被折叠的 条评论
为什么被折叠?



