问题描述
W公司有m个仓库和n个零售商店。第i个仓库有ai个单位的货物;第j个零售商店需要bj个单位的货物。货物供需平衡。从第i个仓库运送每单位货物到第j个零售商店的费用为c[i,j]。试设计一个将仓库中所有货物运送到零售商店的运输方案,使总运输费用最少。
编程任务
对于给定的 m 个仓库和 n 个零售商店间运送货物的费用,计算最优运输方案和最差运输方案。
数据输入
输入文件的第 1行有 2 个正整数 m和 n,分别表示仓库数和零售商店数。接下来的一行中有 m个正整数ai ,1≤i≤m,表示第 i个仓库有 ai个单位的货物。再接下来的一行中有 n个正整数bj,1≤j≤n,表示第 j 个零售商店需要bj个单位的货物。接下来的 m行,每行有 n个整数,表示从第 i 个仓库运送每单位货物到第 j 个零售商店的费用c[i,j] 。
结果输出
程序运行结束时,输出计算出的最少运输费用和最多运输费用。 输入文件示例input.txt
2 3
220 280
170 120 210
77 39 105
150 186 122
输出文件示例
output.txt
48500 69140
把所有仓库看做二分图中顶点Xi,所有零售商店看做二分图中顶点Yi,建立附加源S汇T。1、从S向每个Xi连一条容量为仓库中货物数量ai,费用为0的有向边。2、从每个Yi向T连一条容量为商店所需货物数量bi,费用为0的有向边。3、从每个Xi向每个Yj连接一条容量为无穷大,费用为cij的有向边。
这道题其实就是求一个网络中的最小费用最大流和最大费用最大流,最小费用最大流略过,最大费用最大流有2中方法:
1、把所有费用变成相反数做一遍最小费用最大流,输出答案的相反数;
2、初始化spfa时dis数组全从max改为-1,松弛的条件从 dis[i]>dis[j]+cap[i,j]改为dis[i]<dis[j]+cap[i,j];
此处我采用了第一种方法。
代码:
1 const 2 maxn=100000000; 3 4 var 5 ot,ot1,ne1,cap1,ne,cap,h:array[0..30000]of longint; 6 cost,cost1:array[0..30000,1..2]of longint; 7 g,g1,pre,dis:array[0..1010]of longint; 8 inq:array[0..1010]of boolean; 9 e,s,t,c,i,n,m,ans,j:longint;10 11 procedure addedge(x,y,z,w:longint);12 begin13 ot[e]:=y; ne[e]:=g[x]; cap[e]:=z; cost[e,1]:=w; cost[e,2]:=-w; g[x]:=e; inc(e);14 ot[e]:=x; ne[e]:=g[y]; cap[e]:=0; cost[e,1]:=-w; cost[e,2]:=w; g[y]:=e; inc(e);15 end;16 17 function min(a,b:longint):longint;18 begin19 if a-1 do35 begin36 y:=ot[p];37 if (cap[p]>0)and(dis[y]>dis[x]+cost[p,c])38 then begin39 dis[y]:=dis[x]+cost[p,c]; pre[y]:=p;40 if inq[y]=false41 then begin inq[y]:=true; inc(r); h[r]:=y; end;42 end;43 p:=ne[p];44 end;45 inq[x]:=false;46 end;47 exit(dis[t]<>maxn);48 end;49 50 function find_path(c:longint):longint;51 var52 x,p,tmp,path:longint;53 begin54 x:=t; path:=maxn; tmp:=0;55 while x>s do56 begin57 p:=pre[x];58 path:=min(path,cap[p]);59 x:=ot[p xor 1];60 end;61 x:=t;62 while x>s do63 begin64 p:=pre[x];65 inc(tmp,path*cost[p,c]);66 inc(cap[p xor 1],path);67 dec(cap[p],path);68 x:=ot[p xor 1];69 end;70 exit(tmp);71 end;72 73 begin74 e:=0;75 fillchar(g,sizeof(g),255);76 readln(n,m);77 s:=0; t:=n+m+1; ans:=0;78 for i:=1 to n do79 begin read(c); addedge(s,i,c,0); end;80 for i:=1 to m do81 begin read(c); addedge(n+i,t,c,0); end;82 for i:=1 to n do83 for j:=1 to m do84 begin85 read(c);86 addedge(i,n+j,maxn,c);87 end;88 g1:=g; ot1:=ot; cap1:=cap; ne1:=ne; cost1:=cost;89 while spfa(1) do90 inc(ans,find_path(1));91 writeln(ans);92 ans:=0;93 g:=g1; ot:=ot1; cap:=cap1; ne:=ne1; cost:=cost1;94 while spfa(2) do95 inc(ans,find_path(2));96 writeln(-ans);97 end.