Cod sursa(job #1947827)

Utilizator andrei.arnautuAndi Arnautu andrei.arnautu Data 31 martie 2017 13:53:52
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.27 kb
/**
  *  Worg
  */
#include <queue>
#include <cstdio>
#include <vector>
#include <algorithm>

using std::queue;
using std::vector;
FILE *fin = freopen("maxflow.in", "r", stdin);
FILE *fout = freopen("maxflow.out", "w", stdout);

const int kMaxN = 1 + 1000;
const int kMaxInf = 1e9;

/*-------- Input data --------*/
int N, M;
vector<int > graph[kMaxN];
/*-------- Flow data --------*/
int cap[kMaxN][kMaxN];
/*-------- BFS --------*/
queue<int > my_queue;
bool checked[kMaxN];

int before[kMaxN];
/*-------- --------*/

void ReadInput() {
    scanf("%d%d", &N, &M);
    for(int i = 1; i <= M; i++) {
        int u, v, c; scanf("%d%d%d", &u, &v, &c);
        graph[u].push_back(v); graph[v].push_back(u);
        cap[u][v] += c;
    }
}

bool BFS() {
    const int kStart = 1;
    const int kFinish = N;

    while(!my_queue.empty()) {
        my_queue.pop();
    }
    for(int i = kStart + 1; i <= kFinish; i++) {
        checked[i] = false;
    }
    checked[kStart] = true;
    my_queue.push(kStart);

    while(!my_queue.empty()) {
        int node = my_queue.front(); my_queue.pop();
        if(node == kFinish) {
            return true;
        }
        for(int nxt : graph[node]) {
            if(!checked[nxt] && cap[node][nxt] != 0) {
                checked[nxt] = true;
                before[nxt] = node;
                my_queue.push(nxt);
            }
        }
    }

    return false;
}

int GetMaxFlow() {
    const int kStart = 1;
    const int kFinish = N;

    int max_flow = 0;
    while(BFS()) {
        for(int x : graph[kFinish]) {
            if(checked[x] && cap[x][kFinish] != 0) {
                before[kFinish] = x;

                int flow = kMaxInf;
                for(int node = kFinish; node != kStart; node = before[node]) {
                    flow = std::min(flow, cap[before[node]][node]);
                }

                max_flow += flow;
                for(int node = kFinish; node != kStart; node = before[node]) {
                    cap[before[node]][node] -= flow;
                    cap[node][before[node]] += flow;
                }
            }
        }
    }

    return max_flow;
}

int main() {
    ReadInput();
    printf("%d\n", GetMaxFlow());
    return 0;
}