Advertisement
Wazedrifat

MinCost_MaxFlow.cpp

Jul 4th, 2020
1,196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 KB | None | 0 0
  1. /*
  2.  * Algoritm : Min Cost Max Flow using Bellmen Ford
  3.  * Note : Vertex are 0 indexing Based
  4.  */
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <vector>
  8. #include <algorithm>
  9. using namespace std;
  10. #define MAX_V 3777
  11. #define INF 777777777
  12. struct NODE
  13. {
  14.     long v, Cap, Cost, RevInd; // This ind is necesery for multigraph to knw which edge is used to take flow
  15. };
  16. vector<NODE> Edge[MAX_V + 7];
  17. long nV, nE, P;
  18. long SRC, TNK;
  19. // This PInd is neceserry for multigraph to knw which edge ind of parent is used to take flow
  20. long Par[MAX_V + 7], PInd[MAX_V + 7];
  21. long SD[MAX_V + 7]; // Shortest path
  22.  
  23. void SetEdge(long u, long v, long Cap, long Cost)
  24. {
  25.     NODE U = {v, Cap, Cost, Edge[v].size()};
  26.     NODE V = {u, 0, -Cost, Edge[u].size()};
  27.     Edge[u].push_back(U);
  28.     Edge[v].push_back(V);
  29. }
  30.  
  31. bool BFord(void)
  32. {
  33.     long i, u, k;
  34.     for (i = 0; i < nV; i++)
  35.     {
  36.         Par[i] = -1;
  37.         SD[i] = INF;
  38.     }
  39.     bool IsChange = true;
  40.     SD[SRC] = 0;
  41.     while (IsChange)
  42.     {
  43.         IsChange = false;
  44.         for (u = SRC; u <= TNK; u++)
  45.         {
  46.             for (i = 0; i < Edge[u].size(); i++)
  47.             {
  48.                 if (!Edge[u][i].Cap)
  49.                     continue;
  50.                 long v = Edge[u][i].v;
  51.                 TD = SD[u] + Edge[u][i].Cost;
  52.                 // relaxation
  53.                 if (SD[v] > TD)
  54.                 {
  55.                     SD[v] = TD;
  56.                     Par[v] = u;
  57.                     PInd[v] = i;
  58.                     IsChange = true;
  59.                 }
  60.             }
  61.         }
  62.     }
  63.     return Par[TNK] != -1;
  64. }
  65.  
  66. long FindVol(long s, long t)
  67. {
  68.     long Cap = Edge[Par[t]][PInd[t]].Cap;
  69.     if (s == Par[t])
  70.         return Cap;
  71.     else
  72.         return min(Cap, FindVol(s, Par[t]));
  73. }
  74.  
  75. long AugmentPath(long s, long t, long V)
  76. {
  77.     if (s == t)
  78.         return 0;
  79.     long Cost = Edge[Par[t]][PInd[t]].Cost * V;
  80.     Edge[Par[t]][PInd[t]].Cap -= V;
  81.     Edge[t][Edge[Par[t]][PInd[t]].RevInd].Cap += V;
  82.     return Cost + AugmentPath(s, Par[t], V);
  83. }
  84.  
  85. void MinCost(long &Flow, long &Cost)
  86. {
  87.     Flow = Cost = 0;
  88.     while (BFord())
  89.     {
  90.         long V = FindVol(SRC, TNK);
  91.         Flow += V;
  92.         Cost += AugmentPath(SRC, TNK, V);
  93.     }
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement