joylintp

Cost_flow

Nov 5th, 2021
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. static const int INF = 0x3f3f3f3f;
  2.  
  3. struct Cost_flow
  4. {
  5. static const int N = 3502;
  6. struct Edge
  7. {
  8. int to, cap, rev, cost;
  9. Edge(){}
  10. Edge(int _to, int _cap, int _rev, int _cost) : to(_to), cap(_cap), rev(_rev), cost(_cost){}
  11. };
  12. vector<Edge> G[N];
  13. void add_edge(int from, int to, int cap, int cost)
  14. {
  15. G[from].push_back(Edge(to, cap, (int)G[to].size(), cost));
  16. G[to].push_back(Edge(from, 0, (int)G[from].size() - 1, -cost));
  17. }
  18. int n, s, t;
  19. void init(int _n, int _s, int _t)
  20. {
  21. n = _n, s = _s, t = _t;
  22. for (int i = 0; i < n; i++)
  23. G[i].clear();
  24. }
  25. bool in_que[N];
  26. int par[N], par_id[N], dis[N];
  27. pair<int, int> flow()
  28. {
  29. int flow = 0, cost = 0;
  30. while (true)
  31. {
  32. for (int i = 0; i < N; i++)
  33. dis[i] = INF, in_que[i] = false;
  34. dis[s] = 0;
  35. queue<int> que;
  36. que.push(s);
  37. while (!que.empty())
  38. {
  39. int tmp = que.front();
  40. que.pop();
  41. in_que[tmp] = false;
  42. for (int eid = 0; eid < (int)G[tmp].size(); eid++)
  43. {
  44. Edge e = G[tmp][eid];
  45. if (e.cap > 0 && dis[e.to] > dis[tmp] + e.cost)
  46. {
  47. dis[e.to] = max(INF, dis[tmp] + e.cost);
  48. par[e.to] = tmp;
  49. par_id[e.to] = eid;
  50. if (!in_que[e.to])
  51. {
  52. in_que[e.to] = true;
  53. que.push(e.to);
  54. }
  55. }
  56. }
  57. }
  58. if (dis[t] == INF)
  59. break;
  60. int mn_flow = INF;
  61. for (int i = t; i != s; i = par[i])
  62. mn_flow = min(mn_flow, G[par[i]][par_id[i]].cap);
  63. flow = min(INF, flow + mn_flow), cost = min(INF, cost + mn_flow * dis[t]);
  64. for (int i = t; i != s; i = par[i])
  65. {
  66. G[par[i]][par_id[i]].cap = max(-INF, G[par[i]][par_id[i]].cap - mn_flow);
  67. G[i][G[par[i]][par_id[i]].rev].cap = min(INF, G[i][G[par[i]][par_id[i]].rev].cap + mn_flow);
  68. }
  69. }
  70. return MP(flow, cost);
  71. }
  72. } flow;
Advertisement
Add Comment
Please, Sign In to add comment