题目描述
C++代码
样例
#include<iostream>
#include<algorithm>
#include<string>
#include<unordered_set>
#include<cstring>
#include<vector>
using namespace std;
const int N = 1e4 + 10;
int parent[N];
void Init(int n)
{
for (int i = 1; i <= n; i++)
{
parent[i] = i;
}
}
int find(int a)
{
if (a != parent[a]) {
parent[a] = find(parent[a]);
}
return parent[a];
}
void Unite(int x, int y)
{
int root_x = find(x);
int root_y = find(y);
if (root_x != root_y)
{
parent[root_x] = root_y;
}
}
int main()
{
int T;
int sum = 0;
unordered_set<int> st;
cin >> T;
int o = -1;
vector<vector<int>> a(T);
for(int i=0;i<T;i++)
{
int n;
cin >> n;
for (int j = 0; j < n; j++)
{
int x;
cin >> x;
a[i].push_back(x);
o = max(o, x);
st.insert(x);
}
}
Init(o);
for (int i = 0; i < T; i++)
{
for (int j = 1; j < a[i].size(); j++)
{
Unite(a[i][j], a[i][j - 1]);
}
}
for (int i=1;i<=o;i++)
{
if (parent[i] == i) {
sum++;
}
}
cout << sum << " " << st.size() << endl;
int k;
cin >> k;
for (int i = 0; i < k; i++)
{
int x, y;
cin >> x >> y;
if (find(x) != find(y))
{
cout << "No" << endl;
}
else {
cout << "Yes" << endl;
}
}
return 0;
}