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 (≤10^4) 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 10^4
.
After the pictures there is a positive number Q (≤10^4) 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 7
Sample Output:
2 10
Yes
No
#include<iostream>
using namespace std;
const int maxn=10010;
int fa[maxn]={0};
bool exist[maxn];
int findFather(int x){//直接用递归,不用递归有时候需要压缩路径,不然会超时。
if(x==fa[x]) return x;
else{
int f=findFather(fa[x]);
fa[x]=f;
return f;
}
}
void Union(int a,int b){//Union把两个不同的结点连在一起,谁做根结点无所谓的
int A=findFather(a);
int B=findFather(b);
if(fa[A]!=fa[B]) fa[A]=B;
}
int main(){
int n,q,k,id,temp;
for(int i=1;i<=maxn;i++) fa[i]=i;//注意下标是1-maxn
scanf("%d",&n);
for(int i=0;i<n;i++){//这个循环能生成n棵互相独立的树
scanf("%d%d",&k,&id);//把第一个结点分出来和后面每个结点做Union,保证所有结点可以生成一棵树
exist[id]=true;
for(int j=0;j<k-1;j++){
scanf("%d",&temp);
Union(id,temp);
exist[temp]=true;//所有遍历到的结点都置为true方便统计
}
}
int cnt[maxn]={0};
for(int i=1;i<=maxn;i++){//用exit来统计各个根结点,以及每个根结点有多少个子结点。有多少个根结点就说明有多少棵树
if(exist[i]){
int root=findFather(i);
cnt[root]++;
}
}
int sumTree=0,sumBird=0;
for(int i=1;i<=maxn;i++){
if(exist[i]&&cnt[i]){
sumTree++;
sumBird+=cnt[i];
}
}
printf("%d %d\n",sumTree,sumBird);
int b1,b2;
scanf("%d",&q);
for(int i=0;i<q;i++){
scanf("%d%d",&b1,&b2);
if(fa[b1]==fa[b2]) printf("Yes\n");
else printf("No\n");
}
return 0;
}