网络流(最小费用最大流):POJ 2135 Farm Tour

时间:2021-04-10 15:08:19

Farm Tour

Time Limit: 1000ms
Memory Limit: 65536KB

This problem will be judged on PKU. Original ID: 2135
64-bit integer IO format: %lld      Java class name: Main

 
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

  这题就是在一个无向图中找出两条从点1到点n的路径,同时要求路程最短。
  于是贴最小费用最大流模板就AC啦。
 #include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int INF=;
const int maxn=,maxm=;
int cnt,fir[maxn],nxt[maxm],to[maxm],cap[maxm],val[maxm],dis[maxn],path[maxn]; void addedge(int a,int b,int c,int v)
{
nxt[++cnt]=fir[a];to[cnt]=b;cap[cnt]=c;val[cnt]=v;fir[a]=cnt;
}
int S,T;
int Spfa()
{
queue<int>q;
memset(dis,,sizeof(dis));
q.push(S);dis[S]=;
while(!q.empty())
{
int node=q.front();q.pop();
for(int i=fir[node];i;i=nxt[i])
if(cap[i]&&dis[node]+val[i]<dis[to[i]]){
dis[to[i]]=val[i]+dis[node];
path[to[i]]=i;
q.push(to[i]);
}
}
return dis[T]==dis[T+]?:dis[T];
} int Aug()
{
int p=T,f=INF;
while(p!=S)
{
f=min(f,cap[path[p]]);
p=to[path[p]^];
}
p=T;
while(p!=S)
{
cap[path[p]]-=f;
cap[path[p]^]+=f;
p=to[path[p]^];
}
return f;
} int MCMF()
{
int ret=,d;
while(d=Spfa())
ret+=Aug()*d;
return ret;
} void Init(int n)
{
cnt=;S=;T=n+;
for(int i=;i<=n;i++)fir[i]=;
} int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
Init(n);
int a,b,v;
for(int i=;i<=m;i++)
{
scanf("%d%d%d",&a,&b,&v);
addedge(a,b,,v);
addedge(b,a,,-v);
addedge(b,a,,v);
addedge(a,b,,-v);
}
addedge(S,,,);
addedge(,S,,);
addedge(n,T,,);
addedge(T,n,,);
printf("%d\n",MCMF());
}
return ;
}