Cod sursa(job #2699176)

Utilizator cristina_borzaCristina Borza cristina_borza Data 23 ianuarie 2021 19:23:18
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <bits/stdc++.h>

using namespace std;

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

int c[1005][1005], flow[1005][1005], t[1005];
int n, m, maxFlow;

queue<int> coada;
vector<int> G[1005], GRev[1005];

bool bfs() {
    memset(t, 0, sizeof(t));
    t[1] = -1;
    coada.push(1);

    while(!coada.empty()) {
        int node = coada.front();
        coada.pop();

        for(auto it = G[node].begin(); it != G[node].end(); ++it) {
            if(t[*it] == 0 && flow[node][*it] < c[node][*it]) {
                t[*it] = node;
                coada.push(*it);
            }
        }

        for(auto it = GRev[node].begin(); it != GRev[node].end(); ++it) {
            if(t[*it] == 0 && flow[node][*it] > 0) {
                t[*it] = node;
                coada.push(*it);
            }
        }
    }

    return (t[n] != 0);
}

int main() {
    f >> n >> m;
    for(int i = 1; i <= m; ++i) {
        int x, y, capacitate;
        f >> x >> y >> capacitate;

        G[x].push_back(y);
        GRev[y].push_back(x);
        c[x][y] = capacitate;
    }

    while(bfs()) {
        int u = t[n];
        int val = c[u][n] - flow[u][n];
        while(u != 1) {
            if(c[t[u]][u] == 0) val = min(val, flow[t[u]][u]);
            else val = min(val, c[t[u]][u] - flow[t[u]][u]);
            u = t[u];
        }

        u = t[n];
        flow[u][n] += val;
        while(u != 1) {
            if(c[t[u]][u] == 0) flow[t[u]][u] -= val;
            else flow[t[u]][u] += val;
            u = t[u];
        }

        maxFlow += val;
    }

    g << maxFlow << '\n';
    return 0;
}