题解:CF321D Ciel and Flipboard

· · 题解

设格子 (i, j) 反转次数的奇偶性为 b_{i, j}。

考虑以下三个格子 (i, j), (i, x), (i, j + x)(其中 j < x),一次操作要么会翻转 (i, j), (i, x),要么翻转 (i, x), (i, j + x),要么都不翻转。

所以可以得到:b_{i, j} \oplus b_{i, x} \oplus b_{i, j + x} = 0, j < x。

同理,我们有 b_{i, j} \oplus b_{x, j} \oplus b_{i + x, j} = 0, i < x。

所以有:

b_{i, x} = b_{i, j} \oplus b_{i, j + x}, j < x b_{x, j} = b_{i, j} \oplus b_{i + x, j}, i < x

然后考虑找出固定什么格子可以确定所有格子。

试着只固定中间行:b_{x, 1}, b_{x, 2}, \dots, b_{x, x}。此时我们可以推出 b_{x, x + 1}, b_{x, x + 2}, \dots, b_{x, n}。

然后对于每个 i < x,先枚举 t = b_{i, x},然后对于 j < x,令 u = b_{i, j},可以得出:

b_{i, j} = u; b_{i, j + x} = u \oplus t b_{i + x, j} = u \oplus b_{x, j} b_{i + x, j + x} = u \oplus t \oplus b_{x, j} \oplus b_{x, x}

然后就做完了,时间复杂度 O(2^x x^2)。

#include <bits/stdc++.h>
using namespace std;

const int N = 33, X = 17;
const int inf = 0x3f3f3f3f;

int n, x;
int a[N + 10][N + 10];

int val(int i, int j, int c) {
    if (!c) return a[i][j];
    return -a[i][j];
}

int main() {
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);

    cin >> n; x = (n + 1) / 2;
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
            cin >> a[i][j];
        }
    }

    int ans = -inf;
    for (int s = 0; s < 1 << x; ++s) {
        int tot = 0;

        array<int, X + 1> b;
        for (int i = 1; i <= x; ++i) {
            if ((s >> (i - 1)) & 1) b[i] = 1;
            else b[i] = 0;
            tot += val(x, i, b[i]);
        }
        for (int i = 1; i < x; ++i) {
            tot += val(x, i + x, b[x] ^ b[i]);
        }

        for (int i = 1; i < x; ++i) {
            int sum = -inf;

            for (int t = 0; t <= 1; ++t) {
                int s = 0;

                for (int j = 1; j < x; ++j) {
                    int mx = -inf;

                    for (int u = 0; u <= 1; ++u) {
                        mx = max(mx, val(i, j, u)
                        + val(i, j + x, u ^ t)
                        + val(i + x, j, u ^ b[j])
                        + val(i + x, j + x, u ^ t ^ b[j] ^ b[x]));
                    }

                    s += mx;
                }

                sum = max(sum, s + val(i, x, t) + val(i + x, x, t ^ b[x]));
            }

            tot += sum;
        }

        ans = max(ans, tot);
    }

    cout << ans;

    return 0;
}