Cod sursa(job #2643752)

Utilizator ardutgamerAndrei Bancila ardutgamer Data 21 august 2020 13:19:40
Problema Flux maxim Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.23 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>

using namespace std;

ifstream fin("maxflow.in");
ofstream fout("maxflow.out");

typedef long long LL;
const LL INF = 1e17;
const LL dim = 1005;

struct Muchie {
    LL pana, de;
    LL cap, f = 0;
    Muchie(LL pana, LL de, LL cap) : pana(pana), de(de), cap(cap) {}
};

vector<Muchie> g[dim];
LL q[dim], dist[dim], poz[dim];
LL nr_noduri, sursa, dest;
queue<LL> coada;

void adaugaMuchie(LL de_la, LL pana, LL cap)
{
    g[de_la].push_back(Muchie(pana, (LL)g[pana].size(), cap));
    g[pana].push_back(Muchie(de_la, (LL)g[de_la].size() - 1, 0));
}

bool bfs()
{
    for (LL i = 0; i < nr_noduri; ++i)
        dist[i] = -1;
    dist[sursa] = 0;

    coada.push(sursa);
    while (!coada.empty())
    {
        LL v = coada.front();
        coada.pop();
        for (Muchie e : g[v])
            if (e.f < e.cap && dist[e.pana] == -1)
            {
                dist[e.pana] = dist[v] + 1;
                coada.push(e.pana);
            }
    }
    return dist[dest] != -1;
}

LL dfs(LL v, LL flux)
{
    if (v == dest)
        return flux;
    for (LL& i = poz[v]; i < (LL)g[v].size(); ++i)
    {
        Muchie& e = g[v][i];
        if (e.f < e.cap && dist[e.pana] == dist[v] + 1)
        {
            LL df = dfs(e.pana, min(flux, e.cap - e.f));
            if (df > 0)
            {
                e.f += df;
                g[e.pana][e.de].f -= df;
                return df;
            }
        }
    }
    return 0;
}

LL maxFlow()
{
    LL flux = 0, df; /// df este valoarea cu care pot creste fluxul
    LL i;
    while (bfs())
    {
        for (i = 0; i < nr_noduri; ++i)
            poz[i] = 0;
        while (df = dfs(sursa, INF))
            flux += df;
    }
    return flux;
}

LL n, m, x;
LL de_la[1005], pana[1005], cap[1005];

int main()
{
    LL i;

    fin >> n >> m;

    nr_noduri = n;
    sursa = 0;
    dest = n - 1;

    for (i = 0; i < m; ++i) {
        fin >> de_la[i] >> pana[i] >> cap[i],
            --de_la[i],
            --pana[i];
        adaugaMuchie(de_la[i], pana[i], cap[i]);
    }
        


    fout << maxFlow() << "\n";



    return 0;
}