其他分享
首页 > 其他分享> > UVA11383 Golden Tiger Claw 少林决胜

UVA11383 Golden Tiger Claw 少林决胜

作者:互联网

传送


题面:给定一个\(n\times n\)的矩阵, 每个格子里都有一个正整数\(w(i,j)\)。你的任务是给每行确定一个整数\(row(i)\), 每列也确定一个整数\(col(i)\), 使得对于任意格子\((i,j)\),有\(row(i)+col(j) \geqslant w(i,j)\)。求所有\(row(i)\)和\(col(i)\)的和的最小值。


这题如果不知道KM算法岂不是gg,因为他就是KM的一个副产品。
KM算法就是在满足所有的左右顶标\(lx[i]+ly[j]\geqslant w(i,j)\)的前提下,让\(lx[i],ly[j]\)尽量小。算法结束的时候,所有顶标之和也就是最小的了。
这个刚好就时这道题所要求的的东西。

#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<queue>
#include<assert.h>
#include<ctime>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define In inline
#define forE(i, x, y) for(int i = head[x], y; ~i && (y = e[i].to); i = e[i].nxt)
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 505;
In ll read()
{
	ll ans = 0;
	char ch = getchar(), las = ' ';
	while(!isdigit(ch)) las = ch, ch = getchar();
	while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
	if(las == '-') ans = -ans;
	return ans;
}
In void write(ll x)
{
	if(x < 0) x = -x, putchar('-');
	if(x >= 10) write(x / 10);
	putchar(x % 10 + '0');
}

int n, a[maxn][maxn];

int lft[maxn];
bool vx[maxn], vy[maxn];
int lx[maxn], ly[maxn];
In bool dfs(int now)
{
	vx[now] = 1;
	for(int i = 1; i <= n; ++i)
		if(!vy[i] && lx[now] +ly[i] == a[now][i])
		{
			vy[i] = 1;
			if(!lft[i] || dfs(lft[i])) {lft[i] = now; return 1;}
		}
	return 0;
}

In void KM()
{
	Mem(lx, 0), Mem(ly, 0), Mem(lft, 0);
	for(int i = 1; i <= n; ++i)
		for(int j = 1; j <= n; ++j) lx[i] = max(lx[i], a[i][j]);
	for(int i = 1; i <= n; ++i)
		while(1)
		{
			Mem(vx, 0), Mem(vy, 0);
			if(dfs(i)) break;
			int d = INF;
			for(int j = 1; j <= n; ++j) if(vx[j])
				for(int k = 1; k <= n; ++k) if(!vy[k])
					d = min(d, lx[j] +ly[k] - a[j][k]);
			for(int j = 1; j <= n; ++j)
			{
				if(vx[j]) lx[j] -= d;
				if(vy[j]) ly[j] += d;
			}
		}
}

int main()
{
	while(scanf("%d", &n) != EOF)
	{
		for(int i = 1; i <= n; ++i)
			for(int j = 1; j <= n; ++j) a[i][j] = read();
		KM();
		ll sum = 0;
		for(int i = 1; i <= n; ++i) sum += lx[i], write(lx[i]), space; enter;
		for(int i = 1; i <= n; ++i) sum += ly[i], write(ly[i]), space; enter;
		write(sum), enter;
	}
	return 0;
}

标签:Golden,ch,int,UVA11383,Tiger,maxn,include,lx,define
来源: https://blog.51cto.com/u_15234622/2831622