Cod sursa(job #3377078)

Utilizator R_2008Nechitescu Radu-Andrei R_2008 Data 21 noiembrie 2026 14:03:38
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.09 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
ifstream fin("fmcm.in");
ofstream fout("fmcm.out");
const int nmax = 1000;
const long long oo =1e9;
vector<int> g[nmax + 5];
int n, m, s, d;
int c[nmax + 5][nmax + 5], f[nmax + 5][nmax + 5];
long long cost[nmax + 5][nmax + 5];
long long dist_bf[nmax + 5];
int tt[nmax + 5], inq[nmax + 5];
long long mincost;
queue<int> q;
void read() {
    fin >> n >> m >> s >> d;
    for (int i = 1; i <= m; ++i) {
        int x, y, cap;
        long long w;
        fin >> x >> y >> cap >> w;
        if (c[x][y] == 0 && c[y][x] == 0) {
            g[x].push_back(y);
            g[y].push_back(x);
        }
        c[x][y] += cap;
        cost[x][y] = w;
        cost[y][x] = -w;
    }
}

int bellman_ford() {
    for (int i = 1; i <= n; ++i) {
        dist_bf[i] = oo;
        tt[i] = 0;
        inq[i] = 0;
    }
    dist_bf[s] = 0;
    q.push(s);
    inq[s] = 1;
    while (!q.empty()) {
        int nod = q.front();
        q.pop();
        inq[nod] = 0;

        for (int vecin : g[nod]) {
            if (c[nod][vecin] - f[nod][vecin] <= 0) {
                continue;
            }
            if (dist_bf[nod] + cost[nod][vecin] < dist_bf[vecin]) {
                dist_bf[vecin] = dist_bf[nod] + cost[nod][vecin];
                tt[vecin] = nod;
                if (!inq[vecin]) {
                    q.push(vecin);
                    inq[vecin] = 1;
                }
            }
        }
    }

    return dist_bf[d] < oo;
}
void flow() {
    mincost = 0;
    while (bellman_ford()) {
        int Min = oo;
        for (int nod = d; nod != s; nod = tt[nod]) {
            Min = min(Min, c[tt[nod]][nod] - f[tt[nod]][nod]);
        }
        for (int nod = d; nod != s; nod = tt[nod]) {
            f[tt[nod]][nod] += Min;
            f[nod][tt[nod]] -= Min;
        }
        mincost += 1LL * Min * dist_bf[d];
    }
}
void print() {
    fout << mincost << "\n";
}
int main() {
    read();
    flow();
    print();
    return 0;
}