Cod sursa(job #3281510)

Utilizator rastervcrastervc rastervc Data 1 martie 2025 22:03:10
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
//edmonds karp cu capacity scaling poate merge
#include <bits/stdc++.h>

using namespace std;

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

constexpr int LIM = 1005;
int N, M, s, t, u, v, cap[LIM][LIM], p[LIM], scale;

bool find_augmenting_path() {
    fill_n(p + 1, N, 0);
    queue<int> q({ s });
    p[s] = 1;

    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int i = 1; i <= N; ++i)
            if (!p[i] && cap[u][i] >= scale) {
                q.push(i);
                p[i] = u;
                if (i == t) return true;
            }
    }

    return false;
}

int main() {
    fin >> N >> M;
    for (int i = 1; i <= M; ++i) {
        fin >> u >> v;
        fin >> cap[u][v];
    }

    s = 1, t = N;

    long long max_flow = 0;
    for (scale = (1 << 20); scale; scale >>= 1) {
        while (find_augmenting_path()) {
            int flow = 2e9;
            for (u = t; u != s; u = p[u])
                flow = min(flow, cap[p[u]][u]);
            for (u = t; u != s; u = p[u]) {
                cap[p[u]][u] -= flow;
                cap[u][p[u]] += flow;
            }
            max_flow += flow;
        }
    }

    

    fout << max_flow;

    fin.close();
    fout.close();
    return 0;
}