Cod sursa(job #1957103)

Utilizator razvandRazvan Dumitru razvand Data 7 aprilie 2017 12:37:49
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <climits>

using namespace std;

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

int n,m,s,d;
int flow[353][12503];
int cost[353][12503];
vector<int> e[353];
int cmin[353];
int bef[353];

bool bellman(int nod) {

    for(int i = 1; i <= n; i++) {
        cmin[i] = INT_MAX/2;
        bef[i] = 0;
    }
    cmin[nod] = 0;

    queue<pair<int, int>> Q;
    Q.push({nod, 0});
    int c;
    int nx;

    while(!Q.empty()) {

        nod = Q.front().first;
        c = Q.front().second;
        Q.pop();

        if(c != cmin[nod])
            continue;

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

            nx = e[nod][i];

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

            if(cmin[nx] > cmin[nod]+cost[nod][nx]) {

                cmin[nx] = cmin[nod]+cost[nod][nx];
                Q.push({nx, cmin[nx]});
                bef[nx] = nod;

            }

        }

    }

    if(cmin[d] != INT_MAX/2)
        return 1;
    return 0;

}

int main() {

    in >> n >> m >> s >> d;
    int x,y,z,w;

    for(int i = 1; i <= m; i++) {
        in >> x >> y >> z >> w;

        e[x].push_back(y);
        e[y].push_back(x);

        flow[x][y] = z;
        cost[x][y] = w;
        cost[y][x] = -w;

    }

    int flmx = 0;
    int cosM = 0;

    while(bellman(s)) {

        int flmin = INT_MAX;
        int crr = d;

        while(crr != s) {
            flmin = min(flmin, flow[bef[crr]][crr]);
            crr = bef[crr];
        }

        crr = d;
        flmx += flmin;
        cosM += flmin*cmin[d];

        while(crr != s) {
            flmin = min(flmin, flow[bef[crr]][crr]);
            flow[bef[crr]][crr] -= flmin;
            flow[crr][bef[crr]] += flmin;
            crr = bef[crr];
        }

        //cout << "TEST " << flmx << " " << cosM << '\n';

    }

    out << cosM << '\n';

    return 0;
}