1. 程式人生 > >1118 Birds in Forest (25 分)【並查集的應用】

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;
}