Cod sursa(job #3197618)

Utilizator stefan05Vasilache Stefan stefan05 Data 27 ianuarie 2024 10:59:09
Problema Flux maxim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <fstream>
#include <climits>
#include <vector>
#include <queue>

#define NMAX 1005
#define INF INT_MAX

using namespace std;

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

int n, m;
int x, y, c;
vector<int> l[NMAX];
int src, dest;
int ans;
int niv[NMAX], f[NMAX];
int mat[NMAX][NMAX];
int i, j;

bool flux(int);
int dfs(int, int);
void bfs(int);

int main()
{
    fin >>n>>m;
    for (i = 1; i <= m; ++i)
    {
        fin >>x>>y>>c;

        l[x].push_back(y);
        mat[x][y] = c;

        l[y].push_back(x);
    }

    src = 1; dest = n;
    while (flux(src));

    fout <<ans<<'\n';
    fout.close();
    return 0;
}

bool flux(int nod)
{
    bfs(nod);

    if (niv[dest] == -1)
        return 0;

    int anscrt = 0;
    while(1)
    {
        int x = dfs(1, INF);
        if (!x)
            break;
        anscrt += x;
    }
    ans += anscrt;
    return (anscrt != 0);
}

int dfs(int vf, int minim)
{
    if (vf == n || minim == 0)
        return minim;

    while (f[vf] < l[vf].size())
    {
        int vfnou = l[vf][f[vf]];
        if (mat[vf][vfnou] > 0 && niv[vf]+1 == niv[vfnou])
        {
            int x = dfs(vfnou, min(minim, mat[vf][vfnou]));
            if (x > 0)
            {
                mat[vf][vfnou] -= x;
                mat[vfnou][vf] += x;
                return x;
            }
            else
                f[vf] ++;
        }
        else
            f[vf] ++;
    }

    return 0;
}

void bfs(int nod)
{
    for (int i = 1; i <= n; ++i)
        niv[i] = -1, f[i] = 0;

    queue<int> q;
    niv[nod] = 0; q.push(nod);
    while (!q.empty())
    {
        int vf = q.front(); q.pop();
        for (auto vfnou: l[vf])
            if (niv[vfnou] == -1 && mat[vf][vfnou] > 0)
            {
                niv[vfnou] = niv[vf] + 1;
                q.push(vfnou);
            }
    }
}