Cod sursa(job #3039435)

Utilizator DordeDorde Matei Dorde Data 28 martie 2023 16:08:59
Problema Flux maxim de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
int const inf = 1e9 , N = 351;
int n , m , s , d , l , r , a , b;
int q[12501] , t[N] , viz[N] , dp[N];
int f[N][N] , w[N][N];
vector<int> v[N];
void update(){
    int flow = inf;
    int x = d;
    while(t[x]){
        flow = (flow < f[t[x]][x] ? flow : f[t[x]][x]);
        x = t[x];
    }
    if(!flow)return;
    x = d;
    while(t[x]){
        f[t[x]][x] -= flow;
        f[x][t[x]] += flow;
        x = t[x];
    }
}
bool bellman(){
    for(int i = 1 ; i <= n ; ++ i)
        t[i] = 0 , dp[i] = inf;
    q[l = r = 1] = s;
    dp[s] = 0;
    while(l <= r){
        int x = q[l++];
        for(int y : v[x]){
            if(f[x][y] > 0 && w[x][y] + dp[x] < dp[y]){
                dp[y] = dp[x] + w[x][y];
                t[y] = x;
                q[++r] = y;
            }
        }
    }
    return t[d];
}
void fmcm(){
    while(bellman()){
        update();
    }
}
int main(){
    fin >> n >> m >> s >> d;
    pair<int,int> e[m + 1];
    for(int i = 1 ; i <= m ; ++ i){
        fin >> a >> b >> f[a][b] >> w[a][b];
        v[a].push_back(b);
        v[b].push_back(a);
        e[i] = {a , b};
        w[b][a] = -w[a][b];
    }
    fmcm();
    int cost = 0;
    for(int i = 1 ; i <= m ; ++ i){
        cost += f[e[i].second][e[i].first] * w[e[i].first][e[i].second];
    }
    fout << cost << '\n';
    return 0;
}