Cod sursa(job #2693964)

Utilizator usureluflorianUsurelu Florian-Robert usureluflorian Data 7 ianuarie 2021 18:35:38
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f ("maxflow.in");
ofstream g ("maxflow.out");

const int nmax = 1e3 + 3;

int n, m, act, ant[nmax], usu[nmax][nmax], p[nmax][nmax], sol, a, b, c, ok;
bool viz[nmax];

vector <int> v[nmax];
queue <int> q;

int flux()
{
    q.push(1);
    viz[1] = 1;
    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        if(nod == n) continue;

        for(int i = 0; i < v[nod].size(); ++i)
        {
            int urm = v[nod][i];
            if (viz[urm] || usu[nod][urm] == p[nod][urm]) continue;

            viz[urm] = 1;
            q.push(urm);
            ant[urm] = nod;
        }
    }

    return viz[n];
}

int main()
{
    ios::sync_with_stdio(false);
    f >> n >> m;
    while (m--)
    {
        f >> a >> b >> c;

        v[a].push_back(b);
        v[b].push_back(a);

        usu[a][b] += c;
    }

    ok = 1;
    while (ok)
    {
        memset(viz, 0, sizeof(viz));
        ok = flux();

        for (int i = 0; i < v[n].size(); ++i)
        {
            int nod = v[n][i];
            if (usu[nod][n] == p[nod][n] || !viz[nod]) continue;
            ant[n] = nod;
            nod = n;
            act = 2e9;

            while (nod != 1)
            {
                act = min (act, usu[ant[nod]][nod] - p[ant[nod]][nod]);
                nod = ant[nod];
            }

            if (!act) continue;
            nod = n;

            while (nod != 1)
            {
                p[ant[nod]][nod] += act;
                p[nod][ant[nod]] -= act;
                nod = ant[nod];
            }

            sol += act;
        }
    }

    g << sol;

    return 0;
}