14 bipartite_t *bipartite_new(int n_left, int n_right)
19 size = n_left > 0 ? n_left - 1 : 0;
20 gr = xmalloc(sizeof(*gr) + size * sizeof(void *));
21 memset(gr, 0, sizeof(*gr));
24 gr->n_right = n_right;
26 for(i = 0; i < n_left; ++i)
27 gr->adj[i] = bitset_malloc(n_right);
32 void bipartite_free(bipartite_t *gr)
35 for(i = 0; i < gr->n_left; ++i)
36 bitset_free(gr->adj[i]);
40 void bipartite_add(bipartite_t *gr, int i, int j)
42 assert(i < gr->n_left && j < gr->n_right);
43 bitset_set(gr->adj[i], j);
46 void bipartite_remv(bipartite_t *gr, int i, int j)
48 assert(i < gr->n_left && j < gr->n_right);
49 bitset_clear(gr->adj[i], j);
52 int bipartite_adj(const bipartite_t *gr, int i, int j)
54 assert(i < gr->n_left && j < gr->n_right);
55 return bitset_is_set(gr->adj[i], j);
58 static int apply_alternating_path(const bipartite_t *gr, int *matching,
59 bitset_t *matched_left, bitset_t *matched_right)
62 int done_something = 0;
63 bitset_t *tmp = bitset_alloca(gr->n_right);
65 for(left = 0; left < gr->n_left; ++left) {
66 bitset_t *left_adj = gr->adj[left];
69 bitset_copy(tmp, left_adj);
71 if(matching[left] >= 0) {
72 int old_right = matching[left];
74 /* Check of all neighbors of the left node are already matched.
75 * We cannot improve this edge then. */
76 if(bitset_contains(left_adj, matched_right))
79 bitset_andnot(tmp, matched_right);
80 right = bitset_next_set(tmp, 0);
85 We have to find another left node which has the old right one as a neighbor.
86 This node must not be part of a matching
88 for(i = 0; i < gr->n_left; ++i)
89 if(i != left && bitset_is_set(gr->adj[i], old_right) && !bitset_is_set(matched_left, i))
92 /* If no such node can be found, exit. */
96 /* Else, we can improve this edge. */
97 matching[left] = right;
98 matching[i] = old_right;
99 bitset_set(matched_left, i);
100 bitset_set(matched_right, right);
105 /* We have to create a new single edge */
107 assert(!bitset_is_set(matched_left, left));
109 bitset_andnot(tmp, matched_right);
110 if(bitset_popcnt(tmp) == 0)
113 right = bitset_min(tmp);
114 assert(!bitset_is_set(matched_right, right));
115 matching[left] = right;
116 bitset_set(matched_left, left);
117 bitset_set(matched_right, right);
122 return done_something;
125 void bipartite_matching(const bipartite_t *gr, int *matching)
127 bitset_t *matched_left = bitset_alloca(gr->n_left);
128 bitset_t *matched_right = bitset_alloca(gr->n_right);
130 memset(matching, -1, gr->n_left * sizeof(int));
131 while(apply_alternating_path(gr, matching, matched_left, matched_right));
134 void bipartite_dump_f(FILE *f, const bipartite_t *gr)
138 for(i = 0; i < gr->n_left; ++i) {
139 bitset_fprint(f, gr->adj[i]);
144 void bipartite_dump(const char *name, const bipartite_t *gr) {
145 FILE *f = fopen(name, "w");
148 bipartite_dump_f(f, gr);