Cod sursa(job #903422)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 1 martie 2013 20:38:48
Problema Flux maxim Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.29 kb
#include <cstdio>
#include <cstring>
#include <cassert>

#include <fstream>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>

using namespace std;

typedef long long LL;
typedef vector<int>::iterator it;

const int oo = 0x3f3f3f3f;
const int MAX_N = 1005;
const int NIL = -1;

vector<int> G[MAX_N];
int N, Father[MAX_N], Solution;
int Capacity[MAX_N][MAX_N], Flow[MAX_N][MAX_N];
queue<int> Q;

void InitBFS(int Begin) {
    memset(Father, NIL, sizeof(Father));
    Father[Begin] = Begin;
    Q.push(Begin);
}

bool BFS(int Begin, int End) {
    for (InitBFS(Begin); !Q.empty(); Q.pop()) {
        int X = Q.front();
        if (X == End)
            continue;
        for (it Y = G[X].begin(); Y != G[X].end(); ++Y) {
            if (Father[*Y] == NIL && Capacity[X][*Y] > Flow[X][*Y]) {
                Father[*Y] = X;
                Q.push(*Y);
            }
        }
    }
    return (Father[End] != NIL);
}

int MaximumFlow(int Source, int Sink) {
    int MaxFlow = 0;
    while (BFS(Source, Sink)) {
        for (it Y = G[Sink].begin(); Y != G[Sink].end(); ++Y) {
            if (Father[*Y] == NIL || Capacity[*Y][Sink] <= Flow[*Y][Sink])
                continue;
            Father[Sink] = *Y;
            int CurrentFlow = oo;
            for (int X = Sink; X != Source; X = Father[X])
                CurrentFlow = min(CurrentFlow, Capacity[Father[X]][X] - Flow[Father[X]][X]);
            for (int X = Sink; X != Source; X = Father[X]) {
                Flow[Father[X]][X] += CurrentFlow;
                Flow[X][Father[X]] -= CurrentFlow;
            }
            MaxFlow += CurrentFlow;
        }
    }
    return MaxFlow;
}

void Solve() {
    Solution = MaximumFlow(1, N);
}

inline void AddEdge(int X, int Y, int C) {
    G[X].push_back(Y); G[Y].push_back(X);
    Capacity[X][Y] = C; Capacity[Y][X] = 0;
}

void Read() {
    assert(freopen("maxflow.in", "r", stdin));
    int M; assert(scanf("%d %d", &N, &M) == 2);
    for (; M > 0; --M) {
        int X, Y, C; assert(scanf("%d %d %d", &X, &Y, &C) == 3);
        AddEdge(X, Y, C);
    }
}

void Print() {
    assert(freopen("maxflow.out", "w", stdout));
    printf("%d\n", Solution);
}

int main() {
    Read();
    Solve();
    Print();
    return 0;
}