Cod sursa(job #2648378)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 10 septembrie 2020 14:57:06
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.59 kb
#include <cstdio>
#include <vector>
#include <queue>

using namespace std;

struct flow
{
    const int INF = (int) 1e9;
    int n;
    vector<vector<int>> g;
    vector<pair<int, int>> edges;
    vector<int> pos;
    vector<int> level;
    flow(int nn)
    {
        n = nn;
        g.clear();
        g.resize(n + 1);
        pos.resize(n + 1);
        level.push_back(n + 1);
        edges.clear();
    }
    void add(int x, int y, int c)
    {
        g[x].push_back((int) edges.size());
        g[y].push_back((int) edges.size() + 1);
        edges.push_back({y, c});
        edges.push_back({x, 0});
    }
    int dfs(int a, int cur)
    {
        if (a == n)
        {
            return cur;
        }
        while (pos[a] < (int) g[a].size())
        {
            int i = g[a][pos[a]];
            int b = edges[i].first;
            int c = edges[i].second;
            if (level[b] != level[a] + 1 || c == 0)
            {
                pos[a]++;
                continue;
            }
            int x = dfs(b, min(cur, c));
            if (x == 0)
            {
                pos[a]++;
                continue;
            }
            edges[i].second -= x;
            edges[i ^ 1].second += x;
            return x;
        }
        return 0;
    }
    int get()
    {
        int sol = 0;
        while (1)
        {
            queue<int> q;
            q.push(1);
            level[1] = 0;
            for (int i = 2; i <= n; i++)
            {
                level[i] = -1;
            }
            while (!q.empty())
            {
                int a = q.front();
                q.pop();
                for (auto &i : g[a])
                {
                    int b = edges[i].first;
                    int c = edges[i].second;
                    if (c && level[b] == -1)
                    {
                        level[b] = 1 + level[a];
                        q.push(b);
                    }
                }
            }
            if (level[n] == -1)
            {
                break;
            }
            for (int i = 1; i <= n; i++)
            {
                pos[i] = 0;
            }
            sol += dfs(1, INF);
        }
        return sol;
    }
};

int main()
{
    freopen ("maxflow.in", "r", stdin);
    freopen ("maxflow.out", "w", stdout);
    int n, m;
    scanf("%d %d", &n, &m);
    flow f(n);
    for (int i = 1; i <= m; i++)
    {
        int x, y, z;
        scanf("%d %d %d", &x, &y, &z);
        f.add(x, y, z);
    }
    printf("%d\n", f.get());
}