Cod sursa(job #2679159)

Utilizator irimia_alexIrimia Alex irimia_alex Data 29 noiembrie 2020 18:42:51
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.06 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 1005

using namespace std;

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

struct edge {
    int u, capacity, flow = 0, r;
};

struct p {
    int u, i;
};

vector<edge> g[NMAX];
p parent[NMAX];
int n;

int augment(int u) {
    int min_flow = 1e9;
    int v = u;
    /*while (v != 0) {
        cout << v << ' ';
        v = parent[v].u;
    }
    cout << '\n';
    v = u;*/
    while (parent[v].u != 0) {
        const auto& p = parent[v];
        const auto& e = g[p.u][p.i];
        if (e.capacity - e.flow < min_flow) min_flow = e.capacity - e.flow;
        v = parent[v].u;
    }

    v = u;
    while (parent[v].u != 0) {
        const auto& p = parent[v];
        auto& e = g[p.u][p.i];
        e.flow += min_flow;
        g[e.u][e.r].flow -= min_flow;
        v = parent[v].u;
    }

    return min_flow;
}

int bfs(int u) {
    int flow = 0;
    bool viz[NMAX] = { 0 };
    queue<int> q;
    q.push(u);
    parent[u] = { 0,-1 };
    viz[u] = true;

    while (!q.empty()) {
        u = q.front();
        q.pop();
        for (int i = 0;i < g[u].size();++i) {
            const auto& v = g[u][i];
            if (viz[v.u] == false && v.flow < v.capacity) 
                if (v.u != n) {
                    viz[v.u] = true;
                    parent[v.u] = { u,i };
                    q.push(v.u);
                }
                else {
                    parent[n] = { u,i };
                    flow += augment(n);
                }
        }
    }
    return flow;
}

int max_flow() {
    int flow = 0, f;
    while ((f = bfs(1)) != 0) {
        flow += f;
    }

    return flow;
}

void read() {
    int m;
    fin >> n >> m;

    while (m--) {
        int u, v, c;
        fin >> u >> v >> c;
        g[u].push_back({ v,c,0,(int)g[v].size() });
        g[v].push_back({ u,0,0,(int)g[u].size() - 1 });
    }
}

int main() {
    
    read();

    fout << max_flow();

    return 0;
}