Cod sursa(job #2709208)

Utilizator ArdeleanOficialAlexandru ArdeleanOficial Data 19 februarie 2021 23:39:50
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#include <bits/stdc++.h>

using namespace std;

const int N = 1009;

namespace Flow {

    struct Edge {
        int from, to, flow;
    };


    vector < int > adia[N];
    vector < Edge > muchii;
    int tata[N];
    int S, D, n;


    void AddEdge(int from, int to, int flow) {
        adia[from].push_back(muchii.size());
        muchii.push_back({from, to, flow});
        adia[to].push_back(muchii.size());
        muchii.push_back({to, from, 0});
    }

    bool bfs() {
        fill(tata + 1, tata + n + 1, -1);
        vector < int > q;
        q.push_back(S);
        for (int i = 0; i < q.size(); ++i) {
            int nod = q[i];
            if (nod == D)
                continue;
            for (int next : adia[nod]) {
                auto &x = muchii[next];
                if (tata[x.to] == -1 && x.flow)
                    tata[x.to] = next, q.push_back(x.to);
            }
        }
        return tata[D] != -1;
    }

    int push() {
        int ans(0);
        for (int i : adia[D]) {
            i ^= 1;
            if (!muchii[i].flow)
                continue;
            tata[D] = i;
            int flow(muchii[i].flow);
            for (int nod = D; nod != S; nod = muchii[tata[nod]].from)
                flow = min(flow, muchii[tata[nod]].flow);
            for (int nod = D; nod != S; nod = muchii[tata[nod]].from)
                muchii[tata[nod]].flow -= flow,
                muchii[tata[nod]^1].flow += flow;
            ans += flow;
        }
        return ans;
    }


    int MaxFlow(int s, int d, int _n) {
        n = _n;
        S = s;
        D = d;
        int ans(0);
        while (bfs())
            ans += push();
        return ans;
    }
}

int main()
{
    ifstream fin("maxflow.in");
    ofstream fout("maxflow.out");
    int n, m, a, b, c;
    fin >> n >> m;
    for (int i = 0; i < m; ++i)
        fin >> a >> b >> c, Flow::AddEdge(a, b, c);
    fout << Flow::MaxFlow(1, n, n);
    return 0;
}