Cod sursa(job #3359529)

Utilizator Carnu_EmilianCarnu Emilian Carnu_Emilian Data 29 iunie 2026 16:37:24
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.28 kb
#pragma GCC optimize("Ofast")
// #pragma GCC target("avx2")
#include <bits/stdc++.h>
using namespace std;
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;

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

struct MaxFlow
{
    int n, m;
    queue<int> q;
    vector<int> ad[N];
    int p[N], d[N];
    pair<int, int> cap[M];
    int sursa, destinatie;
    void AddEdge(int x, int y, int c)
    {
        m++;
        cap[2 * m] = {0, x};
        cap[2 * m + 1] = {c, y};
        ad[y].push_back(2 * m);
        ad[x].push_back(2 * m + 1);
    }
    bool BFS()
    {
        for (int i = 1; i <= n; i++)
            d[i] = 1e9;
        while (!q.empty())
            q.pop();
        q.push(sursa);
        d[sursa] = 0;
        while (!q.empty())
        {
            int i = q.front();
            q.pop();
            for (int x : ad[i])
                if (cap[x].first > 0 && d[cap[x].second] > d[i] + 1)
                {
                    d[cap[x].second] = d[i] + 1;
                    q.push(cap[x].second);
                    p[cap[x].second] = x;
                    if (cap[x].second == destinatie)
                        return true;
                }
        }
        return d[destinatie] != 1e9;
    }

    int Saturate()
    {
        int minn = INT_MAX;
        int copyDest = destinatie;
        while (copyDest != sursa)
        {
            minn = min(minn, cap[p[copyDest]].first);
            copyDest = cap[p[copyDest] ^ 1].second;
        }
        copyDest = destinatie;
        while (copyDest != sursa)
        {
            cap[p[copyDest]].first -= minn;
            cap[p[copyDest] ^ 1].first += minn;
            copyDest = cap[p[copyDest] ^ 1].second;
        }
        return minn;
    }

    int Solve()
    {
        int ans = 0;
        while (BFS())
        {
            ans += Saturate();
        }
        return ans;
    }

    MaxFlow(int s, int d, int _n)
    {
        m = 0;
        n = _n;
        sursa = s;
        destinatie = d;
        memset(cap, 0, sizeof(cap));
    }
};


signed main()
{
    fin >> n >> m;
    MaxFlow flow(1, n, n);
    while (m--)
    {
        int x, y, c;
        fin >> x >> y >> c;
        flow.AddEdge(x, y, c);
    }
    fout << flow.Solve();
    return 0;
}