Cod sursa(job #2684114)

Utilizator Iustin01Isciuc Iustin - Constantin Iustin01 Data 12 decembrie 2020 19:45:15
Problema Flux maxim de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.42 kb
#include <bits/stdc++.h>
#define oo 0x3f3f3f3f
#define MAX 355
using namespace std;

ifstream in("fmcm.in");
ofstream out("fmcm.out");

int n, m, s, d, x, y, cost, z, nod, flux, fluxcst;
int cap[MAX][MAX], cst[MAX][MAX], dist2[MAX], dist1[MAX], t[MAX], dreal[MAX];
vector < int > g[MAX];
bitset < MAX > c;
queue < int > q;
priority_queue < pair < int , int > , vector < pair < int , int > > , greater < pair < int , int > > > Q;


bool Dijkstra(){
    memset(dist2, 0x3f, sizeof(dist2));
    dist2[s] = dreal[s] = 0;
    Q.push({ dist2[s], s});

    while(!Q.empty()){
        cost = Q.top().first, nod = Q.top().second;
        Q.pop();
            for(int i = 0; i < g[nod].size(); i++){
                int vec = g[nod][i];
                if(cap[nod][vec]){
                    int dist = dist2[nod] + cst[nod][vec] + dist1[nod] - dist1[vec];
                    if(dist < dist2[vec]){
                        dist2[vec] = dist;
                        dreal[vec] = dreal[nod] + cst[nod][vec];
                        t[vec] = nod;
                        Q.push({dist2[vec], vec});
                    }
                }
            }
    }
    memcpy(dist1, dreal, sizeof(dist1));
    if(dist2[d] >= oo)
        return false;

    ///Edmonds-Karp
    int fluxmin = oo, costnow = 0;

    for(nod = d; nod != s; nod = t[nod])
        fluxmin = min(fluxmin, cap[t[nod]][nod]);

    fluxcst += fluxmin * dreal[d];

    for(nod = d; nod != s; nod = t[nod])
        cap[t[nod]][nod] -= fluxmin, cap[nod][t[nod]] += fluxmin;

    return true;

}

void Belman_Ford(){
    memset(dist1, 0x3f , sizeof(dist1));
    dist1[s] = 0;
    q.push(s);
    c[s] = true;
    while(!q.empty()){
        nod = q.front();
        q.pop();
        c[nod] = false;
        for(int i = 0; i < g[nod].size(); i++){
            int vec = g[nod][i];
            if(cap[nod][vec] && dist1[vec] > dist1[nod] + cst[nod][vec]){
                dist1[vec] = dist1[nod] + cst[nod][vec];
                if(!c[vec]){
                    c[vec] = true;
                    q.push(vec);
                }
            }
        }
    }
}


int main(){
    in>>n>>m>>s>>d;
    while(m--){
        in>>x>>y>>z>>cost;
        g[x].push_back(y);
        g[y].push_back(x);
        cap[x][y] = z;
        cst[x][y] = cost;
        cst[y][x] = -cost;
    }
    Belman_Ford();

    while(Dijkstra());

    out<<fluxcst;
}