Cod sursa(job #2873479)

Utilizator Mirela_MagdalenaCatrina Mirela Mirela_Magdalena Data 19 martie 2022 10:41:04
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>

using namespace std;

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

#define NMAX 1005
#define INF ((1<<30)-1)

int n, m, flow[NMAX][NMAX], cap[NMAX][NMAX], tata[NMAX], flow_max;
bitset<NMAX> viz;
vector<int> G[NMAX];
queue<int> q;

void citire() {
    f >> n >> m;
    int x, y, c;
    for (int i = 1; i <= m; ++i) {
        f >> x >> y >> c;
        cap[x][y] = c;
        G[x].push_back(y);
        G[y].push_back(x);
    }
}

void element_nou(int x) {
    viz[x] = true;
    if (x == n) return;
    for (auto& nod : G[x])
        if (!viz[nod] && flow[x][nod] < cap[x][nod]) {
            q.push(nod);
            tata[nod] = x;
        }
}

bool bfs() {
    viz.reset();
    q.push(1);
    tata[1] = 0;
    while (!q.empty()) {
        int x = q.front();
        q.pop();
        element_nou(x);
    }
    return viz[n];
}

void Edmonds_Karp() {
    while (bfs())
        for (auto& nod : G[n]) {
            if (!viz[nod] || flow[nod][n] == cap[nod][n])
                continue;

            int flow_max_cur = INF;
            tata[n] = nod;
            for (int x = n; tata[x]; x = tata[x])
                flow_max_cur = min(flow_max_cur, cap[tata[x]][x] - flow[tata[x]][x]);

            if (!flow_max_cur)
                continue;

            for (int x = n; tata[x]; x = tata[x]) {
                flow[tata[x]][x] += flow_max_cur;
                flow[x][tata[x]] -= flow_max_cur;
            }

            flow_max += flow_max_cur;
        }
}

int main() {
    citire();
    Edmonds_Karp();
    g << flow_max;
    return 0;
}