Cod sursa(job #3358970)

Utilizator Carnu_EmilianCarnu Emilian Carnu_Emilian Data 22 iunie 2026 14:21:05
Problema Flux maxim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 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 = 1e3 + 5;
int n, m;

struct MaxFlow
{
    int n;
    vector<int> ad[N];
    int p[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);
        cap[x][y] = c;
    }
    void DFS(int nod)
    {
        viz[nod] = true;
        for (int i : ad[nod])
            if (!viz[i] && cap[nod][i] > 0)
            {
                p[i] = nod;
                DFS(i);
            }
    }
    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()
    {
        for (int i = 1; i <= n; i++)
            viz[i] = false;
        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;
}