题目描述

avatar

Code

#include <bits/stdc++.h>
using namespace std;
const int N = 1010, M = 20020;

int n, m, S, T, d[N], pre[N];
int h[N], e[M], f[M], ne[M], idx;
bool vis[N];

void add(int a, int b, int c)
{
    e[idx] = b, f[idx] = c, ne[idx] = h[a], h[a] = idx++;
    e[idx] = a, f[idx] = 0, ne[idx] = h[b], h[b] = idx++;
}

bool bfs()
{
    memset(vis, false, sizeof vis);
    queue<int> q;
    q.push(S), vis[S] = true, d[S] = 0x3f3f3f3f;
    
    while (q.size())
    {
        int t = q.front(); q.pop();
        for (int i = h[t]; i != -1; i = ne[i])
        {
            int ver = e[i];
            if (!vis[ver] && f[i])
            {
                vis[ver] = true;
                d[ver] = min(d[t], f[i]);
                pre[ver] = i;
                if (ver == T)   return true;
                q.push(ver);
            }
        }
    }
    return false;
}

int EK()
{
    int res = 0;
    while (bfs())
    {
        res += d[T];
        for (int i = T; i != S; i = e[pre[i] ^ 1])
            f[pre[i]] -= d[T], f[pre[i] ^ 1] += d[T];
    }
    return res;
}

int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> m >> S >> T;
    while (m--)
    {
        int a, b, c;    cin >> a >> b >> c;
        add(a, b, c);
    }
    
    cout << EK() << endl;
    return 0;
}
上一篇 下一篇