-
Notifications
You must be signed in to change notification settings - Fork 0
/
flow_graph.hpp
480 lines (423 loc) · 15.9 KB
/
flow_graph.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
// Author: Marcus Östlig, Tomas Möre 2019
#include <vector>
#include <queue>
#include <deque>
#include <stack>
#include <optional>
#include <limits>
#include <algorithm>
#include <functional>
namespace popup {
/**
* Edge class used internally by FlowGraph.
*/
template <typename Flow, typename Weight>
class Edge {
size_t from_;
size_t to_;
Flow capacity_;
Flow flow_ = 0;
Weight weight_;
// The edge that goes in the opposite direction of this edge.
Edge<Flow, Weight>* opposite_edge_;
public:
Edge(size_t from, size_t to, Flow capacity, Weight weight) {
from_ = from;
to_ = to;
flow_ = 0;
capacity_ = capacity;
weight_ = weight;
}
/**
* Given a directed edge (u, v), create the opposite edge (u,v)
* and link them to eachother.
*/
Edge<Flow, Weight>* make_opposite() {
Edge<Flow, Weight>* e = new Edge<Flow, Weight>(to_, from_, 0, -weight_);
e->set_opposite(this);
set_opposite(e);
return e;
}
void set_opposite(Edge<Flow, Weight>* opposite) {
opposite_edge_ = opposite;
}
size_t from() const {
return from_;
}
size_t to() const {
return to_;
}
Flow capacity() const {
return capacity_;
}
Flow flow() const {
return flow_;
}
Flow weight() const {
return weight_;
}
/**
* Increase flow in direction of this edge and decreases
* flow in the opposite direction.
*/
void increase_flow(Flow f) {
flow_ += f;
opposite_edge_->flow_ -= f;
}
Flow residual() const {
return capacity_ - flow_;
}
Edge<Flow, Weight>* opposite_edge() const {
return opposite_edge_;
}
};
/**
* Flow graph used to calculate: Maximum flow
* Minimum cost maximum flow, s-t cut (minimum cut).
*/
template <typename Flow, typename Weight>
class FlowGraph {
std::vector<std::vector<Edge<Flow, Weight>*>> list_;
size_t num_nodes_ = 0;
public:
FlowGraph(size_t num_nodes) {
num_nodes_ = num_nodes;
list_.resize(num_nodes, std::vector<Edge<Flow, Weight>*>());
}
size_t num_nodes() const {
return num_nodes_;
}
/**
* Add an edge and another edge in the opposite direction.
*/
void add_edge(size_t from, size_t to, Flow capacity, Weight weight) {
Edge<Flow, Weight>* edge = new Edge<Flow, Weight>(from, to, capacity, weight);
list_[from].emplace_back(edge);
list_[to].emplace_back(edge->make_opposite());
}
/**
* Get the residual graph.
* Only to be used after edmond-karp.
*/
std::vector<Edge<Flow, Weight>*> get_used_edges() {
std::vector<Edge<Flow, Weight>*> used_edges;
for(auto v : list_) {
for(auto edge : v) {
if(edge->flow() > 0 && edge->capacity() > 0) {
used_edges.emplace_back(edge);
}
}
}
return used_edges;
}
/**
* The outbound flow from the source.
*/
Flow outbound_flow(size_t source) {
Flow total = 0;
for(auto edge : list_[source]) {
if(edge->capacity() > 0) {
total += edge->flow();
}
}
return total;
}
/**
* Depth-first search that runs the function f for each visited node.
*/
void dfs(size_t start, std::function<void(size_t)> f) const {
std::stack<size_t> stack;
stack.push(start);
std::vector<bool> visited(num_nodes(), false);
while (!stack.empty()) {
auto node = stack.top();
stack.pop();
f(node);
visited[node] = true;
for (auto& edge : list_[node]) {
if (!visited[edge->to()] && edge->residual() > 0) {
visited[edge->to()] = true;
stack.push(edge->to());
}
}
}
};
/**
* Breath-first search to find the residual of the shortest path (in number of edges)
* from source to sink. Will return 0 if there is no path with any residual.
*/
std::pair<Flow, Weight> bfs(
size_t source,
size_t sink,
std::vector<Edge<Flow, Weight>*> &came_from
) {
std::vector<bool> visited(num_nodes(), false);
std::vector<Flow> min_residual(num_nodes(), std::numeric_limits<Flow>::max());
if (came_from.size() < num_nodes()) {
came_from.resize(num_nodes());
}
std::queue<size_t> queue;
queue.push(source);
while (!queue.empty()) {
auto current_node = queue.front();
queue.pop();
visited[current_node] = true;
for (const auto edge : list_[current_node]) {
if(edge->residual() <= 0) {
continue;
}
if (edge->to() == sink) {
came_from[sink] = edge;
return std::make_pair(std::min(min_residual[current_node], edge->residual()), 0);
}
if (!visited[edge->to()]) {
came_from[edge->to()] = edge;
min_residual[edge->to()] =
std::min(min_residual[current_node], edge->residual());
queue.push(edge->to());
visited[edge->to()] = true;
}
}
}
return std::make_pair(0, 0);
}
/**
* D´Esopo-Pape search to find the residual and weight of the shortest
* paths (in terms of weight) from source to sink. Will return 0 if
* there is no path with any residual.
*/
std::pair<Flow, Weight> desopo_pape(
size_t from,
size_t to,
std::vector<Edge<Flow, Weight>*> &came_from
) {
std::vector<Weight> distances(
num_nodes(),
std::numeric_limits<Weight>::max()
);
std::vector<Flow> min_residual(
num_nodes(),
std::numeric_limits<Flow>::max()
);
distances[from] = 0;
std::vector<int> status(num_nodes(), 2);
std::deque<size_t> que;
que.push_back(from);
std::fill(came_from.begin(), came_from.end(), nullptr);
while (!que.empty()) {
size_t u = que.front();
que.pop_front();
status[u] = 0;
for (auto& edge : list_[u]) {
if (edge->residual() > 0
&& distances[edge->to()] > distances[u] + edge->weight()) {
distances[edge->to()] = distances[u] + edge->weight();
came_from[edge->to()] = edge;
min_residual[edge->to()] = std::min(
min_residual[edge->from()],
edge->residual()
);
if (status[edge->to()] == 2) {
status[edge->to()] = 1;
que.push_back(edge->to());
} else if (status[edge->to()] == 0) {
status[edge->to()] = 1;
que.push_front(edge->to());
}
}
}
}
if (min_residual[to] == std::numeric_limits<Flow>::max()) {
return std::make_pair(0, 0);
} else {
return std::make_pair(min_residual[to], distances[to]);
}
}
/**
* Bellman Ford search to find the residual and weight of the shortest
* paths (in terms of weight) from source to sink. Will return 0 if
* there is no path with any residual.
* TODO: A work in progress
*/
std::pair<Flow, Weight> bellman_ford(
size_t from,
size_t to,
std::vector<Edge<Flow, Weight>*> &came_from
) {
std::vector<Weight> distances(
num_nodes(),
std::numeric_limits<Weight>::max()
);
std::vector<Flow> min_residual(
num_nodes(),
std::numeric_limits<Flow>::max()
);
distances[from] = 0;
Edge<Flow, Weight> dummy_edge =
Edge<Flow, Weight>(0, from, std::numeric_limits<Flow>::max(), 0);
came_from[from] = &dummy_edge;
for (size_t n = 0; n < num_nodes() - 1; n++) {
for (size_t i = 0; i < num_nodes(); i++) {
for (auto& edge : list_[i]) {
if (distances[edge->from()] != std::numeric_limits<Weight>::max()) {
auto trav_cost = distances[edge->from()] + edge->weight();
if (trav_cost < distances[edge->to()] && edge->residual() > 0) {
came_from[edge->to()] = edge;
distances[edge->to()] = trav_cost;
min_residual[edge->to()] = std::min(
min_residual[edge->from()],
edge->residual()
);
}
}
}
}
}
if (min_residual[to] == std::numeric_limits<Flow>::max()) {
return std::make_pair(0, 0);
} else {
return std::make_pair(min_residual[to], distances[to]);
}
}
/**
* Dijkstra search to find the residual and weight of the shortest
* paths (in terms of weight) from source to sink. Will return 0 if
* there is no path with any residual. Does not work with
* Ford Fulkerson, because it cannot handle negative weight.
*/
std::pair<Flow, Weight> dijkstra(
size_t from,
size_t to,
std::vector<Edge<Flow, Weight>*> &came_from
) {
const auto cmp = [](const std::pair<Edge<Flow,Weight>*, Flow>& a,
const std::pair<Edge<Flow,Weight>*, Flow>& b) {
return a.second > b.second;
};
std::priority_queue<
std::pair<Edge<Flow,Weight>*, Weight>,
std::vector<std::pair<Edge<Flow,Weight>*, Weight>>,
decltype(cmp)> queue(cmp);
std::vector<Weight> distances(num_nodes(), std::numeric_limits<Weight>::max());
std::vector<bool> visited(num_nodes(), false);
std::vector<Flow> min_residual(num_nodes(), std::numeric_limits<Flow>::max());
distances[from] = 0;
Edge<Flow, Weight> dummy_edge =
Edge<Flow, Weight>(
0,
from,
std::numeric_limits<Flow>::max(),
0
);
queue.emplace(std::make_pair(&dummy_edge,0));
came_from[from] = &dummy_edge;
while (!queue.empty()) {
auto e = queue.top();
queue.pop();
auto current_edge = e.first;
auto current_node = current_edge->to();
if (visited[current_node]) {
continue;
}
min_residual[current_node] = std::min(
min_residual[current_edge->from()],
current_edge->residual()
);
visited[current_node] = true;
auto cost = e.second;
if (current_node == to) {
break;
}
for (const auto edge : list_[current_node]) {
if (edge->residual() > 0 && !visited[edge->to()]) {
auto node = edge->to();
const auto weight = edge->weight();
auto node_dist = distances[node];
auto alt_dist = weight + cost;
if (node_dist > alt_dist) {
distances[node] = alt_dist;
came_from[node] = edge;
queue.emplace(std::make_pair(edge, alt_dist));
}
}
}
}
if (!visited[to]) {
return std::make_pair(0, 0);
} else {
return std::make_pair(min_residual[to], distances[to]);
}
};
/**
* Ford Fulkerson algorithm it find the maximum flow between
* the source and the sink.
* If used with D´Esopo-Pape, it will return the
* minimum cost maximum flow.
*/
std::pair<Flow, Weight> ford_fulkerson(
size_t source,
size_t sink,
std::function<std::pair<Flow,Weight>(
size_t,
size_t,
std::vector<Edge<Flow, Weight>*>&)> path_algo
) {
std::vector<Edge<Flow, Weight>*> came_from(num_nodes(), nullptr);
Flow flow = 0;
Weight cost = 0;
for (std::pair<Flow, Weight> res = path_algo(source, sink, came_from);
res.first > 0;
res = path_algo(source, sink, came_from)) {
size_t current_node = sink;
flow += res.first;
cost += res.first * res.second;
//std::cerr << "rf: " << res.first << " rs: "<<res.second << std::endl;
while (current_node != source) {
const auto edge = came_from[current_node];
edge->increase_flow(res.first);
current_node = edge->from();
}
}
return std::make_pair(flow,cost);
}
/**
* Returns the maximum flow using minimum cost between the source
* and the sink.
*/
std::pair<Flow, Weight> min_cost_max_flow(size_t source, size_t sink) {
using namespace std::placeholders;
return ford_fulkerson(
source,
sink,
std::bind(&FlowGraph<Flow,Weight>::desopo_pape, this, _1, _2, _3)
);
}
/**
* Returns the maximum flow between the source and the sink.
*/
Flow edmond_karp(size_t source, size_t sink) {
using namespace std::placeholders;
return ford_fulkerson(
source,
sink,
std::bind(&FlowGraph<Flow,Weight>::bfs, this, _1, _2, _3)
).first;
}
/**
* Return a set of nodes U of the minimum cut (in terms of weight)
* given a source and a sink. Uses DFS to find the set U of nodes
* reachable from the source.
*/
std::pair<std::vector<size_t>, Flow> st_cut(
size_t source,
size_t sink
) {
Flow max_flow = edmond_karp(source, sink);
std::vector<size_t> result;
dfs(source, [&](size_t node) {
result.push_back(node);
});
return std::make_pair(result, max_flow);
}
};
} // namespace popup