luogu P4014 分配问题 |费用流

题目描述

有 nnn 件工作要分配给 nnn 个人做。第 iii 个人做第 jjj 件工作产生的效益为 cijc_{ij}cij​ 。试设计一个将 nnn 件工作分配给 nnn 个人做的分配方案,使产生的总效益最大。

输入格式

文件的第 111 行有 111 个正整数 nnn,表示有 nnn 件工作要分配给 nnn 个人做。

接下来的 nnn 行中,每行有 nnn 个整数 cijc_{ij}cij​​​,表示第 iii 个人做第 jjj 件工作产生的效益为 cijc_{ij}cij​。

输出格式

两行分别输出最小总效益和最大总效益。


按照套路建图

#include<cmath>
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
inline int read(){
    int f=1,c=0;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){c=10*c+ch-'0';ch=getchar();}
    return f*c;
}
const int N=1e4+10,M=2e5+10,inf=0x3f3f3f3f;
int n,m,s,t;
int nxt[M],head[N],go[M],edge[M],cost[M],cur[N],tot=1;
inline void add(int u,int v,int o1,int o2){
    nxt[++tot]=head[u],head[u]=tot,go[tot]=v,edge[tot]=o1,cost[tot]=o2;
    nxt[++tot]=head[v],head[v]=tot,go[tot]=u,edge[tot]=0,cost[tot]=-o2;    
}
int dis[N],ret;
bool vis[N];
inline bool spfa(){
    memset(dis,0x3f,sizeof(dis)); 
    queue<int>q; q.push(s),dis[s]=0,vis[s]=1;
    while(q.size()){
        int u=q.front(); q.pop(); vis[u]=0;
        for(int i=head[u];i;i=nxt[i]){
            int v=go[i];
            if(edge[i]&&dis[v]>dis[u]+cost[i]){
                dis[v]=dis[u]+cost[i];
                if(!vis[v])q.push(v),vis[v]=1;
            }
        }
    }
    return dis[t]!=inf;
}
int dinic(int u,int flow){
    if(u==t)return flow;
    vis[u]=1;
    int rest=flow,k;
    for(int i=head[u];i&&rest;i=nxt[i]){
        int v=go[i];
        if(!vis[v]&&edge[i]&&dis[v]==dis[u]+cost[i]){
            k=dinic(v,min(edge[i],rest));
            if(k)ret+=k*cost[i],edge[i]-=k,edge[i^1]+=k,rest-=k;
            else dis[v]=-1;
        }
    }
    vis[u]=0;
    return flow-rest;
}
int c[105][105];
signed main(){
    scanf("%d",&n); t=n*n+1;
    for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)
    add(i,j+n,1,(c[i][j]=read()));
    for(int i=1;i<=n;i++)add(s,i,1,0),add(i+n,t,1,0);
    int flow=0,maxflow=0;
    while(spfa())
    while(flow=dinic(s,inf))maxflow+=flow;
    cout<<ret<<endl;
    
    memset(head,0,sizeof(head)); ret=0;
    memset(nxt,0,sizeof(nxt)); tot=1;
    
    
    for(int i=1;i<=n;i++)for(int j=1;j<=n;j++)
    add(i,j+n,1,-c[i][j]);  
    for(int i=1;i<=n;i++)add(s,i,1,0),add(i+n,t,1,0);
    while(spfa())
    while(flow=dinic(s,inf))maxflow+=flow;
    cout<<-ret<<endl;
}
原文地址:https://www.cnblogs.com/naruto-mzx/p/12204925.html