Raaj Banga · Source on GitHub

Equitable Coloring

Color a graph so neighbors never match, use all k colors, and keep the color groups as close in size as possible.

Graph
Vertices (n)
–
 
Edges
–
 
Colors (k)
–
 
Best possible score
–
 
Answer
–
 

Coloring result

The coloring the program prints for this input.

Program output

Exactly what ./coloring input.txt prints.


        
  • The first line is the color sequence: the size of each color group, largest first.
  • Each line after that lists the vertices that got one color.

Score of this answer

Sort the group sizes and add up the gaps between neighbors. The middle numbers cancel out, so the score is just the biggest group minus the smallest.


        

The best possible score is 0 when k divides n evenly and 1 otherwise. The program stops as soon as it reaches that score, because nothing can beat it.

Problem statement

Given a graph and a number of colors k, color every vertex so that:

  • no two vertices joined by an edge share a color,
  • all k colors are used, and
  • the color groups are as close in size as possible.

If no coloring follows the first two rules, the program prints “no such a sequence exists.”

Solver selection

  • k > n: some color would be empty, so there is no answer.
  • k = n: every vertex gets its own color.
  • n ≤ 16: dynamic programming (Dynamic programming tab).
  • n > 16: branch and bound (Backtracking tab).

Both solvers always find the best score. DP takes about the same time on every graph of a given size, but its memory doubles with every vertex, so it is only used up to 16 vertices.

Hardness

An answer exists exactly when the graph can be colored with k colors. For k = 3 that question is the 3-coloring problem, which is NP-complete.

No polynomial-time method is known, so the program has to search. The work goes into pruning that search: skipping branches that can't lead to a better answer.

Deterministic output

A graph often has several best colorings. The program always prints the same one:

  • Vertex 1 gets the earliest color it can, then vertex 2, and so on.
  • Colors are named in order of first use: Yellow, Blue, Red, Green, …
  • Lines are sorted by group size, then by name.