Cod sursa(job #2545225)

Utilizator IoanaDraganescuIoana Draganescu IoanaDraganescu Data 12 februarie 2020 21:53:56
Problema Flux maxim de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

using namespace std;

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

const int Nmax = 350, inf = 0x3f3f3f3f;

vector <int> g[Nmax + 5];
queue <int> q;
int n, m, start, stop, node, ans;
int tt[Nmax + 5], c[Nmax + 5][Nmax + 5], cost[Nmax + 5][Nmax + 5], f[Nmax + 5][Nmax + 5], d[Nmax + 5];
bool inq[Nmax + 5];

void Read(){
    fin >> n >> m >> start >> stop;
    for (int i = 1; i <= m; i++){
        int x, y, z, t;
        fin >> x >> y >> z >> t;
        g[x].push_back(y);
        g[y].push_back(x);
        c[x][y] = z;
        cost[x][y] = t;
        cost[y][x] = -t;
    }
}

int BellmanFord(){
    memset(d, inf, sizeof d);
    memset(tt, 0, sizeof tt);
    memset(inq, 0, sizeof inq);
    d[start] = 0;
    q.push(start);
    inq[start] = 1;
    while (!q.empty()){
        node = q.front();
        q.pop();
        inq[node] = 0;
        for (auto other : g[node])
            if (d[other] > d[node] + cost[node][other] && c[node][other] - f[node][other] > 0){
                d[other] = d[node] + cost[node][other];
                tt[other] = node;
                if (!inq[other]){
                    inq[other] = 1;
                    q.push(other);
                }
            }
    }
    return d[stop] != inf;
}

void Solve(){
    while (BellmanFord()){
        int addmin = inf;
        for (int i = stop; i != start; i = tt[i])
            addmin = min(addmin, c[tt[i]][i] - f[tt[i]][i]);
        for (int i = stop; i != start; i = tt[i]){
            f[tt[i]][i] += addmin;
            f[i][tt[i]] -= addmin;
            ans += addmin * cost[tt[i]][i];
        }
    }
}

void Print(){
    fout << ans << '\n';
}

int main(){
    Read();
    Solve();
    Print();
    return 0;
}