Cod sursa(job #2960975)

Utilizator TeoDiDiaconescu Teodora TeoDi Data 5 ianuarie 2023 14:45:42
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>

using namespace std;

// max flow algorithm
// O(V^2 * E)

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

int MaxFlow(vector<vector<int>> &cap, int s, int t) {
    int n = cap.size();
    vector<vector<int>> flow(n, vector<int>(n));
    int ans = 0;
    while (true) {
        vector<int> par(n, -1);
        par[s] = -2;
        queue<int> q;
        q.push(s);
        while (!q.empty() && par[t] == -1) {
            int u = q.front();
            q.pop();
            for (int v = 0; v < n; v++) {
                if (par[v] == -1 && cap[u][v] - flow[u][v] > 0) {
                    par[v] = u;
                    q.push(v);
                }
            }
        }
        if (par[t] == -1) {
            break;
        }
        int f = INT_MAX;
        for (int v = t; v != s; v = par[v]) {
            f = min(f, cap[par[v]][v] - flow[par[v]][v]);
        }
        for (int v = t; v != s; v = par[v]) {
            flow[par[v]][v] += f;
            flow[v][par[v]] -= f;
        }
        ans += f;
    }
    return ans;
}

int main()
{
    vector<vector<int>> cap;
    int n, m;
    fin >> n >> m;
    cap.resize(n);
    for (int i = 0; i < n; i++) {
        cap[i].resize(n);
    }
    for (int i = 0; i < m; i++) {
        int u, v, c;
        fin >> u >> v >> c;
        cap[u - 1][v - 1] = c;
    }
    fout << MaxFlow(cap, 0, n - 1) << endl;
    return 0;
}