题目地址

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

#include <cstdio>
#include <cstring>
#include<iostream>
#include <vector>
#include<math.h>
#include<string>
#include <algorithm>
using namespace std;
const int  maxn= 100010;  //最大顶点数
//const int inf = 0x3fffffff;  //无穷大
int father[maxn],course[maxn],isroot[maxn]={0};               //course每棵树的根节点,任意一个人;
int find_father(int a){
    int x=a;
    while(father[a]!=a){
        a=father[a];
    }
    while(father[x]!=x){
        int t=x;
        x=father[x];
        father[t]=a;            //每个人根节点成a;
    }
    return a;
}
void union_tree(int a,int b){
    int fa=find_father(a),fb=find_father(b);
    if(fa!=fb){
        father[fa]=fb;
    }
}
bool cmp(int a,int b){
    return a>b;
}
int main(){
    int n,k,q,ans1=0,ans2=0,bird1,bird2;cin>>n;
    memset(father,-1,sizeof(father));           //初始化为负一,有助于通过fa[a]=a判断树的个数;
    for(int i=0;i<n;i++){
        cin>>k;
        if(k){
            scanf("%d",&bird1);
            if(father[bird1]==-1) father[bird1]=bird1;          //每张图的鸟i
            for(int j=1;j<k;j++){
                cin>>bird2;
                if(father[bird2]==-1) father[bird2]=bird2;
                union_tree(bird1,bird2);
            }
        }
    }
    for(int i=0;i<maxn;i++){
        if(father[i]!=-1) {         //只要是有效结点,就是鸟,比作哈希表;
            ans2++;
            if(father[i]==i) ans1++;        //跟结点,满足father[i]==i;前面虽然每棵树都让其父亲是自己,但是联合后,在相同书上面的根节点合并了;
        }
    }
    cout<<ans1<<" "<<ans2<<endl;
    cin>>q;int qa,qb;
    for(int i=0;i<q;i++){
        cin>>qa>>qb;
        if(find_father(qa)==find_father(qb)) cout<<"Yes"<<endl;
        else cout<<"No"<<endl;
    }
}