Cod sursa(job #2203672)

Utilizator Menage_a_011UPB Cheseli Neatu Popescu Menage_a_011 Data 12 mai 2018 21:06:48
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.5 kb
// https://goo.gl/fBmFxu
#include <bits/stdc++.h>
using namespace std;

#define NMAX        1009
#define kInf        (1 << 30)
#define USE_FILES "MLC"

#ifdef USE_FILES
#define cin fin
#define cout fout
ifstream fin("maxflow.in");
ofstream fout("maxflow.out");
#endif

// number of tests from "in"
int test_cnt = 1;
void clean_test();

// your global variables are here
int n, m, p[NMAX];
vector<int> G[NMAX];
int flow[NMAX][NMAX], cap[NMAX][NMAX];


void read_input() {
    cin >> n >> m;

    for (int i = 1; i <= m; ++i) {
        int x, y, c;
        cin >>  x >> y >> c;

        G[x].push_back(y);
        G[y].push_back(x);
        cap[x][y] += c;
    }
}

bool BFS(int source, int sink) {
    for (int i = 1; i <= n; ++i) {
        p[i] = kInf;
    }

    queue<int> Q;
    Q.push(source);
    p[source] = 0;

    while (!Q.empty()) {
        int node = Q.front();
        Q.pop();

        if (node == sink) {
            continue;
        }

        for (auto &x : G[node]) {
            if (p[x] == kInf && flow[node][x] < cap[node][x]) {
                p[x] = node;
                Q.push( x );
            }
        }
    }

    return p[sink] != kInf;
}

void get_maxflow(int source, int sink) {
    int maxFlow = 0;

    while (BFS(source, sink)) {
        for (auto &x : G[sink]) {
            if (p[x] != kInf && flow[x][sink] < cap[x][sink]) {
                p[sink] = x;

                int minFlow = kInf;
                for (int node = sink; node != source; node = p[node]) {
                    int parent = p[node];
                    int available_flow = cap[ parent ][ node ] - flow[ parent ][ node ];

                    minFlow = min(minFlow, available_flow);
                }

                if (minFlow > 0) {
                    maxFlow += minFlow;

                    for (int node = sink; node != source; node = p[node]) {
                        int parent = p[node];
                        flow[ parent ][ node ] += minFlow;
                        flow[ node ][ parent ] -= minFlow;
                    }
                }
            }
        }
    }

    cout << maxFlow << "\n";
}

// your solution is here
void solve() {
    read_input();
    get_maxflow(1, n);

    if (test_cnt > 0) {
        clean_test();
    }
}


void clean_test() {
    // clean if needed
    memset(flow, 0, sizeof(flow));
    memset(cap, 0, sizeof(cap));

    for (int i = 1; i <= n; ++i) {
        G[i].clear();
    }

    n = 0;
}

int main() {
//     cin >> test_cnt;
    while (test_cnt--) {
        solve();
    }

    return 0;
}