Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
hungarian_test.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
48# include <gtest/gtest.h>
49# include <limits>
50# include <random>
51# include <stdexcept>
52# include <set>
53# include <Hungarian.H>
54# include <tpl_dynMat.H>
55# include <tpl_mincost.H>
56
57using namespace std;
58using namespace Aleph;
59
60// ============================================================================
61// Helper: build a DynMatrix from a 2D initializer list
62// ============================================================================
63template <typename T>
64DynMatrix<T> make_matrix(initializer_list<initializer_list<T>> rows)
65{
66 size_t m = rows.size();
67 size_t n = rows.begin()->size();
68 DynMatrix<T> mat(m, n, T{0});
69 mat.allocate();
70 size_t i = 0;
71 for (const auto & row : rows)
72 {
73 size_t j = 0;
74 for (const auto & val : row)
75 mat(i, j++) = val;
76 ++i;
77 }
78 return mat;
79}
80
81// Helper: compute the actual cost of an assignment using the cost matrix
82template <typename T>
84 const DynList<pair<size_t, size_t>> & pairs)
85{
86 T total = T{0};
87 for (auto it = pairs.get_it(); it.has_curr(); it.next())
88 {
89 auto [r, c] = it.get_curr();
90 total += cost.read(r, c);
91 }
92 return total;
93}
94
95// Helper: verify the assignment is a valid permutation
96void verify_permutation(const Array<long> & row_to_col,
97 const Array<long> & col_to_row,
98 size_t rows, size_t cols)
99{
100 // Each assigned row maps to a unique column
101 set<long> assigned_cols;
102 for (size_t i = 0; i < rows; ++i)
103 {
104 long j = row_to_col[i];
105 if (j >= 0)
106 {
107 EXPECT_LT(static_cast<size_t>(j), cols)
108 << "Row " << i << " assigned to out-of-range column " << j;
109 EXPECT_TRUE(assigned_cols.insert(j).second)
110 << "Column " << j << " assigned to multiple rows";
111 }
112 }
113
114 // Each assigned column maps back correctly
115 for (size_t j = 0; j < cols; ++j)
116 {
117 long i = col_to_row[j];
118 if (i >= 0)
119 {
120 EXPECT_LT(static_cast<size_t>(i), rows)
121 << "Column " << j << " assigned to out-of-range row " << i;
122 EXPECT_EQ(row_to_col[static_cast<size_t>(i)],
123 static_cast<long>(j))
124 << "Inconsistent row/col mapping at row=" << i << " col=" << j;
125 }
126 }
127}
128
129// ============================================================================
130// HungarianBasic: small matrices with known solutions
131// ============================================================================
132
133TEST(HungarianBasic, Matrix1x1)
134{
135 auto mat = make_matrix<int>({{42}});
137
138 EXPECT_EQ(ha.get_total_cost(), 42);
139 EXPECT_EQ(ha.get_assignment(0), 0);
140 EXPECT_EQ(ha.rows(), 1u);
141 EXPECT_EQ(ha.cols(), 1u);
142}
143
144TEST(HungarianBasic, Matrix2x2)
145{
146 // Cost matrix:
147 // 1 2
148 // 3 0
149 // Optimal: (0,0)=1, (1,1)=0 -> cost=1
150 auto mat = make_matrix<int>({{1, 2}, {3, 0}});
152
153 EXPECT_EQ(ha.get_total_cost(), 1);
154
155 auto pairs = ha.get_assignments();
156 EXPECT_EQ(compute_assignment_cost(mat, pairs), 1);
157}
158
159TEST(HungarianBasic, Matrix3x3)
160{
161 // Classic example:
162 // 10 5 13
163 // 3 9 18
164 // 10 6 12
165 // Optimal: (0,1)=5, (1,0)=3, (2,2)=12 -> cost=20
166 auto mat = make_matrix<int>({{10, 5, 13}, {3, 9, 18}, {10, 6, 12}});
168
169 EXPECT_EQ(ha.get_total_cost(), 20);
170}
171
172TEST(HungarianBasic, Matrix4x4)
173{
174 // Example:
175 // 82 83 69 92
176 // 77 37 49 92
177 // 11 69 5 86
178 // 8 9 98 23
179 // Optimal: (0,2)=69, (1,1)=37, (2,0)=11, (3,3)=23 -> cost=140
180 auto mat = make_matrix<int>({
181 {82, 83, 69, 92},
182 {77, 37, 49, 92},
183 {11, 69, 5, 86},
184 { 8, 9, 98, 23}
185 });
187
188 EXPECT_EQ(ha.get_total_cost(), 140);
189
190 auto pairs = ha.get_assignments();
191 EXPECT_EQ(compute_assignment_cost(mat, pairs), 140);
192}
193
194TEST(HungarianBasic, RankOneMatrix4x4)
195{
196 // Rank-1 matrix c[i][j] = (i+1)*(j+1):
197 // 1 2 3 4
198 // 2 4 6 8
199 // 3 6 9 12
200 // 4 8 12 16
201 // Optimal: anti-diagonal (3,2,1,0) -> 4+6+6+4 = 20
202 auto mat = make_matrix<int>({
203 {1, 2, 3, 4},
204 {2, 4, 6, 8},
205 {3, 6, 9, 12},
206 {4, 8, 12, 16}
207 });
209
210 EXPECT_EQ(ha.get_total_cost(), 20);
211}
212
213// ============================================================================
214// HungarianRectangular: non-square matrices
215// ============================================================================
216
217TEST(HungarianRectangular, MoreColsThanRows_2x3)
218{
219 // 2 workers, 3 tasks. One task will be unassigned.
220 // 1 2 3
221 // 4 5 6
222 // Optimal: assign to minimize cost -> (0,0)=1, (1,1)=5 -> cost=6
223 auto mat = make_matrix<int>({{1, 2, 3}, {4, 5, 6}});
225
226 EXPECT_EQ(ha.get_total_cost(), 6);
227
228 auto pairs = ha.get_assignments();
229 EXPECT_EQ(pairs.size(), 2u); // 2 pairs (one per row)
230}
231
232TEST(HungarianRectangular, MoreRowsThanCols_3x2)
233{
234 // 3 workers, 2 tasks. One worker will be unassigned.
235 // 1 4
236 // 2 5
237 // 3 6
238 // Optimal: (0,0)=1, (1,1)=5 -> cost=6
239 auto mat = make_matrix<int>({{1, 4}, {2, 5}, {3, 6}});
241
242 EXPECT_EQ(ha.get_total_cost(), 6);
243
244 auto pairs = ha.get_assignments();
245 EXPECT_EQ(pairs.size(), 2u); // min(rows, cols) assignments
246}
247
248TEST(HungarianRectangular, Wide_2x5)
249{
250 // 10 3 7 2 8
251 // 5 9 1 6 4
252 // Optimal: (0,3)=2, (1,2)=1 -> cost=3
253 auto mat = make_matrix<int>({{10, 3, 7, 2, 8}, {5, 9, 1, 6, 4}});
255
256 EXPECT_EQ(ha.get_total_cost(), 3);
257}
258
259TEST(HungarianRectangular, Tall_5x2)
260{
261 // 10 5
262 // 3 9
263 // 7 1
264 // 2 6
265 // 8 4
266 // Optimal: (3,0)=2, (2,1)=1 -> cost=3
267 auto mat = make_matrix<int>({{10, 5}, {3, 9}, {7, 1}, {2, 6}, {8, 4}});
269
270 EXPECT_EQ(ha.get_total_cost(), 3);
271}
272
273// ============================================================================
274// HungarianDegenerate: edge cases
275// ============================================================================
276
277TEST(HungarianDegenerate, AllZeros)
278{
279 auto mat = make_matrix<int>({{0, 0, 0}, {0, 0, 0}, {0, 0, 0}});
281
282 EXPECT_EQ(ha.get_total_cost(), 0);
283}
284
285TEST(HungarianDegenerate, AllSameCost)
286{
287 auto mat = make_matrix<int>({{7, 7, 7}, {7, 7, 7}, {7, 7, 7}});
289
290 EXPECT_EQ(ha.get_total_cost(), 21);
291}
292
293TEST(HungarianDegenerate, DiagonalZeros)
294{
295 // Diagonal is zero, off-diagonal is large
296 auto mat = make_matrix<int>({{0, 99, 99}, {99, 0, 99}, {99, 99, 0}});
298
299 EXPECT_EQ(ha.get_total_cost(), 0);
300
301 EXPECT_EQ(ha.get_assignment(0), 0);
302 EXPECT_EQ(ha.get_assignment(1), 1);
303 EXPECT_EQ(ha.get_assignment(2), 2);
304}
305
306TEST(HungarianDegenerate, Identity)
307{
308 // Cost = identity matrix
309 auto mat = make_matrix<int>({{1, 0, 0}, {0, 1, 0}, {0, 0, 1}});
311
312 EXPECT_EQ(ha.get_total_cost(), 0);
313}
314
315TEST(HungarianDegenerate, SingleRow)
316{
317 auto mat = make_matrix<int>({{5, 3, 8, 1}});
319
320 EXPECT_EQ(ha.get_total_cost(), 1);
321
322 auto pairs = ha.get_assignments();
323 EXPECT_EQ(pairs.size(), 1u);
324}
325
326TEST(HungarianDegenerate, SingleColumn)
327{
328 auto mat = make_matrix<int>({{5}, {3}, {8}, {1}});
330
331 EXPECT_EQ(ha.get_total_cost(), 1);
332
333 auto pairs = ha.get_assignments();
334 EXPECT_EQ(pairs.size(), 1u);
335}
336
337// ============================================================================
338// HungarianNumerics: different numeric types and negative costs
339// ============================================================================
340
341TEST(HungarianNumerics, IntegerCosts)
342{
343 auto mat = make_matrix<int>({{10, 5, 13}, {3, 9, 18}, {10, 6, 12}});
345 EXPECT_EQ(ha.get_total_cost(), 20);
346}
347
348TEST(HungarianNumerics, DoubleCosts)
349{
350 auto mat = make_matrix<double>({{1.5, 2.5}, {3.5, 0.5}});
352 EXPECT_DOUBLE_EQ(ha.get_total_cost(), 2.0);
353}
354
355TEST(HungarianNumerics, NegativeCosts)
356{
357 // All negative costs
358 auto mat = make_matrix<int>({{-1, -2, -3}, {-4, -5, -6}, {-7, -8, -9}});
360
361 // Minimum cost: (0,2)=-3, (1,1)=-5, (2,0)=-7 or similar
362 // The minimum sum is -3 + -5 + -7 = -15? Let's check:
363 // Actually: (0,2)=-3, (1,0)=-4, (2,1)=-8 = -15
364 // Or: (0,0)=-1, (1,1)=-5, (2,2)=-9 = -15
365 // Or: (0,1)=-2, (1,2)=-6, (2,0)=-7 = -15
366 // All permutations give -15 since c[i][j] = -(3*i + j + 1)
367 // Actually no. Let me recompute:
368 // row 0: -1 -2 -3
369 // row 1: -4 -5 -6
370 // row 2: -7 -8 -9
371 // Minimum cost assignment minimizes sum:
372 // (0,2)=-3, (1,1)=-5, (2,0)=-7: sum=-15
373 // (0,0)=-1, (1,1)=-5, (2,2)=-9: sum=-15
374 // (0,1)=-2, (1,0)=-4, (2,2)=-9: sum=-15
375 // All give -15. This matrix has all-equal permutation sums.
376 EXPECT_EQ(ha.get_total_cost(), -15);
377}
378
379TEST(HungarianNumerics, MixedSigns)
380{
381 auto mat = make_matrix<int>({{-5, 3}, {2, -7}});
383
384 // Options: (0,0)=-5 + (1,1)=-7 = -12 or (0,1)=3 + (1,0)=2 = 5
385 EXPECT_EQ(ha.get_total_cost(), -12);
386}
387
388TEST(HungarianNumerics, LargeCosts)
389{
390 auto mat = make_matrix<long>({{1000000, 2000000}, {3000000, 500000}});
392
393 // (0,0)=1000000 + (1,1)=500000 = 1500000
394 EXPECT_EQ(ha.get_total_cost(), 1500000L);
395}
396
397// ============================================================================
398// HungarianMaximization: maximize profit
399// ============================================================================
400
401TEST(HungarianMaximization, Basic3x3)
402{
403 auto mat = make_matrix<int>({{10, 5, 13}, {3, 9, 18}, {10, 6, 12}});
404 auto result = hungarian_max_assignment(mat);
405
406 // Maximum: (0,2)=13, (1,1)=9, (2,0)=10 = 32
407 // Or: (0,0)=10, (1,2)=18, (2,1)=6 = 34
408 // Let's check all 6 permutations:
409 // (0,1,2): 10+9+12=31
410 // (0,2,1): 10+18+6=34
411 // (1,0,2): 5+3+12=20
412 // (1,2,0): 5+18+10=33
413 // (2,0,1): 13+3+6=22
414 // (2,1,0): 13+9+10=32
415 // Max is 34
416 EXPECT_EQ(result.total_cost, 34);
417}
418
419TEST(HungarianMaximization, Rectangular)
420{
421 auto mat = make_matrix<int>({{1, 2, 3}, {4, 5, 6}});
422 auto result = hungarian_max_assignment(mat);
423
424 // Maximum: (0,1)=2, (1,2)=6 = 8 or (0,2)=3, (1,1)=5 = 8
425 EXPECT_EQ(result.total_cost, 8);
426}
427
428// ============================================================================
429// HungarianAPI: interface correctness
430// ============================================================================
431
432TEST(HungarianAPI, InitializerListConstructor)
433{
435 {10, 5, 13},
436 {3, 9, 18},
437 {10, 6, 12}
438 });
439
440 EXPECT_EQ(ha.get_total_cost(), 20);
441 EXPECT_EQ(ha.rows(), 3u);
442 EXPECT_EQ(ha.cols(), 3u);
443 EXPECT_EQ(ha.dimension(), 3u);
444}
445
446TEST(HungarianAPI, FreeFunctionMinimization)
447{
448 auto mat = make_matrix<int>({{10, 5, 13}, {3, 9, 18}, {10, 6, 12}});
449 auto result = hungarian_assignment(mat);
450
451 EXPECT_EQ(result.total_cost, 20);
452 EXPECT_EQ(result.orig_rows, 3u);
453 EXPECT_EQ(result.orig_cols, 3u);
454
455 auto pairs = result.get_pairs();
456 EXPECT_EQ(pairs.size(), 3u);
457}
458
459TEST(HungarianAPI, GetPairsFiltersDummies)
460{
461 // Rectangular 2x4: only 2 real assignments
462 auto mat = make_matrix<int>({{1, 2, 3, 4}, {5, 6, 7, 8}});
464
465 auto pairs = ha.get_assignments();
466 EXPECT_EQ(pairs.size(), 2u);
467
468 // Verify all pairs are within original dimensions
469 for (auto it = pairs.get_it(); it.has_curr(); it.next())
470 {
471 auto [r, c] = it.get_curr();
472 EXPECT_LT(r, 2u);
473 EXPECT_LT(c, 4u);
474 }
475}
476
477TEST(HungarianAPI, ConsistencyCheck)
478{
479 auto mat = make_matrix<int>({
480 {82, 83, 69, 92},
481 {77, 37, 49, 92},
482 {11, 69, 5, 86},
483 { 8, 9, 98, 23}
484 });
486
487 verify_permutation(ha.get_row_assignments(), ha.get_col_assignments(),
488 ha.rows(), ha.cols());
489
490 // Verify cost matches sum of assigned entries
491 auto pairs = ha.get_assignments();
492 EXPECT_EQ(compute_assignment_cost(mat, pairs), ha.get_total_cost());
493}
494
495// ============================================================================
496// HungarianValidation: permutation and cost correctness
497// ============================================================================
498
499TEST(HungarianValidation, PermutationProperty)
500{
501 // Every valid assignment is a permutation (for square matrices)
502 auto mat = make_matrix<int>({
503 {5, 9, 1},
504 {10, 3, 2},
505 {8, 7, 4}
506 });
508
509 set<long> assigned;
510 for (size_t i = 0; i < 3; ++i)
511 {
512 long col = ha.get_assignment(i);
513 EXPECT_GE(col, 0);
514 EXPECT_LT(col, 3);
515 EXPECT_TRUE(assigned.insert(col).second)
516 << "Column " << col << " assigned twice";
517 }
518}
519
520TEST(HungarianValidation, CostMatchesSum)
521{
522 auto mat = make_matrix<int>({
523 {25, 40, 35},
524 {40, 60, 35},
525 {20, 40, 25}
526 });
528
529 auto pairs = ha.get_assignments();
530 int actual = compute_assignment_cost(mat, pairs);
531 EXPECT_EQ(actual, ha.get_total_cost());
532}
533
534TEST(HungarianValidation, BruteForce3x3)
535{
536 // Verify against brute-force for a 3x3 matrix
537 auto mat = make_matrix<int>({
538 {7, 3, 5},
539 {2, 8, 1},
540 {6, 4, 9}
541 });
542
543 // All 6 permutations of {0,1,2}
544 int perms[6][3] = {
545 {0,1,2}, {0,2,1}, {1,0,2}, {1,2,0}, {2,0,1}, {2,1,0}
546 };
547
548 int min_cost = numeric_limits<int>::max();
549 for (auto & perm : perms)
550 {
551 int cost = 0;
552 for (int i = 0; i < 3; ++i)
553 cost += static_cast<int>(mat.read(i, perm[i]));
554 min_cost = min(min_cost, cost);
555 }
556
558 EXPECT_EQ(ha.get_total_cost(), min_cost);
559}
560
561TEST(HungarianValidation, BruteForce4x4)
562{
563 auto mat = make_matrix<int>({
564 {15, 4, 8, 12},
565 {7, 9, 3, 6},
566 {10, 14, 2, 11},
567 {5, 13, 1, 16}
568 });
569
570 // Brute-force: enumerate all 24 permutations
571 int perm[4] = {0, 1, 2, 3};
572 int min_cost = numeric_limits<int>::max();
573 do
574 {
575 int cost = 0;
576 for (int i = 0; i < 4; ++i)
577 cost += static_cast<int>(mat.read(i, perm[i]));
578 min_cost = min(min_cost, cost);
579 }
580 while (next_permutation(perm, perm + 4));
581
583 EXPECT_EQ(ha.get_total_cost(), min_cost);
584}
585
586// ============================================================================
587// HungarianStress: random large matrices
588// ============================================================================
589
590TEST(HungarianStress, Random10x10)
591{
592 mt19937 rng(42);
593 uniform_int_distribution<int> dist(1, 100);
594
595 DynMatrix<int> mat(10, 10, 0);
596 mat.allocate();
597 for (size_t i = 0; i < 10; ++i)
598 for (size_t j = 0; j < 10; ++j)
599 mat(i, j) = dist(rng);
600
603 10, 10);
604
605 auto pairs = ha.get_assignments();
606 EXPECT_EQ(pairs.size(), 10u);
607 EXPECT_EQ(compute_assignment_cost(mat, pairs), ha.get_total_cost());
608}
609
610TEST(HungarianStress, Random50x50)
611{
612 mt19937 rng(123);
613 uniform_int_distribution<int> dist(1, 1000);
614
615 DynMatrix<int> mat(50, 50, 0);
616 mat.allocate();
617 for (size_t i = 0; i < 50; ++i)
618 for (size_t j = 0; j < 50; ++j)
619 mat(i, j) = dist(rng);
620
623 50, 50);
624
625 auto pairs = ha.get_assignments();
626 EXPECT_EQ(pairs.size(), 50u);
627 EXPECT_EQ(compute_assignment_cost(mat, pairs), ha.get_total_cost());
628}
629
630TEST(HungarianStress, Random100x100)
631{
632 mt19937 rng(456);
633 uniform_int_distribution<int> dist(0, 10000);
634
635 DynMatrix<int> mat(100, 100, 0);
636 mat.allocate();
637 for (size_t i = 0; i < 100; ++i)
638 for (size_t j = 0; j < 100; ++j)
639 mat(i, j) = dist(rng);
640
643 100, 100);
644
645 auto pairs = ha.get_assignments();
646 EXPECT_EQ(pairs.size(), 100u);
647 EXPECT_EQ(compute_assignment_cost(mat, pairs), ha.get_total_cost());
648}
649
650TEST(HungarianStress, RandomRectangular_30x50)
651{
652 mt19937 rng(789);
653 uniform_int_distribution<int> dist(1, 500);
654
655 DynMatrix<int> mat(30, 50, 0);
656 mat.allocate();
657 for (size_t i = 0; i < 30; ++i)
658 for (size_t j = 0; j < 50; ++j)
659 mat(i, j) = dist(rng);
660
663 30, 50);
664
665 auto pairs = ha.get_assignments();
666 EXPECT_EQ(pairs.size(), 30u);
667 EXPECT_EQ(compute_assignment_cost(mat, pairs), ha.get_total_cost());
668}
669
670TEST(HungarianStress, CrossValidateWithMinCostFlow)
671{
672 // Cross-validate with solve_assignment() from tpl_mincost.H
673 // for a small matrix where we can use both approaches
674 auto mat = make_matrix<int>({
675 {82, 83, 69, 92},
676 {77, 37, 49, 92},
677 {11, 69, 5, 86},
678 { 8, 9, 98, 23}
679 });
680
682
683 // Build std::vector for solve_assignment
684 vector<vector<double>> std_costs = {
685 {82, 83, 69, 92},
686 {77, 37, 49, 92},
687 {11, 69, 5, 86},
688 { 8, 9, 98, 23}
689 };
690
691 auto flow_result = solve_assignment(std_costs);
692 ASSERT_TRUE(flow_result.feasible);
693
694 EXPECT_EQ(ha.get_total_cost(), static_cast<int>(flow_result.total_cost));
695}
696
697TEST(HungarianStress, CrossValidateRandom20x20)
698{
699 mt19937 rng(999);
700 uniform_int_distribution<int> dist(1, 100);
701
702 const size_t N = 20;
703
704 DynMatrix<int> mat(N, N, 0);
705 mat.allocate();
706 vector<vector<double>> std_costs(N, vector<double>(N));
707
708 for (size_t i = 0; i < N; ++i)
709 for (size_t j = 0; j < N; ++j)
710 {
711 int val = dist(rng);
712 mat(i, j) = val;
713 std_costs[i][j] = static_cast<double>(val);
714 }
715
717 auto flow_result = solve_assignment(std_costs);
718
719 ASSERT_TRUE(flow_result.feasible);
720 EXPECT_EQ(ha.get_total_cost(), static_cast<int>(flow_result.total_cost));
721}
722
723// ============================================================================
724// Costs near the limits of an integer type
725// ============================================================================
726
727// int keeps its potentials in long long: rows of costs from max() / 2 on,
728// which the infinity of int took for no column, have their optimum
729TEST(HungarianLimits, IntRowsFromHalfOfMaxGiveTheOptimum)
730{
731 constexpr int M = numeric_limits<int>::max();
732 EXPECT_EQ((Hungarian_Assignment<int>({{M / 2 + 1}}).get_total_cost()), M / 2 + 1);
733 EXPECT_EQ((Hungarian_Assignment<int>({{M, M}, {0, 0}}).get_total_cost()), M);
734 EXPECT_EQ((Hungarian_Assignment<int>({{M, 0}, {0, M}}).get_total_cost()), 0);
735 EXPECT_EQ((Hungarian_Assignment<int>({{M - 1, M}, {M, M - 1}, {0, 0}}).get_total_cost()),
736 M - 1);
737}
738
739// An optimum beyond max(), which overflowed the potentials, throws
740TEST(HungarianLimits, AnOptimumBeyondMaxThrows)
741{
742 DynMatrix<int> mat(3, 3, 0);
743 mat.allocate();
744 for (size_t i = 0; i < 3; ++i)
745 for (size_t j = 0; j < 3; ++j)
746 mat(i, j) = 1000000000;
747 EXPECT_THROW((void) hungarian_assignment(mat), std::overflow_error);
748
749 // and a maximum beyond max(), which was cut to the type
750 EXPECT_THROW((void) hungarian_max_assignment(mat), std::overflow_error);
751
752 // the minimum below lowest()
753 for (size_t i = 0; i < 3; ++i)
754 for (size_t j = 0; j < 3; ++j)
755 mat(i, j) = -1000000000;
756 EXPECT_THROW((void) hungarian_assignment(mat), std::overflow_error);
757
758 // two of them fit
759 DynMatrix<int> two(2, 2, 0);
760 two.allocate();
761 for (size_t i = 0; i < 2; ++i)
762 for (size_t j = 0; j < 2; ++j)
763 two(i, j) = 1000000000;
764 EXPECT_EQ(hungarian_assignment(two).total_cost, 2000000000);
765 EXPECT_EQ(hungarian_max_assignment(two).total_cost, 2000000000);
766}
767
768// long long has no wider type: costs near its limits throw, and costs far
769// from them are exact
770TEST(HungarianLimits, LongLongNearItsLimitsThrows)
771{
772 constexpr long long M = numeric_limits<long long>::max();
773 EXPECT_THROW((void) (Hungarian_Assignment<long long>({{M / 2, 1}, {1, M / 2}})),
774 std::overflow_error);
775 EXPECT_THROW((void) (Hungarian_Assignment<long long>({{numeric_limits<long long>::lowest()}})),
776 std::overflow_error);
777 EXPECT_EQ((Hungarian_Assignment<long long>({{M / 64, 1}, {1, M / 64}}).get_total_cost()), 2);
778 EXPECT_EQ((Hungarian_Assignment<long long>({{4000000000LL, 1}, {2, 4000000000LL}})
779 .get_total_cost()), 3);
780}
781// satisfy CI policy
Hungarian (Kuhn-Munkres) algorithm for the optimal assignment problem.
size_t row
Definition ca-c-api.h:115
size_t * rows
Definition ca-c-api.h:112
size_t size_t col
Definition ca-c-api.h:116
size_t cols
Definition ca-c-api.h:105
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
Dynamic matrix with sparse storage.
Definition tpl_dynMat.H:122
const T & read(const size_t i, const size_t j) const
Read the entry at position (i, j).
Definition tpl_dynMat.H:480
void allocate()
Pre-allocate memory for the entire matrix.
Definition tpl_dynMat.H:271
Implementation of the Hungarian (Munkres) algorithm.
Definition Hungarian.H:143
DynList< std::pair< size_t, size_t > > get_assignments() const
Get all assignment pairs.
Definition Hungarian.H:512
const Array< long > & get_row_assignments() const noexcept
Get the row-to-column assignment array.
Definition Hungarian.H:525
const Array< long > & get_col_assignments() const noexcept
Get the column-to-row assignment array.
Definition Hungarian.H:534
Cost_Type get_total_cost() const noexcept
Get the optimal total cost.
Definition Hungarian.H:487
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
#define TEST(name)
static mt19937 rng
#define N
Definition fib.C:294
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
Hungarian_Result< Cost_Type > hungarian_max_assignment(const DynMatrix< Cost_Type > &cost)
Compute maximum-profit assignment (free function).
Definition Hungarian.H:648
Hungarian_Result< Cost_Type > hungarian_assignment(const DynMatrix< Cost_Type > &cost)
Compute minimum-cost assignment (free function).
Definition Hungarian.H:607
DynMatrix< T > make_matrix(initializer_list< initializer_list< T > > rows)
void verify_permutation(const Array< long > &row_to_col, const Array< long > &col_to_row, size_t rows, size_t cols)
T compute_assignment_cost(const DynMatrix< T > &cost, const DynList< pair< size_t, size_t > > &pairs)
Main namespace for Aleph-w library functions.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
bool next_permutation(Array< T > &a, Compare cmp=Compare(), const bool reset_on_last=true)
Compute the next lexicographic permutation of an Array.
Definition ah-comb.H:800
std::pair< First, Second > pair
Alias to std::pair kept for backwards compatibility.
Definition ahPair.H:89
AssignmentResult< Cost_Type > solve_assignment(const std::vector< std::vector< Cost_Type > > &costs)
Solve the assignment problem using min-cost flow.
STL namespace.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Gsl_Compatible_Rng r
Dynamic matrix with lazy allocation.
Advanced minimum cost flow algorithms.