Cod sursa(job #858981)

Utilizator Theorytheo .c Theory Data 19 ianuarie 2013 16:31:26
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include<fstream>
#include<vector>
#include<cstring>
#include<deque>

using namespace std;

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

#define NMAX (1<<10)
#define make_pair mp
#define pb push_back

int TT[NMAX], F[NMAX][NMAX], C[NMAX][NMAX];
int N, M, flow;

deque<int> q;

vector <int> G[NMAX];

bool viz[NMAX];

void Read() {

    fin >>N >>M;
    for(int i = 1; i <= M; ++i) {
        int x, y, cost;

        fin >>x >> y>> cost;
        C[x][y] = cost;
        G[x].pb(y);
        G[y].pb(x);
    }
}

bool BFS() {

    for(int i = 0 ;i <= N; i++) viz[i] = false;


    q.push_back(1);
    viz[1] = true;

    while(!q.empty()) {

        int nod = q.front();
        q.pop_front();

        if(nod == N) continue;

        for(int i = 0 ;i < G[nod].size(); i++) {

            int x = G[nod][i];
            if(F[nod][x] == C[nod][x] || viz[x] == true) continue;

            q.push_back(x);
            viz[x] = true;
            TT[x] = nod;
        }
    }
    return viz[N];
}

int Solve() {


    for(flow = 0; BFS() ; ){
        int fmin = 1<<30;
        for(int i = 0; i < G[N].size(); ++i) {

            int x  = G[N][i];
            if(F[x][N] == C[x][N] || viz[x] == false ) continue;

            TT[N] = x;

            for(int j = N; j != 1; j = TT[j] )
                fmin = min(fmin, C[TT[j]][j] - F[TT[j]][j]);

            if(fmin == 0) continue;

            for(int j = N ; j != 1; j = TT[j]) {

                F[TT[j]][j] += fmin;
                F[j][TT[j]] -= fmin;
            }

            flow += fmin;

        }
    }
    return flow;
}
int main() {

    Read ();

    fout << Solve ();

    return 0;
}