keymasterviriya1150

Code

Apr 18th, 2016
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. typedef vector<VL> VVL;
  2.  
  3. typedef pair<int, int> PII;
  4.  
  5. typedef vector<PII> VPII;
  6.  
  7. const L INF = numeric_limits<L>::max() / 4;
  8.  
  9. struct MinCostMaxFlow {
  10.  
  11. int N;
  12.  
  13. VVL cap, flow, cost;
  14.  
  15. VI found;
  16.  
  17. VL dist, pi, width;
  18.  
  19. VPII dad;
  20.  
  21. MinCostMaxFlow(int N) :
  22.  
  23. N(N), cap(N, VL(N)), flow(N, VL(N)), cost(N, VL(N)),
  24.  
  25. found(N), dist(N), pi(N), width(N), dad(N) {}
  26.  
  27. void AddEdge(int from, int to, L cap, L cost)
  28. {
  29.     this->cap[from][to] = cap;
  30.  
  31.     this->cost[from][to] = cost;
  32. }
  33.  
  34. void Relax(int s, int k, L cap, L cost, int dir)
  35. {
  36.     L val = dist[s] + pi[s] - pi[k] + cost;
  37.  
  38.     if (cap && val < dist[k])
  39.     {
  40.         dist[k] = val;
  41.  
  42.         dad[k] = make_pair(s, dir);
  43.  
  44.         width[k] = min(cap, width[s]);
  45.     }
  46. }
  47.  
  48. L Dijkstra(int s, int t)
  49.  {
  50.     fill(found.begin(), found.end(), false);
  51.  
  52.     fill(dist.begin(), dist.end(), INF);
  53.  
  54.     fill(width.begin(), width.end(), 0);
  55.  
  56.     dist[s] = 0;
  57.  
  58.     width[s] = INF;
  59.     while (s != -1)
  60.      {
  61.         int best = -1;
  62.  
  63.         found[s] = true;
  64.  
  65.         for (int k = 0; k < N; k++)
  66.          {
  67.  
  68.             if (found[k]) continue;
  69.            
  70.             Relax(s, k, cap[s][k] - flow[s][k], cost[s][k], 1);
  71.  
  72.             Relax(s, k, flow[k][s], -cost[k][s], -1);
  73.  
  74.             if (best == -1 || dist[k] < dist[best]) best = k;
  75.  
  76.         }
  77.         s = best;
  78.     }  
  79.  
  80.     for (int k = 0; k < N; k++)
  81.         pi[k] = min(pi[k] + dist[k], INF);
  82.  
  83.     return width[t];
  84.  
  85. }
  86.  
  87. pair<L, L> GetMaxFlow(int s, int t)
  88.  {
  89.  
  90.     L totflow = 0, totcost = 0;
  91.  
  92.     while (L amt = Dijkstra(s, t))
  93.     {
  94.  
  95.         totflow += amt;
  96.  
  97.         for (int x = t; x != s; x = dad[x].first)
  98.          {
  99.             if (dad[x].second == 1)
  100.             {
  101.                 flow[dad[x].first][x] += amt;
  102.  
  103.                 totcost += amt * cost[dad[x].first][x];
  104.             }
  105.             else
  106.             {
  107.                 flow[x][dad[x].first] -= amt;
  108.    
  109.                 totcost -= amt * cost[x][dad[x].first];
  110.             }
  111.         }  
  112.  
  113.     }
  114.         return make_pair(totflow, totcost);
  115.  } 
  116. };
Advertisement
Add Comment
Please, Sign In to add comment