Cod sursa(job #1678534)

Utilizator serbanSlincu Serban serban Data 7 aprilie 2016 13:36:35
Problema Flux maxim de cost minim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.41 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 ds[360];
int real[360];
int mn[360];
int tata[360];
bool vis[360];
priority_queue< pair< int, int> > pq;



int dijkstra() {

    for(int i = 1; i <= n; i ++) ds[i] = oo;
    ds[s] = 0;

    pq.push({0, s});
    while(!pq.empty()) {
        int kost = pq.top().first;
        int act = pq.top().second;
        pq.pop();
        if(kost > ds[act]) continue;
        for(auto it: G[act]) {
            if(ds[act] + cost[act][it] + mn[act] - mn[it] < ds[it] && c[act][it]) {
                real[it] = real[act] + cost[act][it];
                ds[it] = ds[act] + cost[act][it] + mn[act] - mn[it];
                tata[it] = act;
                pq.push({ds[it], it});
            }
        }
    }
    for(int i = 1; i <= n; i ++) mn[i] = real[i];

    if(ds[d] == oo) return -oo;
    int cmn = oo, kost;
    for(int i = d; tata[i]; i = tata[i]) {
        cmn = min(cmn, c[tata[i]][i]);
        kost += cost[tata[i]][i];
    }
    for(int i = d; tata[i]; i = tata[i]) {
        c[tata[i]][i] -= cmn;
        c[i][tata[i]] += cmn;
    }
    return cmn * real[d];
}



queue<int> q;
bool bellmanFord() {

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

    mn[s] = 0;
    vis[s] = true;
    q.push(s);

    while(!q.empty()) {
        int act = q.front();
        q.pop();

        for(auto it: G[act]) {
            if(mn[it] > mn[act] + cost[act][it] && c[act][it]) {
                tata[it] = act;
                mn[it] = mn[act] + cost[act][it];
                if(!vis[it]) {
                    vis[it] = true;
                    q.push(it);
                }
            }
        }
        vis[act] = false;
    }
    if(mn[d] == oo)
        return false;
    return true;
}

int kost = 0;
void flux() {
    if(!bellmanFord()) return ;
    while(true) {
        int add = dijkstra();
        if(add == -oo) return ;
        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);
    }
    flux();
    g << kost << "\n";
    return 0;
}