Cod sursa(job #2946330)

Utilizator verde.cristian2005Verde Flaviu-Cristian verde.cristian2005 Data 24 noiembrie 2022 19:12:21
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.05 kb
#include <bits/stdc++.h>
using namespace std;

struct Dinic{
    struct Edge{
        int from, to, cap, flow, ult;
    };
    int n;
    vector <Edge> es;
    vector <int> last, dist;
    queue <int> q;
    Dinic(int n)
    {
        this->n = n;
        last.assign(n + 1, -1);
    }

    void baga(int a, int b, int c)
    {
        es.push_back({a, b, c, 0, last[a]});
        last[a] = es.size() - 1;
        es.push_back({b, a, 0, 0, last[b]});
        last[b] = es.size() - 1;
    }

    bool bfs(int s, int t)
    {
        dist.assign(n + 1, -1);
        dist[s] = 0;
        q.push(s);
        while(q.size())
        {
            int a = q.front();
            q.pop();
            for(auto x = last[a]; x != -1; x = es[x].ult)
            {
                auto e = es[x];
                if(e.cap > e.flow && dist[e.to] == -1)
                {
                    dist[e.to] = dist[e.from] + 1;
                    q.push(e.to);
                }
            }
        }
        return (dist[t] != -1);
    }

    int dfs(int s, int t, int cat)
    {
        if(s == t)
            return cat;
        int rez = 0;
        for(auto x = last[s]; x != -1; x = es[x].ult)
        {
            auto e = es[x];
            if(e.cap > e.flow && dist[e.to] == dist[e.from] + 1)//Dinic
            {
                int trimis = dfs(e.to, t, min(cat, e.cap - e.flow));
                rez += trimis;
                cat -= trimis;
                es[x].flow += trimis;
                es[x^1].flow -= trimis;
            }
        }
        return rez;
    }

    int fluxmax(int s, int t)
    {
        int rez = 0;
        while(bfs(s, t))
            rez += dfs(s, t, INT_MAX);
        return rez;
    }
};

int main()
{
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);
    int n, m, a, b, c;
    cin >> n >> m;
    Dinic g(n);
    for(int i = 1; i <= m; i++)
    {
        cin >> a >> b >> c;
        g.baga(a, b, c);
    }
    cout << g.fluxmax(1, n);
    return 0;
}