类似最大乘积生成树那样做,只不过是把求生成树改成了求完美匹配。
/* Telekinetic Forest Guard */
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 75, inf = 0x3f3f3f3f;
struct po {
int x, y;
bool operator == (const po &a) const {
return x == a.x && y == a.y;
}
};
int n, A[maxn][maxn], B[maxn][maxn], g[maxn][maxn];
inline int iread() {
int f = 1, x = 0; char ch = getchar();
for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
return f * x;
}
int lx[maxn], ly[maxn], from[maxn], slack[maxn], visx[maxn], visy[maxn], clo;
inline bool hungary(int x) {
visx[x] = clo;
for(int i = 1; i <= n; i++) if(visy[i] != clo) {
int t = lx[x] + ly[i] - g[x][i];
if(!t) {
visy[i] = clo;
if(from[i] == -1 || hungary(from[i])) {
from[i] = x;
return 1;
}
} else slack[i] = min(slack[i], t);
}
return 0;
}
inline po KM() {
for(int i = 1; i <= n; i++) ly[i] = 0, from[i] = -1;
for(int i = 1; i <= n; i++) {
lx[i] = -inf;
for(int j = 1; j <= n; j++) lx[i] = max(lx[i], g[i][j]);
}
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) slack[j] = inf;
while(1) {
clo++;
if(hungary(i)) break;
int d = inf;
for(int j = 1; j <= n; j++) if(visy[j] != clo) d = min(d, slack[j]);
for(int j = 1; j <= n; j++) if(visx[j] == clo) lx[j] -= d;
for(int j = 1; j <= n; j++)
if(visy[j] == clo) ly[j] += d;
else slack[j] -= d;
}
}
po res = (po){0, 0};
for(int i = 1; i <= n; i++)
res.x += A[from[i]][i], res.y += B[from[i]][i];
return res;
}
inline int solve(po a, po b) {
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) g[i][j] = (a.x - b.x) * B[i][j] - (a.y - b.y) * A[i][j];
po mid = KM();
if(a == mid || b == mid) return min(a.x * a.y, b.x * b.y);
return min(solve(a, mid), solve(mid, b));
}
int main() {
for(int T = iread(); T; T--) {
n = iread();
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) A[i][j] = iread();
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) B[i][j] = iread();
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) g[i][j] = -A[i][j];
po a = KM();
for(int i = 1; i <= n; i++) for(int j = 1; j <= n; j++) g[i][j] = -B[i][j];
po b = KM();
printf("%d\n", solve(a, b));
}
return 0;
}