Key ponits
在最小费用流问题中, 平行边变得有意义了:可能会有两条从u->v的弧,费用分别为1,2在没有费用的情况下, 可以把二者合并, 但由于费用的出现,无法合并这两条弧。再如, 如果边(u, v) (v, u)
都存在,且费用都为负数。为了允许反悔(反向增广)规定cap[v][u] = 0并且cost[v][u] = -cost[u][v]表示沿着(u, v)相反方向增广是=时费用减少cost[u][v]
#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
const int N = 1e5 + 10;
struct Edge {
int from, to, cap, flow, cost;
Edge(int u, int v, int c, int f, int w):from(u), to(v), cap(c), flow(f), cost(w)
};
struct MCMF {
int n, m;
vector<Edge> edges;
vector<int> G[N];
int inq[N]; // 是否在队列中
int d[N]; // bellman-Ford
int p[N]; // 上一条弧
int a[N]; // 可改进量
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);//反向边的起点为to
}
bool BellmanFord(int s, int t, int &flow, long long &cost) {
for(int i = 0; i < n; i++) d[i] = inf;//将花费初始化为无穷大
memset(inq, 0, sizeof inq);
d[s] = 0;//d[i] 起点s到i点的花费
inq[s] = 1;//inq[i] 标记i点已经入队
p[s] = 0; //p[i]标记i在路径上的前驱
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++) { //与u点向关联的边
Edge& e = edges[G[u][i]];
if(e.cap > e.flow && d[e.to] > d[u] + e.cost) //如果e这条边的容量大于已经存在的流量,即还有多余的容量时, 并且花费更低时
{
d[e.to] = d[u] + e.cost; // 更新最小花费
p[e.to] = G[u][i]; // 更新以e.to为起点的这条边的编号, 前驱是边的编号
a[e.to] = min(a[u], e.cap - e.flow); // 更新s点到to点的还可以保持的最大容量
if(!inq[e.to]) { Q.push(e.to); inq[e.to] = 1; } // 入队
}
}
}
if(dp[t] == inf) return false; //如果不能到达
flow += a[t]; //最大流增加
cost += (long long)d[t]*(long long)a[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 MinCostMaxflow(int s, int t, long long &cost) {
int flow = 0; cost = 0;
while(BellmanFord(s, t, flow, cost));
retrun flow;
}
};