Cod sursa(job #1678506)

Utilizator serbanSlincu Serban serban Data 7 aprilie 2016 13:06:51
Problema Flux maxim de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define oo 2147483647

using namespace std;

int n, s, d;
vector<int> G[360];
int c[360][360];
int cost[360][306];

int mn[360];
int tata[360];
bool vis[360];
priority_queue< pair<int, int> > q;

int bellmanFord() {

    for(int i = 1; i <= n; i ++) mn[i] = oo;

    mn[s] = 0;
    vis[s] = true;
    q.push({oo, s});

    while(!q.empty()) {
        int ct = q.top().first;
        int act = q.top().second;
        vis[act] = false;
        q.pop();

        for(auto it: G[act]) {
            if(!vis[it] && mn[it] > mn[act] + cost[act][it] && c[act][it]) {
                tata[it] = act;
                mn[it] = mn[act] + cost[act][it];
                vis[it] = true;
                q.push({mn[it], it});
            }
        }
    }
    if(mn[d] != oo) {
        int cmn = oo;
        for(int i = d; tata[i]; i = tata[i])
            cmn = min(cmn, c[tata[i]][i]);
        for(int i = d; tata[i]; i = tata[i]) {
            c[tata[i]][i] -= cmn;
            c[i][tata[i]] += cmn;
        }
        return cmn * mn[d];
    }
    return 0;
}

int kost = 0;
void flux() {
    while(true) {
        int add = bellmanFord();
        if(add == 0) break;
        kost += add;
    }
}

int main()
{
    ifstream f("fmcm.in");
    ofstream g("fmcm.out");
    int m, x, y;
    f >> n >> m >> s >> d;
    for(; m; m --) {
        f >> x >> y;
        f >> c[x][y] >> cost[x][y];
        cost[y][x] = -cost[x][y];
        G[x].push_back(y);
        G[y].push_back(x);
    }
    flux();
    g << kost << "\n";
    return 0;
}