POJ2135 :Farm Tour(最小费用流)
http://poj.org/problem?id=2135
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
题意分析:
有一个农场,农场主想从1到n, 再从n到1,不走重复的路,求走的最小距离。
解题思路:
把距离当作费用,一次去一次回, 算两次最小费用, 注意无向图需要建边两次。
#include <stdio.h>
#include <vector>
#include <algorithm>
#define N 10200
using namespace std;
struct edge{
int v;
int w;
int cost;
int rev;
};
int n, m, inf=99999999;
int dis[N], prevv[N], preve[N];
vector<edge>e[N];
void add(int u, int v, int cost)
{
e[u].push_back(edge{v, 1, cost, e[v].size()});
e[v].push_back(edge{u, 0, -cost, e[u].size()-1});
}
int min_cost(int s, int t)
{
int ans = 0;
int f=2;
while(f--)
{
for (int i=1; i<=n; i++)
dis[i]=inf;
dis[s]=0;
bool update=true;
while(update)
{
update=false;
for(int v=1; v<=n; v++)
{
if(dis[v]==inf)
continue;
for(int i=0; i<e[v].size(); i++)
{
edge &G=e[v][i];
if(G.w>0 && dis[G.v]>dis[v]+G.cost)
{
dis[G.v]=dis[v]+G.cost;
prevv[G.v]=v;
preve[G.v]=i;
update=true;
}
}
}
}
if(dis[t]==inf)
return -1;
int d=inf;
for(int v=t; v!=s; v=prevv[v])
d=min(d, e[prevv[v]][preve[v]].w);
ans+=dis[t];
for(int v=t; v!=s; v=prevv[v]){
edge &G=e[prevv[v]][preve[v]];
G.w-=d;
e[G.v][G.rev].w+=d;
}
}
return ans;
}
int main()
{
int u, v, w;
while(scanf("%d%d", &n, &m)!=EOF)
{
for(int i=1; i<=n; i++)
e[i].clear();
while(m--)
{
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
add(v, u, w);
}
printf("%d\n", min_cost(1, n));
}
return 0;
}