| 1 | /* -*- mode: C++; indent-tabs-mode: nil; -*- |
| 2 | * |
| 3 | * This file is a part of LEMON, a generic C++ optimization library. |
| 4 | * |
| 5 | * Copyright (C) 2003-2011 |
| 6 | * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport |
| 7 | * (Egervary Research Group on Combinatorial Optimization, EGRES). |
| 8 | * |
| 9 | * Permission to use, modify and distribute this software is granted |
| 10 | * provided that this copyright notice appears in all copies. For |
| 11 | * precise terms see the accompanying LICENSE file. |
| 12 | * |
| 13 | * This software is provided "AS IS" with no warranty of any kind, |
| 14 | * express or implied, and with no claim as to its suitability for any |
| 15 | * purpose. |
| 16 | * |
| 17 | */ |
| 18 | |
| 19 | #ifndef LEMON_HOPCROFT_KARP_H |
| 20 | #define LEMON_HOPCROFT_KARP_H |
| 21 | |
| 22 | #include <lemon/core.h> |
| 23 | #include <list> |
| 24 | |
| 25 | /// \ingroup matching |
| 26 | /// \file |
| 27 | /// \brief Hopcroft-Karp algorithm. |
| 28 | namespace lemon { |
| 29 | |
| 30 | /// \brief The Hopcroft-Karp bipartite matching algorithm |
| 31 | /// |
| 32 | /// Finds maximal matching in a given bipartite |
| 33 | /// graph using the Hopcroft-Karp algorithm, |
| 34 | /// having \f$O(e\sqrt{n})\f$ complexity. |
| 35 | template <typename BPG> |
| 36 | class HopcroftKarp { |
| 37 | public: |
| 38 | /// Type of the bipartite graph |
| 39 | typedef BPG BpGraph; |
| 40 | /// Type of the matching map |
| 41 | typedef typename BPG::template NodeMap<typename BPG::Edge> MatchingMap; |
| 42 | private: |
| 43 | TEMPLATE_BPGRAPH_TYPEDEFS(BpGraph); |
| 44 | |
| 45 | const BpGraph& _bpg; |
| 46 | MatchingMap* _matching; |
| 47 | bool _local_matching; |
| 48 | |
| 49 | protected: |
| 50 | void createStructures() { |
| 51 | if (!_matching) { |
| 52 | _matching = new MatchingMap(_bpg, INVALID); |
| 53 | _local_matching = true; |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | void destroyStructures() { |
| 58 | if (_local_matching) { |
| 59 | delete _matching; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | HopcroftKarp() {} |
| 64 | |
| 65 | public: |
| 66 | /// \brief Constructor |
| 67 | /// |
| 68 | /// Constructs the class on the given bipartite graph. |
| 69 | HopcroftKarp(const BpGraph& bpg) : _bpg(bpg), |
| 70 | _matching(0), |
| 71 | _local_matching(false) |
| 72 | {} |
| 73 | |
| 74 | |
| 75 | /// \brief Destructor |
| 76 | /// |
| 77 | /// Destructor. |
| 78 | ~HopcroftKarp() { |
| 79 | destroyStructures(); |
| 80 | } |
| 81 | |
| 82 | /// \brief Sets the matching map |
| 83 | /// |
| 84 | /// Sets the matching map. |
| 85 | /// If you don't use this function before calling \ref init(), |
| 86 | /// an instance will be allocated automatically. |
| 87 | /// The destructor deallocates this automatically allocated map, |
| 88 | /// of course. |
| 89 | /// This member is not to initialize the algorithm with a valid |
| 90 | /// matching; use \ref matchingInit() instead. |
| 91 | /// |
| 92 | /// \return <tt>(*this)</tt> |
| 93 | HopcroftKarp& matchingMap(MatchingMap& map) { |
| 94 | _matching = ↦ |
| 95 | _local_matching = false; |
| 96 | return *this; |
| 97 | } |
| 98 | |
| 99 | /// \brief Returns a const reference to the matching map |
| 100 | /// |
| 101 | /// Returns a const reference to the matching map, which contains |
| 102 | /// the matching edge for every node (and \c INVALID for the |
| 103 | /// unmatched nodes). |
| 104 | const MatchingMap& matchingMap() const { |
| 105 | return *_matching; |
| 106 | } |
| 107 | |
| 108 | |
| 109 | /// \brief Initializes the algorithm |
| 110 | /// |
| 111 | /// Allocates the matching map if necessary, and sets |
| 112 | /// to empty matching. |
| 113 | /// |
| 114 | /// \pre \ref init() is not called. |
| 115 | void init() { |
| 116 | createStructures(); |
| 117 | if (!_local_matching) { |
| 118 | for (NodeIt it(_bpg); it!=INVALID; ++it) { |
| 119 | _matching->set(it, INVALID); |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /// \brief Smarter initialization of the matching. |
| 125 | /// |
| 126 | /// Allocates the matching map if necessary, and initializes |
| 127 | /// the algorithm with a trivially found matching: iterating |
| 128 | /// on every edge, take it in if both endnodes are unmatched. |
| 129 | /// |
| 130 | /// \return Size of the found matching. |
| 131 | /// |
| 132 | /// \note heuristicInit() replaces init() regarding the preconditions. |
| 133 | int heuristicInit() { |
| 134 | init(); |
| 135 | int size = 0; |
| 136 | |
| 137 | for (BlueIt b_it(_bpg); b_it!=INVALID; ++b_it) { |
| 138 | if ((*_matching)[b_it] == INVALID) { |
| 139 | bool matched = false; |
| 140 | for (IncEdgeIt inc(_bpg, b_it); inc != INVALID && !matched; ++inc) { |
| 141 | if ((*_matching)[_bpg.redNode(inc)] == INVALID) { |
| 142 | _matching->set(_bpg.redNode(inc), inc); |
| 143 | _matching->set(b_it, inc); |
| 144 | matched = true; |
| 145 | ++size; |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | return size; |
| 151 | } |
| 152 | |
| 153 | /// \brief Initialize the matching from a map. |
| 154 | /// |
| 155 | /// Allocates the matching map if necessary, and |
| 156 | /// initializes the algorithm with a matching given as a bool edgemap, |
| 157 | /// in which an edge is true if it is in the matching. |
| 158 | /// |
| 159 | /// If the given matching is invalid, some edges will be left out. |
| 160 | /// |
| 161 | /// \return \c false if the given matching is invalid. |
| 162 | /// |
| 163 | /// \note matchingInit() replaces init() regarding the preconditions. |
| 164 | bool matchingInit(const BoolEdgeMap& matching) { |
| 165 | init(); |
| 166 | bool valid = true; |
| 167 | for(EdgeIt it(_bpg); it!=INVALID; ++it) { |
| 168 | if (matching[it]) { |
| 169 | Node red = _bpg.redNode(it); |
| 170 | Node blue = _bpg.blueNode(it); |
| 171 | if ((*_matching)[red] != INVALID || (*_matching)[blue] != INVALID) { |
| 172 | valid = false; |
| 173 | } else { |
| 174 | _matching->set(red, it); |
| 175 | _matching->set(blue, it); |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | return valid; |
| 180 | } |
| 181 | |
| 182 | /// \brief Executes an augmenting phase |
| 183 | /// |
| 184 | /// Searches a maximal set of vertex disjoint shortest alternating paths. |
| 185 | /// Meaning: |
| 186 | /// - alternating: connents an unmatched red- and an unmatched blue node, |
| 187 | /// and exactly every second edge is in the current matching; |
| 188 | /// - shortest: contain a minimal number of edges; |
| 189 | /// - vertex disjoint: every vertex belong to at most one path; |
| 190 | /// - maximal set: a set of path is maximal when it is not expandable |
| 191 | /// further (and not when there does not exist a set with |
| 192 | /// more vertex disjoint shortest alternating paths). |
| 193 | /// |
| 194 | /// After a maximal set is found, it applies the augmenting paths, |
| 195 | /// so edges of the matching are taken out, the others are put in |
| 196 | /// the matching. |
| 197 | /// |
| 198 | /// \return The length of the found augmenting paths, or -1 when none |
| 199 | /// found, which occurs if and only if the current matching is maximal. |
| 200 | /// |
| 201 | /// \pre \ref init() must be called before using this function. |
| 202 | int augment() { |
| 203 | IntNodeMap level(_bpg, -1); |
| 204 | std::list<RedNode> act_rednodes; |
| 205 | std::list<BlueNode> act_bluenodes; |
| 206 | |
| 207 | for (RedIt r_it(_bpg); r_it != INVALID; ++r_it) { |
| 208 | if ((*_matching)[r_it] == INVALID) { |
| 209 | act_rednodes.push_front(r_it); |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | // Raise this flag when a shortest augmenting path is found. |
| 214 | bool path_found = false; |
| 215 | // This nodelist will contain the end nodes of the possible |
| 216 | // augmenting paths. |
| 217 | std::list<BlueNode> path_ends; |
| 218 | |
| 219 | // Layer counter |
| 220 | int cur_level = 0; |
| 221 | |
| 222 | // Starting from the unmatched red nodes search for unmatched |
| 223 | // blue nodes, using Bfs (but only on alternating paths). |
| 224 | while (!path_found) { |
| 225 | while (!act_rednodes.empty()) { |
| 226 | RedNode red = act_rednodes.front(); |
| 227 | act_rednodes.pop_front(); |
| 228 | level[red] = cur_level; |
| 229 | for (IncEdgeIt it(_bpg, red); it!=INVALID; ++it) { |
| 230 | BlueNode blue(_bpg.blueNode(it)); |
| 231 | if (level[blue] == -1) { |
| 232 | act_bluenodes.push_front(blue); |
| 233 | level[blue] = cur_level + 1; |
| 234 | path_found |= ((*_matching)[blue] == INVALID); |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | if (!path_found) { |
| 240 | if (act_bluenodes.empty()) return -1; |
| 241 | while (!act_bluenodes.empty()) { |
| 242 | BlueNode blue = act_bluenodes.front(); |
| 243 | act_bluenodes.pop_front(); |
| 244 | RedNode red = _bpg.redNode((*_matching)[blue]); |
| 245 | act_rednodes.push_front(red); |
| 246 | } |
| 247 | } else { |
| 248 | for (typename std::list<BlueNode>::iterator it=act_bluenodes.begin(); |
| 249 | it != act_bluenodes.end(); |
| 250 | ++it) { |
| 251 | if ((*_matching)[*it] == INVALID) path_ends.push_front(*it); |
| 252 | } |
| 253 | // Now path_ends contains nodes that are ends of |
| 254 | // shortest alternating paths. |
| 255 | } |
| 256 | cur_level += 2; |
| 257 | } |
| 258 | |
| 259 | // The current_edge structure assures that edges iterated at most once |
| 260 | typename BpGraph::template BlueMap<IncEdgeIt*> current_edge(_bpg, 0); |
| 261 | |
| 262 | // Stack for the Dfs |
| 263 | std::list<BlueNode> stack; |
| 264 | |
| 265 | // Searching backward, starting from the previously found |
| 266 | // blue nodes, we build vertex disjoint alternating paths. |
| 267 | typename std::list<BlueNode>::iterator n_it = path_ends.begin(); |
| 268 | |
| 269 | while (n_it != path_ends.end()) { |
| 270 | stack.push_front(*n_it); |
| 271 | path_found = false; |
| 272 | while (!stack.empty() && !path_found) { |
| 273 | BlueNode b = stack.front(); |
| 274 | if (current_edge[b] == 0) { |
| 275 | current_edge[b] = new IncEdgeIt(_bpg, b); |
| 276 | } else { |
| 277 | ++(*current_edge[b]); |
| 278 | } |
| 279 | while (*current_edge[b] != INVALID && |
| 280 | level[_bpg.redNode(*current_edge[b])] != level[b] - 1) { |
| 281 | ++(*current_edge[b]); |
| 282 | } |
| 283 | if (*current_edge[b] == INVALID) { |
| 284 | stack.pop_front(); |
| 285 | } else { |
| 286 | RedNode r = _bpg.redNode(*current_edge[b]); |
| 287 | if ((*_matching)[r] == INVALID) { |
| 288 | path_found = true; |
| 289 | } else { |
| 290 | level[r] = -1; // Do not visit this node again |
| 291 | stack.push_front(_bpg.blueNode((*_matching)[r])); |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | if (path_found) { |
| 296 | BlueNode next = *n_it; |
| 297 | RedNode r; |
| 298 | BlueNode b; |
| 299 | Edge e; |
| 300 | while (next != INVALID) { |
| 301 | e = *current_edge[next]; |
| 302 | b = next; |
| 303 | r = _bpg.redNode(e); |
| 304 | next = (*_matching)[r] == INVALID ? |
| 305 | INVALID :_bpg.blueNode((*_matching)[r]); |
| 306 | _matching->set(b, e); |
| 307 | _matching->set(r, e); |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | stack.clear(); |
| 312 | ++n_it; |
| 313 | } |
| 314 | return cur_level - 1; |
| 315 | } |
| 316 | |
| 317 | /// \brief Executes the algorithm |
| 318 | /// |
| 319 | /// It runs augmenting phases until the optimal solution is reached. |
| 320 | /// |
| 321 | /// \pre \ref init() must be called before using this function. |
| 322 | void start() { |
| 323 | while (augment() > 0) {} |
| 324 | } |
| 325 | |
| 326 | /// \brief Runs the algorithm. |
| 327 | /// |
| 328 | /// hk.run() is just a shorthand for: |
| 329 | /// |
| 330 | ///\code |
| 331 | /// hk.heuristicInit(); |
| 332 | /// hk.start(); |
| 333 | ///\endcode |
| 334 | void run() { |
| 335 | heuristicInit(); |
| 336 | start(); |
| 337 | } |
| 338 | |
| 339 | /// \brief Size of the matching |
| 340 | /// |
| 341 | /// Returns the size of the current matching. |
| 342 | int matchingSize() const { |
| 343 | int size = 0; |
| 344 | for (RedIt it(_bpg); it!=INVALID; ++it) { |
| 345 | if ((*_matching)[it] != INVALID) ++size; |
| 346 | } |
| 347 | return size; |
| 348 | } |
| 349 | |
| 350 | /// \brief Return \c true if the given edge is in the matching. |
| 351 | /// |
| 352 | /// This function returns \c true if the given edge is in the current |
| 353 | /// matching. |
| 354 | bool matching(const Edge& edge) const { |
| 355 | return edge == (*_matching)[_bpg.redNode(edge)]; |
| 356 | } |
| 357 | |
| 358 | /// \brief Return the matching edge incident to the given node. |
| 359 | /// |
| 360 | /// This function returns the matching edge incident to the |
| 361 | /// given node in the current matching or \c INVALID if the node is |
| 362 | /// not covered by the matching. |
| 363 | Edge matching(const Node& n) const { |
| 364 | return (*_matching)[n]; |
| 365 | } |
| 366 | |
| 367 | /// \brief Return the mate of the given node. |
| 368 | /// |
| 369 | /// This function returns the mate of the given node in the current |
| 370 | /// matching or \c INVALID if the node is not covered by the matching. |
| 371 | Node mate(const Node& n) const { |
| 372 | return (*_matching)[n] != INVALID ? |
| 373 | _bpg.oppositeNode(n, (*_matching)[n]) : INVALID; |
| 374 | } |
| 375 | }; |
| 376 | |
| 377 | } |
| 378 | #endif |