Cod sursa(job #1678888)

Utilizator serbanSlincu Serban serban Data 7 aprilie 2016 16:09:01
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>

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

int fluxCost, aux;

bool dijkstra() {
    for(int i = 1; i <= n; i ++)
        ds[i] = real[i] = oo;
    ds[s] = real[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(c[act][it]) {

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

                if(aux < ds[it]) {
                    ds[it] = aux;
                    real[it] = real[act] + cost[act][it];
                    tata[it] = act;
                    pq.push({ds[it], it});
                }
            }
        }
    }
    memcpy(mn, real, sizeof(mn));

    if(ds[d] == oo) return false;
    return true;
}



queue<int> q;
bool bellmanFord() {

    int aux;
    memset(mn, oo, sizeof(mn));

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

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

        for(auto it: G[act]) {

            if(c[act][it]) {
                aux = mn[act] + cost[act][it];

                if(mn[it] > aux) {
                    tata[it] = act;
                    mn[it] = aux;
                    if(!vis[it]) {
                        vis[it] = true;
                        q.push(it);
                    }
                }
            }
        }
    }
    if(mn[d] == oo)
        return false;
    return true;
}

int main()
{
    FILE *f = fopen("fmcm.in", "r");
    FILE *g = fopen("fmcm.out", "w");
    int m, x, y;
    fscanf(f, "%d %d %d %d", &n, &m, &s, &d);
    for(; m; m --) {
        fscanf(f, "%d %d", &x, &y);
        fscanf(f, "%d %d", &c[x][y], &cost[x][y]);
        cost[y][x] = -cost[x][y];
        G[x].push_back(y);
        G[y].push_back(x);
    }

    if(bellmanFord()) {
        while(dijkstra()) {
            int cmn = oo;
            for(int i = d; i != s; 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;
            }
            fluxCost += cmn * real[d];
        }
    }
    fprintf(g, "%d\n", fluxCost);
    return 0;
}