// SPDX-License-Identifier: MIT // Min-cost assignment for a rectangular cost matrix (rows <= cols), CC0-style // Hungarian. #ifndef HUNGARIAN_H_ #define HUNGARIAN_H_ #include #include #include #include #include namespace cppannote::hungarian { inline std::pair> min_cost_assignment( const std::vector>& cost) { const int n = static_cast(cost.size()); if (n == 0) { return {0.0, {}}; } const int m = static_cast(cost[0].size()); if (m < n) { throw std::runtime_error("hungarian: need cols >= rows"); } const int big_n = n + 1; const int big_m = m + 1; const double inf = std::numeric_limits::infinity(); std::vector u(big_n, 0.0); std::vector v(big_m, 0.0); std::vector p(big_m, 0); std::vector way(big_m, 0); for (int i = 1; i < big_n; ++i) { p[0] = i; int j0 = 0; std::vector minv(big_m, inf); std::vector used(big_m, 0); do { used[static_cast(j0)] = 1; const int i0 = p[static_cast(j0)]; double delta = inf; int j1 = 0; for (int j = 1; j < big_m; ++j) { if (!used[static_cast(j)]) { const double cur = cost[static_cast(i0 - 1)] [static_cast(j - 1)] - u[static_cast(i0)] - v[static_cast(j)]; if (cur < minv[static_cast(j)]) { minv[static_cast(j)] = cur; way[static_cast(j)] = j0; } if (minv[static_cast(j)] < delta) { delta = minv[static_cast(j)]; j1 = j; } } } for (int j = 0; j < big_m; ++j) { if (used[static_cast(j)]) { u[static_cast(p[static_cast(j)])] += delta; v[static_cast(j)] -= delta; } else { minv[static_cast(j)] -= delta; } } j0 = j1; } while (p[static_cast(j0)] != 0); do { const int j1 = way[static_cast(j0)]; p[static_cast(j0)] = p[static_cast(j1)]; j0 = j1; } while (j0); } std::vector assignment(static_cast(n), -1); for (int j = 1; j < big_m; ++j) { if (p[static_cast(j)] != 0) { assignment[static_cast(p[static_cast(j)] - 1)] = j - 1; } } double total = 0.0; for (int i = 0; i < n; ++i) { const int j = assignment[static_cast(i)]; if (j >= 0) { total += cost[static_cast(i)][static_cast(j)]; } } return {-v[0], assignment}; } } // namespace cppannote::hungarian #endif // HUNGARIAN_H_