PAT 1118. 森林里的鸟
原题链接
简单
作者:
YAX_AC
,
2024-11-14 21:47:46
,
所有人可见
,
阅读 2
并查集
//indices指标,指数 continuously连续不断地 numbered编号的给…编号 no more than至多,不超过
//which is the number of queries. Then Q lines follow, each contains the indices of two birds.
//这是查询的数量.接下来是Q行,每行都包含两只鸟的索引.
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int N = 10010;
int n;
int p[N];
int birds[10];
bool st[N];
int find(int x)
{
if(p[x]!=x) p[x] = find(p[x]);
return p[x];
}
int main()
{
cin>>n;
for(int i = 1; i<N; i++) p[i] = i;
int cnt = 0;//合并多少次
for(int i = 0; i<n; i++)
{
int k;
cin>>k;
for(int j = 0; j<k; j++)
{
cin>>birds[j];
st[birds[j]] = true;
}
for(int j = 1; j<k; j++)
{
int a = birds[j-1],b = birds[j];
a = find(a),b = find(b);
if(a!=b)
{
p[a] = b;
cnt++;
}
}
}
int sum = 0;
for(int i = 0; i<N; i++) sum += st[i];//鸟的总数
printf("%d %d\n",sum-cnt,sum);//树的数量=鸟的总数-合并的次数
int q;
cin>>q;
while(q--)
{
int a,b;
cin>>a>>b;
if(find(a)==find(b)) puts("Yes");
else puts("No");
}
return 0;
}
棒棒!~(。•̀ᴗ-)✧