网络最大流模板(Dinic 当前弧优化)

// #pragma GCC optimize(2)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#include <bitset>
#define IO                       \
    ios::sync_with_stdio(false); \
    // cin.tie(0);                  \
    // cout.tie(0);
using namespace std;
// int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
typedef unsigned long long ULL;
typedef long long LL;
typedef pair<int, int> P;
const int maxn = 1e6 + 10;
const int maxm = 2e6 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 100003;
const double pi = acos(-1);
struct Edge
{
    int next, to;
    LL cap;
} e[maxm << 1];
int n, m, k, head[maxn];
int s, t;
int cur[maxn];
int dep[maxn];
void add(int u, int v, int w)
{
    e[k].to = v;
    e[k].cap = w;
    e[k].next = head[u];
    head[u] = k++;
}
bool BFS(int s, int t)
{
    memset(dep, 0, sizeof dep);
    dep[s] = 1;
    queue<int> q;
    q.push(s);
    cur[s] = head[s];
    while (!q.empty())
    {
        int u = q.front();
        if (u == t)
            return true;
        q.pop();
        for (int i = head[u]; i != -1; i = e[i].next)
        {
            int v = e[i].to;
            if (e[i].cap && dep[v] == 0)
            {
                dep[v] = dep[u] + 1;
                q.push(v);
                cur[v] = head[v];
            }
        }
    }
    if (dep[t] == 0)
        return false;
    return true;
}
LL DFS(int u, LL flow)
{
    if (u == t)
        return flow;
    LL sum = 0;
    for (int i = cur[u]; i != -1; i = e[i].next)
    {
        cur[u] = i;
        int v = e[i].to;
        if (e[i].cap && dep[v] == dep[u] + 1)
        {
            int f = DFS(v, min(flow - sum, e[i].cap));
            e[i].cap -= f;
            e[i ^ 1].cap += f;
            sum += f;
            if (sum == flow)
                return sum;
        }
    }
    return sum;
}
LL Dinic(int s, int t)
{
    LL ans = 0;
    while (BFS(s, t))
        ans += DFS(s, INF);
    return ans;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    IO;
    int x, y, z;
    cin >> n >> m >> s >> t;
    memset(head, -1, sizeof head);
    for (int i = 0; i < m; i++)
    {
        cin >> x >> y >> z;
        add(x, y, z);
        add(y, x, 0);
    }
    cout << Dinic(s, t);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44115065/article/details/108554144
今日推荐