Cod sursa(job #2958106)

Utilizator AlexPascu007Pascu Ionut Alexandru AlexPascu007 Data 24 decembrie 2022 18:01:42
Problema Flux maxim de cost minim Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.69 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 400;
vector<vector<int>> adj(NMAX);
vector<vector<int>> cost(NMAX, vector<int>(NMAX, 0));
vector<vector<int>> cap(NMAX, vector<int>(NMAX, 0));
vector<int> dist(NMAX, 0);
vector<int> new_dist(NMAX, 0);
vector<int> t(NMAX, 0);
bitset<NMAX> f;
set<pair<int,int>> s;
vector<pair<int,int>> edges;

int n, m, S, D;

void bellmanford() {
    for (int i = 1; i <= n; ++i) {
        dist[i] = 2*1e9;
    }
    dist[S] = 0;
    deque<int> q;
    q.push_back(S);
    f[S] = 1;
    while (!q.empty()) {
        int nod = q.front();
        q.pop_front();
        f[nod] = 0;
        for (auto vecin : adj[nod]) {
            if (cap[nod][vecin] > 0 && dist[vecin] > dist[nod] + cost[nod][vecin]) {
                dist[vecin] = dist[nod] + cost[nod][vecin];
                t[vecin] = nod;
                if (!f[nod]) {
                    q.push_back(vecin);
                    f[vecin] = 1;
                }
            }
        }
    }
}

bool dijkstra() {
    for (int i = 1; i <= n; i++)
        new_dist[i] = 2 * 1e9;
    new_dist[S] = 0;
    s.insert({0, S});
    while (!s.empty()) {
        int nod = s.begin()->second;
        int cst = -s.begin()->first;
        s.erase(s.begin());
        if (new_dist[nod] == cst) {
            for (auto vecin : adj[nod]) {
                if (cap[nod][vecin] > 0) {
                    int d = new_dist[nod] + dist[nod] - dist[vecin] + cost[nod][vecin];
                    if (d < new_dist[vecin]) {
                        new_dist[vecin] = d;
                        t[vecin] = nod;
                        s.insert({-new_dist[vecin], vecin});
                    }
                }
            }
        }
    }
    return (new_dist[D] != 2 * 1e9);
}


int main() {
    fin >> n >> m >> S >> D;
    for (int i = 0; i < m; i++) {
        int x, y, c, z;
        fin >> x >> y >> c >> z;
        edges.push_back({x,y});
        adj[x].push_back(y);
        adj[y].push_back(x);
        cap[x][y] = c;
        cost[x][y] = z;
        cost[y][x] = -z;
    }
    bellmanford();
    int fluxmax = 0, costmin = 0;
    while (dijkstra()) {
        int fluxmin = 1e9;
        int cst = 0;
        for (int nod = D; nod != S; nod = t[nod]) {
            fluxmin = min(fluxmin, cap[t[nod]][nod]);
            cst += cost[t[nod]][nod];
        }
        fluxmax += fluxmin;
        costmin += fluxmin * cst;
        for (int nod = D; nod != S; nod = t[nod]) {
            cap[t[nod]][nod] -= fluxmin;
            cap[nod][t[nod]] += fluxmin;
        }
    }
    fout << costmin;



    return 0;
}