Posted on 2012-05-01 16:37
lenohoo 阅读(89)
评论(0) 编辑 收藏 引用
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
MCF
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
using namespace std;
#define re(i,n) for(int i=0;i<n;i++)
#define MAXN 1001
#define MAXM 40010
#define inf (1<<29)
int N,M,pre[MAXM],dist[MAXN],first[MAXN];
bool vi[MAXN];
struct Edge{
int u,v,f,c,next;
}e[MAXM];
inline void _add(int u,int v,int f,int c){
e[M].u=u;e[M].v=v;e[M].f=f;e[M].c=c;
e[M].next=first[u];first[u]=M++;
}
inline void add(int u,int v,int f,int c){
_add(u,v,f,c);_add(v,u,0,-c);
}
inline bool spfa(int s,int t){
queue<int> Q;
re(i,N) { dist[i]=inf;vi[i]=0;pre[i]=-1; }
dist[s]=0;vi[s]=1;Q.push(s);
while(!Q.empty()){
int u=Q.front();Q.pop();vi[u]=0;
for(int i=first[u];i!=-1;i=e[i].next){
int v=e[i].v;
if(e[i].f && dist[u]+e[i].c<dist[v]){
dist[v]=dist[u]+e[i].c;
pre[v]=i;
if(!vi[v]) { Q.push(v);vi[v]++; }
}
}
}
return dist[t]!=inf;
}
int MCF(int s,int t){
int sum=0;
N+=2;
while(spfa(s,t)){
sum+=dist[t];
for(int i=pre[t];i!=-1;i=pre[e[i].u])
--e[i].f,++e[i^1].f;
}
return sum;
}
int main(){
int m,u,v,w;
scanf("%d%d",&N,&m);
M=0;
memset(first,-1,sizeof first);
re(i,m){
scanf("%d%d%d",&u,&v,&w);
add(u,v,1,w);add(v,u,1,w);
}
add(0,1,2,0);add(N,N+1,2,0);
printf("%d\n",MCF(0,N+1));
}