比 ZKW_flow 快
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<queue> using namespace std; #define maxn 1010 #define maxm 20010 const int inf = 0x3f3f3f3f; struct Nod { int b, nxt; int cap, cst; void init(int b, int nxt, int cap, int cst) { this->b = b; this->nxt = nxt; this->cap = cap; this->cst = cst; } }; struct MinCost { int E[maxn]; int n; Nod buf[maxm * 2]; int len; int p[maxn]; void init(int n) { this->n = n; memset(E, 255, sizeof(E)); len = 0; } void AddEdge(int a, int b, int cap, int cst) { buf[len].init(b, E[a], cap, cst); E[a] = len++; buf[len].init(a, E[b], 0, -cst); E[b] = len++; } bool spfa(int source, int sink) { static queue<int> q; static int d[maxn]; memset(d, 63, sizeof(d)); memset(p, 255, sizeof(p)); d[source] = 0; q.push(source); int u, v; while (!q.empty()) { u = q.front(); q.pop(); for (int i = E[u]; i != -1; i = buf[i].nxt) { v = buf[i].b; if (buf[i].cap > 0 && d[u] + buf[i].cst < d[v]) { d[v] = d[u] + buf[i].cst; p[v] = i; q.push(v); } } } return d[sink] != inf; } int Mincost(int source, int sink) { int minCost = 0, maxFlow = 0;//需要maxFlow的话,想办法返回 while (spfa(source, sink)) { int neck = inf; for (int t = p[sink]; t != -1; t = p[buf[t ^ 1].b])//buf[t^壹].b是父节点 neck = min(neck, buf[t].cap); maxFlow += neck; for (int t = p[sink]; t != -1; t = p[buf[t ^ 1].b]) { buf[t].cap -= neck; buf[t ^ 1].cap += neck; minCost += buf[t].cst * neck; } } return minCost; } } MC;
本文深入探讨了一种比ZKW_flow更快的最小费用流算法实现,通过SPFA改进算法进行寻路,详细介绍了算法的结构、核心数据类型定义及关键函数实现,包括初始化、边的添加、最短路径搜索和最小费用流计算等步骤。
516

被折叠的 条评论
为什么被折叠?



