Cod sursa(job #3312950)

Utilizator paulihno15Ciumandru Paul paulihno15 Data 30 septembrie 2025 21:52:33
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.2 kb
#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
#include <complex.h>
#include <bits/stdc++.h>

using namespace std;

#define NMAX 1000
#define MMAX 4000
#define PMAX 524288
#define LOG 18
#define INF 0x3f3f3f3f
#define BS 666013
#define MOD 1000000007
#define INV_2 500000004
#define INV_24 41666667

#define ll long long
#define ull unsigned long long
#define dbl double
#define pii pair<int, int>
#define piv pair<int, vector<int>>

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

int n, m, a, b, c, ans;
vector<int> niv(NMAX + 2), ptr(NMAX + 2);

struct muchie {
    int to, cap, ind_rev;
};
vector<muchie> gr[NMAX + 2];

void add_mch(int x, int y, int cant) {
    muchie m1 = {y, cant, (int)gr[y].size()};
    muchie m2 = {x, 0, (int)gr[x].size()};
    gr[x].push_back(m1);
    gr[y].push_back(m2);
}

bool bfs(int start, int dest) {
    fill(niv.begin(), niv.end(), -1);
    queue<int> q;
    q.push(start);
    niv[start] = 0;

    while (!q.empty()) {
        int nod = q.front();
        q.pop();

        for (auto it : gr[nod]) {
            if (it.cap && niv[it.to] == -1) {
                niv[it.to] = niv[nod] + 1;
                q.push(it.to);
            }
        }
    }
    return niv[dest] != -1;
}

int dfs(int nod_crt, int dest, int cant_crt) {
    if (nod_crt == dest || cant_crt == 0) {
        return cant_crt;
    }

    for (int &ind = ptr[nod_crt]; ind < (int)gr[nod_crt].size(); ind++) {
        muchie &m = gr[nod_crt][ind];
        if (m.cap > 0 && niv[m.to] == niv[nod_crt] + 1) {
            int tr = dfs(m.to, dest, min(cant_crt, m.cap));
            if (tr) {
                m.cap -= tr;
                gr[m.to][m.ind_rev].cap += tr;
                return tr;
            }
        }
    }
    return 0;
}


int dinic(int start, int dest) {
    int flow = 0;
    while (bfs(start, dest)) {
        fill(ptr.begin(), ptr.end(), 0);
        while (int tr_crt = dfs(start, dest, INF)) {
            flow += tr_crt;
        }
    }
    return flow;
}

int main() {
    ios_base::sync_with_stdio(false);
    fin.tie(NULL);
    fout.tie(NULL);

    fin >> n >> m;

    while (m--) {
        fin >> a >> b >> c;
        add_mch(a, b, c);
    }

    fout << dinic(1, n);
    return 0;
}