Cod sursa(job #2933209)

Utilizator Cosmin2004_InfoMoldoveanu Cosmin Cosmin2004_Info Data 4 noiembrie 2022 20:41:11
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.95 kb
#include <bits/stdc++.h>

using namespace std;
using ll = long long;
class Flow
{
    struct edge
    {
        int from, to, cap;
    };
    int n, s, t;
    vector <vector <int>> g;
    vector <int> lvl, rem;
    vector <edge> e;
public:
    Flow(int n, int s, int t) : n(n), s(s), t(t), g(n + 1), lvl(n + 1), rem(n + 1), e(0) {}
    void add_edge(int u, int v, int w)
    {
        g[u].push_back(e.size());
        e.push_back({u, v, w});
        g[v].push_back(e.size());
        e.push_back({v, u, 0});
    }
    bool bfs()
    {
        fill(lvl.begin(), lvl.end(), 0);
        lvl[s] = 1;
        queue <int> q;
        for(q.push(s); !q.empty(); q.pop()) {
            int u = q.front();
            for(int id : g[u]) {
                int v = e[id].to;
                if(e[id].cap && !lvl[v]) {
                    lvl[v] = lvl[u] + 1;
                    q.push(v);
                }
            }
        }
        return lvl[t];
    }
    int dfs(int u, int flow)
    {
        if(!flow || u == t) return flow;
        for(int& cid = rem[u]; cid < g[u].size(); cid++) {
            int id = g[u][cid];
            int v = e[id].to;
            if(lvl[v] != lvl[u] + 1 || !e[id].cap) continue;
            int f = dfs(v, min(flow, e[id].cap));
            if(!f) continue;
            e[id].cap -= f;
            e[id ^ 1].cap += f;
            return f;
        }
        return 0;
    }
    int dinic()
    {
        long long flow = 0;
        while(bfs())
        {
            fill(rem.begin(), rem.end(), 0);
            while(int f = dfs(s, 1e9))
                flow += f;
        }
        return flow;
    }
};

int main()
{
    ifstream cin("maxflow.in");
    ofstream cout("maxflow.out");
    int n, m;
    cin >> n >> m;
    Flow F(n, 1, n);
    for(int i = 0, u, v, w; i < m; i++) {
        cin >> u >> v >> w;
        F.add_edge(u, v, w);
    }
    cout << F.dinic();
    return 0;
}