GraphLibrary  0.0.1
A simple library that implements various graph algorithms.
 All Classes Namespaces Files Functions Variables Typedefs Macros
HavelHakimi.hpp
Go to the documentation of this file.
1 #ifndef GL_HAVEL_HAKIMI_HPP
2 #define GL_HAVEL_HAKIMI_HPP
3 
4 #include <string>
5 #include <queue>
6 #include <numeric>
7 
8 namespace gl {
9 namespace algorithm {
10 
16 bool havelHakimi (std::deque<gl::index_type> degrees)
17 {
18  using idx_t = gl::index_type;
19  std::sort(degrees.begin(), degrees.end(), [](idx_t a, idx_t b){
20  return a > b;
21  });
22 
23  // check if any entries are negative (only last element needs to be checked, because sorted)
24  if (degrees.back() < 0) return false;
25  // check if any degrees exceed number of nodes-1 (only first element needs to be checked, because sorted)
26  if (degrees.front() > degrees.size() - 1) return false;
27  // sum of degrees must be even
28  if (std::accumulate(degrees.begin(),degrees.end(), 0) % 2) return false;
29  // check if all elements are zero (only front element needs to be checked because sorted)
30  if (!degrees.front()) return true;
31 
32  auto degree = degrees.front();
33  degrees.pop_front();
34 
35  for (idx_t i = 0; i < degree; ++i) {
36  --degrees[i];
37  }
38 
39  return havelHakimi(std::move(degrees));
40 }
41 
47 bool isGraphicSequence (const std::string& degreeSeq)
48 {
49  using idx_t = gl::index_type;
50  std::stringstream iss(degreeSeq);
51  idx_t degree;
52  std::deque<idx_t> degrees;
53  while( iss >> degree )
54  degrees.push_back(degree);
55 
56  return gl::algorithm::havelHakimi(std::move(degrees));
57 }
58 
59 } // namespace algorithm
60 } // namespace gl
61 
62 #endif // GL_HAVEL_HAKIMI_HPP
Graph::idx_list_t degrees(const Graph &graph)
Computes the out-degrees of all nodes in a graph.
Definition: Degrees.hpp:16
std::size_t index_type
Definition: gl_base.hpp:18
bool isGraphicSequence(const std::string &degreeSeq)
Uses the Havel-Hakimi algorithm to determine whether a given degree sequence is graphic.
Definition: HavelHakimi.hpp:47
bool havelHakimi(std::deque< gl::index_type > degrees)
Uses the Havel-Hakimi algorithm to determine whether a given degree sequence is graphic.
Definition: HavelHakimi.hpp:16