Chromatic Number
(graph/chromatic_number.hpp)
- View this file on GitHub
- Last update: 2026-08-13 01:41:40+09:00
- Include:
#include "graph/chromatic_number.hpp"
Overview
Computes the chromatic number of a graph: the minimum number of colors needed to color all vertices so that adjacent vertices have different colors.
The algorithm is intended for small general graphs. It uses inclusion-exclusion
over vertex subsets and supports at most 20 vertices.
Graph Interpretation
Every active edge of Graph<T> is treated as an undirected edge, regardless of
how it was inserted. Parallel edges do not change the answer. Self-loops are
ignored, matching the conventions of the other exact vertex-set algorithms in
this library.
Function
| Function | Signature | Description | Complexity |
|---|---|---|---|
chromatic_number |
template <class T> int chromatic_number(const Graph<T>& g) |
Returns the chromatic number. The empty graph has chromatic number 0. |
$O(N2^N)$ time and $O(2^N)$ memory |
The function asserts that g.size() <= 20.
Algorithm
For every vertex subset S, the implementation first counts the independent
subsets contained in S. Inclusion-exclusion then counts ordered covers of all
vertices by k independent sets. Such a cover exists exactly when the graph is
k-colorable.
The count is evaluated modulo 14 pairwise coprime numbers. For N, k <= 20,
the number of covers is less than 2^(N k) <= 2^400, while the product of the
moduli is greater than 2^412. Thus a positive count cannot vanish modulo all
of them, and the result is deterministic.
Example
#include "graph/chromatic_number.hpp"
#include "graph/graph.hpp"
#include <iostream>
int main() {
m1une::graph::Graph<> g(5);
for (int v = 0; v < 5; v++) g.add_edge(v, (v + 1) % 5);
std::cout << m1une::graph::chromatic_number(g) << "\n"; // 3
}
Depends on
Required by
Verified with
verify/graph/chromatic_number.test.cpp
verify/graph/chromatic_number_randomized.test.cpp
verify/graph/cow_game.test.cpp
verify/graph/graph_algorithms.test.cpp
verify/graph/range_edge_graph.test.cpp
Code
#ifndef M1UNE_GRAPH_CHROMATIC_NUMBER_HPP
#define M1UNE_GRAPH_CHROMATIC_NUMBER_HPP 1
#include <array>
#include <bit>
#include <cassert>
#include <cstdint>
#include <vector>
#include "graph.hpp"
namespace m1une {
namespace graph {
namespace detail {
struct ChromaticResidues {
static constexpr std::array<std::uint32_t, 14> mod = {
1000000007, 1000000009, 998244353, 985661441, 943718401, 935329793, 918552577,
897581057, 880803841, 754974721, 645922817, 595591169, 469762049, 167772161,
};
std::array<std::uint32_t, 14> value;
explicit ChromaticResidues(std::uint32_t x = 0) {
value.fill(x);
}
void multiply(std::uint32_t x) {
for (int i = 0; i < int(mod.size()); i++) {
value[i] = std::uint32_t(std::uint64_t(value[i]) * x % mod[i]);
}
}
};
} // namespace detail
template <class T>
int chromatic_number(const Graph<T>& g) {
int n = g.size();
assert(n <= 20);
if (n == 0) return 0;
std::vector<std::uint32_t> adjacent(n, 0);
for (const auto& e : g.edges()) {
if (e.from == e.to) continue;
adjacent[e.from] |= std::uint32_t(1) << e.to;
adjacent[e.to] |= std::uint32_t(1) << e.from;
}
std::uint32_t subset_count = std::uint32_t(1) << n;
std::vector<std::uint32_t> independent_count(subset_count, 0);
independent_count[0] = 1;
for (std::uint32_t mask = 1; mask < subset_count; mask++) {
int v = std::countr_zero(mask);
std::uint32_t rest = mask ^ (std::uint32_t(1) << v);
independent_count[mask] =
independent_count[rest] + independent_count[rest & ~adjacent[v]];
}
std::vector<detail::ChromaticResidues> power(subset_count, detail::ChromaticResidues(1));
for (int colors = 1; colors <= n; colors++) {
std::array<std::uint32_t, 14> sum = {};
for (std::uint32_t mask = 0; mask < subset_count; mask++) {
power[mask].multiply(independent_count[mask]);
bool positive = ((n - std::popcount(mask)) & 1) == 0;
for (int i = 0; i < int(sum.size()); i++) {
std::uint32_t x = power[mask].value[i];
if (positive) {
sum[i] += x;
if (sum[i] >= detail::ChromaticResidues::mod[i]) {
sum[i] -= detail::ChromaticResidues::mod[i];
}
} else {
sum[i] = (sum[i] >= x ? sum[i] - x
: sum[i] + detail::ChromaticResidues::mod[i] - x);
}
}
}
for (std::uint32_t x : sum) {
if (x != 0) return colors;
}
}
return n;
}
} // namespace graph
} // namespace m1une
#endif // M1UNE_GRAPH_CHROMATIC_NUMBER_HPP#line 1 "graph/chromatic_number.hpp"
#include <array>
#include <bit>
#include <cassert>
#include <cstdint>
#include <vector>
#line 1 "graph/graph.hpp"
#line 6 "graph/graph.hpp"
#include <utility>
#line 8 "graph/graph.hpp"
namespace m1une {
namespace graph {
template <class T = int>
struct Edge {
using cost_type = T;
int from;
int to;
T cost;
int id;
bool alive;
Edge() : from(-1), to(-1), cost(T()), id(-1), alive(true) {}
Edge(int from_, int to_, T cost_ = T(1), int id_ = -1, bool alive_ = true)
: from(from_), to(to_), cost(cost_), id(id_), alive(alive_) {}
int other(int v) const {
assert(v == from || v == to);
return from ^ to ^ v;
}
};
template <class T = int>
struct Graph {
using edge_type = Edge<T>;
using cost_type = T;
private:
struct EdgePositions {
std::array<std::pair<int, int>, 2> value{};
int size = 0;
void push_back(std::pair<int, int> position) {
assert(size < 2);
value[size++] = position;
}
};
int _n;
int _edge_count;
std::vector<std::vector<edge_type>> _g;
std::vector<EdgePositions> _edge_positions;
public:
Graph() : _n(0), _edge_count(0) {}
explicit Graph(int n) : _n(n), _edge_count(0), _g(n) {
assert(0 <= n);
}
int size() const {
return _n;
}
bool empty() const {
return _n == 0;
}
int edge_count() const {
return _edge_count;
}
int add_vertex() {
_g.emplace_back();
return _n++;
}
int add_directed_edge(int from, int to, T cost = T(1)) {
assert(0 <= from && from < _n);
assert(0 <= to && to < _n);
int id = _edge_count++;
int idx = int(_g[from].size());
_g[from].push_back(edge_type(from, to, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({from, idx});
return id;
}
int add_edge(int u, int v, T cost = T(1)) {
assert(0 <= u && u < _n);
assert(0 <= v && v < _n);
int id = _edge_count++;
int u_idx = int(_g[u].size());
_g[u].push_back(edge_type(u, v, cost, id));
int v_idx = int(_g[v].size());
_g[v].push_back(edge_type(v, u, cost, id));
_edge_positions.emplace_back();
_edge_positions.back().push_back({u, u_idx});
_edge_positions.back().push_back({v, v_idx});
return id;
}
void set_edge_alive(int id, bool alive) {
assert(0 <= id && id < _edge_count);
for (int i = 0; i < _edge_positions[id].size; ++i) {
auto [v, idx] = _edge_positions[id].value[i];
_g[v][idx].alive = alive;
}
}
void erase_edge(int id) {
set_edge_alive(id, false);
}
void revive_edge(int id) {
set_edge_alive(id, true);
}
bool is_edge_alive(int id) const {
assert(0 <= id && id < _edge_count);
assert(_edge_positions[id].size != 0);
auto [v, idx] = _edge_positions[id].value[0];
return _g[v][idx].alive;
}
const std::vector<edge_type>& operator[](int v) const {
assert(0 <= v && v < _n);
return _g[v];
}
std::vector<edge_type>& operator[](int v) {
assert(0 <= v && v < _n);
return _g[v];
}
const std::vector<std::vector<edge_type>>& adjacency() const {
return _g;
}
std::vector<std::vector<edge_type>>& adjacency() {
return _g;
}
std::vector<edge_type> edges(bool include_inactive = false) const {
std::vector<edge_type> result;
result.reserve(_edge_count);
std::vector<char> used(_edge_count, false);
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
if (!include_inactive && !e.alive) continue;
if (0 <= e.id && e.id < _edge_count) {
if (used[e.id]) continue;
used[e.id] = true;
}
result.push_back(e);
}
}
return result;
}
Graph reversed() const {
Graph result(_n);
result._edge_count = _edge_count;
result._edge_positions.assign(_edge_count, {});
for (int v = 0; v < _n; v++) {
for (const auto& e : _g[v]) {
int idx = int(result._g[e.to].size());
result._g[e.to].push_back(edge_type(e.to, e.from, e.cost, e.id, e.alive));
if (0 <= e.id && e.id < _edge_count) result._edge_positions[e.id].push_back({e.to, idx});
}
}
return result;
}
};
} // namespace graph
} // namespace m1une
#line 11 "graph/chromatic_number.hpp"
namespace m1une {
namespace graph {
namespace detail {
struct ChromaticResidues {
static constexpr std::array<std::uint32_t, 14> mod = {
1000000007, 1000000009, 998244353, 985661441, 943718401, 935329793, 918552577,
897581057, 880803841, 754974721, 645922817, 595591169, 469762049, 167772161,
};
std::array<std::uint32_t, 14> value;
explicit ChromaticResidues(std::uint32_t x = 0) {
value.fill(x);
}
void multiply(std::uint32_t x) {
for (int i = 0; i < int(mod.size()); i++) {
value[i] = std::uint32_t(std::uint64_t(value[i]) * x % mod[i]);
}
}
};
} // namespace detail
template <class T>
int chromatic_number(const Graph<T>& g) {
int n = g.size();
assert(n <= 20);
if (n == 0) return 0;
std::vector<std::uint32_t> adjacent(n, 0);
for (const auto& e : g.edges()) {
if (e.from == e.to) continue;
adjacent[e.from] |= std::uint32_t(1) << e.to;
adjacent[e.to] |= std::uint32_t(1) << e.from;
}
std::uint32_t subset_count = std::uint32_t(1) << n;
std::vector<std::uint32_t> independent_count(subset_count, 0);
independent_count[0] = 1;
for (std::uint32_t mask = 1; mask < subset_count; mask++) {
int v = std::countr_zero(mask);
std::uint32_t rest = mask ^ (std::uint32_t(1) << v);
independent_count[mask] =
independent_count[rest] + independent_count[rest & ~adjacent[v]];
}
std::vector<detail::ChromaticResidues> power(subset_count, detail::ChromaticResidues(1));
for (int colors = 1; colors <= n; colors++) {
std::array<std::uint32_t, 14> sum = {};
for (std::uint32_t mask = 0; mask < subset_count; mask++) {
power[mask].multiply(independent_count[mask]);
bool positive = ((n - std::popcount(mask)) & 1) == 0;
for (int i = 0; i < int(sum.size()); i++) {
std::uint32_t x = power[mask].value[i];
if (positive) {
sum[i] += x;
if (sum[i] >= detail::ChromaticResidues::mod[i]) {
sum[i] -= detail::ChromaticResidues::mod[i];
}
} else {
sum[i] = (sum[i] >= x ? sum[i] - x
: sum[i] + detail::ChromaticResidues::mod[i] - x);
}
}
}
for (std::uint32_t x : sum) {
if (x != 0) return colors;
}
}
return n;
}
} // namespace graph
} // namespace m1une