Cod sursa(job #3325700)

Utilizator Anul2024Anul2024 Anul2024 Data 26 noiembrie 2025 09:37:13
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin ("maxflow.in");
ofstream fout ("maxflow.out");
const int DIMN = 1000, DIMM = 5000;
struct mch
{
    int nod, pos;
};
mch t[DIMN + 1];
vector <mch> v[DIMN + 1];
int n, m, dp[DIMN + 1];
int c[2 * DIMM + 1];
queue <int> q;
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++)
        dp[i] = 0;
    dp[1] = 1e9;
    q.push (1);
    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, pos = v[nod][i].pos;
            if (!dp[vecin] && c[pos])
            {
                dp[vecin] = min (dp[nod], c[pos]);
                q.push (vecin);
                t[vecin] = {nod, pos};
            }
        }
    }
    return dp[n];
}
void add_flow (int val)
{
    int nod = n;
    while (nod != 1)
    {
        int pos = t[nod].pos;
        c[pos] -= val, c[pos ^ 1] += val;
        nod = t[nod].nod;
    }
}
void solve ()
{
    int sol = 0;
    while (bfs ())
    {
        sol += dp[n];
        add_flow (dp[n]);
    }
    fout << sol;
}
int main ()
{
    read ();
    solve ();
    return 0;
}