题意
给出n张照片,每张照片有若干个鸟,假设一张照片中的鸟都在一棵树上,
要求输出树的数目和鸟的总数。并给出q个问题,每个问题询问两只鸟是否在一棵树上。
思路
典型并查集。
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 "bits/stdc++.h"
using namespace std;
const int N = 10005;
int father[N];
int findFather(int x){
int a = x;
while (father[x] != x) x = father[x];
while (a != x){
int t = a;
a = father[a];
father[t] = x;
}
return x;
}
void _union(int a, int b){
father[findFather(a)] = findFather(b);
}
int main(){
// freopen("input.txt","r",stdin);
int n; cin >> n;
set<int> ids;
for (int i = 0; i < N; ++i) father[i] = i;
for (int i = 0; i < n; ++i) {
int k; scanf("%d",&k);
int head = -1;
for (int j = 0; j < k; ++j) {
int id; scanf("%d",&id); ids.insert(id);
if (j == 0) head = id;
else _union(id,head);
}
}
unordered_map<int,int> group;
for(int id:ids) group[findFather(id)] ++;
cout << group.size() << " " << ids.size() << endl;
int q; cin >> q;
for (int i = 0; i < q; ++i) {
int a, b; scanf("%d%d",&a,&b);
if (findFather(a) == findFather(b)) printf("Yes\n");
else printf("No\n");
}
}