Cod sursa(job #3359474)

Utilizator Carnu_EmilianCarnu Emilian Carnu_Emilian Data 28 iunie 2026 23:15:17
Problema Flux maxim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.55 kb
#pragma optimize("Ofast")
#pragma 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 = 1e2 + 5;
int n, m;

struct MaxFlow
{
    int n;
    bool oprit;
    queue<int> q;
    vector<int> ad[N], t[N];
    int p[N], d[N];
    int cap[N][N]; /// cap[i][j] = cat flux putem sa pusham pe muchia i j
    bool viz[N];
    int sursa, destinatie;
    void AddEdge(int x, int y, int c)
    {
        ad[x].push_back(y);
        ad[y].push_back(x);
        t[y].push_back(x);
        cap[x][y] = c;
    }
    void BFS(int nod)
    {
        q.push(nod);
        d[nod] = 0;
        while (!q.empty())
        {
            int i = q.front();
            q.pop();
            for (int x : t[i])
                if (cap[x][i] > 0 && d[x] > d[i] + 1)
                {
                    d[x] = d[i] + 1;
                    q.push(x);
                }
        }
    }
    void DFS(int nod)
    {
        viz[nod] = true;
        for (int i : ad[nod])
            if (!viz[i] && d[nod] == d[i] + 1 && cap[nod][i] > 0)
            {
                p[i] = nod;
                DFS(i);
                if (oprit)
                    break;
            }
        if (nod == destinatie)
            oprit = true;
    }
    int Saturate()
    {
        int minn = INT_MAX;
        int copyDest = destinatie;
        while (copyDest != sursa)
        {
            minn = min(minn, cap[p[copyDest]][copyDest]);
            copyDest = p[copyDest];
        }
        copyDest = destinatie;
        while (copyDest != sursa)
        {
            cap[p[copyDest]][copyDest] -= minn;
            cap[copyDest][p[copyDest]] += minn;
            copyDest = p[copyDest];
        }
        return minn;
    }

    bool CanAchieve()
    {
        oprit = false;
        for (int i = 1; i <= n; i++)
            d[i] = 1e9;
        for (int i = 1; i <= n; i++)
            viz[i] = false;
        BFS(destinatie);
        DFS(sursa);
        return viz[destinatie];
    }

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

    MaxFlow(int s, int d, int _n)
    {
        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;
}