Dinic(费用流)
creation_hy · · 个人记录
最大流进阶,求解图中起点到终点在流量最大的情况下最小的费用。每个边会给出流量限制和通过费用。
实现
把Dinic的bfs换成SPFA即可。
Code
const int N = 1e5 + 5;
const int M = 5e6 + 5;
const ll inf = 0x3f3f3f3f3f3f3f3f;
int n, m, s, t, etot, head[N], to[M], nxt[M], stt[N], dep[N];
ll val[M], c[M], d[N], flw, cst;
bool vis[N];
inline void link(int u, int v, ll w, ll cost)
{
to[etot] = v;
nxt[etot] = head[u];
val[etot] = w;
c[etot] = cost;
head[u] = etot++;
}
inline void add(int u, int v, ll w, ll cost)
{
link(u, v, w, cost);
link(v, u, 0, -cost);
}
inline bool spfa()
{
queue<int> q;
memset(d, 0x3f, sizeof(d));
q.emplace(s);
d[s] = 0;
vis[s] = true;
while (!q.empty())
{
int x = q.front();
q.pop();
vis[x] = false;
for (int i = head[x]; ~i; i = nxt[i])
if (val[i] && d[to[i]] > d[x] + c[i])
{
dep[to[i]] = dep[x] + 1;
d[to[i]] = d[x] + c[i];
if (!vis[to[i]])
{
vis[to[i]] = true;
q.emplace(to[i]);
}
}
}
return d[t] != inf;
}
inline ll dfs(ll x, ll flow)
{
if (x == t)
return flow;
ll res = 0;
for (int &i = stt[x]; ~i; i = nxt[i])
if (val[i] && dep[to[i]] == dep[x] + 1 && d[to[i]] == d[x] + c[i])
{
ll rs = dfs(to[i], min(flow - res, val[i]));
if (rs)
{
res += rs;
val[i] -= rs;
val[i ^ 1] += rs;
cst += rs * c[i];
if (res == flow)
break;
}
}
return res;
}
inline ll mcmf()
{
while (spfa())
{
memcpy(stt, head, sizeof(head));
flw += dfs(s, inf);
}
return cst;
}