Cod sursa(job #1956683)

Utilizator razvandRazvan Dumitru razvand Data 6 aprilie 2017 22:55:13
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <iostream>
#include <fstream>
#include <climits>
#include <queue>

using namespace std;

ifstream in("maxflow.in");
ofstream out("maxflow.out");

int viz[5003];
int tim;
int n,m;
int flow[1003][1003];
vector<int> e[1003];
int bef[1003];

bool bfs(int nod) {

    tim++;
    queue<int> Q;
    Q.push(nod);
    viz[nod] = tim;
    int nx;

    while(!Q.empty()) {

        nod = Q.front();
        Q.pop();

        for(int i = 0; i < e[nod].size(); i++) {

            nx = e[nod][i];

            if(flow[nod][nx] == 0 || viz[nx] == tim)
                continue;

            viz[nx] = tim;
            bef[nx] = nod;
            Q.push(nx);
            if(nx == n)
                return 1;

        }

    }

    return 0;

}

int main() {

    in >> n >> m;
    int x,y,z;

    for(int i = 1; i <= m; i++) {

        in >> x >> y >> z;

        e[x].push_back(y);
        e[y].push_back(x);
        flow[x][y] = z;

    }

    int fl = 0;
    int tot = 0;

    while(bfs(1)) {

        int flm = INT_MAX;
        int crr = n;

        while(crr != 1) {
            flm = min(flm, flow[bef[crr]][crr]);
            crr = bef[crr];
        }

        crr = n;

        while(crr != 1) {
            flow[bef[crr]][crr] -= flm;
            flow[crr][bef[crr]] += flm;
            crr = bef[crr];
        }

        tot += flm;

    }

    out << tot;

    return 0;
}