Cod sursa(job #1711227)

Utilizator cristian.caldareaCaldarea Cristian Daniel cristian.caldarea Data 30 mai 2016 20:35:12
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;

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

const int Nmax = 1003, Inf = 0x3f3f3f3f;

int n, m, flow, fmin;
int c[Nmax][Nmax], f[Nmax][Nmax], t[Nmax], viz[Nmax];
vector<int> G[Nmax];
queue<int> Q;

bool Bf();

int main()
{
    int x, y, z;

    fin >> n >> m;

    for ( int i = 1; i <= m; i++ )
    {
        fin >> x >> y >> z;
        c[x][y] += z;
        G[x].push_back(y);
        G[y].push_back(x);
    }

    while ( Bf() )
        for ( auto y : G[n] )
        {

            if (f[y][n] == c[y][n] || !viz[y])
                continue;
            t[n] = y;

            fmin = Inf;
            for (int i = n; i != 1; i = t[i])
                fmin = min(fmin, c[t[i]][i] - f[t[i] ][i]);

            if (fmin == 0)
                continue;

            for (int i = n; i != 1; i = t[i])
            {
                f[ t[i] ][i] += fmin;
                f[i][ t[i] ] -= fmin;
            }

            flow += fmin;
        }

    fout << flow;
    return 0;
}

bool Bf()
{
    int x;

    memset(viz, 0, sizeof(viz));

    viz[1] = 1;
    Q.push(1);

    while( !Q.empty() )
    {
        x = Q.front();
        Q.pop();
        if (x == n) continue;
        for ( auto y : G[x] )
            {
                if ( c[x][y] == f[x][y] || viz[y] )
                    continue;
                viz[y] = 1;
                Q.push(y);
                t[y] = x;
            }
    }

    return viz[n];
}