P6691 选择题 题解
_TwilightSnow_ · · 题解
扩展域并查集辣么阔爱,为啥不用捏?
觉得其它的并查集的题解质量都不是很好。
Solution
考虑使用扩展域并查集。
对于选项
再想想怎么处理答案,我们发现,如果一个连通块内的点确定了,那么这一整个连通块就确定了,所以设
Code
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 2e6 + 2, MD = 998244353;
int n, fa[N], a[N], op[N], cnt[N][2];
int find(int x) { return x == fa[x] ? x : (fa[x] = find(fa[x])); }
void join(int x, int y) { fa[find(x)] = find(y); }
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n, iota(fa, fa + 2 * n + 1, 0);
for (int i = 1; i <= n && cin >> a[i] >> op[i]; i++)
if (op[i] == 1) join(i, a[i]), join(i + n, a[i] + n);
else join(i, a[i] + n), join(i + n, a[i]);
for (int i = 1; i <= n; i++)
if (find(i + n) == find(i) || find(a[i] + n) == find(a[i]))
return cout << "No answer\n", 0;
int res = 1, mx = 0, mn = 0;
for (int i = 1; i <= n; i++) (find(i) == i) && (res = res * 2 % MD);
for (int i = 1; i <= n; i++) cnt[find(i)][0]++, cnt[find(i + n)][1]++;
// 记录相对正确/错误的点的个数
for (int i = 1; i <= n; i++)
if (find(i) == i)
mx += max(cnt[i][0], cnt[i][1]), // 如果根是正确的就选 cnt[i][0],反之亦然
mn += min(cnt[i][0], cnt[i][1]); // 那么取最值即可
cout << res << '\n' << mx << '\n' << mn << '\n';
return 0;
}
// 扩展域并查集