|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <sstream> |
| 4 | +#include <string> |
| 5 | + |
| 6 | +// Check whether cost(i, j) is Monge or not |
| 7 | +// Complexity: O(nm) |
| 8 | +// https://hackmd.io/@tatyam-prime/monge1 |
| 9 | +template <bool only_upper = false> |
| 10 | +std::string check_matrix_monge(auto cost, auto inf, int n, int m) { |
| 11 | + if (m < 0) m = n; |
| 12 | + |
| 13 | + auto Detect = [n, m, inf](auto f) -> std::tuple<bool, int, int> { |
| 14 | + for (int i = 0; i + 1 < n; ++i) { |
| 15 | + for (int j = only_upper ? (i + 2) : 0; j + 1 < m; ++j) { |
| 16 | + const auto f00 = f(i, j), f01 = f(i, j + 1), f10 = f(i + 1, j), |
| 17 | + f11 = f(i + 1, j + 1); |
| 18 | + if (f00 >= inf or f01 >= inf) continue; |
| 19 | + if (f00 + f11 > f10 + f01) { return {false, i, j}; } |
| 20 | + } |
| 21 | + } |
| 22 | + return {true, -1, -1}; |
| 23 | + }; |
| 24 | + |
| 25 | + if (auto [is_monge, i, j] = Detect(cost); is_monge) { |
| 26 | + return "Monge OK"; |
| 27 | + } else if (auto [is_anti_monge, ai, aj] = Detect([&cost, inf](int i, int j) { |
| 28 | + auto ret = cost(i, j); |
| 29 | + return ret == inf ? inf : -ret; |
| 30 | + }); |
| 31 | + is_anti_monge) { |
| 32 | + return "Not Monge, but Anti-Monge OK"; |
| 33 | + } else { |
| 34 | + std::stringstream ret; |
| 35 | + ret << "Not Monge!\n"; |
| 36 | + ret << " j=" << std::to_string(j) << " j=" << std::to_string(j + 1) << "\n"; |
| 37 | + ret << "i=" << std::to_string(i) << " " << cost(i, j) << " " << cost(i, j + 1) << "\n"; |
| 38 | + ret << "i=" << std::to_string(i + 1) << " " << cost(i + 1, j) << " " << cost(i + 1, j + 1); |
| 39 | + return ret.str(); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +// Check whether graph weight is Monge or not |
| 44 | +// Complexity: O(n^2) |
| 45 | +std::string check_dag_monge(auto cost, auto inf, int n) { |
| 46 | + return check_matrix_monge<true>(cost, inf, n, n); |
| 47 | +} |
0 commit comments