Cod sursa(job #2762744)

Utilizator siliviuSilion Liviu siliviu Data 9 iulie 2021 14:48:00
Problema Flux maxim de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <bits/stdc++.h>

using namespace std;
using pi = pair<int, int>;

int main() {
    ifstream cin("fmcm.in");
    ofstream cout("fmcm.out");
    int n, m, s, t, x, y, z, w;
    cin >> n >> m >> s >> t;
    vector<vector<pi>> G(n + 1);
    vector<vector<int>> c(n + 1, vector<int>(n + 1));
    while (m--) {
        cin >> x >> y >> z >> w;
        G[x].emplace_back(y, w);
        G[y].emplace_back(x, -w);
        c[x][y] = z;
    }
    int flow = 0, cost = 0;
    while (1) {
        queue<int> Q;
        vector<int> last(n + 1, -1), dp(n + 1, 0x3F3F3F3F), inq(n + 1);
        Q.emplace(s);
        inq[s] = 1;
        dp[s] = 0;
        while (!Q.empty()) {
            int node = Q.front();
            Q.pop();
            inq[node] = 0;
            for (auto x : G[node])
                if (c[node][x.first] && dp[node] + x.second < dp[x.first]) {
                    dp[x.first] = dp[node] + x.second;
                    last[x.first] = node;
                    if (!inq[x.first]) {
                        inq[x.first] = 1;
                        Q.emplace(x.first);
                    }
                }
        }
        int curflow = INT_MAX;
        if (last[t] == -1)
            break;
        for (int i = t; i != s; i = last[i])
            curflow = min(curflow, c[last[i]][i]);
        for (int i = t; i != s; i = last[i]) {
            c[last[i]][i] -= curflow;
            c[i][last[i]] += curflow;
        }
        cost += dp[t] * curflow;
        flow += curflow;
    }
    cout << cost << '\n';
}