Dinic(最大流/最小割)
creation_hy · · 个人记录
每次先bfs做分层图找出所有增广路,然后dfs跑一边就行了。由于贪心可能是错的,所以建反边做撤销操作。
const int N = 1e5 + 5;
const int M = 1e7 + 5;
const ll inf = 1e18;
int n, m, s, t, etot, head[N], to[M], nxt[M], stt[N], d[N];
ll val[M];
inline void link(int u, int v, ll w)
{
to[etot] = v;
nxt[etot] = head[u];
val[etot] = w;
head[u] = etot++;
}
inline void add(int u, int v, ll w)
{
link(u, v, w);
link(v, u, 0);
}
inline bool bfs()
{
queue<int> q;
memset(d, 0, sizeof(d));
d[s] = 1;
q.emplace(s);
while (!q.empty())
{
int x = q.front();
q.pop();
for (int i = head[x]; ~i; i = nxt[i])
if (!d[to[i]] && val[i])
{
d[to[i]] = d[x] + 1;
q.emplace(to[i]);
if (to[i] == t)
return true;
}
}
return false;
}
inline ll dfs(int x, ll flow)
{
if (x == t)
return flow;
ll res = 0;
for (int &i = stt[x]; ~i; i = nxt[i])
if (d[to[i]] == d[x] + 1 && val[i])
{
ll tmp = dfs(to[i], min(flow - res, val[i]));
if (tmp)
{
res += tmp;
val[i] -= tmp;
val[i ^ 1] += tmp;
if (res == flow)
break;
}
}
return res;
}
inline ll dinic()
{
ll res = 0;
while (bfs())
{
memcpy(stt, head, sizeof(head));
res += dfs(s, inf);
}
return res;
}