Uva 10806 求2条不相交最短路 费用流

来源:互联网 发布:js修改文件名称后上传 编辑:程序博客网 时间:2024/05/21 11:23

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=20&page=show_problem&problem=1747

题意:

给定n个点[1,n]

m条无向带权边

下面m行 u v dis 表示边

问:从1走到n 再从n-1,最短需要走多远(走过的路不能再走)

 

思路:

对于普通最短路我们可以用费用流,终点限流为1,费用为边权,每条边限流为1 , 得到

 

这里我们可以看作从 1-n的两条不相交最短路

 

这样我们将终点限流为2,满流时就有两条不相交的最短路

不满流时说明没有这样的两条路。

#include <stdio.h>#include <string.h>#include <iostream>#include <math.h>#include <queue>#include <set>#include <algorithm>#include <stdlib.h>#define N 10001#define M 101000#define inf 107374182#define ll intusing namespace std;//双向边,注意RE 注意这个模版是 相同起末点的边 合并而不是去重//注意 起点<终点&&终点必须为最大点标 && 点标不要太分散struct Edge{int from, to, flow, cap, nex, cost;}edge[M*2];int head[N], edgenum;void addedge(int u,int v,int cap,int cost){//网络流要加反向弧Edge E={u, v, 0, cap, head[u], cost};edge[edgenum]=E;head[u]=edgenum++;Edge E2={v, u, 0, 0, head[v], -cost}; //这里的cap若是单向边要为0edge[edgenum]=E2;head[v]=edgenum++;}int D[N], P[N], A[N];bool inq[N];bool BellmanFord(int s, int t, int &flow, int &cost){for(int i=0;i<=t;i++) D[i]= inf;memset(inq, 0, sizeof(inq));D[s]=0;  inq[s]=1; P[s]=0; A[s]=inf;queue<int> Q;Q.push( s );while( !Q.empty()){int u = Q.front(); Q.pop();inq[u]=0;for(int i=head[u]; i!=-1; i=edge[i].nex){Edge &E = edge[i];if(E.cap > E.flow && 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 - E.flow);if(!inq[E.to]) Q.push(E.to) , inq[E.to] = 1;}}}if(D[t] == inf) return false;flow += A[t];cost += D[t] * A[t];int u = t;while(u != s){edge[P[u]].flow += A[t];edge[P[u]^1].flow -= A[t];u = edge[P[u]].from;}return true;}int Mincost(int s,int t){//返回最小费用int flow = 0, cost = 0;while(BellmanFord(s, t, flow, cost));return cost;}int n, m;int main(){int i, j, u, v, cost;while(scanf("%d",&n),n){scanf("%d",&m);memset(head,-1,sizeof(head)); edgenum =0;while(m--){scanf("%d %d %d",&u,&v,&cost); addedge(u,v,1,cost);addedge(v,u,1,cost);}addedge(n,n+1,2,0);int ans = Mincost(1,n+1);if(edge[edgenum-2].flow == 2)printf("%d\n",ans);else puts("Back to jail");}return 0;}/*211 2 999331 3 102 1 203 2 509121 2 101 3 101 4 102 5 103 5 104 5 105 7 106 7 107 8 106 9 107 9 108 9 100*/


 

0 0
原创粉丝点击