PAT A1118 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

实现思路:

题意是给出几张照片中鸟的id,然后如果在同一张照片的鸟是属于同一棵树上的,结果输出树的棵数,鸟的数量,然后分别给出一对鸟的id用于查询是否在一棵树上,是为yes,反之为no,明显的并查集题型。

AC代码:

#include <iostream>
#include <unordered_map>
#include <set>
using namespace std;
const int N=10010;
int father[N];
int findFather(int x) {
	int a=x;
	while(x!=father[x]) {
		x=father[x];
	}
	while(a!=father[a]) {
		int z=a;
		a=father[a];
		father[z]=x;
	}
	return x;
}

void Union(int a,int b) {
	int faA=findFather(a);
	int faB=findFather(b);
	if(faA!=faB) father[faA]=faB;
}

int main() {
	unordered_map<int,int> mp;
	for(int i=0; i<N; i++) father[i]=i;
	int n,k,id1,id2;
	cin>>n;
	while(n--) {
		scanf("%d",&k);
		if(k>0) {
			scanf("%d",&id1);
			mp[id1]=1;
			k--;
		}
		while(k--) {
			scanf("%d",&id2);
			mp[id2]=1;
			Union(id1,id2);
			id1=id2;
		}
	}
	int hashT[N]= {0},q1,q2;
	set<int> st;
	for(auto it : mp)
		st.insert(findFather(it.first));
	cout<<st.size()<<" "<<mp.size()<<endl;
	cin>>k;
	while(k--) {
		scanf("%d %d",&q1,&q2);
		if(findFather(q1)==findFather(q2)) printf("Yes\n");
		else printf("No\n");
	}
	return 0;
}
posted @ 2021-02-27 15:16  coderJ_ONE  阅读(46)  评论(0编辑  收藏  举报