Cod sursa(job #2960493)

Utilizator GeorgeNistorNistor Gheorghe GeorgeNistor Data 4 ianuarie 2023 15:04:21
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
/*
 * https://infoarena.ro/problema/fmcm 70/100
 * Complexity: O(V^2*E^2)
 */

#include <bits/stdc++.h>

using namespace std;

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

int V, E, s, t;
vector<int> parrent, dist;
vector<vector<int>> adjListRes;
vector<vector<int>> capacity, cost;

void init() {
    adjListRes.resize(V+1);
    parrent.resize(V+1);
    dist.resize(V+1);
    capacity.resize(V+1, vector<int>(V+1));
    cost.resize(V+1, vector<int>(V+1));
}

void addEdge(int u, int v, int c, int w){
    adjListRes[u].push_back(v);
    adjListRes[v].push_back(u);
    capacity[u][v] = c;
    cost[u][v] =  w;
    cost[v][u] = -w;
};

void read(){
    in >> V >> E >> s >> t;
    init();
    for(int i = 1; i <= E; i++){
        int u, v, c, w;
        in >> u >> v >> c >> w;
        addEdge(u, v, c, w);
    }
    in.close();
}

bool bellmanFord(){
    fill(dist.begin(), dist.end(), INT_MAX);
    dist[s] = 0;
    vector<bool> inQueue(V+1);
    queue<int> q;
    q.push(s);
    inQueue[s] = true;
    dist[s] = 0;
    while(!q.empty()){
        int u = q.front();
        q.pop();
        inQueue[u] = false;
        for(auto v: adjListRes[u]){
            if(capacity[u][v] > 0 and dist[u] + cost[u][v] < dist[v]){
                dist[v] = dist[u]+cost[u][v];
                parrent[v] = u;
                if(!inQueue[v]){
                    q.push(v);
                    inQueue[v] = true;
                }
            }
        }
    }
    return dist[t] != INT_MAX;
}

int solve(){
    int minCost = 0;
    while(bellmanFord()){
        cout << dist[t] << endl;
        int pathFlow = INT_MAX, pathCost = 0;
        for(int v = t; v != s; v = parrent[v]){
            int u = parrent[v];
            pathFlow = min(pathFlow, capacity[u][v]);
        }
        for(int v = t; v != s; v = parrent[v]){
            int u = parrent[v];
            capacity[u][v] -= pathFlow;
            capacity[v][u] += pathFlow;
        }
        minCost += pathFlow*dist[t];
    }
    return minCost;
}

int main(){
    read();
    out << solve() << endl;
    out.close();
    return 0;
}