Cod sursa(job #3041212)

Utilizator dorufDoru Floare doruf Data 31 martie 2023 10:24:44
Problema Flux maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
using pii = pair<int,int>;
#define eb emplace_back

const string TASK("fmcm");

ifstream fin(TASK + ".in");
ofstream fout(TASK + ".out");

const int N = 355, Inf = 1e9;
int cap[N][N], cost[N][N], n, m, src, dest, t[N], ans, f[N][N];
vi g[N];
int od[N], d[N], rd[N];
bitset<N> vis;

void bellman() {
  fill(od + 1, od + n + 2, Inf);
  od[src] = 0;
  queue<int> q;
  q.emplace(src);
  while (!q.empty()) {
    int u = q.front(); q.pop();
    for (auto v : g[u])
      if (cap[u][v] - f[u][v] > 0) {
        if (od[v] > od[u] + cost[u][v]) {
          od[v] = od[u] + cost[u][v];
          q.emplace(v);
        }
      }
  }
  if (od[dest] == Inf) {
    fout << 0;
    exit(0);
  }
}

bool dijkstra() {
  priority_queue<pii,vector<pii>,greater<pii>> q;
  fill(d + 1, d + n + 2, Inf);
  vis.reset();
  d[src] = 0;
  q.emplace(0, src);
  while (!q.empty()) {
    int u = q.top().second; q.pop();
    if (vis[u]) continue;
    vis[u] = 1;
    for (auto v : g[u])
      if (cap[u][v] - f[u][v] > 0) {
        int C = d[u] + cost[u][v] + od[u] - od[v];
        if (d[v] > C && !vis[v]) {
          d[v] = C;
          rd[v] = rd[u] + cost[u][v];
          t[v] = u;
          q.emplace(d[v], v);
        }
      }
  }
  for (int i = 1; i <= n; ++i) od[i] = rd[i];
  if (d[dest] == Inf) return 0;
  int u = dest;
  int flux = Inf;
  while (u != src) {
    int v = t[u];
    flux = min(flux, cap[v][u] - f[v][u]);
    u = v;
  }
  u = dest;
  while (u != src) {
    int v = t[u];
    f[u][v] -= flux;
    f[v][u] += flux;
    ans += cost[v][u] * flux;
    u = v;
  }
  return 1;
}

int32_t main() {
  fin >> n >> m >> src >> dest;
  for (int u, v, c, w, i = 1; i <= m; ++i) {
    fin >> u >> v >> c >> w;
    cap[u][v] = c;
    cost[u][v] = w;
    cost[v][u] = -w;
    g[u].eb(v); g[v].eb(u);
  }
  bellman();
  while (dijkstra());
  fout << ans;
}