1118. Birds in Forest (25)
Some scientists took pictures of thousands of birds in a forest. Assume that all the birds appear in the same picture belong to the same tree. You are supposed to help the scientists to count the maximum number of trees in the forest, and for any pair of birds, tell if they are on the same tree.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive number N (<= 104) which is the number of pictures. Then N lines follow, each describes a picture in the format:
K B1 B2 ... BK
where K is the number of birds in this picture, and Bi's are the indices of birds. It is guaranteed that the birds in all the pictures are numbered continuously from 1 to some number that is no more than 104.
After the pictures there is a positive number Q (<= 104) which is the number of queries. Then Q lines follow, each contains the indices of two birds.
Output Specification:
For each test case, first output in a line the maximum possible number of trees and the number of birds. Then for each query, print in a line "Yes" if the two birds belong to the same tree, or "No" if not.
Sample Input:4 3 10 1 2 2 3 4 4 1 5 7 8 3 9 6 4 2 10 5 3 7Sample Output:
2 10 Yes No
分析:并查集。
#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <queue>
#include <vector>
#include <functional>
#define rep(i,j,k) for(int i=j;i<=k;++i)
const int Max=10001;
int a[Max];
using namespace std;
int Find(int x)
{
if (a[x]>0) return Find(a[x]);
else return x;
}
void Union(int x, int y)
{
if (a[x]==0) a[x]=-1;
if (a[y]==0) a[y]=-1;
x=Find(x);
y=Find(y);
if (x==y) return;
if (a[x]<a[y]) {
a[x]+=a[y];
a[y]=x;
}else{
a[y]+=a[x];
a[x]=y;
}
}
bool isUnion(int x, int y)
{
if (Find(x)==Find(y)) return true;
else return false;
}
int main()
{
// freopen("test.txt","r",stdin);
rep(i,1,Max-1) a[i]=0;
int N;
cin>>N;
rep(i,1,N){
int k;
cin>>k;
int x;
if (k>0) {
cin>>x;
if (a[x]==0) a[x]=-1;
}
rep(j,1,k-1){
int y;
cin>>y;
Union(x,y);
}
}
int sum1=0,sum2=0;
rep(i,1,Max-1){
if (a[i]<0){
++sum1;
sum2-=a[i];
}
}
cout<<sum1<<' '<<sum2<<endl;
int m;
cin>>m;
rep(i,1,m){
int x,y;
cin>>x>>y;
if (isUnion(x,y)) cout<<"Yes\n";
else cout<<"No\n";
}
return 0;
}
本文介绍了一个使用并查集算法解决的实际问题:基于鸟类照片数据统计森林中树木的最大数量及特定鸟类是否位于同一棵树上。文章详细展示了输入输出规格,并提供了完整的C++实现代码。
384

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



