PAT甲级——1118 Birds in Forest (并查集)

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张照片,每张照片里面有K只鸟,它们属于同一棵树,每只鸟从1开始连续编号。接着有Q条查询指令,每条指令包含两只鸟的编号;要求先输出树的数量和鸟的数量,再对每条查询指令判断这两只鸟是否属于同一棵树。

思路:并查集的操作没啥好说的,略过~~,定义一个大数组S作为集合,并将所有元素初始化为-1;由于鸟的编号是连续的,那么最大的那个编号就是鸟的数量,同时也是集合S的size,遍历集合S,S中小于0的元素的数量就是树的数量。

#include <iostream>
#include <vector>
using namespace std;
int findRoot(int X);//寻找树的根
void unionSet(int root, int Y);
vector <int> S(10001, -1);//将集合元素初始化为-1
int main()
{
	int N, setSize = 0, Q, treeNum = 0;
	scanf("%d", &N);
	for (int i = 0; i < N; i++) {
		int K, B, root;
		scanf("%d%d", &K, &B);
		root = findRoot(B);
		if (setSize < B) setSize = B;
		for (int j = 1; j < K; j++) {
			scanf("%d", &B);
			if (setSize < B) setSize = B;
			unionSet(root, B);
		}
	}
	for (int i = 1; i <= setSize; i++) 
		if (S[i] < 0) 
			treeNum++;
	printf("%d %d\n", treeNum, setSize);
	scanf("%d", &Q);
	for (int i = 0; i < Q; i++) {
		int X, Y;
		scanf("%d%d", &X, &Y);
		printf(findRoot(X) == findRoot(Y) ? "Yes\n" : "No\n");
	}
}
void unionSet(int root, int Y) {
	int rootY = findRoot(Y);
	S[rootY] = root;
}
int findRoot(int X) {
	if (S[X] < 0) {
		return X;
	}
	else {
		return S[X] = findRoot(S[X]);//递归地进行路径压缩
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_44385565/article/details/89819984