1
5
2016
0

【POJ2135】【费用流】Farm Tour

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

有一段时间没写博客了,2016快乐!

题意:n个点m条边的无向图,找出1到n的两条不同路径使路径之和最小

做法:添加超级源s超级汇t,从s到1连一条容量为2(表示可以走两次),费用为0(不计入总距离)的边,从n到t连一条容量为2,费用为0的边。

RE是因为数组大小开错了。手生了。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<queue>
#define inf 1<<30
#define for2(i,s,t) for(int i=(s);i<=(t);i++)
using namespace std;
const int N=2000,M=50000;
int n,m,s,t,tot=1,ans;
bool inq[N];
int head[N],d[N],p[N];
struct edge{
	int from,go,next,v,c;
}e[M];
inline void add_edge(int x,int y,int v,int c)
{
	e[++tot]=(edge){x,y,head[x],v,c};head[x]=tot;
	e[++tot]=(edge){y,x,head[y],0,-c};head[y]=tot;//-c!
}
inline bool spfa()
{
	queue<int> q;
	memset(inq,false,sizeof(inq));
	for2(i,1,t) d[i]=inf;
	d[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].go;
			if(e[i].v&&d[x]+e[i].c<d[y]){
				d[y]=d[x]+e[i].c;
				p[y]=i;//标记
				if(!inq[y]) {
					q.push(y);
					inq[y]=true;
				}
			}
		}
	}
	return d[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+=d[t]*tmp;
		for(int i=p[t];i;i=p[e[i].from]){
			e[i].v-=tmp;
			e[i^1].v+=tmp;
		}
	}
}
int main()
{
	scanf("%d%d",&n,&m);
	int x,y,c;
	s=0,t=n+1;
	for2(i,1,m){
		scanf("%d%d%d",&x,&y,&c);
		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);
	return 0;
}
Category: 网络流 | Tags: | Read Count: 282

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

Host by is-Programmer.com | Power by Chito 1.3.3 beta | Theme: Aeros 2.0 by TheBuckmaker.com