Cod sursa(job #3208618)

Utilizator smunteanuMunteanu Stefan Catalin smunteanu Data 29 februarie 2024 05:09:13
Problema Flux maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.26 kb
#include <iostream>
#include <queue>
#include <climits>
using namespace std;

const int NMAX = 357;

int n, m, s, d;
vector<int> adj[NMAX];
int cap[NMAX][NMAX];
int cost[NMAX][NMAX];
int dist[3][NMAX];
int par[NMAX];
bool inq[NMAX];


void bf() {

  queue<int> q;
  q.push(s);
  inq[s] = true;

  while (!q.empty()) {
    int u = q.front();
    q.pop();
    inq[u] = false;
    for (int v : adj[u]) {
      if (cap[u][v] > 0 && dist[0][u] + cost[u][v] < dist[0][v]) {
        dist[0][v] = dist[0][u] + cost[u][v];
        if (!inq[v]) q.push(v), inq[v] = true;
      }
    }
  }
}


bool dijkstra() {

  struct Comp {
    bool operator()(pair<int, int> u, pair<int, int> v) const {
      return u.second > v.second;
    }
  };

  priority_queue<pair<int, int>, vector<pair<int, int>>, Comp> pq;

  fill(par + 1, par + n + 1, -1);
  fill(dist[1] + 1, dist[1] + n + 1, INT_MAX);

  pq.push({s, 0});
  dist[1][s] = dist[2][s] = 0;
  par[s] = 0;

  while (!pq.empty()) {
    auto [u, d] = pq.top();
    pq.pop();
    if (dist[1][u] < d) continue;
    for (int v : adj[u]) {
      if (cap[u][v] > 0 && dist[1][u] + dist[0][u] - dist[0][v] + cost[u][v] < dist[1][v]) {
        par[v] = u;
        dist[1][v] = dist[1][u] + dist[0][u] - dist[0][v] + cost[u][v];
        dist[2][v] = dist[2][u] + cost[u][v];
        pq.push({v, dist[1][v]});
      }
    }
  }

  copy(dist[2] + 1, dist[2] + n + 1, dist[0] + 1);

  return par[d] != -1;
}


long long solve() {

  cin >> n >> m >> s >> d;

  for (int i = 0; i < m; i++) {
    int u, v, f, c;
    cin >> u >> v >> f >> c;
    adj[u].push_back(v);
    adj[v].push_back(u);
    cap[u][v] = f;
    cost[u][v] = c;
    cost[v][u] = -c;
  }

  bf();

  long long total_cost = 0;

  while (dijkstra()) {

    int current_flow = INT_MAX;

    for (int u = d; u != s; u = par[u]) {
      current_flow = min(current_flow, cap[par[u]][u]);
    }

    for (int u = d; u != s; u = par[u]) {
      cap[par[u]][u] -= current_flow;
      cap[u][par[u]] += current_flow;
    }

    total_cost += 1ll * current_flow * dist[0][d];
  }

  return total_cost;
}

int main() {

  freopen("fmcm.in", "r", stdin);
  freopen("fmcm.out", "w", stdout);

  cout << solve() << endl;
}