Cod sursa(job #1684846)

Utilizator serbanSlincu Serban serban Data 11 aprilie 2016 12:28:43
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.44 kb
#include <fstream>
#include <string.h>
#include <queue>

#define oo 0x3f3f3f3f

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

int fluxCost, aux;

bool dijkstra() {
    int kost, act;
    vector<int>::iterator it;
    memset(ds, oo, sizeof(ds));
    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});
            }
        }
    }
    memcpy(mn, real, sizeof(real));

    return (ds[d] != oo);
}

queue<int> q;
void bellmanFord() {

    int aux, i, act;
    vector<int>::iterator it;
    memset(mn, oo, sizeof(mn));

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

int main()
{
    ifstream f("fmcm.in");
    ofstream g("fmcm.out");
    int m, x, y, z, t, cmn, i;
    f >> n >> m >> s >> d;
    for(; m; m --) {
        f >> x >> y >> z >> t;
        c[x][y] = z;
        cost[x][y] = t;
        cost[y][x] = -t;
        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]);

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