您的位置:首页 > 理论基础 > 计算机网络

网络流24题 -No.17 运输问题

2015-06-11 18:34 543 查看
[b]问题描述 [/b]
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];

此处我采用了第一种方法。

代码:

const
maxn=100000000;

var
ot,ot1,ne1,cap1,ne,cap,h:array[0..30000]of longint;
cost,cost1:array[0..30000,1..2]of longint;
g,g1,pre,dis:array[0..1010]of longint;
inq:array[0..1010]of boolean;
e,s,t,c,i,n,m,ans,j:longint;

procedure addedge(x,y,z,w:longint);
begin
ot[e]:=y; ne[e]:=g[x]; cap[e]:=z; cost[e,1]:=w; cost[e,2]:=-w; g[x]:=e; inc(e);
ot[e]:=x; ne[e]:=g[y]; cap[e]:=0; cost[e,1]:=-w; cost[e,2]:=w; g[y]:=e; inc(e);
end;

function min(a,b:longint):longint;
begin
if a<b then exit(a) else exit(b);
end;

function spfa(c:longint):boolean;
var
x,y,l,r,p:longint;
begin
for i:=s to t do
begin dis[i]:=maxn; inq[i]:=false; end;
l:=0; r:=1; dis[s]:=0; inq[s]:=true; h[1]:=s; pre[s]:=-1;
while l<r do
begin
inc(l);
x:=h[l];
p:=g[x];
while p>-1 do
begin
y:=ot[p];
if (cap[p]>0)and(dis[y]>dis[x]+cost[p,c])
then begin
dis[y]:=dis[x]+cost[p,c]; pre[y]:=p;
if inq[y]=false
then begin inq[y]:=true; inc(r); h[r]:=y; end;
end;
p:=ne[p];
end;
inq[x]:=false;
end;
exit(dis[t]<>maxn);
end;

function find_path(c:longint):longint;
var
x,p,tmp,path:longint;
begin
x:=t; path:=maxn; tmp:=0;
while x>s do
begin
p:=pre[x];
path:=min(path,cap[p]);
x:=ot[p xor 1];
end;
x:=t;
while x>s do
begin
p:=pre[x];
inc(tmp,path*cost[p,c]);
inc(cap[p xor 1],path);
dec(cap[p],path);
x:=ot[p xor 1];
end;
exit(tmp);
end;

begin
e:=0;
fillchar(g,sizeof(g),255);
readln(n,m);
s:=0; t:=n+m+1; ans:=0;
for i:=1 to n do
begin read(c); addedge(s,i,c,0); end;
for i:=1 to m do
begin read(c); addedge(n+i,t,c,0); end;
for i:=1 to n do
for j:=1 to m do
begin
read(c);
addedge(i,n+j,maxn,c);
end;
g1:=g; ot1:=ot; cap1:=cap; ne1:=ne; cost1:=cost;
while spfa(1) do
inc(ans,find_path(1));
writeln(ans);
ans:=0;
g:=g1; ot:=ot1; cap:=cap1; ne:=ne1; cost:=cost1;
while spfa(2) do
inc(ans,find_path(2));
writeln(-ans);
end.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: