题目链接
第一道
第二道
①统计全体个数,用map标记或set存储
②处理某个大集合的额外信息,只需要揪出其首领就好,判断条件:father[i]=i;
代码
using namespace std;
#include<bits/stdc++.h>
map<int, bool>book;
int father[10010],number[10010],cnt,num, p, q;
int findfather(int x) {
int a = x;
while (x != father[x])x = father[x];
while (a != father[a]) {
int z = a;
a = father[a];
father[z] = x;
}
return x;
}
void Union(int a, int b) {
int fa = findfather(a);
int fb = findfather(b);
if (fa != fb)father[fb] =fa, number[fa]+=number[fb], number[fb]=0;
}
int main() {
int n;
cin >> n;
for (int i = 1; i < 10000; i++)father[i] = i;
fill(number+1, number + 10000, 1);
for (int i = 0; i < n; i++) {
int k,a,b;
cin >> k;
for (int j= 0; j < k; j++) {
if (j == 0)cin >> a, book[a] = true;
else {
cin >> b, book[b] = true;
Union(a, b);
a = b;
}
}
}
for (auto p = book.begin(); p != book.end(); p++) {
if (father[p->first] == p->first)cnt++;
}
cout << cnt << " " << book.size() << endl;
cin >> num;
for (int i = 0; i < num; i++) {
cin >> p >> q;
if (findfather(q) != findfather(p))cout << "No" << endl;
else cout << "Yes" << endl;
}
return 0;
}