您的位置:首页 > 其它

poj2135 Farm Tour

2015-12-12 19:53 441 查看
Farm Tour

Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 13818 Accepted: 5251
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 Green

最小费用最大流的应用。

问题等价于求1到n的两条不相交路径长度和的最小值。可以转化为流量问题,按原图添加双向边,再从源点s到1连一条容量2、费用0的边,从n到汇点t连一条容量2、费用0的边。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<queue>
#define F(i,j,n) for(int i=j;i<=n;i++)
#define D(i,j,n) for(int i=j;i>=n;i--)
#define LL long long
#define pa pair<int,int>
#define MAXN 2000
#define MAXM 50000
#define INF 1000000000
using namespace std;
int n,m,s,t,ans,cnt=1;
int head[MAXN],dis[MAXN],p[MAXN];
bool inq[MAXN];
struct edge_type
{
int from,to,next,v,c;
}e[MAXM];
inline int read()
{
int x=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') ch=-1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
inline void add_edge(int x,int y,int v,int c)
{
e[++cnt]=(edge_type){x,y,head[x],v,c};head[x]=cnt;
e[++cnt]=(edge_type){y,x,head[y],0,-c};head[y]=cnt;
}
inline bool spfa()
{
queue<int>q;
memset(inq,false,sizeof(inq));
F(i,1,t) dis[i]=INF;
dis[s]=0;inq[s]=true;q.push(s);
while (!q.empty())
{
int x=q.front();q.pop();inq[x]=false;
for(int i=head[x];i;i=e[i].next)
{
int y=e[i].to;
if (e[i].v&&dis[x]+e[i].c<dis[y])
{
dis[y]=dis[x]+e[i].c;
p[y]=i;
if (!inq[y]){q.push(y);inq[y]=true;}
}
}
}
return dis[t]!=INF;
}
inline void mcf()
{
while (spfa())
{
int tmp=INF;
for(int i=p[t];i;i=p[e[i].from]) tmp=min(tmp,e[i].v);
ans+=dis[t]*tmp;
for(int i=p[t];i;i=p[e[i].from]){e[i].v-=tmp;e[i^1].v+=tmp;}
}
}
int main()
{
int x,y,c;
n=read();m=read();
s=n+1;t=s+1;
F(i,1,m)
{
x=read();y=read();c=read();
add_edge(x,y,1,c);
add_edge(y,x,1,c);
}
add_edge(s,1,2,0);
add_edge(n,t,2,0);
mcf();
printf("%d\n",ans);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: