Cod sursa(job #3285838)

Utilizator verde.cristian2005Verde Flaviu-Cristian verde.cristian2005 Data 13 martie 2025 15:10:03
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.45 kb
#include <bits/stdc++.h>
#pragma GCC optimize("O3", "Ofast", "unroll-loops")

using namespace std;

using ll = long long;
// #define int ll
using pii = pair<int, int>;

const int MOD = 1e9 + 7;
const int INF = 1e9;
const int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1}; // N S E V
const int MAXN = 2e5 + 5;

int n, m;

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

    vector<Edge> e;
    vector<vector<int>> adj;
    vector<int> d;

    void init()
    {
        adj.resize(n + 1);
    }

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

    bool bfs(int s, int t)
    {
        d.assign(n + 1, INF);
        d[s] = 0;
        queue<int> q;
        q.push(s);
        while(!q.empty())
        {
            int u = q.front();
            q.pop();
            for(int y : adj[u])
            {
                if(e[y].c && d[e[y].v] == INF)
                {
                    d[e[y].v] = d[u] + 1;
                    q.push(e[y].v);
                }
            }
        }
        return d[t] != INF;
    }

    int dfs(int s, int t, int flow)
    {
        if(s == t)
            return flow;
        int rez = 0;
        for(int y : adj[s])
        {
            if(e[y].c && d[e[y].v] == d[s] + 1)
            {
                int newflow = dfs(e[y].v, t, min(e[y].c, flow));
                if(newflow)
                {
                    e[y].c -= newflow;
                    e[y ^ 1].c += newflow;
                    rez += newflow;
                    flow -= newflow;
                    if(!flow)
                        break;
                    //return newflow;
                }
                else {
                    d[e[y].v] = 0;
                }
            }
        }
        return rez;
    }

    int maxflow(int s, int t)
    {
        int ans = 0;
        int x;
        while(bfs(s, t))
        {
            while(x = dfs(s, t, INF))
                ans += x;
        }
        return ans;
    }
};

Dinic mf;

int32_t main()
{
    #ifndef LOCAL
        ifstream cin("maxflow.in");
        ofstream cout("maxflow.out");
    #endif
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin >> n >> m;
    mf.init();
    for(int i = 1; i <= m; i++)
    {
        int u, v, c;
        cin >> u >> v >> c;
        mf.add_edge(u, v, c);
    }
    cout << mf.maxflow(1, n);
    return 0;
}