原题:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1747
题意:
有n个点,1到n;
给出m条无向边的花费;
问从1 走到 n,再从n 走到 1(不走重复的路)的最小花费;
思路:
不走重复的路,即流量为1,;
设1为源点,n+1为汇点,节点到汇点的流量设为2, 花费为0;
#include<stdio.h>
#include<string.h>
#include<queue>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll int
#define inf 0x3f3f3f3f
#define N 605*605*2
#define M 605*605*4
int n, m;
struct Edge
{
ll to, cap, cost, nex;
Edge(){}
Edge(ll to,ll cap,ll cost,ll next):to(to),cap(cap),cost(cost),nex(next){}
} edge[M<<1];
ll head[N], edgenum;
ll D[N], A[N], P[N];
bool inq[N];
void add(ll from,ll to,ll cap,ll cost)
{
edge[edgenum] = Edge(to,cap,cost,head[from]);
head[from] = edgenum++;
edge[edgenum] = Edge(from,0,-cost,head[to]);
head[to] = edgenum++;
}
bool spfa(ll s, ll t, ll &flow, ll &cost)
{
for(ll i = 0; i <= t; i++) D[i] = inf;
memset(inq, 0, sizeof inq);
queue<ll>q;
q.push(s);
D[s] = 0; A[s] = inf;
while(!q.empty())
{
ll u = q.front(); q.pop();
inq[u] = 0;
for(ll i = head[u]; ~i; i = edge[i].nex)
{
Edge &e = edge[i];
if(e.cap && D[e.to] > D[u] + e.cost)
{
D[e.to] = D[u] + e.cost;
P[e.to] = i;
A[e.to] = min(A[u], e.cap);
if(!inq[e.to])
{inq[e.to]=1; q.push(e.to);}
}
}
}
if(D[t] == inf) return false;
cost += D[t] * A[t];
flow += A[t];
ll u = t;
while(u != s)
{
edge[ P[u] ].cap -= A[t];
edge[P[u]^1].cap += A[t];
u = edge[P[u]^1].to;
}
return true;
}
ll Mincost(ll s,ll t)
{
ll flow = 0, cost = 0;
while(spfa(s, t, flow, cost));
if(flow == 2)
printf("%d\n", cost);
else
printf("Back to jail\n");
}
void init()
{
memset(head,-1,sizeof head);
edgenum = 0;
}
int main()
{
while(scanf("%d", &n)!=EOF)
{
if(n == 0) break;
scanf("%d", &m);
init();
while(m--)
{
int u, v, cos;
scanf("%d%d%d", &u, &v, &cos);
add(u, v, 1, cos);
add(v, u, 1, cos);
}
add(n, n+1, 2, 0);
Mincost(1, n+1);
}
return 0;
}