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
1 #include <stdio.h> 2 #include <algorithm> 3 #include <iostream> 4 #include <map> 5 #include <vector> 6 #include <queue> 7 #include <set> 8 using namespace std; 9 int n,k,m; 10 const int maxn=10010; 11 int father[maxn]; 12 set<int> bird,tree; 13 void init(){ 14 for(int i=0;i<maxn;i++){ 15 father[i]=i; 16 } 17 } 18 int findfather(int x){ 19 int a=x; 20 while(x!=father[x]){ 21 x=father[x]; 22 } 23 while(a!=father[a]){ 24 int z=a; 25 a=father[a]; 26 father[z]=x; 27 } 28 return x; 29 } 30 void munion(int a,int b){ 31 int fa=findfather(a); 32 int fb=findfather(b); 33 if(fa!=fb){ 34 father[fa]=fb; 35 } 36 } 37 int main(){ 38 scanf("%d",&n); 39 init(); 40 for(int i=1;i<=n;i++){ 41 scanf("%d",&k); 42 int fi; 43 scanf("%d",&fi); 44 bird.insert(fi); 45 for(int j=1;j<k;j++){ 46 int tmp; 47 scanf("%d",&tmp); 48 munion(fi,tmp); 49 bird.insert(tmp); 50 } 51 } 52 for(auto it=bird.begin();it!=bird.end();it++){ 53 tree.insert(findfather(*it)); 54 } 55 printf("%d %d\n",tree.size(),bird.size()); 56 scanf("%d",&k); 57 for(int i=0;i<k;i++){ 58 int b1,b2; 59 scanf("%d %d",&b1,&b2); 60 if(findfather(b1)==findfather(b2))printf("Yes\n"); 61 else printf("No\n"); 62 } 63 }
注意点:第一次做到并查集的题目,看过的都已经忘记了,照着答案敲了一遍,还是要多加复习。