Cod sursa(job #875152)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 9 februarie 2013 19:14:00
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.17 kb
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstring>

using namespace std;

typedef vector<int>::iterator it;

const int MaxN = 1005;
const int MaxE = 5005;
const int oo = 1000000000;
const int NIL = -1;

struct Edge {
    int V, Capacity, Flow;
};

vector<int> G[MaxN];
Edge E[MaxE];
int N, M, Source, Sink, Father[MaxN], MaxFlow;
queue<int> Q;

inline int NonE(const int e) {
    return e < M ? e + M : e - M;
}

inline void InitBFS(const int Start) {
    memset(Father, NIL, sizeof(Father));
    Q.push(Start), Father[Start] = 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 e = G[X].begin(); e != G[X].end(); ++e)
            if (Father[E[*e].V] == NIL && E[*e].Capacity > E[*e].Flow)
                Q.push(E[*e].V), Father[E[*e].V] = NonE(*e);
    }
    return (Father[End] != NIL);
}

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

void Read() {
    ifstream fin("maxflow.in");
    fin >> N >> M;
    for (int i = 0; i < M; ++i) {
        int X, Y, C; fin >> X >> Y >> C;
        G[X].push_back(i), G[Y].push_back(i+M);
        E[i].V = Y, E[i].Capacity = C, E[i].Flow = 0;
        E[NonE(i)].V = X, E[NonE(i)].Capacity = 0, E[NonE(i)].Flow = 0;
    }
    Source = 1, Sink = N;
    fin.close();
}

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

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