Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Karger.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
31
43# ifndef KARGER_H
44# define KARGER_H
45
46# include <type_traits>
47# include <ah-graph-concepts.H>
48
49# include <cmath>
50# include <limits>
51# include <vector>
52# include <htlist.H>
53# include <tpl_sgraph.H>
54# include <generate_graph.H>
55# include <tpl_graph_utils.H>
56# include <ah-errors.H>
57# include <ah-random.H>
58
59namespace Aleph
60{
163 template <AlephGraph GT, ArcFilter<GT> SA = Dft_Show_Arc<GT>>
165 {
166 // Each node contains the list of contracted nodes
170
171 using Node = typename GT::Node;
172 using Arc = typename GT::Arc;
173
178 {
179 std::vector<Karc *> arcs;
180
181 public:
182 void insert(Karc *a)
183 {
184 ARC_COUNTER(a) = static_cast<long>(arcs.size());
185 arcs.push_back(a);
186 }
187
188 Karc * select(size_t i) const
189 {
190 assert(i < arcs.size());
191 return arcs[i];
192 }
193
194 void remove(Karc *a)
195 {
196 const long raw_idx = ARC_COUNTER(a);
197 if (raw_idx < 0) // Already removed (parallel arc processed twice)
198 return;
199
200 auto idx = static_cast<size_t>(raw_idx);
201 assert(idx < arcs.size());
202 assert(arcs[idx] == a);
203 if (idx < arcs.size() - 1)
204 {
205 arcs[idx] = arcs.back();
206 ARC_COUNTER(arcs[idx]) = static_cast<long>(idx);
207 }
208 arcs.pop_back();
209 ARC_COUNTER(a) = -1; // Mark as removed
210 }
211
212 void empty() { arcs.clear(); }
213
214 [[nodiscard]] size_t size() const { return arcs.size(); }
215
216 void swap(ArcIndex & other) noexcept { arcs.swap(other.arcs); }
217 };
218
219
220 bool has_self_loop(const GT & g) const
221 {
222 for (typename GT::Arc_Iterator it(g); it.has_curr(); it.next_ne())
223 if (auto a = it.get_curr(); g.get_src_node(a) == g.get_tgt_node(a))
224 return true;
225 return false;
226 }
227
228 bool is_connected_filtered(const GT & g) const
229 {
230 if (g.get_num_nodes() == 0)
231 return false;
232
234 return dft(g) == g.get_num_nodes();
235 }
236
237 void validate_graph(GT & g) const
238 {
239 ah_domain_error_if(g.get_num_nodes() < 2) << "Graph must have at least 2 nodes";
240 ah_domain_error_if(g.get_num_arcs() == 0) << "Graph has no arcs";
241 ah_domain_error_if(has_self_loop(g)) << "Graph contains self-loop";
242 ah_domain_error_if(not is_connected_filtered(g)) << "Graph is disconnected";
243 }
244
245 unsigned long seed;
246 Gsl_Compatible_Rng_Owner r; // the generator, in dynamic memory
247 SA sa;
248
254 void build_kgraph(GT & g, Kgraph & kg, ArcIndex & arcs)
255 {
256 clear_graph(kg);
257 arcs.empty();
258 g.reset_nodes();
259 g.reset_arcs();
260
261 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next_ne())
262 {
263 auto p = it.get_curr();
264 auto q = kg.insert_node();
265 q->get_info().append(p);
266 g.map_nodes(p, q);
267 }
268
269 // Use arc filter SA to determine which arcs to include
270 for (Arc_Iterator<GT, SA> it(g, sa); it.has_curr(); it.next_ne())
271 {
272 auto a = it.get_curr();
273 auto s = mapped_node<GT, Kgraph>(g.get_src_node(a));
274 auto t = mapped_node<GT, Kgraph>(g.get_tgt_node(a));
275 auto ka = kg.insert_arc(s, t, a);
276 arcs.insert(ka);
277 }
278 }
279
288 void update_arcs(Kgraph & kg, Knode *p, Knode *t, Knode *cp,
289 ArcIndex & arcs)
290 {
291 for (typename Kgraph::Node_Arc_Iterator it(p); it.has_curr(); it.next_ne())
292 {
293 auto pa = it.get_curr();
294 auto tgt = it.get_tgt_node_ne();
295
296 arcs.remove(pa); // remove from index; removed from graph when nodes deleted
297 if (tgt == t)
298 continue; // parallel arc ==> ignore
299
300 auto ka = kg.insert_arc(cp, tgt, pa->get_info());
301 arcs.insert(ka);
302 }
303 }
304
308 {
309 arcs.empty();
310 for (typename Kgraph::Arc_Iterator it(kg); it.has_curr(); it.next_ne())
311 arcs.insert(it.get_curr());
312 }
313
318 [[gnu::noinline]] size_t draw_arc(const size_t num_arcs)
319 {
320 return r->uniform_int(num_arcs);
321 }
322
331 void contract(Kgraph & kg, size_t left_num_nodes,
332 ArcIndex & arcs)
333 {
334 while (kg.get_num_nodes() > left_num_nodes)
335 { // randomly select an arc from kg
336 assert(arcs.size() == kg.get_num_arcs() &&
337 "Arc index and graph arc count must be in sync");
338 auto num_arc = draw_arc(arcs.size());
339 auto a = arcs.select(num_arc); // arc to remove
340 auto s = kg.get_src_node(a); // nodes to "contract"
341 auto t = kg.get_tgt_node(a);
342
343 arcs.remove(a); // remove from kg and index
344 kg.remove_arc(a);
345
346 auto cp = kg.insert_node(); // new contracted node representing s-t
347
348 update_arcs(kg, s, t, cp, arcs);
349 update_arcs(kg, t, s, cp, arcs);
350
351 cp->get_info().swap(s->get_info());
352 cp->get_info().append(t->get_info());
353
354 kg.remove_node(s);
355 kg.remove_node(t);
356 }
357 }
358
367 size_t karger_min_cut(GT & g,
371 const size_t num_iter)
372 {
374
375 auto min_cut = std::numeric_limits<size_t>::max();
376
377 Kgraph kg;
378 ArcIndex arcs; // reused across iterations
379
380 for (size_t i = 0; i < num_iter; ++i)
381 {
382 build_kgraph(g, kg, arcs);
383
384 contract(kg, 2, arcs);
385
386 const size_t cut_size = kg.get_num_arcs();
387
388 if (cut_size >= min_cut)
389 continue;
390
391 min_cut = cut_size;
392
393 // Early termination: cut of 1 is optimal for connected graphs
394 if (min_cut == 1)
395 {
396 auto ka = kg.get_first_arc();
397 cut.empty();
398 cut.append(ka->get_info());
399 vs.empty();
400 vt.empty();
401 vs.swap(kg.get_src_node(ka)->get_info());
402 vt.swap(kg.get_tgt_node(ka)->get_info());
403 return 1;
404 }
405
406 // update minimum cut
407 cut.empty();
408
409 // traverse the arcs of the super nodes (these are the cut edges)
410 for (typename Kgraph::Arc_Iterator it(kg); it.has_curr(); it.next_ne())
411 {
412 auto ka = it.get_curr();
413 assert(kg.get_src_node(ka) != kg.get_tgt_node(ka));
414
415 cut.append(ka->get_info());
416 }
417
418 auto ka = kg.get_first_arc();
419 auto S = kg.get_src_node(ka);
420 auto T = kg.get_tgt_node(ka);
421
422 assert(S->get_info().size() + T->get_info().size() ==
423 g.get_num_nodes());
424
425 vs.empty();
426 vt.empty();
427 vs.swap(S->get_info());
428 vt.swap(T->get_info());
429 }
430 return min_cut;
431 }
432
436 {
437 const size_t n = kg.get_num_nodes();
438
439 if (n <= 6)
440 {
441 // Base case: for small graphs, contract to 2 nodes and return cut
442 contract(kg, 2, arcs);
443 return kg.get_num_arcs();
444 }
445
446 // Contract to t = ceil(1 + n/sqrt(2)) nodes
447 const auto t = static_cast<size_t>(std::ceil(1.0 + n / std::sqrt(2.0)));
448
449 // Branch 1: copy graph and rebuild arc index for the copy
450 Kgraph h1(kg);
451 ArcIndex arcs1;
452 rebuild_arc_index(h1, arcs1);
453 contract(h1, t, arcs1);
454 const size_t cut1 = __fast_karger_min_cut(h1, arcs1);
455
456 // Branch 2: copy graph and rebuild arc index for the copy
457 Kgraph h2(kg);
458 ArcIndex arcs2;
459 rebuild_arc_index(h2, arcs2);
460 contract(h2, t, arcs2);
461 const size_t cut2 = __fast_karger_min_cut(h2, arcs2);
462
463 // Return the better cut
464 if (cut1 < cut2)
465 {
466 kg.swap(h1);
467 arcs.swap(arcs1);
468 return cut1;
469 }
470
471 kg.swap(h2);
472 arcs.swap(arcs2);
473 return cut2;
474 }
475
476 public:
487 Karger_Min_Cut(const unsigned long _seed = time(nullptr), SA _sa = SA())
488 : seed(_seed), r(seed % Gsl_Compatible_Rng::max()), sa(_sa)
489 {
490 // empty
491 }
492
495
498
503 noexcept(std::is_nothrow_move_constructible_v<SA>)
504 : seed(other.seed), sa(std::move(other.sa))
505 {
506 r.swap(other.r);
507 }
508
513 noexcept(std::is_nothrow_move_assignable_v<SA>)
514 requires std::is_move_assignable_v<SA>
515 {
516 if (this != &other)
517 {
518 sa = std::move(other.sa); // first, which may throw
519 seed = other.seed;
520 r = std::move(other.r);
521 }
522 return *this;
523 }
524
526 [[nodiscard]] unsigned long get_seed() const noexcept { return seed; }
527
530 void reseed(const unsigned long new_seed) noexcept
531 {
532 seed = new_seed;
533 if (r.get() != nullptr)
535 }
536
547 size_t compute_min_cut_size(GT & g, size_t num_iter = 0)
548 {
549 assert(r.get() != nullptr && "Cannot use moved-from Karger_Min_Cut object");
551
552 if (num_iter == 0)
553 {
554 const size_t n = g.get_num_nodes();
555 num_iter = static_cast<size_t>(1.05 * n * n);
556 }
557
558 size_t min_cut = std::numeric_limits<size_t>::max();
559
560 Kgraph kg;
562
563 for (size_t i = 0; i < num_iter; ++i)
564 {
565 build_kgraph(g, kg, arcs);
566 contract(kg, 2, arcs);
567
568 const size_t cut_size = kg.get_num_arcs();
569 if (cut_size < min_cut)
570 {
571 min_cut = cut_size;
572 if (min_cut == 1)
573 return 1; // Early termination
574 }
575 }
576 return min_cut;
577 }
578
589 size_t operator ()(GT & g,
593 const size_t num_iter)
594 {
595 assert(r.get() != nullptr && "Cannot use moved-from Karger_Min_Cut object");
596 return karger_min_cut(g, vs, vt, cut, num_iter);
597 }
598
611 size_t operator ()(GT & g,
615 {
616 assert(r.get() != nullptr && "Cannot use moved-from Karger_Min_Cut object");
617 const size_t n = g.get_num_nodes();
618 // 1.05 * n^2 iterations gives high probability of finding min cut
619 const auto num_iter = static_cast<size_t>(1.05 * n * n);
620 return karger_min_cut(g, vs, vt, cut, num_iter);
621 }
622
639 size_t fast(GT & g,
643 size_t num_iter = 0)
644 {
645 assert(r.get() != nullptr && "Cannot use moved-from Karger_Min_Cut object");
647
648 // Default iterations: ceil(log^2 n) for high probability
649 if (num_iter == 0)
650 {
651 const double log_n = std::log2(static_cast<double>(g.get_num_nodes()));
652 num_iter = static_cast<size_t>(std::ceil(log_n * log_n));
653 if (num_iter < 1)
654 num_iter = 1;
655 }
656
657 size_t best_cut = std::numeric_limits<size_t>::max();
658
659 for (size_t i = 0; i < num_iter; ++i)
660 {
661 Kgraph kg;
663 build_kgraph(g, kg, arcs);
664
665 const size_t current_cut = __fast_karger_min_cut(kg, arcs);
666
667 if (current_cut >= best_cut)
668 continue;
669
670 best_cut = current_cut;
671
672 cut.empty();
673 for (typename Kgraph::Arc_Iterator it(kg); it.has_curr(); it.next_ne())
674 cut.append(it.get_curr()->get_info());
675
676 auto ka = kg.get_first_arc();
677 auto S = kg.get_src_node(ka);
678 auto T = kg.get_tgt_node(ka);
679
680 vs.empty();
681 vt.empty();
682 vs.swap(S->get_info());
683 vt.swap(T->get_info());
684
685 // Early termination
686 if (best_cut == 1)
687 return 1;
688 }
689
690 return best_cut;
691 }
692 };
693} // namespace Aleph
694
695# endif // KARGER_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.
The random number generators of Aleph: the one that gives the numbers of the gsl_rng_mt19937 of GSL,...
Stateful depth-first traversal functor.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
void empty() noexcept
empty the list
Definition htlist.H:1576
DynList & swap(DynList &l) noexcept
Definition htlist.H:1253
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
A Gsl_Compatible_Rng in dynamic memory, so that what holds it grows only by a pointer,...
Definition ah-random.H:494
void swap(Gsl_Compatible_Rng_Owner &o) noexcept
Swaps the generators, with their gsl_rng.
Definition ah-random.H:569
Gsl_Compatible_Rng * get() const noexcept
The generator, or nullptr after a move.
Definition ah-random.H:578
A random number generator with the sequences of GSL's gsl_rng_mt19937.
Definition ah-random.H:147
static constexpr result_type max() noexcept
The greatest number of operator()(): 2^32 - 1.
Definition ah-random.H:259
void seed(const unsigned long s) noexcept
Seeds again, as gsl_rng_set(r, s).
Definition ah-random.H:277
unsigned long uniform_int(const unsigned long n)
An integer in [0, n), each with the same probability, as gsl_rng_uniform_int(r, n).
Definition ah-random.H:302
Arc index with O(1) operations and deterministic ordering.
Definition Karger.H:178
Karc * select(size_t i) const
Definition Karger.H:188
std::vector< Karc * > arcs
Definition Karger.H:179
void swap(ArcIndex &other) noexcept
Definition Karger.H:216
Karger's randomized minimum cut algorithm.
Definition Karger.H:165
size_t compute_min_cut_size(GT &g, size_t num_iter=0)
Compute only the minimum cut size (without partition info).
Definition Karger.H:547
unsigned long get_seed() const noexcept
Get the random seed used by this solver (useful for reproducibility).
Definition Karger.H:526
typename GT::Node Node
Definition Karger.H:171
Karger_Min_Cut(const Karger_Min_Cut &)=delete
Disable copy constructor (class owns its generator)
size_t operator()(GT &g, DynList< typename GT::Node * > &vs, DynList< typename GT::Node * > &vt, DynList< typename GT::Arc * > &cut, const size_t num_iter)
Compute a minimum cut with a specified number of iterations.
Definition Karger.H:589
void contract(Kgraph &kg, size_t left_num_nodes, ArcIndex &arcs)
Contract the graph by randomly merging edges until left_num_nodes remain.
Definition Karger.H:331
bool has_self_loop(const GT &g) const
Definition Karger.H:220
size_t __fast_karger_min_cut(Kgraph &kg, ArcIndex &arcs)
Karger-Stein fast minimum cut algorithm (recursive version).
Definition Karger.H:435
void rebuild_arc_index(Kgraph &kg, ArcIndex &arcs)
Rebuild the arc index from scratch for the given graph.
Definition Karger.H:307
bool is_connected_filtered(const GT &g) const
Definition Karger.H:228
void update_arcs(Kgraph &kg, Knode *p, Knode *t, Knode *cp, ArcIndex &arcs)
Update arcs when contracting nodes p and t into cp.
Definition Karger.H:288
Karger_Min_Cut(const unsigned long _seed=time(nullptr), SA _sa=SA())
Construct a Karger minimum cut solver.
Definition Karger.H:487
size_t fast(GT &g, DynList< typename GT::Node * > &vs, DynList< typename GT::Node * > &vt, DynList< typename GT::Arc * > &cut, size_t num_iter=0)
Compute minimum cut using Karger-Stein fast algorithm.
Definition Karger.H:639
void validate_graph(GT &g) const
Definition Karger.H:237
Karger_Min_Cut & operator=(const Karger_Min_Cut &)=delete
Disable copy assignment (class owns its generator)
void build_kgraph(GT &g, Kgraph &kg, ArcIndex &arcs)
Build the contracted graph representation from the original graph.
Definition Karger.H:254
Gsl_Compatible_Rng_Owner r
Definition Karger.H:246
typename GT::Arc Arc
Definition Karger.H:172
void reseed(const unsigned long new_seed) noexcept
Change the random seed.
Definition Karger.H:530
unsigned long seed
Definition Karger.H:245
size_t draw_arc(const size_t num_arcs)
The position of an arc among num_arcs, drawn out of line: a contraction takes much longer than a draw...
Definition Karger.H:318
size_t karger_min_cut(GT &g, DynList< typename GT::Node * > &vs, DynList< typename GT::Node * > &vt, DynList< typename GT::Arc * > &cut, const size_t num_iter)
Internal implementation of Karger's minimum cut algorithm.
Definition Karger.H:367
Karger_Min_Cut(Karger_Min_Cut &&other) noexcept(std::is_nothrow_move_constructible_v< SA >)
Move constructor.
Definition Karger.H:502
Karger_Min_Cut & operator=(Karger_Min_Cut &&other) noexcept(std::is_nothrow_move_assignable_v< SA >)
Move assignment operator.
Definition Karger.H:512
Iterator on the arcs of a graph.
Definition tpl_graph.H:854
Graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:439
Arc * get_first_arc(Node *node) const
Return any arc adjacent to a node.
Definition tpl_graph.H:609
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
void swap(List_Graph &g) noexcept
Swap in constant time this with g
Definition tpl_graph.H:1007
virtual void remove_arc(Arc *arc) noexcept
Remove an arc from the graph and free it.
Definition tpl_graph.H:673
virtual void remove_node(Node *node)
Remove a node from the graph and free its memory.
Definition tpl_graph.H:557
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
NodeInfo & get_info() noexcept
Return a modifiable reference to the data contained in the node.
Definition graph-dry.H:753
void reset_arcs() const
Reset all the arcs of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1213
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
void reset_nodes() const
Reset all the nodes of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1206
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
static void map_nodes(N1 *p, N2 *q) noexcept
Map the nodes through their cookies.
Definition graph-dry.H:1281
Graph visualization and output generation utilities.
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
#define ARC_COUNTER(p)
Return the counter of arc p.
void clear_graph(GT &g)
Clean a graph: all its nodes and arcs are removed and freed.
Definition tpl_graph.H:4776
Singly linked list implementations with head-tail access.
Main namespace for Aleph-w library functions.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
Net::Flow_Type min_cut(Net &net, DynSetTree< typename Net::Node * > &vs, DynSetTree< typename Net::Node * > &vt, DynList< typename Net::Arc * > &cuts, DynList< typename Net::Arc * > &cutt)
Compute max flow and the corresponding minimum cut.
Definition tpl_net.H:2790
STL namespace.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Node belonging to a graph implemented with a double linked adjacency list.
Definition tpl_graph.H:126
Iterator on all arcs of a graph.
Definition tpl_graph.H:941
Utility algorithms and operations for graphs.
Simple graph implementation with adjacency lists.