【Tyvj1982】武器分配(费用流)

时间:2023-03-09 13:15:49
【Tyvj1982】武器分配(费用流)

题意:有N个人要从A个物品中各取一个,B个物品中各取一个,选取第i个A类物品和第j个B类物品的费用是(a[i]-b[j])^2

求最小总花费

n<=a,b<=80 a[i],b[i]<=10000

思路:第一题费用流

由源点到每个A类物品连容量为1,费用为0的边

每个B类物品到第一个汇点连容量为1,费用为0的边

对于ai和bj连容量为1,费用为(a[i]-b[j])^2的边

因为只需要N对物品,由第一个汇点到第二个汇点连容量为N,费用为0的边来限制流量上限

答案就是从源点到第二个汇点流量为N的最小费用

跑SPFA费用流即可

PS:其实这道根据排序不等式是个DP,排序后做即可 但是谁叫你数据太小呢

 var q:array[..]of longint;
head,vet,next,len1,len2,dis,fan:array[..]of longint;
pre:array[..,..]of longint;
c,d:array[..]of longint;
inq:array[..]of boolean;
n,m,i,source,src,tot,ans,a,b,j:longint; procedure add(a,b,c,d:longint);
begin
inc(tot);
next[tot]:=head[a];
vet[tot]:=b;
len1[tot]:=c;
len2[tot]:=d;
head[a]:=tot;
inc(tot);
next[tot]:=head[b];
vet[tot]:=a;
len1[tot]:=;
len2[tot]:=-d;
head[b]:=tot;
end; function min(x,y:longint):longint;
begin
if x<y then exit(x);
exit(y);
end; function spfa:boolean;
var t,u,e,v,i,w:longint;
begin
for i:= to do
begin
dis[i]:=maxlongint div ;
inq[i]:=false;
end;
t:=-; w:=; q[]:=source; inq[source]:=true; dis[source]:=;
while t<w do
begin
inc(t); u:=q[t mod ];
inq[u]:=false;
e:=head[u];
while e<> do
begin
v:=vet[e];
if (len1[e]>)and(dis[u]+len2[e]<dis[v]) then
begin
pre[v,]:=u;
pre[v,]:=e;
dis[v]:=dis[u]+len2[e];
if not inq[v] then
begin
inc(w); q[w mod ]:=v;
inq[v]:=true;
end;
end;
e:=next[e];
end;
end;
if dis[src]=maxlongint div then exit(false)
else exit(true);
end; procedure mcf;
var k,t,e:longint;
begin
k:=src; t:=maxlongint;
while k<>source do
begin
t:=min(t,len1[pre[k,]]);
k:=pre[k,];
end;
k:=src;
while k<>source do
begin
e:=pre[k,];
len1[e]:=len1[e]-t;
len1[fan[e]]:=len1[fan[e]]+t;
ans:=ans+t*len2[e];
k:=pre[k,];
end;
end; begin
assign(input,'tyvj1982.in'); reset(input);
assign(output,'tyvj1982.out'); rewrite(output);
readln(n,a,b);
for i:= to do
if i mod = then fan[i]:=i+
else fan[i]:=i-;
for i:= to a do read(c[i]);
for i:= to b do read(d[i]);
for i:= to a do
for j:= to b do add(i,a+j,,(c[i]-d[j])*(c[i]-d[j]));
source:=; src:=;
for i:= to a do add(source,i,,);
for i:= to b do add(i+a,,,);
add(,src,n,);
while spfa do mcf;
writeln(ans);
close(input);
close(output);
end.