Cod sursa(job #3323168)

Utilizator Anul2024Anul2024 Anul2024 Data 17 noiembrie 2025 13:36:12
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin ("maxflow.in");
ofstream fout ("maxflow.out");
const int DIM = 1000, DIMM = 5000;
struct muchie
{
    int nod, pos;
};
muchie t[DIM + 1];
vector <muchie> v[DIM + 1];
int n, m, dp[DIM + 1];
queue <int> q;
int c[2 * DIMM + 1];
void read ()
{
    int x, y, p;
    fin >> n >> m;
    for (int i = 0; i < m; i++)
    {
        fin >> x >> y >> p;
        v[x].push_back ({y, 2 * i});
        v[y].push_back ({x, 2 * i + 1});
        c[2 * i] = p, c[2 * i + 1] = 0;
    }
}
bool bfs ()
{
    for (int i = 1; i <= n; i++)
        t[i] = {0, 0}, dp[i] = 0;
    q.push (1);
    dp[1] = 1e9;
    while (!q.empty ())
    {
        int nod = q.front ();
        q.pop ();
        for (int i = 0; i < (int) v[nod].size (); i++)
        {
            int vecin = v[nod][i].nod;
            int pos = v[nod][i].pos;
            if (dp[vecin] == 0 && c[pos])
            {
                t[vecin] = {nod, pos};
                q.push (vecin);
                dp[vecin] = min (c[pos], dp[nod]);
            }
        }
    }
    return dp[n];
}
void add_flux (int flux)
{
    int nod = n;
    while (nod != 1)
    {
        c[t[nod].pos] -= flux;
        c[t[nod].pos ^ 1] += flux;
        nod = t[nod].nod;
    }
}
void solve ()
{
    /**
    Gasim un drum de augmentare. Sacdem din muchii fluxul nou gasit. Facem cat timp fluxul > 0.
    **/
    int sol = 0;
    while (bfs ())
    {
        int flux = dp[n];
        add_flux (flux);
        sol += flux;
    }
    fout << sol;
}
int main ()
{
    read ();
    solve ();
    return 0;
}