Skip to content

Instantly share code, notes, and snippets.

@goldsborough
Last active January 9, 2016 21:01
Show Gist options
  • Save goldsborough/4ecbdb86029a8cae5f47 to your computer and use it in GitHub Desktop.
Save goldsborough/4ecbdb86029a8cae5f47 to your computer and use it in GitHub Desktop.
Havel-Hakimi algorithm to determine if a graph with the given list of degree is possible.
bool graph_exists(std::vector<int> degrees)
{
auto remaining = degrees.size();
for (auto i = degrees.begin(), end = degrees.end(); i != end; ++i)
{
std::sort(i, end, std::greater<int>());
if (*i == 0) return true;
if (*i >= remaining--) return false;
auto stop = i;
std::advance(stop, *i + 1);
for (auto j = std::next(i); j != stop; ++j)
{
if (--*j < 0) return false;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment