Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
min_cut_example.cc
Go to the documentation of this file.
1
48#include <iostream>
49#include <iomanip>
50#include <string>
51#include <vector>
52#include <cmath>
53#include <limits>
54
55#include <Karger_Stein.H>
56#include <Stoer_Wagner.H>
57#include <tpl_graph.H>
58
59using namespace std;
60using namespace Aleph;
61
62// ============================================================================
63// Helper: Print partition
64// ============================================================================
65template <typename GT>
66void print_partition(const string& name,
68{
69 cout << " " << name << ": { ";
70 bool first = true;
71 for (auto node : partition)
72 {
73 if (!first) cout << ", ";
74 cout << node->get_info();
75 first = false;
76 }
77 cout << " }\n";
78}
79
80// ============================================================================
81// Helper: Print cut edges
82// ============================================================================
83template <typename GT>
85{
86 cout << " Cut edges:\n";
87 for (auto arc : cut)
88 {
89 cout << " " << g.get_src_node(arc)->get_info()
90 << " --(" << arc->get_info() << ")-- "
91 << g.get_tgt_node(arc)->get_info() << "\n";
92 }
93}
94
95// ============================================================================
96// EXAMPLE 1: Network Reliability Analysis
97// ============================================================================
98// Use case: Find the weakest point in a network topology
99// Real-world: Data center, power grid, social network analysis
100// ============================================================================
101
103{
104 cout << "╔════════════════════════════════════════════════════════════════╗\n";
105 cout << "║ EXAMPLE 1: Network Reliability Analysis ║\n";
106 cout << "╚════════════════════════════════════════════════════════════════╝\n\n";
107
108 cout << "SCENARIO: A company has 6 offices connected by network links.\n";
109 cout << " We need to find the minimum number of links that,\n";
110 cout << " if cut, would split the network into two parts.\n\n";
111
113 GT network;
114
115 // Create offices
116 cout << "STEP 1: Building network topology\n";
117 cout << " Offices: HQ, Branch1, Branch2, Branch3, Remote1, Remote2\n\n";
118
119 auto hq = network.insert_node("HQ");
120 auto branch1 = network.insert_node("Branch1");
121 auto branch2 = network.insert_node("Branch2");
122 auto branch3 = network.insert_node("Branch3");
123 auto remote1 = network.insert_node("Remote1");
124 auto remote2 = network.insert_node("Remote2");
125
126 // HQ is well-connected (hub topology)
127 network.insert_arc(hq, branch1, 1); network.insert_arc(branch1, hq, 1);
128 network.insert_arc(hq, branch2, 1); network.insert_arc(branch2, hq, 1);
129 network.insert_arc(hq, branch3, 1); network.insert_arc(branch3, hq, 1);
130
131 // Branches have some redundancy
132 network.insert_arc(branch1, branch2, 1); network.insert_arc(branch2, branch1, 1);
133 network.insert_arc(branch2, branch3, 1); network.insert_arc(branch3, branch2, 1);
134
135 // Remote offices only connected to one branch each (vulnerability!)
136 network.insert_arc(branch1, remote1, 1); network.insert_arc(remote1, branch1, 1);
137 network.insert_arc(branch3, remote2, 1); network.insert_arc(remote2, branch3, 1);
138
139 cout << " Network structure:\n";
140 cout << " Remote1\n";
141 cout << " |\n";
142 cout << " Branch1--+--HQ--Branch3--Remote2\n";
143 cout << " | |\n";
144 cout << " Branch2-------+\n\n";
145
146 cout << " Total: " << network.get_num_nodes() << " offices, "
147 << network.get_num_arcs() / 2 << " unique links\n\n";
148
149 // Find min-cut using Karger-Stein
150 cout << "STEP 2: Finding minimum cut with Karger-Stein\n";
151 cout << " (Running 20 iterations for accuracy)\n\n";
152
156
157 size_t min_cut = ks(network, S, T, cut, 20);
158
159 cout << "RESULT:\n";
160 cout << " Minimum cut size: " << min_cut / 2 << " links\n"; // Divide by 2 for undirected
161 print_partition<GT>("Partition 1", S);
162 print_partition<GT>("Partition 2", T);
163
164 cout << "\nINTERPRETATION:\n";
165 cout << " The network can be split by cutting just " << min_cut / 2 << " link(s).\n";
166 cout << " RECOMMENDATION: Add redundant links to vulnerable offices.\n\n";
167}
168
169// ============================================================================
170// EXAMPLE 2: Weighted Network - Bandwidth Optimization
171// ============================================================================
172// Use case: Find the bottleneck in a network with different link capacities
173// Real-world: Network capacity planning, traffic analysis
174// ============================================================================
175
177{
178 cout << "╔════════════════════════════════════════════════════════════════╗\n";
179 cout << "║ EXAMPLE 2: Weighted Network - Bandwidth Analysis ║\n";
180 cout << "╚════════════════════════════════════════════════════════════════╝\n\n";
181
182 cout << "SCENARIO: A data center has servers connected with varying bandwidth.\n";
183 cout << " Find the minimum total bandwidth that could bottleneck.\n\n";
184
186 GT datacenter;
187
188 // Create servers
189 auto web1 = datacenter.insert_node("Web1");
190 auto web2 = datacenter.insert_node("Web2");
191 auto app = datacenter.insert_node("App");
192 auto db = datacenter.insert_node("Database");
193 auto cache = datacenter.insert_node("Cache");
194
195 cout << "STEP 1: Network topology with bandwidth (Gbps)\n\n";
196
197 // High bandwidth core connections
198 datacenter.insert_arc(web1, app, 10); datacenter.insert_arc(app, web1, 10);
199 datacenter.insert_arc(web2, app, 10); datacenter.insert_arc(app, web2, 10);
200 datacenter.insert_arc(app, cache, 20); datacenter.insert_arc(cache, app, 20);
201 datacenter.insert_arc(cache, db, 5); datacenter.insert_arc(db, cache, 5); // Bottleneck!
202 datacenter.insert_arc(app, db, 2); datacenter.insert_arc(db, app, 2); // Backup link
203
204 cout << " Web1 --10-- App --20-- Cache --5-- Database\n";
205 cout << " Web2 --10-- | |\n";
206 cout << " +-------2---------+\n\n";
207
208 // Find min-cut using Stoer-Wagner (handles weights properly)
209 cout << "STEP 2: Finding minimum cut with Stoer-Wagner\n\n";
210
214
215 int min_bandwidth = sw(datacenter, S, T, cut);
216
217 cout << "RESULT:\n";
218 cout << " Minimum cut bandwidth: " << min_bandwidth / 2 << " Gbps\n";
219 print_partition<GT>("Partition 1", S);
220 print_partition<GT>("Partition 2", T);
221 cout << "\n Bottleneck links:\n";
222 for (auto arc : cut)
223 {
224 cout << " " << datacenter.get_src_node(arc)->get_info()
225 << " <-> " << datacenter.get_tgt_node(arc)->get_info()
226 << " (" << arc->get_info() << " Gbps)\n";
227 }
228
229 cout << "\nINTERPRETATION:\n";
230 cout << " The database access is the bottleneck at " << min_bandwidth / 2 << " Gbps.\n";
231 cout << " RECOMMENDATION: Upgrade Cache-Database link or add more paths.\n\n";
232}
233
234// ============================================================================
235// EXAMPLE 3: Community Detection
236// ============================================================================
237// Use case: Find natural divisions in a social network
238// Real-world: Social media analysis, market segmentation
239// ============================================================================
240
242{
243 cout << "╔════════════════════════════════════════════════════════════════╗\n";
244 cout << "║ EXAMPLE 3: Community Detection in Social Network ║\n";
245 cout << "╚════════════════════════════════════════════════════════════════╝\n\n";
246
247 cout << "SCENARIO: A social network with two friend groups loosely connected.\n";
248 cout << " Find the natural division between communities.\n\n";
249
251 GT social;
252
253 // Group 1: Tech enthusiasts
254 auto alice = social.insert_node("Alice");
255 auto bob = social.insert_node("Bob");
256 auto carol = social.insert_node("Carol");
257
258 // Group 2: Sports fans
259 auto dave = social.insert_node("Dave");
260 auto eve = social.insert_node("Eve");
261 auto frank = social.insert_node("Frank");
262
263 cout << "STEP 1: Building social connections\n\n";
264
265 // Dense connections within Group 1
266 social.insert_arc(alice, bob, 1); social.insert_arc(bob, alice, 1);
267 social.insert_arc(alice, carol, 1); social.insert_arc(carol, alice, 1);
268 social.insert_arc(bob, carol, 1); social.insert_arc(carol, bob, 1);
269
270 // Dense connections within Group 2
271 social.insert_arc(dave, eve, 1); social.insert_arc(eve, dave, 1);
272 social.insert_arc(dave, frank, 1); social.insert_arc(frank, dave, 1);
273 social.insert_arc(eve, frank, 1); social.insert_arc(frank, eve, 1);
274
275 // Sparse connections between groups (just 1 link)
276 social.insert_arc(carol, dave, 1); social.insert_arc(dave, carol, 1);
277
278 cout << " Group 1 (Tech): Group 2 (Sports):\n";
279 cout << " Alice--Bob Dave--Eve\n";
280 cout << " \\ / \\ /\n";
281 cout << " Carol ---- Dave Frank\n";
282 cout << " (weak link)\n\n";
283
284 // Run both algorithms and compare
285 cout << "STEP 2: Running both algorithms\n\n";
286
287 // Karger-Stein
289 DynList<GT::Node*> ks_S, ks_T;
290 DynList<GT::Arc*> ks_cut;
291 size_t ks_result = ks(social, ks_S, ks_T, ks_cut, 30);
292
293 // Stoer-Wagner
295 DynList<GT::Node*> sw_S, sw_T;
296 DynList<GT::Arc*> sw_cut;
297 int sw_result = sw(social, sw_S, sw_T, sw_cut);
298
299 cout << "KARGER-STEIN RESULT:\n";
300 cout << " Min-cut size: " << ks_result / 2 << "\n";
301 print_partition<GT>("Community 1", ks_S);
302 print_partition<GT>("Community 2", ks_T);
303
304 cout << "\nSTOER-WAGNER RESULT:\n";
305 cout << " Min-cut size: " << sw_result / 2 << "\n";
306 print_partition<GT>("Community 1", sw_S);
307 print_partition<GT>("Community 2", sw_T);
308
309 cout << "\nINTERPRETATION:\n";
310 cout << " Both algorithms identify the two communities correctly.\n";
311 cout << " The Carol-Dave connection is the bridge between groups.\n\n";
312}
313
314// ============================================================================
315// EXAMPLE 4: Algorithm Comparison - Accuracy vs Speed
316// ============================================================================
317
319{
320 cout << "╔════════════════════════════════════════════════════════════════╗\n";
321 cout << "║ EXAMPLE 4: Algorithm Comparison ║\n";
322 cout << "╚════════════════════════════════════════════════════════════════╝\n\n";
323
324 cout << "SCENARIO: Compare Karger-Stein vs Stoer-Wagner on the same graph.\n\n";
325
327 GT g;
328
329 // Build two 5-cliques connected by 3 edges
330 const int CLIQUE_SIZE = 5;
331 const int BRIDGE_COUNT = 3;
332
333 vector<GT::Node*> left(CLIQUE_SIZE), right(CLIQUE_SIZE);
334
335 for (int i = 0; i < CLIQUE_SIZE; ++i)
336 {
337 left[i] = g.insert_node(i);
338 right[i] = g.insert_node(CLIQUE_SIZE + i);
339 }
340
341 // Left clique
342 for (int i = 0; i < CLIQUE_SIZE; ++i)
343 for (int j = i + 1; j < CLIQUE_SIZE; ++j)
344 {
345 g.insert_arc(left[i], left[j], 1);
346 g.insert_arc(left[j], left[i], 1);
347 }
348
349 // Right clique
350 for (int i = 0; i < CLIQUE_SIZE; ++i)
351 for (int j = i + 1; j < CLIQUE_SIZE; ++j)
352 {
353 g.insert_arc(right[i], right[j], 1);
354 g.insert_arc(right[j], right[i], 1);
355 }
356
357 // Bridges
358 for (int i = 0; i < BRIDGE_COUNT; ++i)
359 {
360 g.insert_arc(left[i], right[i], 1);
361 g.insert_arc(right[i], left[i], 1);
362 }
363
364 cout << "GRAPH: Two K" << CLIQUE_SIZE << " cliques connected by "
365 << BRIDGE_COUNT << " edges\n";
366 cout << " Expected min-cut: " << BRIDGE_COUNT << "\n";
367 cout << " Nodes: " << g.get_num_nodes() << ", Edges: "
368 << g.get_num_arcs() / 2 << "\n\n";
369
370 // Run Karger-Stein with varying iterations
371 cout << "KARGER-STEIN (varying iterations):\n";
373
374 for (int iters : {1, 5, 10, 20, 50})
375 {
378 size_t result = ks(g, S, T, cut, iters);
379 cout << " " << setw(2) << iters << " iterations: min-cut = "
380 << result / 2 << "\n";
381 }
382
383 // Run Stoer-Wagner
384 cout << "\nSTOER-WAGNER (deterministic):\n";
388 int result = sw(g, S, T, cut);
389 cout << " Result: min-cut = " << result / 2 << "\n";
390
391 cout << "\nCONCLUSION:\n";
392 cout << " - Karger-Stein converges to correct answer with more iterations\n";
393 cout << " - Stoer-Wagner always gives exact answer in one run\n";
394 cout << " - Choose based on: graph size, accuracy needs, weighted/unweighted\n\n";
395}
396
397// ============================================================================
398// EXAMPLE 5: Practical API Usage Patterns
399// ============================================================================
400
402{
403 cout << "╔════════════════════════════════════════════════════════════════╗\n";
404 cout << "║ EXAMPLE 5: API Usage Patterns ║\n";
405 cout << "╚════════════════════════════════════════════════════════════════╝\n\n";
406
408 GT g;
409
410 auto a = g.insert_node("A");
411 auto b = g.insert_node("B");
412 auto c = g.insert_node("C");
413 auto d = g.insert_node("D");
414
415 g.insert_arc(a, b, 1); g.insert_arc(b, a, 1);
416 g.insert_arc(b, c, 1); g.insert_arc(c, b, 1);
417 g.insert_arc(c, d, 1); g.insert_arc(d, c, 1);
418 g.insert_arc(a, d, 1); g.insert_arc(d, a, 1);
419
420 cout << "PATTERN 1: Basic single-run (Karger-Stein)\n";
421 cout << "-------------------------------------------\n";
422 cout << R"(
423 Karger_Stein_Min_Cut<GT> ks;
424 DynList<GT::Node*> S, T;
425 DynList<GT::Arc*> cut;
426 size_t result = ks(g, S, T, cut);
427)";
428
429 {
433 size_t result = ks(g, S, T, cut);
434 cout << " Result: " << result << "\n\n";
435 }
436
437 cout << "PATTERN 2: Multiple iterations for accuracy (Karger-Stein)\n";
438 cout << "-----------------------------------------------------------\n";
439 cout << R"(
440 size_t result = ks(g, S, T, cut, 20);
441)";
442
443 {
447 size_t result = ks(g, S, T, cut, 20);
448 cout << " Result: " << result << "\n\n";
449 }
450
451 cout << "PATTERN 3: Reproducible results with seed\n";
452 cout << "------------------------------------------\n";
453 cout << R"(
454 Karger_Stein_Min_Cut<GT> ks(12345); // Seed = 12345
455 // Or: ks.set_seed(12345);
456)";
457
458 {
459 Karger_Stein_Min_Cut<GT> ks1(12345);
460 Karger_Stein_Min_Cut<GT> ks2(12345);
461 DynList<GT::Node*> S1, T1, S2, T2;
462 DynList<GT::Arc*> cut1, cut2;
463 size_t r1 = ks1(g, S1, T1, cut1);
464 size_t r2 = ks2(g, S2, T2, cut2);
465 cout << " Same seed → same result: " << (r1 == r2 ? "YES" : "NO") << "\n\n";
466 }
467
468 cout << "PATTERN 4: Weighted graph (Stoer-Wagner)\n";
469 cout << "-----------------------------------------\n";
470 cout << R"(
471 Stoer_Wagner_Min_Cut<GT> sw;
472 int weight = sw(g, S, T, cut); // Returns total weight of cut edges
473)";
474
475 {
479 int weight = sw(g, S, T, cut);
480 cout << " Result: " << weight << "\n\n";
481 }
482
483 cout << "PATTERN 5: Just the weight, no partition (Stoer-Wagner)\n";
484 cout << "--------------------------------------------------------\n";
485 cout << R"(
486 int weight = sw.min_cut_weight(g); // Slightly faster
487)";
488
489 {
491 int weight = sw.min_cut_weight(g);
492 cout << " Result: " << weight << "\n\n";
493 }
494
495 cout << "PATTERN 6: Unweighted graph with Stoer-Wagner\n";
496 cout << "----------------------------------------------\n";
497 cout << R"(
498 Stoer_Wagner_Min_Cut<GT, Unit_Weight<GT>> sw;
499 size_t num_edges = sw(g, S, T, cut); // Counts edges, ignores weights
500)";
501
502 {
506 size_t num_edges = sw(g, S, T, cut);
507 cout << " Result: " << num_edges << " edges\n\n";
508 }
509}
510
511// ============================================================================
512// EXAMPLE 6: When to Use Which Algorithm
513// ============================================================================
514
516{
517 cout << "╔════════════════════════════════════════════════════════════════╗\n";
518 cout << "║ EXAMPLE 6: Algorithm Selection Guide ║\n";
519 cout << "╚════════════════════════════════════════════════════════════════╝\n\n";
520
521 cout << "DECISION FLOWCHART:\n";
522 cout << "═══════════════════\n\n";
523
524 cout << " ┌─────────────────────────────────────────┐\n";
525 cout << " │ Do you need the EXACT minimum cut? │\n";
526 cout << " └────────────────┬────────────────────────┘\n";
527 cout << " │\n";
528 cout << " ┌─────────┴─────────┐\n";
529 cout << " │ │\n";
530 cout << " YES NO\n";
531 cout << " │ │\n";
532 cout << " ▼ ▼\n";
533 cout << " ┌──────────────┐ ┌──────────────────────┐\n";
534 cout << " │ STOER-WAGNER │ │ Is the graph large? │\n";
535 cout << " │ Deterministic│ │ (n > 100) │\n";
536 cout << " └──────────────┘ └──────────┬───────────┘\n";
537 cout << " │\n";
538 cout << " ┌─────────┴─────────┐\n";
539 cout << " │ │\n";
540 cout << " YES NO\n";
541 cout << " │ │\n";
542 cout << " ▼ ▼\n";
543 cout << " ┌──────────────┐ ┌──────────────┐\n";
544 cout << " │ KARGER-STEIN │ │ STOER-WAGNER │\n";
545 cout << " │ O(n² log³ n) │ │ Simple cases │\n";
546 cout << " └──────────────┘ └──────────────┘\n\n";
547
548 cout << "COMPARISON TABLE:\n";
549 cout << "═════════════════\n\n";
550
551 cout << " ┌────────────────┬───────────────────┬───────────────────┐\n";
552 cout << " │ Criterion │ Karger-Stein │ Stoer-Wagner │\n";
553 cout << " ├────────────────┼───────────────────┼───────────────────┤\n";
554 cout << " │ Time │ O(n² log³ n) │ O(nm + n² log n) │\n";
555 cout << " │ Space │ O(n + m) │ O(n²) │\n";
556 cout << " │ Deterministic? │ No (randomized) │ Yes │\n";
557 cout << " │ Weighted? │ No │ Yes │\n";
558 cout << " │ Exact? │ High probability │ Always │\n";
559 cout << " │ Large graphs │ ✓ Better │ OK │\n";
560 cout << " │ Small graphs │ OK │ ✓ Better │\n";
561 cout << " └────────────────┴───────────────────┴───────────────────┘\n\n";
562
563 cout << "PRACTICAL RECOMMENDATIONS:\n";
564 cout << "══════════════════════════\n\n";
565
566 cout << " 1. NETWORK RELIABILITY → Stoer-Wagner (exact answer matters)\n";
567 cout << " 2. BANDWIDTH ANALYSIS → Stoer-Wagner (needs weights)\n";
568 cout << " 3. COMMUNITY DETECTION → Either (approximate OK)\n";
569 cout << " 4. LARGE SOCIAL GRAPH → Karger-Stein (faster)\n";
570 cout << " 5. VLSI DESIGN → Stoer-Wagner (precision critical)\n\n";
571}
572
573// ============================================================================
574// Main
575// ============================================================================
576
577int main()
578{
579 cout << "\n";
580 cout << "████████████████████████████████████████████████████████████████████\n";
581 cout << "██ ██\n";
582 cout << "██ MINIMUM CUT ALGORITHMS - EDUCATIONAL EXAMPLES ██\n";
583 cout << "██ Karger-Stein (Randomized) & Stoer-Wagner (Deterministic) ██\n";
584 cout << "██ ██\n";
585 cout << "████████████████████████████████████████████████████████████████████\n";
586 cout << "\n";
587
594
595 cout << "════════════════════════════════════════════════════════════════════\n";
596 cout << " All examples completed successfully!\n";
597 cout << "════════════════════════════════════════════════════════════════════\n\n";
598
599 return 0;
600}
Karger-Stein randomized min-cut algorithm (alias for Karger.H fast method).
Stoer-Wagner deterministic min-cut algorithm.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
Karger's randomized minimum cut algorithm.
Definition Karger.H:165
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Stoer-Wagner deterministic minimum cut algorithm.
Weight min_cut_weight(GT &g)
Find only the minimum cut weight (faster, no partition info).
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
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
void example_weighted_bandwidth()
void example_community_detection()
void print_cut_edges(GT &g, const DynList< typename GT::Arc * > &cut)
void example_algorithm_comparison()
void print_partition(const string &name, const DynList< typename GT::Node * > &partition)
void example_network_reliability()
int main()
void example_algorithm_selection()
void example_api_patterns()
Main namespace for Aleph-w library functions.
std::pair< TgtContainer< typename SrcContainer::Item_Type >, TgtContainer< typename SrcContainer::Item_Type > > partition(const SrcContainer &c, std::function< bool(const typename SrcContainer::Item_Type &)> operation)
Partition a container into two based on a predicate.
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.
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Generic graph and digraph implementations.