【题解】CF662C Binary Table

题目传送门

\(\text{FWT}\) 好题。

分析

首先有一个 \(O(2^nm)\) 的暴力,就是枚举行被反转的状态,然后每一列取 \(0\) 的数量和 \(1\) 的数量的较小值再相加。形式化的,我们记 \(g_i = \min(\text{popcnt}(i), \text{popcnt}(i \oplus (2^n - 1)))\),那么此时的结果就是 \[ \min_S \left\{ \sum_{i = 1}^m g_{f_i \oplus S} \right\} \] 其中 \(f_i\) 表示当前列状态压缩的结果,但是这很显然不是 \(\text{FWT}\) 的形式,所以我们要变化一下,考虑有很多 \(f_i\) 会重复,所以考虑开桶,记 \(h_i = \sum_{j = 1}^m [f_j = i]\),这样我们的式子就变为了 \[ \min_S \left\{ \sum_{i = 0}^{2^n - 1} g_{i \oplus S} \cdot h_i \right\} \] 因为始终有 \((i \oplus S) \oplus i = S\),所以上面的式子可以改写为 \[ \min_S \left\{ \sum_{i \oplus j = S} g_i \cdot h_j \right\} \] 这样就是一个 \(\text{FWT}\) 的形式了,直接计算即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <bits/stdc++.h>
#define L(i, j, k) for(int i = (j); i <= (k); i++)
#define R(i, j, k) for(int i = (j); i >= (k); i--)
#define G(i, u) for (int i = h[(u)]; ~i; i = ne[i])
#define int long long
#define ld long double
#define ull unsigned long long

using namespace std;
const int N = 21, M = 1e5 + 10;
int a[N][M], f[1 << N], g[1 << N];

inline int read() {
int x = 0, y = 1; char c = getchar();
while (c < '0' || c > '9') {if (c == '-') y = -1; c = getchar();}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * y;
}

inline int popcnt(int x) {
int res = 0;
while (x) x -= x & -x, res++;
return res;
}

inline void fwtXOR(int a[], int n, int flg) {
for (int o = 2, k = 1; o <= n; o <<= 1, k <<= 1)
for (int i = 0; i < n; i += o)
L(j, 0, k - 1) {
int x = a[i + j], y = a[i + j + k];
a[i + j] = (x + y) / flg;
a[i + j + k] = (x - y) / flg;
}
}

signed main() {
int n = read(), m = read(), lim = 1 << n;
L(i, 1, n) L(j, 1, m) {
char c; cin >> c;
a[i][j] = c - '0';
}
L(i, 1, m) {
int s = 0;
L(j, 1, n) s |= (1 << (j - 1)) * a[j][i];
f[s]++;
}
L(i, 0, lim - 1) g[i] = min(popcnt(i), popcnt(i ^ (lim - 1)));
fwtXOR(f, lim, 1), fwtXOR(g, lim, 1);
L(i, 0, lim - 1) f[i] *= g[i];
fwtXOR(f, lim, 2);
int res = 1ll << 60;
L(i, 0, lim - 1) res = min(res, f[i]);
printf("%lld\n", res);
return 0;
}