Cod sursa(job #1956697)

Utilizator razvandRazvan Dumitru razvand Data 6 aprilie 2017 23:03:24
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 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();

        if(nod == n)
            continue;

        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);

        }

    }

    return (viz[n] == tim);

}

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;
    int todo;

    while(bfs(1)) {

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

            todo = e[n][i];

            if(viz[todo] != tim)
                continue;

            bef[n] = todo;
            //cout << " " << todo << '\n';
            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;
}