【ZJOI2017 Round1练习&&BZOJ5353】D7T2 guess(费用流)
阅读原文时间:2023年07月13日阅读:1

题意:

思路:

var head,vet,next,len1,len2,x,y,p1,p2,dis,a,b,fan:array[..]of longint;
pre:array[..,..]of longint;
inq:array[..]of boolean;
q:array[..]of longint;
n,m,i,j,ans,tot,source,src,s,t1,t2:longint;

function min(x,y:longint):longint;
begin
if x<y then exit(x);
exit(y);
end;

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 find(x,y:longint):boolean;
var i:longint;
begin
for i:= to n do
if (x=a[i])and(y=b[i]) then exit(true);
exit(false);
end;

function spfa:boolean;
var u,e,v,i,t,w,t1,w1:longint;
begin
for i:= to s do
begin
dis[i]:=maxlongint>>;
inq[i]:=false;
end;
t:=; w:=; t1:=; w1:=; q[]:=source; dis[source]:=; inq[source]:=true;
while t do
begin
v:=vet[e];
if (len1[e]>)and(dis[u]+len2[e]> then exit(false);
exit(true);
end;

procedure mcf;
var k,e,t: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,'guess.in'); reset(input);
assign(output,'guess.out'); rewrite(output);
readln(n);
for i:= to do
if i and = then fan[i]:=i+
else fan[i]:=i-;
for i:= to n do
begin
readln(a[i],b[i]);
inc(x[a[i]]); inc(y[b[i]]);
end;
for i:= to do
if x[i]> then inc(s);
for i:= to do
if y[i]> then inc(s);
source:=s+; src:=s+; s:=s+;
for i:= to do
if x[i]> then
begin
inc(t1); p1[t1]:=i;
add(source,t1,x[i],);
end;
for i:= to do
if y[i]> then
begin
inc(t2); p2[t2]:=i;
add(t1+t2,src,y[i],);
end;
for i:= to t1 do
for j:= to t2 do
if find(p1[i],p2[j]) then add(i,j+t1,,)
else add(i,j+t1,,);
while spfa do mcf;
writeln(ans);
close(input);
close(output);
end.