BZOJ 2039 employ人员雇佣

Posted on 2017-02-09 14:48  ziliuziliu  阅读(183)  评论(0编辑  收藏  举报

最小割。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define maxv 2050
#define maxe 3005000
#define inf 0x7f7f7f7f7f7f7f7fLL
using namespace std;
long long n,E[maxv][maxv],g[maxv],nume=1,dis[maxv],tot[maxv],a[maxv],s,t,sum=0,max_flow=0;
struct edge
{
    long long v,f,nxt;
}e[maxe];
queue <long long> q;
void addedge(long long u,long long v,long long f)
{
    e[++nume].v=v;e[nume].f=f;
    e[nume].nxt=g[u];g[u]=nume;
    e[++nume].v=u;e[nume].f=0;
    e[nume].nxt=g[v];g[v]=nume;
}
void build()
{
    for (long long i=1;i<=n;i++) addedge(s,i,tot[i]);
    for (long long i=1;i<=n;i++)
        for (long long j=1;j<=n;j++)
            addedge(j+n,i,2*E[i][j]);
    for (long long i=1;i<=n;i++) addedge(i+n,t,a[i]),addedge(i,i+n,inf);
}
bool bfs()
{
    for (long long i=s;i<=t;i++) dis[i]=inf;
    dis[s]=0;q.push(s);
    while (!q.empty())
    {
        long long head=q.front();q.pop();
        for (long long i=g[head];i;i=e[i].nxt)
        {
            long long v=e[i].v;
            if ((e[i].f) && (dis[v]>dis[head]+1))
            {
                dis[v]=dis[head]+1;
                q.push(v);
            }
        }
    }
    return dis[t]!=inf;
}
long long dinic(long long x,long long low)
{
    if (x==t) return low;
    long long ret=0;
    for (long long i=g[x];low && i;i=e[i].nxt)
    {
        long long v=e[i].v;
        if ((e[i].f) && (dis[v]==dis[x]+1))
        {
            long long dd=dinic(v,min(low,e[i].f));
            ret+=dd;low-=dd;
            e[i].f-=dd;e[i^1].f+=dd;
        }
    }
    if (!ret) dis[x]=inf;
    return ret;
}
int main()
{
    scanf("%lld",&n);s=0;t=2*n+1;
    for (long long i=1;i<=n;i++) scanf("%lld",&a[i]);
    for (long long i=1;i<=n;i++)
        for (long long j=1;j<=n;j++)
        {
            scanf("%lld",&E[i][j]);
            tot[i]+=E[i][j];sum+=E[i][j];
        }
    build();
    while (bfs())
        max_flow+=dinic(s,inf);
    printf("%lld\n",sum-max_flow);
    return 0;
}