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

题目链接: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 int

using 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若是单向边要为0
	edge[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;
}
/*
2
1
1 2 999
3
3
1 3 10
2 1 20
3 2 50
9
12
1 2 10
1 3 10
1 4 10
2 5 10
3 5 10
4 5 10
5 7 10
6 7 10
7 8 10
6 9 10
7 9 10
8 9 10
0

*/


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值