题目链接:
L2-024 部落 (25分)
思路:
并查集裸题
代码:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e4 + 5;
int n, par[maxn], rk[maxn];
inline void init_set() { for(int i = 1; i < maxn ; par[i] = i, i++); }
inline int find(int x) {
if(x == par[x]) return x;
return par[x] = find(par[x]);
}
inline void unite(int x, int y) {
x = find(x);
y = find(y);
if(x == y) return;
if(rk[y] > rk[x]) par[x] = y;
else {
par[y] = x;
if(rk[x] == rk[y]) ++rk[x];
}
}
inline bool same(int x, int y) { return find(x) == find(y); }
int main() {
#ifdef MyTest
freopen("Sakura.txt", "r", stdin);
#endif
ios::sync_with_stdio(false);
cin.tie(0);
init_set();
int kase, ans = 0;
cin >> kase;
while(kase--) {
int k; cin >> k;
vector<int> v(k);
for(int i = 0; i < k; ++i) {
cin >> v[i];
n = max(n, v[i]);
if(i) unite(v[i], v[i - 1]);
}
}
for(int i = 1; i <= n; ++i) if(find(i) == i) ++ans;
cout << n << ' ' << ans << '\n';
int q; cin >> q;
while(q--) {
int x, y; cin >> x >> y;
cout << (same(x, y) ? "Y" : "N") << '\n';
}
return 0;
}
Yuhan の Blog
发布了288 篇原创文章 · 获赞 8 · 访问量 6942
私信
关注