Advertisement
tuki2501

mincost.cpp

Feb 20th, 2022
989
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. typedef long long ll;
  5. typedef pair<int,int> II;
  6.  
  7. const int N = 105;
  8.  
  9. int n, m, k, s, t;
  10. vector<int> adj[N];
  11. int cost[N][N], capa[N][N], flow[N][N];
  12. int dist[N], water[N], prv[N];
  13.  
  14. template<typename T>
  15. bool chmin(T &a, T b) {
  16.   return a > b ? a = b, 1 : 0;
  17. }
  18.  
  19. bool bmf(int k) {
  20.   memset(dist, 0x3f, sizeof(dist));
  21.   memset(water, 0, sizeof(water));
  22.   queue<II> q; q.push({0, s});
  23.   dist[s] = 0; water[s] = k;
  24.   while (q.size()) {
  25.     int d, i;
  26.     tie(d, i) = q.front(); q.pop();
  27.     if (d > dist[i]) continue;
  28.     for (auto &j : adj[i]) {
  29.       bool b = (flow[i][j] >= 0);
  30.       int f = (b ? capa[i][j] - flow[i][j] : -flow[i][j]);
  31.       if (f == 0) continue;
  32.       if (chmin(dist[j], dist[i] + cost[i][j] * (b ? 1 : -1))) {
  33.         water[j] = min(water[i], f);
  34.         prv[j] = i;
  35.         q.push({dist[j], j});
  36.       }
  37.     }
  38.   }
  39.   return water[t];
  40. }
  41.  
  42. void incFlow() {
  43.   for (int i = t; i != s; i = prv[i]) {
  44.     flow[prv[i]][i] += water[t];
  45.     flow[i][prv[i]] -= water[t];
  46.   }
  47. }
  48.  
  49. int main() {
  50.   cin.tie(0)->sync_with_stdio(0);
  51.   cin >> n >> m >> k >> s >> t;
  52.   for (int i = 1; i <= m; i++) {
  53.     int u, v, c, d;
  54.     cin >> u >> v >> c >> d;
  55.     adj[u].push_back(v);
  56.     adj[v].push_back(u);
  57.     cost[u][v] = cost[v][u] = c;
  58.     capa[u][v] = capa[v][u] = d;
  59.   }
  60.   int ans = 0;
  61.   while (k > 0 && bmf(k)) {
  62.     incFlow();
  63.     k -= water[t];
  64.     ans += dist[t] * water[t];
  65.   }
  66.   if (k > 0) {
  67.     cout << -1 << '\n';
  68.     return 0;
  69.   }
  70.   cout << ans << '\n';
  71.   for (int i = 1; i <= n; i++) {
  72.     for (auto &j : adj[i]) {
  73.       if (flow[i][j] > 0) {
  74.         cout << i << ' ' << j << ' ' << flow[i][j] << '\n';
  75.       }
  76.     }
  77.   }
  78.   cout << "0 0 0" << '\n';
  79. }
  80.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement