Cod sursa(job #2725133)

Utilizator retrogradLucian Bicsi retrograd Data 18 martie 2021 14:33:08
Problema Flux maxim de cost minim Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>
 
using namespace std;
using ll = int;
const ll INF = 1e9;
 
struct ZKW {
  struct Edge { int a, b, nxt; ll f, c, k; };
  int n;
  vector<Edge> E;
  vector<int> graph, ptr, vis;
  vector<ll> pi;

  ZKW(int n) : n(n), graph(n, -1), ptr(n, -1), pi(n, 0) {}
 
  void AddEdge(int a, int b, ll c, ll k) {
    E.push_back({a, b, graph[a], 0, c, k}); 
    graph[a] = E.size() - 1;
    E.push_back({b, a, graph[b], 0, 0, -k}); 
    graph[b] = E.size() - 1;
  }
  bool relabel() {
    ll upd = INF;
    for (auto& e : E) if (vis[e.a] && !vis[e.b] && e.f < e.c)
      upd = min(upd, pi[e.a] + e.k - pi[e.b]);
    assert(upd >= 0);
    for (int i = 0; i < n; ++i) if (!vis[i]) pi[i] += upd;
    ptr = graph;
    return upd != INF;
  }
  ll dfs(int v, int t, ll flow) {
    vis[v] = true;
    if (v == t) return flow;
    for (int& i = ptr[v]; i != -1; i = E[i].nxt) {
      auto& e = E[i]; ll ret;
      if (pi[e.b] == pi[e.a] + e.k && e.f < e.c && !vis[e.b] &&
          (ret = dfs(e.b, t, min(flow, e.c - e.f)))) 
        return E[i].f += ret, E[i ^ 1].f -= ret, ret; 
    }
    return 0;
  }
  pair<ll, ll> Compute(int s, int t) {
    ll flow = 0, cost = 0, f;
    while (true) {
      vis.assign(n, 0);
      if (!(f = dfs(s, t, INF)) && !relabel()) break;
      flow += f; cost += f * pi[t];
    }
    return {flow, cost};
  }
  void SetPi(int s) {
    for (int ch = 1; ch--; ) 
      for (auto& e : E) 
        if (e.f < e.c && pi[e.b] > pi[e.a] + e.k)
          pi[e.b] = pi[e.a] + e.k, ch = 1;
  }
};
 
int main() {
  ifstream cin("fmcm.in");
  ofstream cout("fmcm.out");
  int n, m, s, t; cin >> n >> m >> s >> t; --s; --t;
  ZKW F(n);
  for (int i = 0; i < m; ++i) {
    int a, b, c, k; cin >> a >> b >> c >> k; 
    F.AddEdge(a - 1, b - 1, c, k);
  }
  F.SetPi(s);
  cout << F.Compute(s, t).second << endl;
  return 0;
}