PAT(A) 1118. Birds in Forest (25)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huqiao1206/article/details/79515656

title: PAT(A) 1118. Birds in Forest (25)
date: 2018-03-11 13:29:12
tags: PAT
description:
updated:
comments:
categories: PAT甲级
permalink:

原题目:

原题链接:https://www.patest.cn/contests/pat-a-practise/1118

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 (<= 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.

After 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

题目大意

给定N个照片,里面有相应K只鸟,说明在同一棵树上,再给出Q个问题,判断两只鸟是否在同一棵树上。

解题报告

并查集。

代码

/*
* Problem: 1118. Birds in Forest (25)
* Author: HQ
* Time: 2018-03-11
* State: Done
* Memo:
*/
#include "iostream"
#include "vector"
#include "algorithm"
using namespace std;

int father[10000 + 5];
int N,Q;

int getF(int x) {
	int a = father[x];
	if (a != x) {
		father[x] = getF(a);
		return father[x];
	}
	else
		return a;
}

void Union(int x, int y) {
	int a = getF(x);
	int b = getF(y);
	b = b ? b : y;
	if (a != b)
		father[b] = x;
}

int main() {
	cin >> N;
	int x, y,M,K;
	for (int i = 0; i < N; i++) {
		cin >> K;
		cin >> x;
		M = max(M, x);
		if (father[x] == 0)
			father[x] = x;
		for (int j = 1; j < K; j++) {
			cin >> y;
			M = max(M, y);
			Union(x, y);
		}
	}
	int tree = 0, birds = 0;
	int i;
	for (i = 1; i <= M; i++) {
		father[i] = getF(father[i]);
		if (father[i])
			birds++;
		if (father[i] == i)
			tree++;
	}
	cout << tree << " " << birds << endl;
	cin >> Q;
	for (int i = 0; i < Q; i++) {
		cin >> x >> y;
		if (getF(x) == getF(y))
			cout << "Yes" << endl;
		else
			cout << "No" << endl;
	}
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/huqiao1206/article/details/79515656