-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEdmondBlossomMaxMatch.java
568 lines (487 loc) · 16.4 KB
/
EdmondBlossomMaxMatch.java
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import javax.xml.crypto.dsig.spec.HMACParameterSpec;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Get Maximum matching in general undirected graph Uses Edmonds blossom
* matching algorithm
*
* @author austin
*
*/
public class EdmondBlossomMaxMatch {
int earr[],narr[];
enum MNodeType {
EVEN, ODD, FREE
}
class MNode {
int label = 0;
MNodeType type;
MNode parent = null;
LinkedHashSet<MNode> nbrs = new LinkedHashSet<MNode>();
boolean contracted = false;
MNode matchedWith = null;
int forIteration;
public Set<MNode> getNbrs() {
return nbrs;
}
void addNbr(MNode nbr) {
if (nbr == null) {
return;
}
if (nbr == this) {
return;
}
if (nbrs.contains(nbr)) {
return;
}
nbrs.add(nbr);
}
void removeNbr(MNode nbr) {
nbrs.remove(nbr);
}
public MNode getMatchedWith() {
return matchedWith;
}
public void setMatchedWith(MNode matchedWith) {
this.matchedWith = matchedWith;
}
@Override
public String toString() {
return "" + label;
}
}
class Blossom {
MNode root;
List<MNode> cycle;
MNode blossomAlias;
}
class Graph {
int nodeCount;
ArrayList<MNode> nodes = new ArrayList<MNode>();
}
final static int BLOSSOMLABEL = -1;
static boolean verbose = true;
Graph g = null;
//list of current blossoms stored in a map
HashMap<MNode, Blossom> currBlossoms = new HashMap<MNode, Blossom>();
// current list of Blossoms in a List
ArrayList<Blossom> currB = new ArrayList<Blossom>();
int bLabel = -2; // Blossom start label
MNode currFreeNode = null;
void edmondExec() {
creatMAlternatingTrees(g.nodes);
printMatchings(true);
}
/**
* Take all the freenodes and find an alternating path with it If found then
* , update the augmenting path with new matchings
*
* @param freeNodes
*/
void creatMAlternatingTrees(ArrayList<MNode> freeNodes) {
int iter = 1;
MNode augNode = null;
for (MNode freeNode : freeNodes) {
if (freeNode.type != MNodeType.FREE)
continue;
currFreeNode = freeNode;
if ((augNode = createMAlternatingTree(freeNode, iter, null)) != null) {
while ((augNode != null) && (augNode.label < BLOSSOMLABEL))// blossom
{
augNode = createMAlternatingTree(freeNode, ++iter, null);
}
if (augNode != null) {
updateAugmentingPath(augNode, iter);
}
}
if (augNode == null) {
updateNode(freeNode, iter, null, MNodeType.FREE);
}
expandAllBlossoms(iter);
iter++;
}
}
/**
* Find alternating paths recursively. Node parameter will only be Even
* nodes.
*
* @param node
* @param iter
* @param parent
* @return
*/
MNode createMAlternatingTree(MNode node, int iter, MNode parent) {
ArrayList<MNode> cycle;
MNode nodeMatched = null;
Blossom blossom = null;
updateNode(node, iter, parent, MNodeType.EVEN);
LinkedList<MNode> nbrsQ = new LinkedList<MNode>(node.getNbrs());
MNode nbr = null;
while ((nbr = nbrsQ.poll()) != null) {
if (nbr.contracted)
continue;
if ((nbr == node))
continue;
if (nbr.forIteration != iter) {
if (nbr.type == MNodeType.FREE) {
updateNode(nbr, iter, node, MNodeType.ODD);
return nbr;
} else {
updateNode(nbr, iter, node, MNodeType.ODD);
nodeMatched = nbr.matchedWith;
MNode nodeInPath = null;
nodeInPath = createMAlternatingTree(nodeMatched, iter, nbr);
if (nodeInPath != null) {
return nodeInPath;
} else {
updateNode(node, iter, parent, MNodeType.EVEN);
continue;
}
}
}
if (nbr.type == MNodeType.ODD) {
continue;
}
if (nbr.type == MNodeType.EVEN) {
cycle = findBlossom(nbr, node, iter);
if (cycle == null) { // root.parent == null, we can ignore this
continue;
}
blossom = contractBlossom(cycle.subList(0, cycle.size()),
cycle.get(cycle.size() - 1), iter);
currBlossoms.put(blossom.blossomAlias, blossom);
currB.add(blossom);
return blossom.blossomAlias;
}
}
return null;
}
/**
* Find the Odd cycle that can be contracted into a blossom
*
* @param node
* @param nbr
* @param iter
* @return
*/
ArrayList<MNode> findBlossom(MNode node, MNode nbr, int iter) {
ArrayList<MNode> cycle = new ArrayList<MNode>();
MNode root = node;
MNode origNbr = nbr;
if ((root == currFreeNode) || (nbr == currFreeNode)) {
return null;
}
cycle.add(root);
while ((nbr != null) && (nbr != root)) {
cycle.add(nbr);
nbr = nbr.parent;
}
root.parent = origNbr;
cycle.add(root);
return cycle;
}
/**
* Contract the blossom into a Blossom structure, updating the nbrs of the
* nodes comprising the odd cycle
*
* @param cycle
* @param root
* @param iter
* @return
*/
Blossom contractBlossom(List<MNode> cycle, MNode root, int iter) {
MNode bALias = new MNode();
MNode node = null;
bALias.forIteration = iter;
bALias.type = MNodeType.EVEN;
bALias.label = bLabel--;
Blossom blossom = new Blossom();
blossom.cycle = cycle;
blossom.root = root;
blossom.blossomAlias = bALias;
for (int i = 0; i < cycle.size(); i++) {
node = cycle.get(i);
node.contracted = true;
}
for (int i = 0; i < cycle.size(); i++) {
node = cycle.get(i);
for (MNode nbr : node.getNbrs()) {
if (nbr.contracted)
continue;
nbr.addNbr(bALias);
bALias.addNbr(nbr);
}
node.forIteration = iter;
}
if (root.matchedWith != null) {
bALias.matchedWith = root.matchedWith;
root.matchedWith.matchedWith = bALias;
}
return blossom;
}
/**
* Expand the blossom, update the neighbors and the parent pointers
*
* @param blossom
* @param stem
* @param antennae
* @param iter
* @return
*/
MNode expandBlossom(Blossom blossom, MNode stem, MNode antennae, int iter) {
List<MNode> cycle = blossom.cycle;
MNode newRoot = null;
MNode newOut = null;
for (MNode node : cycle) {
for (MNode nbr : node.getNbrs()) {
if (nbr.contracted)
continue;
nbr.removeNbr(blossom.blossomAlias);
if ((newRoot == null) && (nbr == stem)
&& (node == blossom.root)) {
newRoot = node;
} else if ((newOut == null) && (nbr == antennae)) {
newOut = node;
}
}
node.forIteration = iter;
}
for (MNode node : cycle) {
node.contracted = false;
}
if (newRoot == null)
newRoot = blossom.root;
if ((blossom.root != null)
&& (blossom.root.matchedWith != null)
&& (blossom.root.matchedWith.matchedWith == blossom.blossomAlias)) {
blossom.root.matchedWith.matchedWith = blossom.root;
}
antennae.parent = newOut;
if (newRoot == blossom.root) {
if (newOut.matchedWith.parent == newOut) {
Collections.reverse(cycle);
MNode n = null;
for (int i = 0; i < cycle.size() - 1; i++) {
n = cycle.get(i);
n.parent = cycle.get(i + 1);
}
}
} else {
if (newRoot.parent == newRoot.matchedWith) {
Collections.reverse(cycle);
MNode n = null;
for (int i = 0; i < cycle.size() - 1; i++) {
n = cycle.get(i);
n.parent = cycle.get(i + 1);
}
}
}
if (newRoot != null)
newRoot.parent = stem;
return newOut;
}
/**
* Expand all the blossoms. Will be called when no alternating path through
* the existing blossoms can be found
*
* @param iter
*/
void expandAllBlossoms(int iter) {
Blossom blossom = null;
for (int i = currB.size() - 1; i >= 0; i--) {
blossom = currB.get(i);
List<MNode> cycle = blossom.cycle;
for (MNode node : cycle) {
node.contracted = false;
for (MNode nbr : node.getNbrs()) {
if (nbr.contracted)
continue;
nbr.removeNbr(blossom.blossomAlias);
}
node.forIteration = iter;
}
if ((blossom.root != null)
&& (blossom.root.matchedWith != null)
&& (blossom.root.matchedWith.matchedWith == blossom.blossomAlias)) {
blossom.root.matchedWith.matchedWith = blossom.root;
}
}
currB.clear();
currBlossoms.clear();
}
/**
* Update the alternating path , with new matchings, expanding blossoms
* along the path
*
* @param pathNode
* @param iter
*/
void updateAugmentingPath(MNode pathNode, int iter) {
MNode n = pathNode;
MNode np = null;
MNode npp = null;
Blossom blossom;
while (n != null) {
np = n.parent;
npp = np.parent;
if (np.label < BLOSSOMLABEL) {
blossom = currBlossoms.get(np);
while ((n.parent = expandBlossom(blossom, npp, n, iter)).label < BLOSSOMLABEL) {
np = n.parent;
blossom = currBlossoms.get(np);
npp = np.parent;
}
np = n.parent;
npp = np.parent;
}
if ((npp != null) && (npp.label < BLOSSOMLABEL)) {
blossom = currBlossoms.get(npp);
while ((np.parent = expandBlossom(blossom, npp.parent, np, iter)).label < BLOSSOMLABEL) {
npp = np.parent;
blossom = currBlossoms.get(np);
}
npp = np.parent;
}
n.matchedWith = np;
np.matchedWith = n;
n = npp;
}
}
void updateNode(MNode node, int iter, MNode parent, MNodeType type) {
node.forIteration = iter;
node.parent = parent;
node.type = type;
}
void readNextGraph(BufferedReader bufReader) throws Exception {
try {
int nodesCount = Integer.parseInt(bufReader.readLine());
int edgesCount = Integer.parseInt(bufReader.readLine());
g = new Graph();
g.nodeCount = nodesCount;
int u,v;
narr = new int[nodesCount];
earr = new int[edgesCount*2];
initGraph();
for(int j=0;j< nodesCount;j++)
{
String[] strarr = bufReader.readLine().split(",");
narr[j]=Integer.parseInt(strarr[2]);
}
for (int k = 0; k < edgesCount; k++)
{
String[] strArr = bufReader.readLine().split(","); u=0;v=0;
u = Integer.parseInt(strArr[0]);
v = Integer.parseInt(strArr[1]);
createNode(u,v);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
void changegraph(BufferedReader bufReader) throws Exception {
try{
int u,v;
int nodesCount = Integer.parseInt(bufReader.readLine());
int edgesCount = Integer.parseInt(bufReader.readLine());
for(int j=0;j< nodesCount;j++)
{
String[] strarr = bufReader.readLine().split(",");
narr[j]=Integer.parseInt(strarr[2]);
}
for (int k = 0; k < edgesCount; k++)
{
String[] strArr = bufReader.readLine().split(",");
u = Integer.parseInt(strArr[0]);
v = Integer.parseInt(strArr[1]);
for(int m=3;m<=5;m++)
{
strArr[m]="0";
}
for(int l=0;l<edgesCount;l=l+2)
{
if(u== earr[l] || u== earr[l+1])
{
if(v==earr[l] || v== earr[l+1])
strArr[3]="255";
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
void initGraph() {
for (int i = 0; i < g.nodeCount; i++) {
g.nodes.add(createNode(i));
}
currBlossoms.clear();
}
MNode createNode(int u) {
MNode node = null;
node = new MNode();
node.label = u;
node.type = MNodeType.FREE;
// g.nodes.set(u, node);
return node;
}
void createNode(int u, int v) {
ArrayList<Integer> nodes = new ArrayList<Integer>();
g.nodes.get(u).addNbr(g.nodes.get(v));
g.nodes.get(v).addNbr(g.nodes.get(u));
}
void printMatchings(boolean print) {
if ((!print) && (!verbose))
return;
// ArrayList<MNode> matched = new ArrayList<MNode>();
int c = 0;
for (MNode node : g.nodes) {
if (node.matchedWith == null)
continue;
earr[c]=node.label;
earr[c+1]=node.matchedWith.label;
c=c+2;
}
}
public static void main(String filepath) {
BufferedReader bufReader = null;
if (filepath.length() < 0) {
System.out.println(filepath);
// Unit Test Mode
bufReader = new BufferedReader(
new StringReader(
"1\n10\n10\n0 1\n0 2\n2 3\n3 4\n4 5\n5 0\n6 1\n4 7\n8 1\n7 9\n"));
} else {
try {
bufReader = new BufferedReader(new FileReader(filepath));
} catch (Exception e) {
e.printStackTrace();
return;
}
EdmondBlossomMaxMatch dsp = new EdmondBlossomMaxMatch();
try {
dsp.readNextGraph(bufReader);
dsp.edmondExec();
dsp.changegraph(bufReader);
} catch (Exception e) {
System.err.println("Exiting : " + e);
e.printStackTrace();
} finally {
try {
bufReader.close();
} catch (Exception f) {
}
}
}
}
}