2 * This file is part of libFirm.
3 * Copyright (C) 2012 University of Karlsruhe.
8 * @brief Specialized implementation for perfect bipartite matching.
9 * @author Sebastian Hack
17 #include "bipartite.h"
25 bipartite_t *bipartite_new(int n_left, int n_right)
27 bipartite_t *gr = XMALLOCFZ(bipartite_t, adj, n_left);
31 gr->n_right = n_right;
33 for (i = 0; i < n_left; ++i)
34 gr->adj[i] = bitset_malloc(n_right);
39 void bipartite_free(bipartite_t *gr)
42 for (i = 0; i < gr->n_left; ++i)
43 bitset_free(gr->adj[i]);
47 void bipartite_add(bipartite_t *gr, int i, int j)
49 assert(i < gr->n_left && j < gr->n_right);
50 bitset_set(gr->adj[i], j);
53 void bipartite_remv(bipartite_t *gr, int i, int j)
55 assert(i < gr->n_left && j < gr->n_right);
56 bitset_clear(gr->adj[i], j);
59 int bipartite_adj(const bipartite_t *gr, int i, int j)
61 assert(i < gr->n_left && j < gr->n_right);
62 return bitset_is_set(gr->adj[i], j);
65 static int apply_alternating_path(const bipartite_t *gr, int *matching,
66 bitset_t *matched_left, bitset_t *matched_right)
69 int done_something = 0;
70 bitset_t *tmp = bitset_alloca(gr->n_right);
72 for (left = 0; left < gr->n_left; ++left) {
73 bitset_t *left_adj = gr->adj[left];
76 bitset_copy(tmp, left_adj);
78 if (matching[left] >= 0) {
79 int old_right = matching[left];
81 /* Check of all neighbors of the left node are already matched.
82 * We cannot improve this edge then. */
83 if (bitset_contains(left_adj, matched_right))
86 bitset_andnot(tmp, matched_right);
87 right = bitset_next_set(tmp, 0);
92 We have to find another left node which has the old right one as a neighbor.
93 This node must not be part of a matching
95 for (i = 0; i < gr->n_left; ++i)
96 if (i != left && bitset_is_set(gr->adj[i], old_right) && !bitset_is_set(matched_left, i))
99 /* If no such node can be found, exit. */
103 /* Else, we can improve this edge. */
104 matching[left] = right;
105 matching[i] = old_right;
106 bitset_set(matched_left, i);
107 bitset_set(matched_right, right);
112 /* We have to create a new single edge */
114 assert(!bitset_is_set(matched_left, left));
116 bitset_andnot(tmp, matched_right);
117 if (bitset_is_empty(tmp))
120 right = bitset_next_set(tmp, 0);
121 assert(!bitset_is_set(matched_right, right));
122 matching[left] = right;
123 bitset_set(matched_left, left);
124 bitset_set(matched_right, right);
129 return done_something;
132 void bipartite_matching(const bipartite_t *gr, int *matching)
134 bitset_t *matched_left = bitset_alloca(gr->n_left);
135 bitset_t *matched_right = bitset_alloca(gr->n_right);
137 memset(matching, -1, gr->n_left * sizeof(int));
138 while (apply_alternating_path(gr, matching, matched_left, matched_right)) {
142 void bipartite_dump_f(FILE *f, const bipartite_t *gr)
146 for (i = 0; i < gr->n_left; ++i) {
147 fprintf(f, "%d: ", i);
148 bitset_fprint(f, gr->adj[i]);
153 void bipartite_dump(const char *name, const bipartite_t *gr)
155 FILE *f = fopen(name, "w");
158 bipartite_dump_f(f, gr);