A1118. Birds in Forest
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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 using namespace std; 5 int father[10001]; 6 int findRoot(int x){ 7 int temp = x; 8 while(x != father[x]){ 9 x = father[x]; 10 } 11 int temp2; 12 while(temp != x){ 13 temp2 = father[temp]; 14 father[temp] = x; 15 temp = temp2; 16 } 17 return x; 18 } 19 void union_(int a, int b){ 20 int fa = findRoot(a); 21 int fb = findRoot(b); 22 if(fa == fb) 23 return; 24 father[fb] = fa; 25 } 26 int main(){ 27 int N, K, cnt = -1; 28 for(int i = 0; i < 10001; i++){ 29 father[i] = i; 30 } 31 scanf("%d", &N); 32 for(int i = 0; i < N; i++){ 33 int b1, b2, maxb; 34 scanf("%d%d", &K, &b1); 35 cnt = max(b1, cnt); 36 for(int j = 1; j < K; j++){ 37 scanf("%d", &b2); 38 union_(b1, b2); 39 maxb = max(b1, b2); 40 cnt = max(maxb, cnt); 41 } 42 } 43 int tree = 0; 44 for(int i = 1; i <= cnt; i++){ 45 if(father[i] == i) 46 tree++; 47 } 48 printf("%d %d\n", tree, cnt); 49 int Q; 50 scanf("%d", &Q); 51 for(int i = 0; i < Q; i++){ 52 int q1, q2; 53 scanf("%d%d", &q1, &q2); 54 if(findRoot(q1) == findRoot(q2)) 55 printf("Yes\n"); 56 else printf("No\n"); 57 } 58 cin >> N; 59 return 0; 60 }
1、因为birds并不是连续出现的,需要用set来存储bird的编号。