forked from chrisboyle/sgtpuzzles
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxflow.c
461 lines (400 loc) · 9.97 KB
/
maxflow.c
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
/*
* Edmonds-Karp algorithm for finding a maximum flow and minimum
* cut in a network. Almost identical to the Ford-Fulkerson
* algorithm, but apparently using breadth-first search to find the
* _shortest_ augmenting path is a good way to guarantee
* termination and ensure the time complexity is not dependent on
* the actual value of the maximum flow. I don't understand why
* that should be, but it's claimed on the Internet that it's been
* proved, and that's good enough for me. I prefer BFS to DFS
* anyway :-)
*/
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "maxflow.h"
#include "puzzles.h" /* for snewn/sfree */
int maxflow_with_scratch(void *scratch, int nv, int source, int sink,
int ne, const int *edges, const int *backedges,
const int *capacity, int *flow, int *cut)
{
int *todo = (int *)scratch;
int *prev = todo + nv;
int *firstedge = todo + 2*nv;
int *firstbackedge = todo + 3*nv;
int i, j, head, tail, from, to;
int totalflow;
/*
* Scan the edges array to find the index of the first edge
* from each node.
*/
j = 0;
for (i = 0; i < ne; i++)
while (j <= edges[2*i])
firstedge[j++] = i;
while (j < nv)
firstedge[j++] = ne;
assert(j == nv);
/*
* Scan the backedges array to find the index of the first edge
* _to_ each node.
*/
j = 0;
for (i = 0; i < ne; i++)
while (j <= edges[2*backedges[i]+1])
firstbackedge[j++] = i;
while (j < nv)
firstbackedge[j++] = ne;
assert(j == nv);
/*
* Start the flow off at zero on every edge.
*/
for (i = 0; i < ne; i++)
flow[i] = 0;
totalflow = 0;
/*
* Repeatedly look for an augmenting path, and follow it.
*/
while (1) {
/*
* Set up the prev array.
*/
for (i = 0; i < nv; i++)
prev[i] = -1;
/*
* Initialise the to-do list for BFS.
*/
head = tail = 0;
todo[tail++] = source;
/*
* Now do the BFS loop.
*/
while (head < tail && prev[sink] <= 0) {
from = todo[head++];
/*
* Try all the forward edges out of node `from'. For a
* forward edge to be valid, it must have flow
* currently less than its capacity.
*/
for (i = firstedge[from]; i < ne && edges[2*i] == from; i++) {
to = edges[2*i+1];
if (to == source || prev[to] >= 0)
continue;
if (capacity[i] >= 0 && flow[i] >= capacity[i])
continue;
/*
* This is a valid augmenting edge. Visit node `to'.
*/
prev[to] = 2*i;
todo[tail++] = to;
}
/*
* Try all the backward edges into node `from'. For a
* backward edge to be valid, it must have flow
* currently greater than zero.
*/
for (i = firstbackedge[from];
j = backedges[i], i < ne && edges[2*j+1]==from; i++) {
to = edges[2*j];
if (to == source || prev[to] >= 0)
continue;
if (flow[j] <= 0)
continue;
/*
* This is a valid augmenting edge. Visit node `to'.
*/
prev[to] = 2*j+1;
todo[tail++] = to;
}
}
/*
* If prev[sink] is non-null, we have found an augmenting
* path.
*/
if (prev[sink] >= 0) {
int max;
/*
* Work backwards along the path figuring out the
* maximum flow we can add.
*/
to = sink;
max = -1;
while (to != source) {
int spare;
/*
* Find the edge we're currently moving along.
*/
i = prev[to];
from = edges[i];
assert(from != to);
/*
* Determine the spare capacity of this edge.
*/
if (i & 1)
spare = flow[i / 2]; /* backward edge */
else if (capacity[i / 2] >= 0)
spare = capacity[i / 2] - flow[i / 2]; /* forward edge */
else
spare = -1; /* unlimited forward edge */
assert(spare != 0);
if (max < 0 || (spare >= 0 && spare < max))
max = spare;
to = from;
}
/*
* Fail an assertion if max is still < 0, i.e. there is
* an entirely unlimited path from source to sink. Also
* max should not _be_ zero, because by construction
* this _should_ be an augmenting path.
*/
assert(max > 0);
/*
* Now work backwards along the path again, this time
* actually adjusting the flow.
*/
to = sink;
while (to != source) {
/*
* Find the edge we're currently moving along.
*/
i = prev[to];
from = edges[i];
assert(from != to);
/*
* Adjust the edge.
*/
if (i & 1)
flow[i / 2] -= max; /* backward edge */
else
flow[i / 2] += max; /* forward edge */
to = from;
}
/*
* And adjust the overall flow counter.
*/
totalflow += max;
continue;
}
/*
* If we reach here, we have failed to find an augmenting
* path, which means we're done. Output the `cut' array if
* required, and leave.
*/
if (cut) {
for (i = 0; i < nv; i++) {
if (i == source || prev[i] >= 0)
cut[i] = 0;
else
cut[i] = 1;
}
}
return totalflow;
}
}
int maxflow_scratch_size(int nv)
{
return (nv * 4) * sizeof(int);
}
void maxflow_setup_backedges(int ne, const int *edges, int *backedges)
{
int i, n;
for (i = 0; i < ne; i++)
backedges[i] = i;
/*
* We actually can't use the C qsort() function, because we'd
* need to pass `edges' as a context parameter to its
* comparator function. So instead I'm forced to implement my
* own sorting algorithm internally, which is a pest. I'll use
* heapsort, because I like it.
*/
#define LESS(i,j) ( (edges[2*(i)+1] < edges[2*(j)+1]) || \
(edges[2*(i)+1] == edges[2*(j)+1] && \
edges[2*(i)] < edges[2*(j)]) )
#define PARENT(n) ( ((n)-1)/2 )
#define LCHILD(n) ( 2*(n)+1 )
#define RCHILD(n) ( 2*(n)+2 )
#define SWAP(i,j) do { int swaptmp = (i); (i) = (j); (j) = swaptmp; } while (0)
/*
* Phase 1: build the heap. We want the _largest_ element at
* the top.
*/
n = 0;
while (n < ne) {
n++;
/*
* Swap element n with its parent repeatedly to preserve
* the heap property.
*/
i = n-1;
while (i > 0) {
int p = PARENT(i);
if (LESS(backedges[p], backedges[i])) {
SWAP(backedges[p], backedges[i]);
i = p;
} else
break;
}
}
/*
* Phase 2: repeatedly remove the largest element and stick it
* at the top of the array.
*/
while (n > 0) {
/*
* The largest element is at position 0. Put it at the top,
* and swap the arbitrary element from that position into
* position 0.
*/
n--;
SWAP(backedges[0], backedges[n]);
/*
* Now repeatedly move that arbitrary element down the heap
* by swapping it with the more suitable of its children.
*/
i = 0;
while (1) {
int lc, rc;
lc = LCHILD(i);
rc = RCHILD(i);
if (lc >= n)
break; /* we've hit bottom */
if (rc >= n) {
/*
* Special case: there is only one child to check.
*/
if (LESS(backedges[i], backedges[lc]))
SWAP(backedges[i], backedges[lc]);
/* _Now_ we've hit bottom. */
break;
} else {
/*
* The common case: there are two children and we
* must check them both.
*/
if (LESS(backedges[i], backedges[lc]) ||
LESS(backedges[i], backedges[rc])) {
/*
* Pick the more appropriate child to swap with
* (i.e. the one which would want to be the
* parent if one were above the other - as one
* is about to be).
*/
if (LESS(backedges[lc], backedges[rc])) {
SWAP(backedges[i], backedges[rc]);
i = rc;
} else {
SWAP(backedges[i], backedges[lc]);
i = lc;
}
} else {
/* This element is in the right place; we're done. */
break;
}
}
}
}
#undef LESS
#undef PARENT
#undef LCHILD
#undef RCHILD
#undef SWAP
}
int maxflow(int nv, int source, int sink,
int ne, const int *edges, const int *capacity,
int *flow, int *cut)
{
void *scratch;
int *backedges;
int size;
int ret;
/*
* Allocate the space.
*/
size = ne * sizeof(int) + maxflow_scratch_size(nv);
backedges = smalloc(size);
if (!backedges)
return -1;
scratch = backedges + ne;
/*
* Set up the backedges array.
*/
maxflow_setup_backedges(ne, edges, backedges);
/*
* Call the main function.
*/
ret = maxflow_with_scratch(scratch, nv, source, sink, ne, edges,
backedges, capacity, flow, cut);
/*
* Free the scratch space.
*/
sfree(backedges);
/*
* And we're done.
*/
return ret;
}
#ifdef TESTMODE
#define MAXEDGES 256
#define MAXVERTICES 128
#define ADDEDGE(i,j) do{edges[ne*2] = (i); edges[ne*2+1] = (j); ne++;}while(0)
int compare_edge(const void *av, const void *bv)
{
const int *a = (const int *)av;
const int *b = (const int *)bv;
if (a[0] < b[0])
return -1;
else if (a[0] > b[0])
return +1;
else if (a[1] < b[1])
return -1;
else if (a[1] > b[1])
return +1;
else
return 0;
}
int main(void)
{
int edges[MAXEDGES*2], ne, nv;
int capacity[MAXEDGES], flow[MAXEDGES], cut[MAXVERTICES];
int source, sink, p, q, i, j, ret;
/*
* Use this algorithm to find a maximal complete matching in a
* bipartite graph.
*/
ne = 0;
nv = 0;
source = nv++;
p = nv;
nv += 5;
q = nv;
nv += 5;
sink = nv++;
for (i = 0; i < 5; i++) {
capacity[ne] = 1;
ADDEDGE(source, p+i);
}
for (i = 0; i < 5; i++) {
capacity[ne] = 1;
ADDEDGE(q+i, sink);
}
j = ne;
capacity[ne] = 1; ADDEDGE(p+0,q+0);
capacity[ne] = 1; ADDEDGE(p+1,q+0);
capacity[ne] = 1; ADDEDGE(p+1,q+1);
capacity[ne] = 1; ADDEDGE(p+2,q+1);
capacity[ne] = 1; ADDEDGE(p+2,q+2);
capacity[ne] = 1; ADDEDGE(p+3,q+2);
capacity[ne] = 1; ADDEDGE(p+3,q+3);
capacity[ne] = 1; ADDEDGE(p+4,q+3);
/* capacity[ne] = 1; ADDEDGE(p+2,q+4); */
qsort(edges, ne, 2*sizeof(int), compare_edge);
ret = maxflow(nv, source, sink, ne, edges, capacity, flow, cut);
printf("ret = %d\n", ret);
for (i = 0; i < ne; i++)
printf("flow %d: %d -> %d\n", flow[i], edges[2*i], edges[2*i+1]);
for (i = 0; i < nv; i++)
if (cut[i] == 0)
printf("difficult set includes %d\n", i);
return 0;
}
#endif