Cod sursa(job #3298377)

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

using namespace std;

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

int n, m;

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

    vector<Edge> e;
    vector<int> adj[MAXN];
    bool visited[MAXN];
    int depth[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, 0});
    }

    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(depth[e[v0].v] == depth[u] + 1 && (newd = flow(e[v0].v, min(d, e[v0].c))))
            {
                e[v0].c -= newd;
                e[v0 ^ 1].c += newd;
                return newd;
            }
        }
        return 0;
    }

    bool canbfs(int s, int t)
    {
        for(int i = 1; i <= n; i++)
            visited[i] = false;
        queue<int> q;
        q.push(s);
        visited[s] = true;
        while(!q.empty())
        {
            int u = q.front();
            q.pop();
            for(int v0 : adj[u])
            {
                int v = e[v0].v;
                if(visited[v] || e[v0].c <= 0)
                    continue;
                visited[v] = true;
                depth[v] = depth[u] + 1;
                q.push(v);
            }
        }
        return visited[t];
    }

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

DINIC dinic;

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;
}