poj2135 Farm Tour(费用流)

时间:2023-03-09 03:09:11
poj2135 Farm Tour(费用流)

Description

When FJ's friends visit him on the farm, he likes to show them around. His farm comprises N (1 <= N <= 1000) fields numbered 1..N, the first of which contains his house and the Nth of which contains the big barn. A total M (1 <= M <= 10000) paths that connect the fields in various ways. Each path connects two different fields and has a nonzero length smaller than 35,000.

To show off his farm in the best way, he walks a tour that starts at his house, potentially travels through some fields, and ends at the barn. Later, he returns (potentially through some fields) back to his house again.

He wants his tour to be as short as possible, however he doesn't want to walk on any given path more than once. Calculate the shortest tour possible. FJ is sure that some tour exists for any given farm.

Input

* Line 1: Two space-separated integers: N and M.

* Lines 2..M+1: Three space-separated integers that define a path: The starting field, the end field, and the path's length.

Output

A single line containing the length of the shortest tour. 

Sample Input

4 5
1 2 1
2 3 1
3 4 1
1 3 2
2 4 2

Sample Output

6

Source

USACO 2003 February Gree
费用流,建图还是比较好想的。据说题中数据范围不对要当成2000个点20000条边才能过。
题目大意及题解:
poj2135 Farm Tour(费用流)

poj2135 Farm Tour(费用流)

poj2135 Farm Tour(费用流)

 program rrr(input,output);
const
inf=;
type
etype=record
t,c,w,next,rev:longint;
end;
var
e:array[..]of etype;
a,q,dis,fre,frv:array[..]of longint;
inq:array[..]of boolean;
n,m,i,x,y,w,cnt,h,t,ans:longint;
procedure ins(x,y,c,w:longint);
begin
inc(cnt);e[cnt].t:=y;e[cnt].c:=c;e[cnt].w:=w;e[cnt].next:=a[x];a[x]:=cnt;
end;
procedure add(x,y,w:longint);
begin
ins(x,y,,w);e[cnt].rev:=cnt+;
ins(y,x,,-w);e[cnt].rev:=cnt-;
end;
procedure spfa;
begin
for i:= to n do dis[i]:=inf;
fillchar(inq,sizeof(inq),false);
h:=;t:=;dis[]:=;q[]:=;inq[]:=true;
while h<>t do
begin
inc(h);if h> then h:=;
i:=a[q[h]];
while i<> do
begin
if (e[i].c>) and (dis[q[h]]+e[i].w<dis[e[i].t]) then
begin
dis[e[i].t]:=dis[q[h]]+e[i].w;
fre[e[i].t]:=i;frv[e[i].t]:=q[h];
if not inq[e[i].t] then
begin
inc(t);if t> then t:=;
q[t]:=e[i].t;inq[e[i].t]:=true;
end;
end;
i:=e[i].next;
end;
inq[q[h]]:=false;
end;
end;
begin
assign(input,'r.in');assign(output,'r.out');reset(input);rewrite(output);
readln(n,m);
fillchar(a,sizeof(a),);cnt:=;
for i:= to m do begin readln(x,y,w);add(x,y,w);add(y,x,w); end;
ans:=;
spfa;
i:=n;while i<> do begin e[fre[i]].c:=;e[e[fre[i]].rev].c:=;ans:=ans+e[fre[i]].w;i:=frv[i]; end;
spfa;
i:=n;while i<> do begin ans:=ans+e[fre[i]].w;i:=frv[i]; end;
write(ans);
close(input);close(output);
end.