思路
设最终对第 行的总异或值为 ,对第 列的总异或值为 ,则 。
考虑先固定 ,则 ,。
接着检查是否对于所有的 都成立,若不成立则输出 。
假设我们最后某一个位置选择的值为 ,而上限为 ,记花费为 。
于是我们构造 个形如 的二元组,其中 为 或 , 为对应的上限,我们的目标是找出一个非负整数 ,使得 最小,即使 最小,即使 最大。
对于所有大于 的最高位的位 ,则 的第 位必须等于 的第 位,若无法满足则输出 。
对于剩下没有固定的位,我们构建一个 01-Trie。
对于 ,从高位到低位去比较。设 为 的该位, 为 的该位。
- 若到达了叶子,直接令权值 并返回。
- 若 ,选择 的该位为 则后面所有的位可以任意选,直接令整个子树的权值 。选择 的该位为 则继续递归。
- 若 ,只能选择 的该位为 并继续递归。
对于 ,直接递归到叶子并令权值 即可。
最后我们维护一个最大值即可,细节详见代码。
时间复杂度:。
代码
// 思路参考deepseek
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
#define clz __builtin_clz
int read() {
int x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=x*10+ch-48;ch=getchar();}
return x*f;
}
const int N = 5e4 + 10,W = 30;
int T;
int n,m;
struct Trie {
int son[2];
int val;
int mx;
#define son(i) trie[i].son
#define val(i) trie[i].val
#define mx(i) trie[i].mx
} trie[2 * W * N];
int cnt = 1;
void pushup(int p) {
mx(p) = max(mx(son(p)[0]),mx(son(p)[1])) + val(p);
}
int lim[W];
void add1(int p,int w,int r,int x) {
if (w == -1) {
val(p)++;
mx(p)++;
return;
}
int a = r >> w & 1,b = x >> w & 1;
if (a == 0) {
if (lim[w] != (b ^ 1)) {
if (son(p)[b] == 0) {
son(p)[b] = ++cnt;
}
add1(son(p)[b],w - 1,r,x);
}
}
else {
if (lim[w] != (b ^ 1)) {
if (son(p)[b] == 0) {
son(p)[b] = ++cnt;
}
val(son(p)[b])++;
mx(son(p)[b])++;
}
if (lim[w] != b) {
if (son(p)[b ^ 1] == 0) {
son(p)[b ^ 1] = ++cnt;
}
add1(son(p)[b ^ 1],w - 1,r,x);
}
}
pushup(p);
}
void add2(int p,int w,int x) {
if (w == -1) {
val(p)++;
mx(p)++;
return;
}
int a = x >> w & 1;
if (son(p)[a] == 0) {
son(p)[a] = ++cnt;
}
add2(son(p)[a],w - 1,x);
pushup(p);
}
int solve() {
n = read(),m = read();
vector<int> r(n),c(m),x(n),y(m);
vector<vector<int>> a(n,vector<int>(m));
for (int i = 0; i < n; i++) {
r[i] = read();
}
for (int j = 0; j < m; j++) {
c[j] = read();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = read();
}
}
x[0] = 0;
for (int j = 0; j < m; j++) {
y[j] = x[0] ^ a[0][j];
}
for (int i = 1; i < n; i++) {
x[i] = y[0] ^ a[i][0];
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if ((x[i] ^ y[j]) != a[i][j]) {
return -1;
}
}
}
memset(lim,-1,sizeof(lim));
for (int i = 0; i < n; i++) {
for (int w = (r[i] == 0 ? 0 : 32 - clz(r[i])); w < 30; w++) {
if (lim[w] == -1) {
lim[w] = x[i] >> w & 1;
}
else if (lim[w] != (x[i] >> w & 1)) {
return -1;
}
}
}
for (int j = 0; j < m; j++) {
for (int w = (c[j] == 0 ? 0 : 32 - clz(c[j])); w < 30; w++) {
if (lim[w] == -1) {
lim[w] = y[j] >> w & 1;
}
else if (lim[w] != (y[j] >> w & 1)) {
return -1;
}
}
}
son(1)[0] = son(1)[1] = 0;
val(1) = mx(1) = 0;
for (int i = 0; i < n; i++) {
add1(1,29,r[i],x[i]);
add2(1,29,x[i]);
}
for (int j = 0; j < m; j++) {
add1(1,29,c[j],y[j]);
add2(1,29,y[j]);
}
return 2 * (n + m) - mx(1);
return 0;
}
int main() {
T = read();
while (T--) {
cout << solve() << "\n";
}
return 0;
}