Cod sursa(job #1708840)

Utilizator UPB_Darius_Rares_SilviuPeace my pants UPB_Darius_Rares_Silviu Data 28 mai 2016 00:05:05
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.21 kb
#include <cstdio>
#include <algorithm>
#include <queue>
#include <vector>
#define NMAX 1009
#define oo (1<<30)
using namespace std;

int N, M, cap[ NMAX ][ NMAX ], flow[ NMAX ][ NMAX ], d[ NMAX ], T[ NMAX ], inQ[ NMAX ];
queue<int> Q;
vector<int> G[NMAX];

bool BFS(int S, int D) {
    for (int i = 1; i <= N; ++i) {
        d[ i ] = oo;
        T[ i ] = 0;
    }

    d[ S ] = 0;
    T[ S ] = S;
    Q.push( S );
    inQ[ S ] = 1;

    while (!Q.empty()) {
        int node = Q.front();
        Q.pop();
        inQ[ node ] = 0;

        if (node == D) {
            continue;
        }
        for (vector<int>::iterator it = G[node].begin(); it != G[node].end(); ++it) {
            if (d[ node ] + 1 < d[ *it] && flow[ node ][ *it ] < cap[ node ][ *it ]) {
                d[ *it ] = d[ node ] + 1;
                T[ *it ] = node;

                if (!inQ[ *it ]) {
                    inQ[ *it ] = 1;
                    Q.push( *it );
                }
            }
        }
    }

    return T[ D ];
}

int maxflow(int S, int D) {
    int sol = 0;

    while (BFS(S, D)) {
        for (vector<int>::iterator it = G[ D ].begin(); it != G[ D ].end(); ++it) {
            if (T[ *it] && flow[ *it ][ D ] < cap[ *it ][ D ]) {
                T[ D ] = *it;
                int minFlow = oo;
                for (int node = D; node != S; node = T[ node]) {
                    minFlow = min( minFlow, cap[ T[node] ][ node ] - flow[ T[node] ][ node ]);
                }

                if (minFlow > 0) {
                    sol += minFlow;
                    for (int node = D; node != S; node = T[ node]) {
                        flow[ T[node] ][ node ] += minFlow;
                        flow[ node ][ T[node] ] -= minFlow;
                    }
                }
            }
        }
    }

    return sol;
}
int main() {
    freopen("maxflow.in", "r", stdin);
    freopen("maxflow.out", "w", stdout);

    scanf("%d%d", &N, &M);
    while (M--) {
        int x, y, c;
        scanf("%d%d%d", &x, &y, &c);
        cap[ x ][ y ] += c;
        G[ x ].push_back( y );
        G[ y ].push_back( x );
    }

    printf("%d\n", maxflow(1, N));

    return 0;
}