Cod sursa(job #1678650)

Utilizator serbanSlincu Serban serban Data 7 aprilie 2016 14:37:17
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.67 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

#define oo 2147483646

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() {
    memset(ds, 0x3f, sizeof(ds));
    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(int i = 0; i < G[act].size(); i ++) {

            if(c[act][G[act][i]]) {

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

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

    if(ds[d] == 0x3f3f3f3f) return false;

    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];
    return true;
}



queue<int> q;
bool bellmanFord() {

    int aux;
    memset(mn, 0x3f, sizeof(mn));

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

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

        for(int i = 0; i < G[act].size(); i ++) {

            if(c[act][G[act][i]]) {

                aux = mn[act] + cost[act][G[act][i]];

                if(mn[G[act][i]] > aux) {

                    mn[G[act][i]] = aux;
                    if(!vis[G[act][i]]) {
                        vis[G[act][i]] = true;
                        q.push(G[act][i]);
                    }
                }
            }
        }
    }
    if(mn[d] == 0x3f3f3f3f)
        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);
    }

    bellmanFord();
    while(dijkstra());
    fprintf(g, "%d\n", fluxCost);
    return 0;
}