Luogu_4014 分配问题

传送门
https://www.luogu.org/problemnew/show/P4014

题解
km算法(费用流算法)裸题。
最小总效益把边权取负即可。

#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 0x7f7f7f7f
using namespace std;
const int maxn=100;
int n,Time;
int c[maxn+8][maxn+8];
int dx[maxn+8],dy[maxn+8],vis_x[maxn+8],vis_y[maxn+8],match[maxn+8];

int read()
{
    int x=0,f=1;char ch=getchar();
    for (;ch<'0'||ch>'9';ch=getchar()) if (ch=='-') f=-1;
    for (;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0';
    return x*f;
}

bool extra(int x)
{
    vis_x[x]=Time;
    for (int i=1;i<=n;i++)
	{
	    if (vis_y[i]==Time) continue;
	    if (dy[i]+dx[x]!=c[x][i]) continue;
	    vis_y[i]=Time;
	    if ((!match[i])||(extra(match[i])))
		{
		    match[i]=x;
		    return 1;
		}
	}
    return 0;
}

void km(int t)
{
    memset(dx,128,sizeof(dx));
    memset(dy,0,sizeof(dy));
    memset(match,0,sizeof(match));
    for (int i=1;i<=n;i++)
	for (int j=1;j<=n;j++)
	    dx[i]=max(dx[i],c[i][j]);
    for (int i=1;i<=n;i++)
	{
	    while(1)
		{
		    Time++;
		    if (extra(i)) break;
		    int d=inf;
		    for (int i=1;i<=n;i++)
			if (vis_x[i]==Time)
			for (int j=1;j<=n;j++)
			    if (vis_y[j]!=Time)
				d=min(d,dx[i]+dy[j]-c[i][j]);
		    for (int i=1;i<=n;i++)
			{
			    if (vis_x[i]==Time) dx[i]-=d;
			    if (vis_y[i]==Time) dy[i]+=d;
			}
		}
	}
    int ans=0;
    for (int i=1;i<=n;i++) ans+=c[match[i]][i];
    printf("%d\n",ans*t);
}

int main()
{
    n=read();
    for (int i=1;i<=n;i++)
	for (int j=1;j<=n;j++)
	    c[i][j]=read()*-1;
    km(-1);
    for (int i=1;i<=n;i++)
	for (int j=1;j<=n;j++)
	    c[i][j]*=-1;
    km(1);
    return 0;
}
posted @ 2019-01-05 16:26  Alseo_Roplyer  阅读(119)  评论(0编辑  收藏  举报