Cod sursa(job #575131)

Utilizator AndrewTheGreatAndrei Alexandrescu AndrewTheGreat Data 7 aprilie 2011 22:32:17
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.65 kb
#include <fstream>
#include <vector>
#include <queue>
#include <string.h>
#define pb push_back
#define TR(C, i)\
    for(i = C.begin(); i != C.end(); i++)

using namespace std;

int N, M;
const int nmax = 1024;
vector<int> G[nmax];
int C[nmax][nmax], F[nmax][nmax];
int TT[nmax], viz[nmax];

void read()
{
    ifstream in ("maxflow.in");
    in >> N >> M;
    int i, a, b, c;
    for(i = 1; i <= M; i++)
    {
        in >> a >> b >> c;
        G[a].pb( b );
        G[b].pb( a );
        C[a][b] += c;
    }
}

queue <int> Q;

int BF()
{
    Q.push(1);
    int vf; memset(viz, 0, sizeof(viz));
    vector<int>::iterator it;

    while(!Q.empty())
    {
        vf = Q.front();
        Q.pop();

        if(vf == N) continue;

        TR(G[vf], it)
        {
            if(!viz[*it] && C[vf][*it] - F[vf][*it])
            {
                viz[*it] = 1;
                TT[*it] = vf;
                Q.push(*it);
            }
        }
    }
    return viz[N];
}

void solve()
{
    vector<int>::iterator it;
    int fmin, nod, flow;
    for(flow = 0; BF();)
        TR(G[N], it)
        {
            fmin = C[*it][N] - F[*it][N];
            for(nod = *it; nod != 1 && fmin; nod = TT[nod])
                fmin = min(fmin, C[TT[nod]][nod] - F[TT[nod]][nod]);

            if(!fmin) continue;

            TT[N] = *it;
            for(nod = N; nod != 1; nod = TT[nod])
                F[TT[nod]][nod] += fmin,
                F[nod][TT[nod]] -= fmin;

            flow += fmin;
        }
    ofstream out("maxflow.out");
    out<< flow << '\n';
}

int main()
{
    read();
    solve();
    return 0;
}