【UVA11082】Matrix Decompressing(有上下界的网络流)

时间:2022-08-01 19:47:07

题意:给出一个矩阵前i列所有元素的和,和前j行所有元素的和,求这个矩阵解压以后的原型。(答案不唯一)

n,m<=20,1<=a[i,j]<=20

思路:这道题把边上的流量作为原先矩阵中的点

把每一行,每一列都看成一个点

S——>i行 a[i]-m

i行——>j列 19

j列——>T b[i]-n

跑最大流,边(i,j+n)上的流量就是a[i,j]的值

为什么容量是a[i]-m,19,b[i]-n?

因为点权(边权)不能为0,所以要先把所有值+1,上限就-1,输出的时候+1即可

 var fan:array[..]of longint;
head,vet,next,len,gap,dis,a,b,c1,c2:array[..]of longint;
num:array[..,..]of longint;
n,m,i,j,tot,s,source,src,cas,v:longint; procedure add(a,b,c:longint);
begin
inc(tot);
next[tot]:=head[a];
vet[tot]:=b;
len[tot]:=c;
head[a]:=tot; inc(tot);
next[tot]:=head[b];
vet[tot]:=a;
len[tot]:=;
head[b]:=tot;
end; function min(x,y:longint):longint;
begin
if x<y then exit(x);
exit(y);
end; function dfs(u,aug:longint):longint;
var e,v,t,flow,val:longint;
begin
if u=src then exit(aug);
e:=head[u]; flow:=; val:=s-;
while e<> do
begin
v:=vet[e];
if len[e]> then
begin
if dis[u]=dis[v]+ then
begin
t:=dfs(v,min(len[e],aug-flow));
len[e]:=len[e]-t;
len[fan[e]]:=len[fan[e]]+t;
flow:=flow+t;
if dis[source]>=s then exit(flow);
if aug=flow then break;
end;
val:=min(val,dis[v]);
end;
e:=next[e];
end;
if flow= then
begin
dec(gap[dis[u]]);
if gap[dis[u]]= then dis[source]:=s;
dis[u]:=val+;
inc(gap[dis[u]]);
end;
exit(flow);
end; function maxflow:longint;
var ans:longint;
begin
fillchar(gap,sizeof(gap),);
fillchar(dis,sizeof(dis),);
gap[]:=s; ans:=;
while dis[source]<s do ans:=ans+dfs(source,maxlongint);
exit(ans);
end; begin
assign(input,'UVA11082.in'); reset(input);
assign(output,'UVA11082.out'); rewrite(output);
for i:= to do
if i mod = then fan[i]:=i+
else fan[i]:=i-;
readln(cas);
for v:= to cas do
begin
fillchar(head,sizeof(head),); tot:=;
fillchar(num,sizeof(num),);
fillchar(len,sizeof(len),);
readln(n,m);
for i:= to n do
begin
read(a[i]); c1[i]:=a[i]-a[i-];
end;
for i:= to m do
begin
read(b[i]); c2[i]:=b[i]-b[i-];
end;
s:=n+m+; source:=n+m+; src:=n+m+;
for i:= to n do add(source,i,c1[i]-m);
for i:= to m do add(i+n,src,c2[i]-n);
for i:= to n do
for j:= to m do
begin
num[i,j]:=tot+;
add(i,j+n,);
end;
maxflow;
writeln('Matrix ',v);
for i:= to n do
begin
for j:= to m- do write(len[num[i,j]]+,' ');
write(len[num[i,m]]+);
writeln;
end;
if v<>cas then writeln;
end; close(input);
close(output);
end.