Cod sursa(job #934655)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 30 martie 2013 22:49:44
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.19 kb
#include <cstdio>
#include <cstring>
#include <cassert>

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

using namespace std;

typedef long long int64;
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, Source, Sink, Father[MAX_N], Capacity[MAX_N][MAX_N], Flow[MAX_N][MAX_N];
queue<int> Q;
int Solution;

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

bool BFS(const int Start, const 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 && Flow[X][*Y] < Capacity[X][*Y]) {
                Father[*Y] = X;
                Q.push(*Y);
            }
        }
    }
    return (Father[End] != NIL);
}

int MaximumFlow() {
    int MaxFlow = 0;
    while (BFS(Source, Sink)) {
        for (it Y = G[Sink].begin(); Y != G[Sink].end(); ++Y) {
            if (Father[*Y] == NIL || Flow[*Y][Sink] == Capacity[*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 Read() {
    ifstream in("maxflow.in");
    int M; in >> N >> M;
    for (; M > 0; --M) {
        int X, Y, C; in >> X >> Y >> C;
        G[X].push_back(Y); G[Y].push_back(X);
        Capacity[X][Y] += C;
    }
    Source = 1; Sink = N;
    in.close();
}

void Print() {
    ofstream out("maxflow.out");
    out << Solution << "\n";
    out.close();
}

int main() {
    Read();
    Solution = MaximumFlow();
    Print();
    return 0;
}