【BZOJ3571】[Hnoi2014]画框【最小乘积匹配】

【题目链接】

类似最大乘积生成树那样做,只不过是把求生成树改成了求完美匹配。

【chenyushuo的题解】

/* 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;
}
五月病越来越严重了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值