# L2-024 部落 (25 point(s)) （并查集）

### 输入格式：

K P[1] P[2] ⋯ P[K]

### 输入样例：

4
3 10 1 2
2 3 4
4 1 5 7 8
3 9 6 4
2
10 5
3 7


### 输出样例：

10 2
Y
N


// Murabito-B 21/04/21
#include <bits/stdc++.h>
using namespace std;
using ll    = long long;
const int N = 1e4 + 10;
int Max     = -1; // 总人数，编号最大的
int fa[N];
int find(int x) { return fa[x] == x ? x : fa[x] = find(fa[x]); }
void merge(int x, int y) {
x = find(x), y = find(y);
if (x == y) return;
fa[y] = fa[x];
}
void solve() {
for (int i = 1; i <= N; ++i) fa[i] = i;
int n;
cin >> n;
for (int i = 1, k, x; i <= n; ++i) {
cin >> k;
int p[k + 1];
for (int i = 0; i < k; ++i) cin >> p[i], Max = max(Max, p[i]);
for (int i = 0; i < k - 1; ++i) merge(p[i], p[i + 1]);
}
int q, cnt = 0;
cin >> q;
vector<char> v;
for (int i = 1; i <= Max; ++i)
if (fa[i] == i) cnt++;
cout << Max << " " << cnt << "\n";
while (q--) {
int a, b;
cin >> a >> b;
cout << (find(a) == find(b) ? "Y\n" : "N\n");
}
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(0);
solve();
return 0;
}

posted @ 2021-04-21 20:42  RioTian  阅读(10)  评论(0编辑  收藏