题目中规中矩,没有什么难度,标准的并查集就能拿下。
#include<iostream>
#include<vector>
using namespace std;
int father[10010];
int findFather(int x) {
int a = x;
while (x != father[x]) {
x = father[x];
}
while (a != father[a]) {
int z = a;
father[a] = x;
a = father[z];
}
return x;
}
int main() {
int pic_num,num,temp,N,que_num;
N = -1;
cin >> pic_num;
vector<vector<int> > picture(pic_num);
for (int i = 0; i < pic_num; i++) {
cin >> num;
for (int j = 0; j < num; j++) {
cin >> temp;
if (temp > N)N = temp;
picture[i].push_back(temp);
}
}
for (int i = 1; i <= N; i++)father[i] = i;
for (int i = 0; i < pic_num; i++) {
int size = picture[i].size();
int pre = picture[i][0];
for (int j = 1; j < size; j++) {
int f1 = findFather(pre);
int f2 = findFather(picture[i][j]);
if (f1 != f2)father[f1] = f2;
}
}
int cnt = 0;
for (int i = 1; i <= N; i++) {
if (father[i] == i)cnt++;
}
cout << cnt <<" "<< N<<endl;
cin >> que_num;
for (int i = 0; i < que_num; i++) {
int q1, q2;
cin >> q1 >> q2;
int f1 = findFather(q1);
int f2 = findFather(q2);
if (f1 == f2)printf("Yes\n");
else printf("No\n");
}
system("pause");
return 0;
}