PAT_A 1118. Birds in Forest (25)

来源:互联网 发布:淘宝网开店 编辑:程序博客网 时间:2024/06/04 17:46

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

  • 分析
    查并集,算法导论上不相交集合,或者森林。
    确定一共几棵树,几只鸟。照片可能拍了半棵树,由于鸟的编号是确定的,及通过编号,如果两个照片上有同一个编号,则这张照片上的鸟是一棵树上的。可以确定一棵树。然后确定两只鸟时候在一个可树上,这事就是找他爹
    说一下自己最开始犯错的情况吧:
    3 10 1 2
    2 5 6
    2 1 5
    我们可以确定以上编号的鸟是一棵树上的。
  • code
#include <cstdio>using namespace std;int n, m, k;const int maxn = 10010;int fa[maxn] = {0}, cnt[maxn] = {0};int findFather(int x) {    int a = x;    while(x != fa[x]) {        x = fa[x];    }    while(a != fa[a]) {        int z = a;        fa[a] = x;        a = fa[z];    }    return x;}void Union(int a, int b) {    int faA = findFather(a);    int faB = findFather(b);    if(faA != faB) {        fa[faA] = faB;    }}bool exist[maxn];int main() {    scanf("%d", &n);    for(int i = 1; i <= maxn; i++) {        fa[i] = i;    }    int id, temp;    for(int i = 0; i < n; i++) {        scanf("%d%d", &k, &id);        exist[id] = true;        for(int j = 0; j < k-1; j++) {            scanf("%d", &temp);            Union(id, temp);            exist[temp] = true;        }    }    for(int i = 1; i <= maxn; i++) {        if(exist[i] == true) {            int root = findFather(i);            cnt[root]++;        }    }    int numTrees = 0, numBirds = 0;    for(int i = 1; i <= maxn; i++) {        if(exist[i] == true && cnt[i] != 0) {            numTrees++;            numBirds += cnt[i];        }    }    printf("%d %d\n", numTrees, numBirds);    scanf("%d", &m);    int ida, idb;    for(int i = 0; i < m; i++) {        scanf("%d%d", &ida, &idb);        if(findFather(ida) == findFather(idb)) {            printf("Yes\n");        } else {            printf("No\n");        }    }    return 0;}
0 0
原创粉丝点击