Advertisement
Guest User

Untitled

a guest
Aug 24th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.78 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <memory.h>
  3. #include <vector>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. struct MaxFlowDinic // V^2 * E
  9. {
  10. typedef long long flow_t;
  11.  
  12. struct Edge
  13. {
  14. int next;
  15. int inv; /* inverse edge index */
  16. flow_t res; /* residual */
  17. };
  18.  
  19. int n;
  20. vector<vector<Edge>> graph;
  21.  
  22. vector<unsigned> q, l, start;
  23.  
  24. vector <bool> vst; // *optional
  25.  
  26. void Init(int _n){
  27. n = _n;
  28. graph.resize(n);
  29. vst.resize(n); // *optional
  30. for (int i = 0; i < n; i++) graph[i].clear();
  31. }
  32. void AddNodes(int count) {
  33. n += count;
  34. graph.resize(n);
  35. }
  36. void AddEdge(int s, int e, flow_t cap, flow_t caprev = 0) {
  37. Edge forward = { e, graph[e].size(), cap };
  38. Edge reverse = { s, graph[s].size(), caprev };
  39. graph[s].push_back(forward);
  40. graph[e].push_back(reverse);
  41. }
  42.  
  43. bool AssignLevel(int source, int sink) {
  44. int t = 0;
  45. memset(&l[0], 0, sizeof(l[0]) * l.size());
  46. l[source] = 1;
  47. q[t++] = source;
  48. for (int h = 0; h < t && !l[sink]; h++) {
  49. int cur = q[h];
  50. for (unsigned i = 0; i < graph[cur].size(); i++) {
  51. int next = graph[cur][i].next;
  52. if (l[next]) continue;
  53. if (graph[cur][i].res > 0) {
  54. l[next] = l[cur] + 1;
  55. q[t++] = next;
  56. }
  57. }
  58. }
  59. return l[sink] != 0;
  60. }
  61.  
  62. flow_t BlockFlow(int cur, int sink, flow_t currentFlow) {
  63. if (cur == sink) return currentFlow;
  64. for (unsigned &i = start[cur]; i < graph[cur].size(); i++) {
  65. int next = graph[cur][i].next;
  66. if (graph[cur][i].res == 0 || l[next] != l[cur] + 1)
  67. continue;
  68. if (flow_t res = BlockFlow(next, sink, min(graph[cur][i].res, currentFlow))) {
  69. int inv = graph[cur][i].inv;
  70. graph[cur][i].res -= res;
  71. graph[next][inv].res += res;
  72. return res;
  73. }
  74. }
  75. return 0;
  76. }
  77.  
  78. flow_t Solve(int source, int sink)
  79. {
  80. q.resize(n);
  81. l.resize(n);
  82. start.resize(n);
  83. flow_t ans = 0;
  84. while (AssignLevel(source, sink)) {
  85. memset(&start[0], 0, sizeof(start[0])*n);
  86. while (flow_t flow = BlockFlow(source, sink, numeric_limits<flow_t>::max())) {
  87. ans += flow;
  88. }
  89. }
  90. return ans;
  91. }
  92.  
  93. void FindMinCutComponent(int c){ // *optional
  94. vst[c] = true;
  95. for (int i = 0; i < graph[c].size(); i++){
  96. int n = graph[c][i].next;
  97. if (graph[c][i].res && !vst[n]){
  98. FindMinCutComponent(n);
  99. } // vst[i] && !vst[n + i] >> min cut component
  100. }
  101. }
  102.  
  103. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement