luogu P4015 运输问题 |费用流

题目描述

\(W\) 公司有 \(m\) 个仓库和 \(n\) 个零售商店。第 \(i\) 个仓库有 \(a_i\) 个单位的货物;第 \(j\) 个零售商店需要 \(b_j\)​ 个单位的货物。

货物供需平衡,即 \(\sum\limits_{i=1}^{m}a_i=\sum\limits_{j=1}^{n}b_i\)

从第 \(i\) 个仓库运送每单位货物到第 \(j\) 个零售商店的费用为 \(c_{ij}\)​​​ 。

试设计一个将仓库中所有货物运送到零售商店的运输方案,使总运输费用最少。

输入格式

第 1 行有 2 个正整数 \(m\)\(n\),分别表示仓库数和零售商店数。

接下来的一行中有 \(m\) 个正整数 \(a_i\)​,表示第 \(i\) 个仓库有 \(a_i\)​个单位的货物。

再接下来的一行中有 \(n\) 个正整数 \(b_j\)​,表示第 \(j\) 个零售商店需要 \(b_j\)​ 个单位的货物。

接下来的 \(m\) 行,每行有 \(n\) 个整数,表示从第 \(i\) 个仓库运送每单位货物到第 \(j\) 个零售商店的费用 \(c_{ij}\)​。

输出格式

两行分别输出最小运输费用和最大运输费用。

说明/提示

\(1\leq n, m \leq 100\)

扫描二维码关注公众号,回复: 8663663 查看本文章

#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 a[N],b[N],c[105][105];
signed main(){
    cin>>n>>m; t=m+n+2;
    for(int i=1;i<=n;i++)add(s,i,a[i]=read(),0);
    for(int i=1;i<=m;i++)add(i+n,t,b[i]=read(),0);
    for(int i=1;i<=n;i++)
    for(int j=1;j<=m;j++)add(i,j+n,inf,c[i][j]=read());
    
    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++)add(s,i,a[i],0);
    for(int i=1;i<=m;i++)add(i+n,t,b[i],0);   
    for(int i=1;i<=n;i++)
    for(int j=1;j<=m;j++)add(i,j+n,inf,-c[i][j]);
    flow=0,maxflow=0;
    while(spfa())
    while(flow=dinic(s,inf))maxflow+=flow;
    cout<<-ret<<endl;
}

猜你喜欢

转载自www.cnblogs.com/naruto-mzx/p/12205561.html