1118 Birds in Forest (25 分)【并查集的应用】

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 (≤10​4​​) which is the number of pictures. Then N lines follow, each describes a picture in the format:

K B​1​​ 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

题意:有n张图片,每张图片会有几只鸟,图片可能重合,给出每张图片鸟的编号,问最大可能有几棵树,有几只鸟

解题思路:非常明显的并查集题。数据还行,直接暴力,每一个点都寻找父亲那个点,不同就合并,相同就在那个父亲加1,然后我们再全部循环求出几个不同父亲结点并且每个父亲结点的数量加起来就是鸟的数量。

#include<bits/stdc++.h>
using namespace std;
int father[10010],ans[10010]={0};
bool judge[10010];//判断点是否存在
//并查集模板
int findFather(int x)
{
	if(x!=father[x] )return father[x]=findFather(father[x]);//不能return x=findFather[x],会超时
	return x;
}
void combine(int a,int b)
{
	int x=findFather(a);
	int y=findFather(b);
	if(x!=y) father[x]=y;
}

int main(void)
{
	for(int i=1;i<=10010;i++)
	father[i]=i;
	int n,k,q;
	scanf("%d",&n);
	for(int i=0;i<n;i++)
	{
		int id,temp;
		scanf("%d %d",&k,&id);
		judge[id]=true;
		for(int j=1;j<k;j++)
		{
			scanf("%d",&temp);
			combine(id,temp);
			judge[temp]=true;
		}
	}
	for(int i=1;i<=10010;i++)
	{
		int root;
		if(judge[i]==true)
		{
			root=findFather(i);
			ans[root]++;
		}
	}
	int tree=0,birds=0;
	for(int i=1;i<=10010;i++)
	{
		if(judge[i]==true&&ans[i]!=0)
		{
			tree++;
			birds+=ans[i];
		}
	}
	cout<<tree<<" "<<birds<<endl;
	int a,b;
	scanf("%d",&q);
	for(int i=0;i<q;i++)
	{
		scanf("%d %d",&a,&b);
		printf("%s\n",(findFather(a)==findFather(b))?"Yes":"No");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Imagirl1/article/details/83961587