学习博客
最小费用 == 最短路
费用流 在参与网络上寻找最短路
最大流量只有一个 流法却有很多种 即要保持最大流又要保持最小费用 所以需要最短路
由于dijkstra不能跑负权边 所以基本上用的都是spfa
但是如果可以采用一种方法加上一个基准值base 将所有数据都跑在整数的话就可以了(可是dijsktra做这道好像会T)
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
const int INF = 0x3f3f3f3f;
int n, m, k;
namespace cost_flows { //最小费用最大流板子
//设定起点和终点
int st;//起点-源点
int ed;//终点-汇点
struct egde {
int to, next;
int flow;//剩余流量
int dis; //花费
} e[N * 2];
int head[N], tot = 1;
void add(int u, int v, int w, int cost) {//出发点 下一个点 流量 费用
e[++tot] = {v, head[u], w, cost};
head[u] = tot;
e[++tot] = {u, head[v], 0, -cost};
head[v] = tot;//费用流反相边流量为0 费用是-dis
}
queue<int> q;
int flow[N];//增广路上最小流量
int inq[N];//是否在队里里 等同于vis
int last[N];//每个点所连的前一条边的编号
int dis[N];//到达每个节点的最小花费 即 最短路
int pre[N];//每个节点的前驱节点
bool spfa() {
memset(flow, INF, sizeof(flow));
memset(dis, INF, sizeof(dis));//注意了 这里是最大值
memset(inq, 0, sizeof(inq));
q.push(st);
dis[st] = 0;
inq[st] = 1;//在队列中 标记
pre[ed] = -1;//ok 还没有到达汇点
while (!q.empty()) {
int u = q.front();
q.pop();
inq[u] = 0;//出队 标记
for (int i = head[u]; i; i = e[i].next) {
int v = e[i].to;
if (dis[v] > dis[u] + e[i].dis && e[i].flow) { //有流量才能松弛
dis[v] = dis[u] + e[i].dis;
pre[v] = u;
last[v] = i;
flow[v] = min(flow[u], e[i].flow);
if (!inq[v]) {
inq[v] = 1;
q.push(v);
}
}
}
}
return pre[ed] != -1;//即 没有到达汇点
}
int max_flow, min_cost;
void MCMF() {// - 费用流主体
while (spfa()) {//如果有增广路
int now = ed;
max_flow += flow[ed];
min_cost += flow[ed] * dis[ed];
while (now != st) {//遍历这条增广路
//从汇点一直回溯到源点
e[last[now]].flow -= flow[ed];
e[last[now] ^ 1].flow += flow[ed];
now = pre[now];
}
}
}
void init() {
tot = 1;
memset(head, 0, sizeof(head));
while (!q.empty()) q.pop();
max_flow=0;
min_cost=0;
}
}
using namespace cost_flows;
int main() {
ios::sync_with_stdio(0);
cin >> n >> m >> st >> ed;
for (int i = 1,u,v,w,c; i <= m; ++i) {
cin>>u>>v>>w>>c;
add(u,v,w,c);
}
MCMF();
cout <<max_flow<<" "<<min_cost << endl;
return 0;
}