紫书海军上将

该博客讨论了一种利用最小费用最大流算法解决有向加权图中寻找两条不相交路径的问题。通过将节点拆分为两个并用容量为1的边连接,确保每条路径只使用一次,然后应用贝尔曼-福特算法进行最短路径搜索,并在扩展增广路径时限制总流量不超过2。最终,通过最小费用最大流算法找到总费用最小的两条路径。
摘要由CSDN通过智能技术生成

给出一个v(3≤v≤1000)个点e(3≤e≤10000)条边的有向加权图,求1~v的两条不相交(除了起点和终点外没有公共点)的路径,使得权和最小.

分析 什么是两条不相交的边?就是让各个点的容量为1(不是只有流量)。这是怎么做到的?

就是把一个点拆成两个点,中间连一条容量为一的边,要保证拆后的两个点编号不同。然后拆完点跑一次最小费用流就可以了。但是这时候的流量是有限制的,因为只能是两条路,所以在扩展增广路的时候要加上一条这个东西。

f(flow+a[t]>flow_limit) a[t]=flow_limit-flow;

这样就能保证总的流量不会超过flow_limit了。

代码(注上边那个形式(流量限制)才是对的)

#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
#include<cstring>
#define maxn 10005
#define INF 999999
using namespace std;
struct Edge{
	int from,to,cap,flow,cost;
};
struct MCMF{
	int n,m,s,t;
	vector<Edge> edges;vector<int> G[maxn];
	int inq[maxn],d[maxn],a[maxn],p[maxn];
	void init(int n){
		this->n=n;
		for(int i=0;i<n;i++) G[i].clear();
		edges.clear();
	}
	void addedge(int from,int to,int cap,int cost){
		edges.push_back((Edge){ from,to,cap,0,cost});
		edges.push_back((Edge){ to,from,0,0,-cost});
		m=edges.size();G[from].push_back(m-2);G[to].push_back(m-1);
	}
	bool BellmanFord(int s,int t,int &flow,int &cost){
		for(int i=0;i<=n;i++) d[i]=INF;
		memset(inq,0,sizeof(inq));
		inq[s]=1;d[s]=0;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=0;i<G[u].size();i++){
				Edge &e=edges[G[u][i]];
				if(e.cap>e.flow&&d[e.to]>d[u]+e.cost){
					d[e.to]=d[u]+e.cost;
					a[e.to]=min(a[u],e.cap-e.flow);
					p[e.to]=G[u][i];
					if(!inq[e.to]){Q.push(e.to);inq[e.to]=1;
					}
				}
			}
		}
		if(d[t]==INF) return false;
		if(flow+a[t]>2) a[t]=2;
		flow+=a[t];
		cost+=a[t]*d[t];
		for(int u=t;u!=s;u=edges[p[u]].from){
			edges[p[u]].flow+=a[t];
			edges[p[u]^1].flow-=a[t];
		}
		return true;
	}
	int Mincostflow(int s,int t,int &cost){
		int flow=0; cost=0;
		while(flow<2&&BellmanFord(s,t,flow,cost));
		return flow;
	}
};
MCMF g;
int main(){ int n,m,s,t,u,v,cost,cap,i,j,w;
while(scanf("%d%d",&n,&m)==2&&n){
	g.init(2*n-2);
	for(int i=2;i<=n-1;i++)
	g.addedge(i-1,i+n-2,1,0);

while(m--){
	scanf("%d%d%d",&u,&v,&w);
	if(u!=1&&u!=n) u+=n-2; else u--;
	v--;
	g.addedge(u,v,1,w); 
}
int cost=0;
g.Mincostflow(0,n-1,cost);
	printf("%d\n",cost);
}
return 0;}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

minato_yukina

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值