Cod sursa(job #1194643)

Utilizator mihai995mihai995 mihai995 Data 4 iunie 2014 14:16:49
Problema Flux maxim Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <fstream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

const int N = 1 + 1e3, inf = 0x3f3f3f3f;

struct Nod{
    int x, y, c;

    Nod(int x, int y, int c) : x(x), y(y), c(c) {};

    inline bool operator<(const Nod& N) const {
        return c < N.c;
    }
};

int cap[N][N], flux[N][N], T[N], n;
vector<int> graph[N];
bool use[N];

inline int getCap(int x, int y){
    return cap[x][y] - flux[x][y];
}

bool bfs(int x, int D){
    memset(use, false, sizeof(use));
    priority_queue<Nod> Q;
    int t;

    Q.push( Nod(0, x, 0) );
    while (!Q.empty() && !use[D]){
        x = Q.top().y;
        t = Q.top().x;
        Q.pop();

        if (use[x])
            continue;
        use[x] = true;
        T[x] = t;

        for (int i : graph[x])
            if (!use[i] && getCap(x, i) > 0)
                Q.push( Nod(x, i, getCap(x, i)) );
    }

    return use[D];
}

int maxFlow(int S, int D){
    int flow = 0, F;
    while ( bfs(S, D) ){
        F = inf;
        for (int i = D ; i != S ; i = T[i])
            F = min(F, getCap(T[i], i));
        for (int i = D ; i != S ; i = T[i]){
            flux[ T[i] ][i] += F;
            flux[i][ T[i] ] -= F;
        }
        flow += F;
    }
    return flow;
}

int main(){
    ifstream in("maxflow.in");
    int m, x, y;
    in >> n >> m;

    while (m--){
        in >> x >> y;
        in >> cap[x][y];

        graph[x].push_back(y);
    }

    in.close();

    ofstream out("maxflow.out");
    out << maxFlow(1, n) << '\n';
    out.close();

    return 0;
}