POJ 2135 Farm Tour 最小費用最大流
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再回到1,不能走重邊,要求總路程最小,費用流模板題, 每條路流量設為1就可以了
EK演算法介紹:點選檢視
#include<iostream> #include<cstdio> #include<cstring> #include<queue> #include<algorithm> #define INF 0x3f3f3f3f using namespace std; const int N=1010; const int M=40010; struct node { int u,to,nex,cap,val; }e[M]; int n,m; int head[N],dis[N],vis[N],pre[N],len; void init() { len=0; memset(head,-1,sizeof(head)); } void add(int u,int v,int z,int cap) { e[len].u=u; e[len].to=v; e[len].cap=cap; e[len].val=z; e[len].nex=head[u]; head[u]=len++; e[len].u=v; e[len].to=u; e[len].cap=0; e[len].val=-z; e[len].nex=head[v]; head[v]=len++; } bool spfa(int s,int t,int nnum) { memset(vis,0,sizeof(vis)); memset(pre,-1,sizeof(pre)); for(int i=0;i<=nnum;i++) dis[i]=INF; queue<int> q; q.push(s); dis[s]=0; vis[s]=1; while(!q.empty()) { int temp=q.front();q.pop(); vis[temp]=0; for(int i=head[temp];i!=-1;i=e[i].nex) { if(e[i].cap) { int to=e[i].to; if(dis[to]>dis[temp]+e[i].val) { dis[to]=dis[temp]+e[i].val; pre[to]=i; if(!vis[to]) { vis[to]=1; q.push(to); } } } } } if(dis[t]==INF) return 0; return 1; } int GetMincost(int s,int t,int f) { int ans=0; int temp,minc; while(f>0) { spfa(s,t,n); temp=t; minc=INF; while(pre[temp]!=-1) { minc=min(e[pre[temp]].cap,minc); temp=e[pre[temp]].u; } temp=t; f-=minc; while(pre[temp]!=-1) { e[pre[temp]].cap-=minc; int ss=pre[temp]^1; e[ss].cap+=minc; temp=e[pre[temp]].u; } ans+=dis[t]*minc; } return ans; } int main() { int x,y,z; while(~scanf("%d%d",&n,&m)) { init(); for(int i=1;i<=m;i++) { scanf("%d%d%d",&x,&y,&z); add(x,y,z,1); add(y,x,z,1); } printf("%d\n",GetMincost(1,n,2)); } return 0; }