【PAT】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

题意:给出一些图片,在一张图上的鸟属于同一棵树。问有多少颗树,几只鸟,以及给出两只鸟判断它们是否属于同一棵树。

分析:使用并查集,把一张图中的鸟合并到一个集合中,如果之后的图片又出现了之前出现过的鸟t,就把这张图上的鸟继续合并到 fa[t] 的集合中。合并方式:----------10->1->2 ,一种类似链表的形式。

#include <iostream>
using namespace std;
int fa[10002];
int findFather(int x) {
    int a = x;
    while(0 != fa[x]) 
	x = fa[x];
    while(0 != fa[a]) {
        int z = a;
        a = fa[a];
        fa[z] = x;
    }
    return x;
}
void Union(int a, int b) {
    int faA = findFather(a);
    int faB = findFather(b);
    if(faA != faB) fa[faA] = faB;
}
int main() {
    int n, q, k, id, temp, max = 0, cnt = 0;
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
        scanf("%d%d", &k, &id);
        if(id > max) max = id;
        for(int j = 1; j < k; j++) {
            scanf("%d", &temp);
	    if(temp > max) max = temp;
            Union(id, temp);
        }
    }
    for(int i = 1; i <= max; i++) {
	if(0 == fa[i]) cnt++;	
    }
    printf("%d %d\n", cnt, max);
    scanf("%d", &q);
    for(int i = 0; i < q; i++) {
        scanf("%d%d", &id, &temp);
        printf("%s\n", (findFather(id) == findFather(temp)) ? "Yes" : "No");
    }
    return 0;
}
发布了30 篇原创文章 · 获赞 26 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_36032963/article/details/88928825
今日推荐