Cod sursa(job #2916160)

Utilizator AlexNeaguAlexandru AlexNeagu Data 28 iulie 2022 11:49:39
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.02 kb
#include<bits/stdc++.h>
// #define int long long 
#define x first
#define y second 
using namespace std;

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

class MaxFlow {
    vector<vector<int>> capacity;
    vector<vector<int>> E;
    int nodes, s, t;
    const int INF = 2e9;
public:
    MaxFlow(int _nodes) : s(1), t(_nodes), nodes(_nodes) {
        capacity.assign(nodes + 5, vector<int> (nodes + 5, 0));
        E.resize(nodes + 5);
    }
    void AddEdge(int u, int v, int cap) {
        capacity[u][v] = cap;
        E[u].push_back(v);
        E[v].push_back(u);
    }
    int bfs(vector<int> &par) {
        fill(par.begin(), par.end(), -1);
        par[s] = -INF;
        queue<pair<int,int>> Q;
        Q.push({s, INF});
        while(Q.size()) {
            auto [cur_node, cur_flow] = Q.front();
            Q.pop();
            for(auto it : E[cur_node]) {
                if(capacity[cur_node][it] && par[it] == -1) {
                    par[it] = cur_node;
                    int pushed_flow = min(cur_flow, capacity[cur_node][it]);
                    if(it == t) return pushed_flow;
                    Q.push({it, pushed_flow});
                }
            }
        }
        return 0;
    }
    int Compute_Flow() {
        int flow = 0, flow_pushed;
        vector<int> par(nodes + 1);
        while(flow_pushed = bfs(par)) {
            flow += flow_pushed;
            int cur_node = t;
            while(cur_node != s) {
                int prd = par[cur_node];
                capacity[prd][cur_node] -= flow_pushed;
                capacity[cur_node][prd] += flow_pushed;
                cur_node = prd;
            }
        }
        return flow;
    }
};

int n, m;

int32_t main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    in >> n >> m;
    MaxFlow Flow(n);
    for(int i = 0; i < m; ++i) {
        int u, v, cap;
        in >> u >> v >> cap; 
        Flow.AddEdge(u, v, cap); 
    }
    out << Flow.Compute_Flow() << '\n';
    return 0;
}