【题目链接】 http://poj.org/problem?id=3068
【题目大意】
给出一张图,要把两个物品从起点运到终点,他们不能运同一条路过
每条路都有一定的费用,求最小费用
【题解】
题目等价于求两条无交叉最短路,可用流量为2的费用流求解
【代码】
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
const int INF=0x3f3f3f3f;
struct edge{int to,cap,cost,rev;};
const int MAX_V=10000;
int V,dist[MAX_V],prevv[MAX_V],preve[MAX_V];
vector<edge> G[MAX_V];
void add_edge(int from,int to,int cap,int cost){
G[from].push_back((edge){to,cap,cost,G[to].size()});
G[to].push_back((edge){from,0,-cost,G[from].size()-1});
}
int min_cost_flow(int s,int t,int f){
int res=0;
while(f>0){
fill(dist,dist+V,INF);
dist[s]=0;
bool update=1;
while(update){
update=0;
for(int v=0;v<V;v++){
if(dist[v]==INF)continue;
for(int i=0;i<G[v].size();i++){
edge &e=G[v][i];
if(e.cap>0&&dist[e.to]>dist[v]+e.cost){
dist[e.to]=dist[v]+e.cost;
prevv[e.to]=v;
preve[e.to]=i;
update=1;
}
}
}
}
if(dist[t]==INF)return -1;
int d=f;
for(int v=t;v!=s;v=prevv[v]){
d=min(d,G[prevv[v]][preve[v]].cap);
}f-=d;
res+=d*dist[t];
for(int v=t;v!=s;v=prevv[v]){
edge &e=G[prevv[v]][preve[v]];
e.cap-=d;
G[v][e.rev].cap+=d;
}
}return res;
}
void clear(){for(int i=0;i<V;i++)G[i].clear();}
int N,M;
int cas=0;
void solve(){
int s=N,t=s+1;
V=t+1; clear();
add_edge(s,0,2,0);
add_edge(N-1,t,2,0);
for(int i=0;i<M;i++){
int u,v,cost;
scanf("%d%d%d",&u,&v,&cost);
add_edge(u,v,1,cost);
}
int ans=min_cost_flow(s,t,2);
printf("Instance #%d: ", ++cas);
if(ans==-1)puts("Not possible");
else printf("%d\n",ans);
}
int main(){
while(~scanf("%d%d",&N,&M),N&&M){
solve();
}return 0;
}