Cod sursa(job #2900266)

Utilizator ptudortudor P ptudor Data 10 mai 2022 17:26:58
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>
using namespace std;

#ifdef LOCAL
ifstream in("in.in");
ofstream out("out.out");
#else
ifstream in("maxflow.in");
ofstream out("maxflow.out");
#endif
const int nmax = 1005;
int n,m,cap[nmax][nmax],flow[nmax][nmax];
vector<vector<int>> g;
const int inf = 1000000005;

int find_augmenting_path() {
    queue<int> q;
    vector<int> viz(n + 1, 0);
    vector<int> path(n + 1, 0);
    q.push(1);
    while(!q.empty()) {
        int node = q.front();
        q.pop();

        for (auto k : g[node]) {
            if (viz[k] == 0 && cap[node][k] > flow[node][k]) {
                viz[k] = 1;
                path[k] = node;
                q.push(k);
            }
        }
    }

    if (viz[n] == 0) {
        return -1;
    }

    int node = n,bottle_neck = inf;
    while(node != 1) {
        int from = path[node];
        bottle_neck = min(bottle_neck , cap[from][node] - flow[from][node]);
        node = from;
    }

    node = n;
    while(node != 1) {
        int from = path[node];
        flow[from][node] += bottle_neck;
        flow[node][from] -= bottle_neck;
        node = from;
    }

    return bottle_neck;
}
int maxflow() {
    int added_flow,total_flow = 0;
    while(true) {
        int added_flow = find_augmenting_path();
        if (added_flow == -1) {
            return total_flow;
        } else {
            total_flow += added_flow;
        }
    }
}
int main() {
    in >> n >> m;

    g.resize(n + 1);
    for (int i = 1; i <= m; i++) {
        int u,v,c;
        in >> u >> v >> c;
        g[u].push_back(v);
        g[v].push_back(u);
        cap[u][v] += c;
    }

    out << maxflow() << "\n";
}