给出一个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;}