Cod sursa(job #3376417)

Utilizator Carnu_EmilianCarnu Emilian Carnu_Emilian Data 17 noiembrie 2026 17:03:25
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.2 kb
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
typedef long long ll;

const int N = 1e3 + 5;
int n, m, ans;

struct Flow
{
    vector<int> adj[N];
    int c[N][N], source, destination, d[N], ind[N];

    void AddEdge(int u, int v, int w)
    {
        adj[u].push_back(v);
        adj[v].push_back(u);
        c[u][v] = w;
    }

    void ResetD()
    {
        for (int &i : d)
        {
            i = 1e9;
        }
    }

    void BFS()
    {
        ResetD();
        d[source] = 0;
        queue<int> q;
        q.push(source);
        while (!q.empty())
        {
            int node = q.front();
            q.pop();
            for (int i : adj[node])
            {
                if (d[i] > d[node] + 1 && c[node][i] != 0)
                {
                    d[i] = d[node] + 1;
                    q.push(i);
                }
            }
        }
    }

    int DFS(int node, int pushed)
    {
        if (node == destination)
        {
            return pushed;
        }
        for (; ind[node] < adj[node].size(); ind[node]++)
        {
            int v = adj[node][ind[node]];
            if (d[node] + 1 == d[v] && c[node][v] != 0)
            {
                int x = DFS(v, min(pushed, c[node][v]));
                if (x > 0)
                {
                    c[node][v] -= x;
                    c[v][node] += x;
                    return x;
                }
            }
        }
        return 0;
    }

    void Solve()
    {
        while (true)
        {
            BFS();
            if (d[destination] == 1e9)
            {
                break;
            }
            for (int &i : ind)
            {
                i = 0;
            }
            while (true)
            {
                int a = DFS(source, 1e9);
                if (a == 0)
                {
                    break;
                }
                ans += a;
            }
        }
    }
} flow;

signed main()
{
    fin >> n >> m;
    while (m--)
    {
        int a, b, c;
        fin >> a >> b >> c;
        flow.AddEdge(a, b, c);
    }
    flow.source = 1;
    flow.destination = n;
    flow.Solve();
    fout << ans;
    return 0;
}