1118. Birds in Forest (25)

来源:互联网 发布:linux 断电 丢失 文件 编辑:程序博客网 时间:2024/05/16 14:00

1118. Birds in Forest (25)

时间限制
150 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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:
43 10 1 22 3 44 1 5 7 83 9 6 4210 53 7
Sample Output:
2 10YesNo


并查集


#include<stdio.h>int tree[10010];int num[10010];void init(){int i;for(i=1;i<=10010;i++){tree[i]=-1;}}int findroot(int x){if(tree[x]==-1)return x;return tree[x]=findroot(tree[x]);}int main(){int n,i,j,k,bird1,bird2,maxbird=0;scanf("%d",&n);init();for(i=0;i<n;i++){scanf("%d",&k);scanf("%d",&bird1);num[bird1]=1;if(bird1>maxbird){maxbird=bird1;}for(j=0;j<k-1;j++){scanf("%d",&bird2);if(bird2>maxbird){maxbird=bird2;}num[bird2]=1;int a=findroot(bird1);int b=findroot(bird2);if(a!=b){tree[a]=b;bird1=b;}}}int treenum=0,birdnum=0;for(i=1;i<=maxbird;i++){if(tree[i]==-1){treenum++;}if(num[i]==1){birdnum++;}}printf("%d %d\n",treenum,birdnum);int q;scanf("%d",&q);for(i=0;i<q;i++){scanf("%d %d",&bird1,&bird2);int a=findroot(bird1);int b=findroot(bird2);if(a!=b){printf("No\n");}else{printf("Yes\n");}}} 



原创粉丝点击