739. [网络流24题] 运输问题

739. [网络流24题] 运输问题

★★   输入文件:tran.in   输出文件:tran.out   简单对比
时间限制:1 s   内存限制:128 MB

«问题描述:

«编程任务:
对于给定的m 个仓库和n 个零售商店间运送货物的费用,计算最优运输方案和最差运
输方案。
«数据输入:

«结果输出:
程序运行结束时,将计算出的最少运输费用和最多运输费用输出到文件tran.out中。
输入文件示例 输出文件示例
tran.in
2 3
220 280
170 120 210
77 39 105

150 186 122

tran.out

48500

69140

对于所有数据:1<=N,M<=100

题解:
比较容易想到费用流。
建图:
1>建立虚拟源S和汇T。
2>从S到m个仓库建流量为a[i],费用为0的边。
3>从n个商店向T建流量为b[i],费用为0的边。
4>从m个仓库向n个商店建流量为无穷大,费用为c[i][j]的边。
然后跑一边最小费用,再跑一边最大费用就好了。

AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#define m(s,t) memset(s,t,sizeof s)
#define R register
#define inf 2139062143
using namespace std;
int read(){
    R int x=0;bool f=1;
    R char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=0;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-'0';ch=getchar();}
    return f?x:-x;
}
const int N=310;
struct node{
    int v,next,cap,cost;
}e[N*N];int tot=1;
int n,m,S,T,ans,head[N],pree[N],prev[N],flow[N],dis[N],q[N*10];
int a[N],b[N],c[N][N];
bool vis[N];
void add(int x,int y,int a,int b){
    e[++tot].v=y;e[tot].cap=a;e[tot].cost=b;e[tot].next=head[x];head[x]=tot;
}
void ins(int x,int y,int a,int b){
    add(x,y,a,b);add(y,x,0,-b);
}
void build(){
    S=0,T=m+n+1;
    for(int i=1;i<=m;i++) ins(S,i,a[i],0);
    for(int i=1;i<=n;i++) ins(i+m,T,b[i],0);
    for(int i=1;i<=m;i++){
        for(int j=1;j<=n;j++){
            ins(i,j+m,inf,c[i][j]);
        }
    }
}
void Cl(){
    tot=1;ans=0;
    m(head,0);m(pree,0);m(prev,0);m(flow,0);
}
bool spfa(int k){
    m(vis,0);k>0?m(dis,127):m(dis,128);
    int h=0,t=1;
    q[t]=S;dis[S]=0;vis[S]=1;flow[S]=inf;
    while(h!=t){
        int x=q[++h];
        vis[x]=0;
        for(int i=head[x];i;i=e[i].next){
            int v=e[i].v,cap=e[i].cap,cost=e[i].cost;
            if(cap>0&&((k>0&&dis[v]>dis[x]+cost)||(k<0&&dis[v]<dis[x]+cost))){
                dis[v]=dis[x]+cost;
                prev[v]=x;pree[v]=i;
                flow[v]=min(flow[x],cap);
                if(!vis[v]){
                    vis[v]=1;
                    q[++t]=v;
                }
            }
        }
    }
    if(k>0) return dis[T]<inf;
    else return dis[T]>0;
}
void work(){
    for(int i=T;i!=S;i=prev[i]){
        e[pree[i]].cap-=flow[T];
        e[pree[i]^1].cap+=flow[T];
    }
    ans+=flow[T]*dis[T];
}
int main(){
    freopen("tran.in","r",stdin);
    freopen("tran.out","w",stdout);
    m=read();n=read();
    for(int i=1;i<=m;i++) a[i]=read();
    for(int i=1;i<=n;i++) b[i]=read();
    for(int i=1;i<=m;i++){
        for(int j=1;j<=n;j++){
            c[i][j]=read();
        }
    }
    build();
    while(spfa(1)) work();
    printf("%d
",ans);
    Cl();build();
    while(spfa(-1)) work();
    printf("%d
",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/shenben/p/6220688.html