Cod sursa(job #3208616)

Utilizator smunteanuMunteanu Stefan Catalin smunteanu Data 29 februarie 2024 04:47:07
Problema Flux maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.37 kb
#include <bits/stdc++.h>
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];

void bf() {

  static bool inq[NMAX];

  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> x, pair<int, int> y) const {
      return x.second > y.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] = 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;
    cap[u][v] = f;
    cost[u][v] = c;
    cost[v][u] = -c;
    adj[u].push_back(v);
    adj[v].push_back(u);
  }

  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 * dist[0][d] * current_flow;
  }

  return total_cost;

}

int main() {

  #ifdef LOCAL
  freopen("file.in", "r", stdin);
  #else
  freopen("fmcm.in", "r", stdin);
  freopen("fmcm.out", "w", stdout);
  #endif

  ios_base::sync_with_stdio(false), cin.tie(NULL);

  cout << solve() << endl;
}