bipartite.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /**
  2. *
  3. * Copyright (c) 2010 Matthias Walter (xammy@xammy.homelinux.net)
  4. *
  5. * Authors: Matthias Walter
  6. *
  7. * Distributed under the Boost Software License, Version 1.0. (See
  8. * accompanying file LICENSE_1_0.txt or copy at
  9. * http://www.boost.org/LICENSE_1_0.txt)
  10. *
  11. */
  12. #ifndef BOOST_GRAPH_BIPARTITE_HPP
  13. #define BOOST_GRAPH_BIPARTITE_HPP
  14. #include <utility>
  15. #include <vector>
  16. #include <exception>
  17. #include <boost/graph/properties.hpp>
  18. #include <boost/graph/adjacency_list.hpp>
  19. #include <boost/graph/depth_first_search.hpp>
  20. #include <boost/graph/one_bit_color_map.hpp>
  21. namespace boost
  22. {
  23. namespace detail
  24. {
  25. /**
  26. * The bipartite_visitor_error is thrown if an edge cannot be colored.
  27. * The witnesses are the edges incident vertices.
  28. */
  29. template < typename Vertex >
  30. struct BOOST_SYMBOL_VISIBLE bipartite_visitor_error : std::exception
  31. {
  32. std::pair< Vertex, Vertex > witnesses;
  33. bipartite_visitor_error(Vertex a, Vertex b) : witnesses(a, b) {}
  34. const char* what() const throw() { return "Graph is not bipartite."; }
  35. };
  36. /**
  37. * Functor which colors edges to be non-monochromatic.
  38. */
  39. template < typename PartitionMap > struct bipartition_colorize
  40. {
  41. typedef on_tree_edge event_filter;
  42. bipartition_colorize(PartitionMap partition_map)
  43. : partition_map_(partition_map)
  44. {
  45. }
  46. template < typename Edge, typename Graph >
  47. void operator()(Edge e, const Graph& g)
  48. {
  49. typedef typename graph_traits< Graph >::vertex_descriptor
  50. vertex_descriptor_t;
  51. typedef color_traits<
  52. typename property_traits< PartitionMap >::value_type >
  53. color_traits;
  54. vertex_descriptor_t source_vertex = source(e, g);
  55. vertex_descriptor_t target_vertex = target(e, g);
  56. if (get(partition_map_, source_vertex) == color_traits::white())
  57. put(partition_map_, target_vertex, color_traits::black());
  58. else
  59. put(partition_map_, target_vertex, color_traits::white());
  60. }
  61. private:
  62. PartitionMap partition_map_;
  63. };
  64. /**
  65. * Creates a bipartition_colorize functor which colors edges
  66. * to be non-monochromatic.
  67. *
  68. * @param partition_map Color map for the bipartition
  69. * @return The functor.
  70. */
  71. template < typename PartitionMap >
  72. inline bipartition_colorize< PartitionMap > colorize_bipartition(
  73. PartitionMap partition_map)
  74. {
  75. return bipartition_colorize< PartitionMap >(partition_map);
  76. }
  77. /**
  78. * Functor which tests an edge to be monochromatic.
  79. */
  80. template < typename PartitionMap > struct bipartition_check
  81. {
  82. typedef on_back_edge event_filter;
  83. bipartition_check(PartitionMap partition_map)
  84. : partition_map_(partition_map)
  85. {
  86. }
  87. template < typename Edge, typename Graph >
  88. void operator()(Edge e, const Graph& g)
  89. {
  90. typedef typename graph_traits< Graph >::vertex_descriptor
  91. vertex_descriptor_t;
  92. vertex_descriptor_t source_vertex = source(e, g);
  93. vertex_descriptor_t target_vertex = target(e, g);
  94. if (get(partition_map_, source_vertex)
  95. == get(partition_map_, target_vertex))
  96. throw bipartite_visitor_error< vertex_descriptor_t >(
  97. source_vertex, target_vertex);
  98. }
  99. private:
  100. PartitionMap partition_map_;
  101. };
  102. /**
  103. * Creates a bipartition_check functor which raises an error if a
  104. * monochromatic edge is found.
  105. *
  106. * @param partition_map The map for a bipartition.
  107. * @return The functor.
  108. */
  109. template < typename PartitionMap >
  110. inline bipartition_check< PartitionMap > check_bipartition(
  111. PartitionMap partition_map)
  112. {
  113. return bipartition_check< PartitionMap >(partition_map);
  114. }
  115. /**
  116. * Find the beginning of a common suffix of two sequences
  117. *
  118. * @param sequence1 Pair of bidirectional iterators defining the first
  119. * sequence.
  120. * @param sequence2 Pair of bidirectional iterators defining the second
  121. * sequence.
  122. * @return Pair of iterators pointing to the beginning of the common suffix.
  123. */
  124. template < typename BiDirectionalIterator1,
  125. typename BiDirectionalIterator2 >
  126. inline std::pair< BiDirectionalIterator1, BiDirectionalIterator2 >
  127. reverse_mismatch(
  128. std::pair< BiDirectionalIterator1, BiDirectionalIterator1 > sequence1,
  129. std::pair< BiDirectionalIterator2, BiDirectionalIterator2 > sequence2)
  130. {
  131. if (sequence1.first == sequence1.second
  132. || sequence2.first == sequence2.second)
  133. return std::make_pair(sequence1.first, sequence2.first);
  134. BiDirectionalIterator1 iter1 = sequence1.second;
  135. BiDirectionalIterator2 iter2 = sequence2.second;
  136. while (true)
  137. {
  138. --iter1;
  139. --iter2;
  140. if (*iter1 != *iter2)
  141. {
  142. ++iter1;
  143. ++iter2;
  144. break;
  145. }
  146. if (iter1 == sequence1.first)
  147. break;
  148. if (iter2 == sequence2.first)
  149. break;
  150. }
  151. return std::make_pair(iter1, iter2);
  152. }
  153. }
  154. /**
  155. * Checks a given graph for bipartiteness and fills the given color map with
  156. * white and black according to the bipartition. If the graph is not
  157. * bipartite, the contents of the color map are undefined. Runs in linear
  158. * time in the size of the graph, if access to the property maps is in
  159. * constant time.
  160. *
  161. * @param graph The given graph.
  162. * @param index_map An index map associating vertices with an index.
  163. * @param partition_map A color map to fill with the bipartition.
  164. * @return true if and only if the given graph is bipartite.
  165. */
  166. template < typename Graph, typename IndexMap, typename PartitionMap >
  167. bool is_bipartite(
  168. const Graph& graph, const IndexMap index_map, PartitionMap partition_map)
  169. {
  170. /// General types and variables
  171. typedef
  172. typename property_traits< PartitionMap >::value_type partition_color_t;
  173. typedef
  174. typename graph_traits< Graph >::vertex_descriptor vertex_descriptor_t;
  175. /// Declare dfs visitor
  176. // detail::empty_recorder recorder;
  177. // typedef detail::bipartite_visitor <PartitionMap,
  178. // detail::empty_recorder> dfs_visitor_t; dfs_visitor_t dfs_visitor
  179. // (partition_map, recorder);
  180. /// Call dfs
  181. try
  182. {
  183. depth_first_search(graph,
  184. vertex_index_map(index_map).visitor(make_dfs_visitor(
  185. std::make_pair(detail::colorize_bipartition(partition_map),
  186. std::make_pair(detail::check_bipartition(partition_map),
  187. put_property(partition_map,
  188. color_traits< partition_color_t >::white(),
  189. on_start_vertex()))))));
  190. }
  191. catch (const detail::bipartite_visitor_error< vertex_descriptor_t >&)
  192. {
  193. return false;
  194. }
  195. return true;
  196. }
  197. /**
  198. * Checks a given graph for bipartiteness.
  199. *
  200. * @param graph The given graph.
  201. * @param index_map An index map associating vertices with an index.
  202. * @return true if and only if the given graph is bipartite.
  203. */
  204. template < typename Graph, typename IndexMap >
  205. bool is_bipartite(const Graph& graph, const IndexMap index_map)
  206. {
  207. typedef one_bit_color_map< IndexMap > partition_map_t;
  208. partition_map_t partition_map(num_vertices(graph), index_map);
  209. return is_bipartite(graph, index_map, partition_map);
  210. }
  211. /**
  212. * Checks a given graph for bipartiteness. The graph must
  213. * have an internal vertex_index property. Runs in linear time in the
  214. * size of the graph, if access to the property maps is in constant time.
  215. *
  216. * @param graph The given graph.
  217. * @return true if and only if the given graph is bipartite.
  218. */
  219. template < typename Graph > bool is_bipartite(const Graph& graph)
  220. {
  221. return is_bipartite(graph, get(vertex_index, graph));
  222. }
  223. /**
  224. * Checks a given graph for bipartiteness and fills a given color map with
  225. * white and black according to the bipartition. If the graph is not
  226. * bipartite, a sequence of vertices, producing an odd-cycle, is written to
  227. * the output iterator. The final iterator value is returned. Runs in linear
  228. * time in the size of the graph, if access to the property maps is in
  229. * constant time.
  230. *
  231. * @param graph The given graph.
  232. * @param index_map An index map associating vertices with an index.
  233. * @param partition_map A color map to fill with the bipartition.
  234. * @param result An iterator to write the odd-cycle vertices to.
  235. * @return The final iterator value after writing.
  236. */
  237. template < typename Graph, typename IndexMap, typename PartitionMap,
  238. typename OutputIterator >
  239. OutputIterator find_odd_cycle(const Graph& graph, const IndexMap index_map,
  240. PartitionMap partition_map, OutputIterator result)
  241. {
  242. /// General types and variables
  243. typedef
  244. typename property_traits< PartitionMap >::value_type partition_color_t;
  245. typedef
  246. typename graph_traits< Graph >::vertex_descriptor vertex_descriptor_t;
  247. typedef typename graph_traits< Graph >::vertex_iterator vertex_iterator_t;
  248. vertex_iterator_t vertex_iter, vertex_end;
  249. /// Declare predecessor map
  250. typedef std::vector< vertex_descriptor_t > predecessors_t;
  251. typedef iterator_property_map< typename predecessors_t::iterator, IndexMap,
  252. vertex_descriptor_t, vertex_descriptor_t& >
  253. predecessor_map_t;
  254. predecessors_t predecessors(
  255. num_vertices(graph), graph_traits< Graph >::null_vertex());
  256. predecessor_map_t predecessor_map(predecessors.begin(), index_map);
  257. /// Initialize predecessor map
  258. for (boost::tie(vertex_iter, vertex_end) = vertices(graph);
  259. vertex_iter != vertex_end; ++vertex_iter)
  260. {
  261. put(predecessor_map, *vertex_iter, *vertex_iter);
  262. }
  263. /// Call dfs
  264. try
  265. {
  266. depth_first_search(graph,
  267. vertex_index_map(index_map).visitor(make_dfs_visitor(
  268. std::make_pair(detail::colorize_bipartition(partition_map),
  269. std::make_pair(detail::check_bipartition(partition_map),
  270. std::make_pair(
  271. put_property(partition_map,
  272. color_traits< partition_color_t >::white(),
  273. on_start_vertex()),
  274. record_predecessors(
  275. predecessor_map, on_tree_edge())))))));
  276. }
  277. catch (const detail::bipartite_visitor_error< vertex_descriptor_t >& error)
  278. {
  279. typedef std::vector< vertex_descriptor_t > path_t;
  280. path_t path1, path2;
  281. vertex_descriptor_t next, current;
  282. /// First path
  283. next = error.witnesses.first;
  284. do
  285. {
  286. current = next;
  287. path1.push_back(current);
  288. next = predecessor_map[current];
  289. } while (current != next);
  290. /// Second path
  291. next = error.witnesses.second;
  292. do
  293. {
  294. current = next;
  295. path2.push_back(current);
  296. next = predecessor_map[current];
  297. } while (current != next);
  298. /// Find beginning of common suffix
  299. std::pair< typename path_t::iterator, typename path_t::iterator >
  300. mismatch = detail::reverse_mismatch(
  301. std::make_pair(path1.begin(), path1.end()),
  302. std::make_pair(path2.begin(), path2.end()));
  303. /// Copy the odd-length cycle
  304. result = std::copy(path1.begin(), mismatch.first + 1, result);
  305. return std::reverse_copy(path2.begin(), mismatch.second, result);
  306. }
  307. return result;
  308. }
  309. /**
  310. * Checks a given graph for bipartiteness. If the graph is not bipartite, a
  311. * sequence of vertices, producing an odd-cycle, is written to the output
  312. * iterator. The final iterator value is returned. Runs in linear time in the
  313. * size of the graph, if access to the property maps is in constant time.
  314. *
  315. * @param graph The given graph.
  316. * @param index_map An index map associating vertices with an index.
  317. * @param result An iterator to write the odd-cycle vertices to.
  318. * @return The final iterator value after writing.
  319. */
  320. template < typename Graph, typename IndexMap, typename OutputIterator >
  321. OutputIterator find_odd_cycle(
  322. const Graph& graph, const IndexMap index_map, OutputIterator result)
  323. {
  324. typedef one_bit_color_map< IndexMap > partition_map_t;
  325. partition_map_t partition_map(num_vertices(graph), index_map);
  326. return find_odd_cycle(graph, index_map, partition_map, result);
  327. }
  328. /**
  329. * Checks a given graph for bipartiteness. If the graph is not bipartite, a
  330. * sequence of vertices, producing an odd-cycle, is written to the output
  331. * iterator. The final iterator value is returned. The graph must have an
  332. * internal vertex_index property. Runs in linear time in the size of the
  333. * graph, if access to the property maps is in constant time.
  334. *
  335. * @param graph The given graph.
  336. * @param result An iterator to write the odd-cycle vertices to.
  337. * @return The final iterator value after writing.
  338. */
  339. template < typename Graph, typename OutputIterator >
  340. OutputIterator find_odd_cycle(const Graph& graph, OutputIterator result)
  341. {
  342. return find_odd_cycle(graph, get(vertex_index, graph), result);
  343. }
  344. }
  345. #endif /// BOOST_GRAPH_BIPARTITE_HPP