P6691 选择题 题解

· · 题解

扩展域并查集辣么阔爱,为啥不用捏?

觉得其它的并查集的题解质量都不是很好。

Solution

考虑使用扩展域并查集。

对于选项 i,将 i 的分为两种点:i 与 i + n,表示选项 i 是相对正确或错误的。那么,对于每一个输入,若 op = 1,那么我们就将 i 与 a_i、i + n 与 a_i + n 分别合并(应为要么就两个都对,要么两个都错)。若 op = 0,那么将 i 与 a_i + n、i + n 与 a_i 合并(一对一错嘛!)。那么如果发现 i 与 i + n 在同一个连通块了(既正确又错误肯定无解嘛!)就无解了。

再想想怎么处理答案,我们发现,如果一个连通块内的点确定了,那么这一整个连通块就确定了,所以设 tot 为连通块个数,方案数是 2^{tot}。然后正确选项最多和最少的答案需要我们使用一个 cnt 数组记录,cnt_{i, 0/1} 表示以 i 为根的连通块内有多少个相对正确或错误的点,那么正确选项最多与最少就去一个最值再求和即可。

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;
}
// 扩展域并查集