Alex_tz307

Flux maxim de cost minim SPFA(70p infoarena)

Oct 16th, 2020 (edited)
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. ifstream fin("fmcm.in");
  6. ofstream fout("fmcm.out");
  7.  
  8. int N, source, sink;
  9. bool flag;
  10. vector < vector < int > > Graph, Capacity, Cost;
  11. vector < int > parent, D;
  12.  
  13. const int INF = 2e9;
  14.  
  15. inline void min_self(int& a, int b) {
  16.     a = min(a, b);
  17. }
  18.  
  19. int SPFA() {
  20.     D.assign(N + 1, INF);
  21.     parent.assign(N + 1, -1);
  22.     D[source] = 0;
  23.     queue < int > Q;
  24.     Q.emplace(source);
  25.     vector < bool > inQ(N + 1);
  26.     inQ[source] = true;
  27.     while(!Q.empty()) {
  28.         int curr = Q.front();
  29.         Q.pop();
  30.         inQ[curr] = false;
  31.         for(int next : Graph[curr])
  32.             if(Capacity[curr][next] && D[curr] + Cost[curr][next] < D[next]) {
  33.                 D[next] = D[curr] + Cost[curr][next];
  34.                 parent[next] = curr;
  35.                 if(!inQ[next]) {
  36.                     Q.emplace(next);
  37.                     inQ[next] = true;
  38.                 }
  39.             }
  40.     }
  41.     if(D[sink] != INF) {
  42.         flag = true;
  43.         int new_flow = INF;
  44.         for(int node = sink; node != source; node = parent[node])
  45.             min_self(new_flow, Capacity[parent[node]][node]);
  46.         if(new_flow == 0)
  47.             return 0;
  48.         for(int node = sink; node != source; node = parent[node]) {
  49.             Capacity[parent[node]][node] -= new_flow;
  50.             Capacity[node][parent[node]] += new_flow;
  51.         }
  52.         return new_flow * D[sink];
  53.     }
  54.     return 0;
  55. }
  56.  
  57. int min_cost_flow() {
  58.     int ans = 0;
  59.     flag = true;
  60.     while(flag) {
  61.         flag = false;
  62.         ans += SPFA();
  63.     }
  64.     return ans;
  65. }
  66.  
  67. int main() {
  68.     fin.sync_with_stdio(false);
  69.     fout.sync_with_stdio(false);
  70.     fin.tie(nullptr);
  71.     fout.tie(nullptr);
  72.     int M;
  73.     fin >> N >> M >> source >> sink;
  74.     Graph.resize(N + 1);
  75.     Capacity = Cost = vector < vector < int > >(N + 1, vector < int >(N + 1));
  76.     while(M--) {
  77.         int u, v, capacity, w;
  78.         fin >> u >> v >> capacity >> w;
  79.         Graph[u].emplace_back(v);
  80.         Graph[v].emplace_back(u);
  81.         Capacity[u][v] = capacity;
  82.         Cost[u][v] = w;
  83.         Cost[v][u] = -w;
  84.     }
  85.     fout << min_cost_flow();
  86. }
  87.  
Advertisement
Add Comment
Please, Sign In to add comment