Cod sursa(job #984155)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 13 august 2013 17:46:32
Problema Flux maxim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
#include <cstring>

using namespace std;

#define Nmax 1005
#define Mmax 5005
#define INF 0x3f3f3f

vector <int> G[Nmax];
int TT[Nmax], viz[Nmax];
queue <int> Q;
int C[Nmax][Nmax], F[Nmax][Nmax];

int N, M;

void read()
{
    ifstream f("maxflow.in");

    f >> N >> M;

    for ( int i = 1, a, b, c; i <= M; ++i )
    {
        f >> a >> b >> c;

        C[a][b] = c;

        G[a].push_back( b );
    }

    f.close();
}
int BF()
{
    int i, j, nod, V;

    Q.push( 1 );
    memset(viz, 0, sizeof(viz));
    viz[1] = 1;

    for (; !Q.empty(); )
    {
        nod = Q.front();
        Q.pop();
        for (j = 0; j < G[nod].size(); j++)
            {
                V = G[nod][j];
                if (C[nod][V] == F[nod][V] || viz[V]) continue;
                viz[V] = 1;
                Q.push( V );
                TT[V] = nod;
                if (V == N) return 1;
            }
    }

    return 0;
}


int Ford_Fulkerson( int sourse, int destination )
{
    int flow, fmin, nod;

    for (flow = 0; BF(); flow += fmin)
    {
        fmin = INF;
        for (nod = N; nod != 1; nod = TT[nod])
            fmin = min(fmin, C[ TT[nod] ][nod] - F[ TT[nod] ][nod]);
        for (nod = N; nod != 1; nod = TT[nod])
        {
            F[ TT[nod] ][nod] += fmin;
            F[nod][ TT[nod] ] -= fmin;
        }
    }

    return flow;
}

void print()
{
    ofstream g("maxflow.out");

    g << Ford_Fulkerson( 1, N ) << "\n";

    g.close();
}

int main()
{
    read();
    print();

    return 0;
}