Cod sursa(job #3298370)

Utilizator Turcanu_DavidTurcanu David Turcanu_David Data 29 mai 2025 09:57:13
Problema Flux maxim Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1005;
const int INF = 1e9;
using pii = pair<int, int>;

struct DINIC
{
    struct Edge
    {
        int u, v, c;
    };

    vector<Edge> e;
    vector<int> adj[MAXN];

    void add_edge(int u, int v, int c)
    {
        adj[u].push_back(e.size());
        e.push_back({u, v, c});
        adj[v].push_back(e.size());
        e.push_back({v, u, -c});
    }

    int t1;

    int flow(int u, int d)
    {
        if(d <= 0)
            return 0;
        if(u == t1)
            return max(d, 0);
        for(int v0 : adj[u])
        {
            int newd;
            if(newd = flow(e[v0].v, min(d, e[v0].c)))
            {
//            cerr << u << ' ' << e[v0].v << ' ' << e[v0].c << '\n';
                e[v0].c -= newd;
                e[v0 ^ 1].c += newd;
                return newd;
            }
        }
        return 0;
    }

    int dinic(int s, int t)
    {
        t1 = t;
        int ans = 0;
        int x;
        while(x = flow(s, INF))
        {
            ans += x;
        }
        return ans;
    }
};

DINIC dinic;

int n, m;

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