Cod sursa(job #2770978)

Utilizator retrogradLucian Bicsi retrograd Data 24 august 2021 15:57:36
Problema Flux maxim de cost minim Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.72 kb
#include <bits/stdc++.h>

using namespace std;
using ll = long long;
const int INF = 1e9; // greater than sum(e.k), INF * sum(sup) should fit

struct NetworkSimplex {
  struct Edge { int a, b, c, k, f = 0; };

  int n;
  vector<int> sup, pei, depth, pi;
  vector<Edge> E;
  vector<set<int>> tree;
  vector<int> q;
  
  NetworkSimplex(int n) : 
    n(n), sup(n, 0), pei(n + 1, -1), 
    depth(n + 1, 0), pi(n + 1, 0), tree(n + 1) {}
  
  int AddEdge(int a, int b, int c, int k) {
    E.push_back({a, b, c, k});
    E.push_back({b, a, 0, -k});
    return E.size() - 2;
  }

  void dfs(int node) {
    for (auto ei : tree[node]) {
      if (ei == pei[node]) continue;
      int vec = E[ei].b;
      pi[vec] = pi[node] + E[ei].k;
      pei[vec] = (ei ^ 1);
      depth[vec] = 1 + depth[node];
      dfs(vec);
    }
  }

  int pivot(int ein) {
    int flow = 2e9;
    pair<int, int> eout = {flow, -1};
    auto walk = [&](int ei, int phase) {
      auto nxt = [&](int ei, int dir) {
        ei ^= dir;
        int res = E[ei].c - E[ei].f;
        if (phase == 0) {
          flow = min(flow, res);
          eout = min(eout, make_pair(res, ei));
        } else {
          E[ei].f += flow;
          E[ei^1].f -= flow;
        }
        ei ^= dir;
        return E[ei].b;
      };
      nxt(ei, 0);
      int a = E[ei].a, b = E[ei].b;
      while (a != b) {
        if (depth[a] > depth[b]) 
          a = nxt(pei[a], 1);
        else b = nxt(pei[b], 0);
      }
    };
    for (int phase : {0, 1}) 
      walk(ein, phase);
    tree[E[ein].a].insert(ein);
    tree[E[ein].b].insert(ein^1);
    tree[E[eout.second].a].erase(eout.second);
    tree[E[eout.second].b].erase(eout.second^1);
    return flow;
  }

  ll Compute() {
    for (int i = 0; i < n; ++i) {
      int a = n, b = i; ll c = sup[i], k = -INF;
      if (c < 0) c *= -1, swap(a, b);
      int ei = AddEdge(a, b, c, k);
      tree[E[ei].a].insert(ei);
      tree[E[ei].b].insert(ei^1);
    }  
    
    ll answer = 0;
    while (true) { 
      dfs(n);
      pair<int, int> ein = {0, -1};
      for (int i = 0; i < (int)E.size(); ++i) {
        auto& e = E[i];
        if (e.f < e.c)
          ein = min(ein, make_pair(pi[e.a] + e.k - pi[e.b], i));
        if (i % (3 * n) == 0 && ein.first > 0) break;
      }
      if (ein.first == 0) break;
      int flow = pivot(ein.second);
      answer += 1LL * flow * ein.first;
    }
    return answer;
  }
};

int main() {
  ifstream cin("fmcm.in");
  ofstream cout("fmcm.out");

  int n, m, s, t; cin >> n >> m >> s >> t;
  NetworkSimplex NS(n);
  for (int i = 0; i < m; ++i) {
    int a, b, c, k; cin >> a >> b >> c >> k;
    NS.AddEdge(a - 1, b - 1, c, k);
  }
  int ed = NS.AddEdge(t - 1, s - 1, INF, -INF);
  cout << NS.Compute() + 1LL * INF * NS.E[ed].f << endl;

  return 0;
}