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
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
结尾无空行
经典并查集问题,昨天晚上没休息好,完全不在状态,连并查集都忘了初始化了淦。
注意并查集的路径优化问题,如果不优化,应该会超时
如果两只鸟的父亲一样,说明是在同一棵树上
注意一些细节:编号是从 1 开始的,路径优化问题,需要掌握
#include<iostream>
#include<bits/stdc++.h>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<deque>
#include<unordered_set>
#include<unordered_map>
#include<cctype>
#include<algorithm>
#include<stack>
using namespace std;
const int N = 10001;
int father[N];
bool flag[N] = {false};
set<int> ss;
int findFather(int x) {
if (x == father[x]) {
return x;
} else {
int F = findFather(father[x]);
father[x] = F;
return F;
}
}
void init() {
for (int i = 0; i < N; i++) {
father[i] = i;
}
}
void Union(int x, int y) {
int fa = findFather(x);
int fb = findFather(y);
if (fa != fb) {
father[fa] = fb;
}
}
int main() {
int n;
cin >> n;
init();
set<int>st;
int maxn = -1;
while (n--) {
int k;
cin >> k;
int x;
cin >> x;
st.insert(x);
flag[x] = true;
maxn = max(maxn, x);
for (int i = 1; i < k; i++) {
int y;
cin >> y;
st.insert(y);
flag[y] = true;
maxn = max(maxn, y);
Union(x, y);
}
}
int count = 0;
for (int i = 1; i <= maxn; i++) {
if (father[i] == i) {
count++;
}
}
cout << count << " " << st.size() << endl;
int m;
cin >> m;
while (m--) {
int x, y;
cin >> x >> y;
if (findFather(x) == findFather(y)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
}
return 0;
}