Cod sursa(job #1684791)

Utilizator serbanSlincu Serban serban Data 11 aprilie 2016 12:07:46
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.64 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#include <bitset>

#define oo 1000000000

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];
bitset<360> vis;
priority_queue< pair< int, int>, vector< pair<int, int> >, greater< pair<int, int> > > pq;

int fluxCost, aux;

bool dijkstra() {
    int i, kost, act;
    vector<int>::iterator it;
    for(i = 1; i <= n; i ++)
        ds[i] = real[i] = oo;
    ds[s] = real[s] = 0;
    pq.push({0, s});
    while(!pq.empty()) {
        kost = pq.top().first;
        act = pq.top().second;
        pq.pop();
        if(kost != ds[act]) continue;

        for(it = G[act].begin(); it != G[act].end(); it ++) {

            int i = *it;
            if(c[act][i] == 0) continue;

            aux = ds[act] + cost[act][i] + mn[act] - mn[i];

            if(aux < ds[i]) {
                ds[i] = aux;
                real[i] = real[act] + cost[act][i];
                tata[i] = act;
                pq.push({ds[i], i});
            }
        }
    }
    for(i = 1; i <= n; i ++)
        mn[i] = real[i];

    return ds[i] != oo;
}



queue<int> q;
bool bellmanFord() {

    int aux, i, act;
    vector<int>::iterator it;
    for(i = 1; i <= n; i ++)
        mn[i] = oo;

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

    while(!q.empty()) {
        act = q.front();
        vis[act] = false;
        q.pop();

        for(it = G[act].begin(); it != G[act].end(); it ++) {

            int i = *it;
            if(c[act][i] == 0) continue;

            if(mn[act] + cost[act][i] < mn[i]) {
                mn[i] = mn[act] + cost[act][i];
                if(!vis[i]) {
                    vis[i] = true;
                    q.push(i);
                }
            }
        }
    }
    if(mn[d] == oo)
        return false;
    return true;
}

int main()
{
    ifstream f("fmcm.in");
    ofstream g("fmcm.out");
    int m, x, y, cmn, i;
    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);
    }

    bellmanFord();
    while(dijkstra()) {
        cmn = oo;
        for(i = d; i != s; i = tata[i])
            cmn = min(cmn, c[tata[i]][i]);
        if(cmn <= 0) break;

        for(i = d; tata[i]; i = tata[i]) {
            c[tata[i]][i] -= cmn;
            c[i][tata[i]] += cmn;
        }
        fluxCost += cmn * mn[d];
    }
    g << fluxCost << "\n";
    return 0;
}