Cod sursa(job #2954363)

Utilizator T_george_TGeorge Teodorescu T_george_T Data 14 decembrie 2022 01:17:21
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <vector>
#include <fstream>
#include <queue>
#include <string.h>

using namespace std;

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

const int NMAX = 1e3 + 10;

int n, m, cap[NMAX][NMAX], seen[NMAX], f[NMAX][NMAX], father[NMAX];

vector<int> g[NMAX];

int bf() {
    queue<int> q;
    memset(seen, 0, sizeof(seen));

    q.push(1);
    seen[1] = 1;
    while (!q.empty()) {
        int node = q.front();
        q.pop();
        if (node == n)
            continue;
        for (int next: g[node]) {
            if (cap[node][next] == f[node][next] || seen[next])
                continue;
            seen[next] = 1;
            q.push(next);
            father[next] = node;

        }
    }

    return seen[n];
}

int main() {

    in >> n >> m;

    for (int i = 1, a, b, c; i <= m; i++) {
        in >> a >> b >> c;
        g[a].push_back(b);
        g[b].push_back(a);
        cap[a][b] = c;
    }
    int flow = 0;
    while (bf())
        for (int node: g[n]) {
            int fmin = 2e9;

            if (f[node][n] == cap[node][n] || !seen[node])
                continue;
            father[n] = node;
            for (int node = n; node != 1; node = father[node]) {
                fmin = min(fmin, cap[father[node]][node] - f[father[node]][node]);
            }
            if (fmin == 0)
                continue;
            for (int node = n; node != 1; node = father[node]) {
                f[father[node]][node] += fmin;
                f[node][father[node]] -= fmin;
            }
            flow += fmin;
        }

    out << flow;

    return 0;
}