Cod sursa(job #883610)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 20 februarie 2013 10:42:14
Problema Flux maxim Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.17 kb
#include <cstdio>
#include <cstring>
#include <cassert>

#include <vector>
#include <algorithm>
#include <queue>

using namespace std;

typedef vector<int>::iterator it;

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

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

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

bool BFS(int Start, int End) {
    for (InitBFS(Start); !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) {
    memset(Flow, 0, sizeof(Flow));
    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;
}

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();
    Solution = MaximumFlow(1, N);
    Print();
    return 0;
}