#define PROBLEM "https://judge.yosupo.jp/problem/cartesian_tree" #include <functional> #include <iostream> #include <tuple> #include "Mylib/Algorithm/cartesian_tree.cpp" #include "Mylib/IO/input_vector.cpp" #include "Mylib/IO/join.cpp" namespace hl = haar_lib; int main() { std::cin.tie(0); std::ios::sync_with_stdio(false); int N; std::cin >> N; auto a = hl::input_vector<int>(N); auto ans = std::get<1>(hl::cartesian_tree(a, std::less<>())); for (int i = 0; i < N; ++i) { std::cout << ans[i].value_or(i) << "\n"; } return 0; }
#line 1 "test/yosupo-judge/cartesian_tree/main.test.cpp" #define PROBLEM "https://judge.yosupo.jp/problem/cartesian_tree" #include <functional> #include <iostream> #include <tuple> #line 2 "Mylib/Algorithm/cartesian_tree.cpp" #include <optional> #line 4 "Mylib/Algorithm/cartesian_tree.cpp" #include <vector> namespace haar_lib { template <typename T, typename Compare> auto cartesian_tree(const std::vector<T> &a, Compare compare) -> std::tuple< int, // root std::vector<std::optional<int>>, // parent nodes std::vector<std::optional<int>>, // left nodes std::vector<std::optional<int>> // right nodes > { const int n = a.size(); std::vector<std::optional<int>> p(n), l(n), r(n); int root = 0; for (int i = 0; i < n; ++i) { if (i == 0) { continue; } int j = i - 1; while (1) { if (compare(a[i], a[j])) { if (not p[j]) { p[j] = i; l[i] = j; root = i; break; } j = *p[j]; continue; } auto t = r[j]; r[j] = i; p[i] = j; l[i] = t; if (t) p[*t] = i; break; } } return std::make_tuple(root, p, l, r); } } // namespace haar_lib #line 4 "Mylib/IO/input_vector.cpp" namespace haar_lib { template <typename T> std::vector<T> input_vector(int N) { std::vector<T> ret(N); for (int i = 0; i < N; ++i) std::cin >> ret[i]; return ret; } template <typename T> std::vector<std::vector<T>> input_vector(int N, int M) { std::vector<std::vector<T>> ret(N); for (int i = 0; i < N; ++i) ret[i] = input_vector<T>(M); return ret; } } // namespace haar_lib #line 3 "Mylib/IO/join.cpp" #include <sstream> #include <string> namespace haar_lib { template <typename Iter> std::string join(Iter first, Iter last, std::string delim = " ") { std::stringstream s; for (auto it = first; it != last; ++it) { if (it != first) s << delim; s << *it; } return s.str(); } } // namespace haar_lib #line 9 "test/yosupo-judge/cartesian_tree/main.test.cpp" namespace hl = haar_lib; int main() { std::cin.tie(0); std::ios::sync_with_stdio(false); int N; std::cin >> N; auto a = hl::input_vector<int>(N); auto ans = std::get<1>(hl::cartesian_tree(a, std::less<>())); for (int i = 0; i < N; ++i) { std::cout << ans[i].value_or(i) << "\n"; } return 0; }