POJ 2135 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

AC代码:

#include
#include
#include
#include
#include

using namespace std;

const int N = 10000 * 4 + 10;
const int X = 1000 + 10;
const int maxn = 205;
const int inf = 1e8 + 7;

int anss,n,m,tot,h[X],nxt[N],tov[N],w[N],f[N],dis[N];
int q[N],head,tail,src,sink,pree[N],pred[N];
int minflow,maxflow;
bool ins[N];

void add_edge(int x,int y,int z,int zz)  {
	tot++;
	nxt[tot] = h[x];
	tov[tot] = y;
	w[tot] = z;
	f[tot] = zz;
	h[x] = tot;
	
	tot++;
	nxt[tot] = h[y];
	tov[tot] = x;
	w[tot] = -z;
	f[tot] = 0;
	h[y] = tot;
}

bool spfa()  {
	memset(ins,0,sizeof(ins));
	memset(dis,0x7f,sizeof(dis));
	head = tail = 0;
	q[head] = src;
	dis[src] = 0;
	ins[src] = true;
	while (head <= tail)  {
		int u = q[head++];
		for (int i = h[u]; i;i = nxt[i])  {
			int v = tov[i];
			if (f[i] && dis[v] > dis[u] + w[i])  {
				dis[v] = dis[u] + w[i];
				pree[v] = i;
				pred[v] = u;
				if (!ins[v])  {
					ins[v] = true;
					q[++tail] = v;
				}
			}
		}
		ins[u] = false;
	}
	return dis[sink] < inf;
}

void augment()  {
	int u = sink;
	int zelda =  inf;
	while (u != src)  {
		if (f[pree[u]] < zelda )  {
			zelda = f[pree[u]];	
		}
		u = pred[u];
	}
	u = sink;
	while (u != src)  {
		f[pree[u]] -= zelda;
		f[pree[u] ^ 1] +=zelda;
		u = pred[u];
	}
	minflow += dis[sink] * zelda;
}

int main()  {
	ios::sync_with_stdio(false);
	cin>>n>>m;
	tot = 1;
	for (int i = 1; i <= m; i++)  {
		int a,b,c;
		cin>>a>>b>>c;
		add_edge(a,b,c,1);
		add_edge(b,a,c,1);
	}
	add_edge(0,1,0,2);
	add_edge(1,0,0,2);
	add_edge(n,n+1,0,2);
	add_edge(n+1,n,0,2);
	src = 0;
	sink = n + 1;
	while (spfa())  
		augment();
	cout<

你可能感兴趣的:(poj,网络流)