1118 Birds in Forest(并查集)

科学家拍摄了森林中数千只鸟的照片。所有在同一张照片中的鸟都属于同一棵树。任务是帮助科学家计算森林中最多可能有多少棵树,并判断任意两只鸟是否属于同一棵树。输入包含照片数量和每张照片的鸟的编号,之后是查询数量和每对鸟的编号。输出是最大可能的树的数量、鸟的数量以及每对鸟是否在同一棵树上的回答。

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 B​2… B​K

​​

where K is the number of birds in this picture, and B​i’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; 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值