最小费用流

来源:互联网 发布:linux date命令 编辑:程序博客网 时间:2024/05/22 18:10

概念:这就是在最大流问题的网络中,给边新加上了费用,而求的不再是流量的最大值,而是流量为F时费用的最小值,这类问题叫做最小费用流。

思路:在残余网络上总是沿最短路增广,此时,残余网络中的反向边的费用应该是原边费用的相反数,以保证过程是可逆而正确的,因为有负权边,所以就不能用Dijkstra算法求最短路了,而需要用Bellman-Ford算法。

时间复杂度:最坏复杂度为O(F*V*E)


代码:

//用于表示边的结构体(终点,容量,费用,反向边) struct edge{int to,cap,cost,rev;};int V;//顶点数 vector<edge> G[max_v];//图的邻接表表示 int dist[max_v];//最短距离 int prevv[max_v],preve[max_v]//最短路中的前驱结点和对应的边 //向图中增加一条从fron到to容量为cap费用为cost的边 void add_edge(int from,int to,int cap,int cost){G[from].push_back((edge){to,cap,cost,G[to].size()});G[to].push_back((edge){from,0,-cost,G[from].size()-1});}//求解从s到t流量为f的最小费用流 //如果不能再增广则返回-1 int min_cost_flow(int s,int t,int f){int res=0;while(f>0){//利用Bellman-Ford算法求s到t的最短路 fill(dist,dist+V,INF);dist[s]=0;bool update=true;while(update){update=false;for(int v=0;v<V;v++){if(dist[v]==INF)    continue;for(int i=0;i<G[v].size();i++){edge &e=G[v][i];if(e.cap>0&&dist[e.to]>dist[v]+e.cost){dist[e.to]=dist[v]+e.cost;prevv[e.to]=v;preve[e.to]=i;update=true;}}}}if(dist[t]==INF){//不能再增广 return -1;}//沿s到t的最短路尽量增广 int d=f;for(int v=t;v!=s;v=prevv[v]){d=min(d,G[prevv[v]][preve[v]].cap);}f-=d;res+=d*dist[t];for(int v=t;v!=s;v=prevv[v]){edge &e=G[prevv[v]][preve[v]];e.cap-=d;g[e.to][e.rev].cap+=d;}}return res;}