1. 程式人生 > 實用技巧 >【LibreOJ101】模板:最大流

【LibreOJ101】模板:最大流

LibreOJ https://loj.ac/p/101


#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<cctype>
#include<cmath>
using namespace std;
#define add_edge(a,b,c) ++tot,nxt[tot]=head[a],head[a]=tot,to[tot]=b,cap[tot]=c
const int maxn = 105, maxm = 12450; //
int nxt[maxm], head[maxn], to[maxm];
long long cap[maxm]; // 注意必須開 long long,只要 s 多接幾條 2^31-1 就會炸 int
int dis[maxn], q[maxn], cur[maxn];
int n, m, tot = 1, s, t;
// 是 ^ 而不是 ~ (也當然明顯不能用'~')
bool BFS()
{
    memset(dis, 0, sizeof(dis));
    dis[s] = 1;
    int st = 1, ed = 1, x;
    q[ed++] = s;
    while (st < ed)
    {
        x = q[st];
        ++st;
        for (int i = head[x]; i; i = nxt[i])
        {
            if (dis[to[i]] || (cap[i] == 0)) continue;
            dis[to[i]] = dis[x] + 1;
            q[ed++] = to[i];
        }
    }
    return (dis[t] != 0);
}
long long dfs(int x, long long maxflow) // long long
{
    if ( x == t || maxflow == 0 ) return maxflow;
    long long curflow = 0, flow;
    for ( int &i = cur[x]; i; i = nxt[i] ) // 多路增廣
    {
        if ( cap[i] && ( dis[to[i]] == dis[x] + 1 ) )
        {
            if (flow = dfs(to[i], min(maxflow, cap[i])))
            {
                cap[i] -= flow; // 正向邊減流量
                cap[i ^ 1] += flow; // 反向邊加流量

                // cap 寫成了 cur