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 (<= 104) 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 104. Afer the pictures there is a positive number Q (<= 104) 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从1开始并且连续,所以在输入的过程中统计最大id即为鸟的个数
树木棵树:并查集,将所有属于一张照片中的鸟(也在一棵树上)合并到一个集合。统计集合个数即为树木棵树
查询:若两只鸟在并查集中同一集合,即为同一棵树上的鸟

Code

#include <iostream>
#include <set>
using namespace std;
int father[10010];
void init() {
	for(int i=0; i<10010; i++) father[i]=i;
}
int find(int x) {
	int e = x;
	while(x!=father[x]) {
		x = father[x];
	}
	while(e!=father[e]) {
		int temp =father[e];
		father[e]=x;
		e = temp;
	}
	return x;
}
void Union(int a, int b) {
	int fa = find(a);
	int fb = find(b);
	if(fa<fb)father[fa]=fb;
	else father[fb]= fa;
}
int maxbi=-1;
int main(int argc,char * argv[]) {
	init();
	int n,k,b,q,b1,b2;
	scanf("%d",&n);
	for(int i=0; i<n; i++) {
		scanf("%d",&k);
		int head = -1;
		for(int j=0; j<k; j++) {
			scanf("%d", &b);
			if(maxbi<b)maxbi=b;
			if(j==0)head=b;
			Union(head,b);
		}
	}

	// 统计集合个数
	set<int> rts;
	for(int i=1; i<=maxbi; i++) {
		int f = find(i);
		rts.insert(f);
	}
	printf("%d %d
",rts.size(),maxbi);
	scanf("%d", &q);
	for(int i=0; i<q; i++) {
		scanf("%d %d",&b1,&b2);
		if(find(b1)==find(b2))printf("Yes
");
		else printf("No
");
	}
	return 0;
}
原文地址:https://www.cnblogs.com/houzm/p/12865146.html