Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Graph_Coloring.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
66#ifndef GRAPH_COLORING_H
67#define GRAPH_COLORING_H
68
69# include <ah-graph-concepts.H>
70
71#include <tpl_graph.H>
72#include <tpl_array.H>
73#include <tpl_dynMapTree.H>
74#include <tpl_dynSetTree.H>
75#include <tpl_sort_utils.H>
76#include <cookie_guard.H>
77#include <ah-errors.H>
78
79namespace Aleph {
80
81namespace graph_coloring_detail {
82
83inline void *encode_color(size_t c) noexcept
84{
85 return reinterpret_cast<void *>(static_cast<uintptr_t>(c + 1));
86}
87
88inline bool is_colored(void *cookie) noexcept
89{
90 return cookie != nullptr;
91}
92
93inline size_t decode_color(void *cookie) noexcept
94{
95 return static_cast<size_t>(reinterpret_cast<uintptr_t>(cookie)) - 1;
96}
97
98inline size_t smallest_available(const DynSetTree<size_t> &used)
99{
100 size_t c = 0;
101 while (used.search(c) != nullptr)
102 ++c;
103 return c;
104}
105
112template <AlephGraph GT, ArcFilter<GT> SA>
115 SA &sa)
116{
117 using Node = typename GT::Node;
118
119 // Ensure all nodes are present in the adjacency map with empty lists.
120 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
121 adj.insert(it.get_curr(), DynList<Node *>());
122
123 // Temporary per-node neighbor sets to deduplicate parallel arcs.
125 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
126 neighbor_sets.insert(it.get_curr(), DynSetTree<Node *>());
127
128 // Collect undirected neighbors, deduplicating parallel arcs.
129 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
130 {
131 auto *arc = it.get_curr();
132 if (not sa(arc))
133 continue;
134 Node *u = g.get_src_node(arc);
135 Node *v = g.get_tgt_node(arc);
136 if (u == v)
137 continue;
138 neighbor_sets[u].insert(v);
139 neighbor_sets[v].insert(u);
140 }
141
142 // Materialize deduplicated neighbor sets into adjacency lists.
143 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
144 {
145 Node *u = it.get_curr();
146 auto &adj_list = adj[u];
147 auto &nbrs = neighbor_sets[u];
148 for (auto sit = nbrs.get_it(); sit.has_curr(); sit.next_ne())
149 adj_list.append(sit.get_curr());
150 }
151}
152
153template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
154void validate_no_self_loops(const GT &g, SA &sa)
155{
156 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
157 {
158 auto *arc = it.get_curr();
159 ah_domain_error_if(sa(arc) and g.get_src_node(arc) == g.get_tgt_node(arc))
160 << "graph coloring does not support self-loops";
161 }
162}
163
164} // end namespace graph_coloring_detail
165
198template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
200 SA sa = SA())
201{
202 using Node = typename GT::Node;
203 using namespace graph_coloring_detail;
204
205 colors = {};
206 if (g.get_num_nodes() == 0)
207 return 0;
208
209 validate_no_self_loops<GT, SA>(g, sa);
210
212 build_undirected_adj<GT, SA>(g, adj, sa);
213
214 Cookie_Saver<GT> saver(g, true, false);
215 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
216 NODE_COOKIE(it.get_curr()) = nullptr;
217
218 size_t num_colors = 0;
219 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
220 {
221 Node *v = it.get_curr();
223
224 for (auto nit = adj[v].get_it(); nit.has_curr(); nit.next_ne())
225 if (Node *w = nit.get_curr(); is_colored(NODE_COOKIE(w)))
226 used.insert(decode_color(NODE_COOKIE(w)));
227
228 size_t c = smallest_available(used);
229 NODE_COOKIE(v) = encode_color(c);
230 colors.insert(v, c);
231
232 if (c + 1 > num_colors)
233 num_colors = c + 1;
234 }
235
236 return num_colors;
237}
238
268template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
270 SA sa = SA())
271{
272 using Node = typename GT::Node;
273 using namespace graph_coloring_detail;
274
275 colors = {};
276 if (g.get_num_nodes() == 0)
277 return 0;
278
279 validate_no_self_loops<GT, SA>(g, sa);
280
282 build_undirected_adj<GT, SA>(g, adj, sa);
283
284 Cookie_Saver<GT> saver(g, true, false);
286 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
287 {
288 Node *p = it.get_curr();
289 NODE_COOKIE(p) = nullptr;
290 nodes.append(p);
291 }
292
293 mergesort(nodes, [&adj](Node *a, Node *b)
294 {
295 return adj[a].size() > adj[b].size();
296 });
297
298 size_t num_colors = 0;
299 for (auto nit = nodes.get_it(); nit.has_curr(); nit.next_ne())
300 {
301 Node *v = nit.get_curr();
303
304 for (auto ait = adj[v].get_it(); ait.has_curr(); ait.next_ne())
305 {
306 Node *w = ait.get_curr();
307 if (is_colored(NODE_COOKIE(w)))
308 used.insert(decode_color(NODE_COOKIE(w)));
309 }
310
311 size_t c = smallest_available(used);
312 NODE_COOKIE(v) = encode_color(c);
313 colors.insert(v, c);
314
315 if (c + 1 > num_colors)
316 num_colors = c + 1;
317 }
318
319 return num_colors;
320}
321
353template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
355 SA sa = SA())
356{
357 using Node = typename GT::Node;
358 using namespace graph_coloring_detail;
359
360 colors = {};
361 if (const size_t n = g.get_num_nodes(); n == 0)
362 return 0;
363
364 validate_no_self_loops<GT, SA>(g, sa);
365
367 build_undirected_adj<GT, SA>(g, adj, sa);
368
369 Cookie_Saver<GT> saver(g, true, false);
371 DynSetTree<Node *> uncolored_nodes;
372
373 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
374 {
375 Node *v = it.get_curr();
376 NODE_COOKIE(v) = nullptr;
377 uncolored_nodes.insert(v);
378 saturation_sets.insert(v, DynSetTree<size_t>());
379 }
380
381 size_t num_colors = 0;
382 while (not uncolored_nodes.is_empty())
383 {
384 Node *best = nullptr;
385 size_t best_sat = 0;
386 size_t best_deg = 0;
387
388 // Select best node: O(V)
389 for (auto it = uncolored_nodes.get_it(); it.has_curr(); it.next_ne())
390 {
391 Node *v = it.get_curr();
392 size_t sat = saturation_sets[v].size();
393 size_t deg = adj[v].size();
394
395 if (best == nullptr or sat > best_sat or (sat == best_sat and deg > best_deg))
396 {
397 best = v;
398 best_sat = sat;
399 best_deg = deg;
400 }
401 }
402
403 size_t c = smallest_available(saturation_sets[best]);
404 NODE_COOKIE(best) = encode_color(c);
405 colors.insert(best, c);
406 uncolored_nodes.remove(best);
407
408 if (c + 1 > num_colors)
409 num_colors = c + 1;
410
411 // Update neighbors: O(deg(best) log colors)
412 for (auto it = adj[best].get_it(); it.has_curr(); it.next_ne())
413 if (Node *w = it.get_curr(); not is_colored(NODE_COOKIE(w)))
414 saturation_sets[w].insert(c);
415 }
416
417 return num_colors;
418}
419
449template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
450[[nodiscard]] bool is_valid_coloring(const GT &g,
452 SA sa = SA())
453{
454 using Node = typename GT::Node;
455
456 // Explicit per-node check: every graph node must have a color entry.
457 // A size match alone is insufficient — the map could be keyed with
458 // foreign pointers that coincidentally match the node count.
459 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
460 if (colors.search(it.get_curr()) == nullptr)
461 return false;
462
463 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
464 {
465 auto *arc = it.get_curr();
466 if (not sa(arc))
467 continue;
468 Node *u = g.get_src_node(arc);
469 Node *v = g.get_tgt_node(arc);
470 if (u == v)
471 return false;
472 auto *pu = colors.search(u);
473 auto *pv = colors.search(v);
474 if (pu == nullptr or pv == nullptr)
475 return false;
476 if (pu->second == pv->second)
477 return false;
478 }
479
480 return true;
481}
482
517template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
519 SA sa = SA())
520{
521 using Node = typename GT::Node;
522 using namespace graph_coloring_detail;
523
525 << "chromatic_number: graph has " << g.get_num_nodes() << " nodes (max 64)";
526
527 colors = {};
528 if (g.get_num_nodes() == 0)
529 return 0;
530
531 validate_no_self_loops<GT, SA>(g, sa);
532
533 DynMapTree<Node *, size_t> best_colors;
534 size_t upper = dsatur_coloring<GT, SA>(g, best_colors, sa);
535
536 if (upper <= 2)
537 {
538 colors = std::move(best_colors);
539 return upper;
540 }
541
542 DynList<Node *> node_list;
543 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
544 node_list.append(it.get_curr());
545
546 const size_t n = node_list.size();
547 Array<Node *> nodes(n, nullptr);
548 size_t idx = 0;
549 for (auto it = node_list.get_it(); it.has_curr(); it.next_ne())
550 nodes[idx++] = it.get_curr();
551
553 {
554 Cookie_Saver<GT> saver(g, true, false);
555 for (size_t i = 0; i < n; ++i)
556 NODE_COOKIE(nodes[i]) = reinterpret_cast<void *>(static_cast<uintptr_t>(i));
557
558 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
559 {
560 auto *arc = it.get_curr();
561 if (not sa(arc))
562 continue;
563 size_t i = reinterpret_cast<uintptr_t>(NODE_COOKIE(g.get_src_node(arc)));
564 size_t j = reinterpret_cast<uintptr_t>(NODE_COOKIE(g.get_tgt_node(arc)));
565 if (i != j)
566 {
567 adj_idx[i].append(j);
568 adj_idx[j].append(i);
569 }
570 }
571 }
572
573 Array<size_t> coloring(n, static_cast<size_t>(0));
574 auto reset_coloring = [&]()
575 {
576 for (size_t i = 0; i < n; ++i)
577 coloring[i] = 0;
578 };
579
580 auto try_k_coloring = [&](size_t k, auto &self, size_t node_idx) -> bool
581 {
582 if (node_idx == n)
583 return true;
584 for (size_t c = 0; c < k; ++c)
585 {
586 bool feasible = true;
587 for (auto jit = adj_idx[node_idx].get_it(); jit.has_curr(); jit.next_ne())
588 {
589 size_t j = jit.get_curr();
590 if (j < node_idx and coloring[j] == c)
591 {
592 feasible = false;
593 break;
594 }
595 }
596 if (feasible)
597 {
598 coloring[node_idx] = c;
599 if (self(k, self, node_idx + 1))
600 return true;
601 }
602 }
603 coloring[node_idx] = 0;
604 return false;
605 };
606
607 size_t lo = 2, hi = upper;
608 while (lo < hi)
609 {
610 size_t mid = (lo + hi) / 2;
611 reset_coloring();
612 if (try_k_coloring(mid, try_k_coloring, 0))
613 hi = mid;
614 else
615 lo = mid + 1;
616 }
617
618 if (lo < upper)
619 {
620 reset_coloring();
621 try_k_coloring(lo, try_k_coloring, 0);
622 colors = {};
623 for (size_t i = 0; i < n; ++i)
624 colors.insert(nodes[i], coloring[i]);
625 }
626 else
627 colors = std::move(best_colors);
628
629 return lo;
630}
631
644template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
646{
647 SA sa;
648
649public:
651 explicit Greedy_Coloring(SA __sa = SA()) : sa(std::move(__sa)) {}
652
660 {
661 return greedy_coloring<GT, SA>(g, colors, sa);
662 }
663};
664
672template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
674{
675 SA sa;
676
677public:
679 explicit Welsh_Powell_Coloring(SA __sa = SA()) : sa(std::move(__sa)) {}
680
688 {
689 return welsh_powell_coloring<GT, SA>(g, colors, sa);
690 }
691};
692
700template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
702{
703 SA sa;
704
705public:
707 explicit DSatur_Coloring(SA __sa = SA()) : sa(std::move(__sa)) {}
708
716 {
717 return dsatur_coloring<GT, SA>(g, colors, sa);
718 }
719};
720
721} // end namespace Aleph
722
723#endif // GRAPH_COLORING_H
Exception handling system with formatted messages for Aleph-w.
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
C++20 concepts for the protocol shared by graph algorithms.
WeightedDigraph::Node Node
long double w
Definition btreepic.C:153
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
RAII guard that saves and restores graph cookies.
Functor wrapper for dsatur_coloring.
size_t operator()(const GT &g, DynMapTree< typename GT::Node *, size_t > &colors) const
Execute DSatur coloring.
DSatur_Coloring(SA __sa=SA())
Keeps sa, the filter of the arcs.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
Generic key-value map implemented on top of a binary search tree.
Pair * search(const Key &key) noexcept(nothrow_search)
Collect all keys.
Pair * append(const Key &key, const Data &data)
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
Dynamic set backed by balanced binary search trees with automatic memory management.
const size_t & size() const
Returns the cardinality of the set.
Key * insert(const Key &key)
Inserts a key into the dynamic set.
size_t remove(const Key &key)
Removes a key from the dynamic set.
Key * search(const Key &key)
Find an element in the set.
bool is_empty() const
returns true if the set is empty
Functor wrapper for greedy_coloring.
Greedy_Coloring(SA __sa=SA())
Keeps sa, the filter of the arcs.
size_t operator()(const GT &g, DynMapTree< typename GT::Node *, size_t > &colors) const
Execute greedy coloring.
Functor wrapper for welsh_powell_coloring.
Welsh_Powell_Coloring(SA __sa=SA())
Keeps sa, the filter of the arcs.
size_t operator()(const GT &g, DynMapTree< typename GT::Node *, size_t > &colors) const
Execute Welsh-Powell coloring.
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
auto get_arc_it() const noexcept
Obtains an iterator to the arc of graph.
Definition graph-dry.H:3144
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
auto get_node_it() const noexcept
Obtains an iterator to the nodes of graph.
Definition graph-dry.H:3122
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
RAII guards for graph node/arc cookies.
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
size_t chromatic_number(const GT &g, DynMapTree< typename GT::Node *, size_t > &colors, SA sa=SA())
Computes the exact chromatic number of a small graph.
size_t greedy_coloring(const GT &g, DynMapTree< typename GT::Node *, size_t > &colors, SA sa=SA())
Greedy graph coloring in iteration order.
bool is_valid_coloring(const GT &g, const DynMapTree< typename GT::Node *, size_t > &colors, SA sa=SA())
Validates a graph coloring.
#define NODE_COOKIE(p)
Return the node cookie
size_t dsatur_coloring(const GT &g, DynMapTree< typename GT::Node *, size_t > &colors, SA sa=SA())
DSatur graph coloring (saturation-degree heuristic).
size_t welsh_powell_coloring(const GT &g, DynMapTree< typename GT::Node *, size_t > &colors, SA sa=SA())
Welsh-Powell graph coloring.
size_t decode_color(void *cookie) noexcept
bool is_colored(void *cookie) noexcept
size_t smallest_available(const DynSetTree< size_t > &used)
void build_undirected_adj(const GT &g, DynMapTree< typename GT::Node *, DynList< typename GT::Node * > > &adj, SA &sa)
Internal helper to pre-build undirected adjacency lists.
void * encode_color(size_t c) noexcept
void validate_no_self_loops(const GT &g, SA &sa)
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
and
Check uniqueness with explicit hash + equality functors.
void mergesort(T *a, const long l, const long r, Array< T > &buf, Compare cmp)
Sort an array using merge sort with a reusable buffer.
STL namespace.
static int * k
Dynamic array container with automatic resizing.
Dynamic key-value map based on balanced binary search trees.
Dynamic set implementations based on balanced binary search trees.
Generic graph and digraph implementations.
Comprehensive sorting algorithms and search utilities for Aleph-w.