Thanks to visit codestin.com
Credit goes to hitonanode.github.io

cplib-cpp

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub hitonanode/cplib-cpp

:heavy_check_mark: tree/test/cartesian_tree.test.cpp

Depends on

Code

#define PROBLEM "https://judge.yosupo.jp/problem/cartesian_tree"
#include "../cartesian_tree.hpp"
#include <cassert>
#include <iostream>
using namespace std;

int main() {
    cin.tie(nullptr), ios::sync_with_stdio(false);
    int N;
    cin >> N;
    std::vector<int> A(N);
    for (auto &x : A) cin >> x;
    auto Ainv = A;
    for (auto &x : Ainv) x = -x;
    auto ret = cartesian_tree(A);
    auto ret2 = cartesian_tree<int, std::greater<int>>(Ainv);
    assert(ret == ret2);
    for (int i = 0; i < N; ++i) cout << (ret[i] < 0 ? i : ret[i]) << (i + 1 == N ? '\n' : ' ');
}
#line 1 "tree/test/cartesian_tree.test.cpp"
#define PROBLEM "https://judge.yosupo.jp/problem/cartesian_tree"
#line 2 "tree/cartesian_tree.hpp"
#include <functional>
#include <vector>

// Cartesian tree
// Complexity: O(n)
// By default, the smaller node is nearer to the root
// Return : -1 (root), parent_idx (otherwise)
// Example: [1, 0, 2] => [1, -1, 1]
// Verified: https://judge.yosupo.jp/problem/cartesian_tree
template <class T, class Cmp = std::less<T>>
std::vector<int> cartesian_tree(const std::vector<T> &X) {
    const int n = X.size();
    Cmp comp;
    std::vector<int> st(n);
    int sz = 0;

    std::vector<int> par(n, -1);

    for (int i = 0; i < n; ++i) {
        while (sz >= 2 and comp(X[i], X[st[sz - 1]])) {
            par[st[sz - 1]] = comp(X[i], X[st[sz - 2]]) ? st[sz - 2] : i;
            --sz;
        }
        if (sz == 1 and comp(X[i], X[st[sz - 1]])) par[st[--sz]] = i;
        st[sz++] = i;
    }
    for (; sz > 1; --sz) par[st[sz - 1]] = st[sz - 2];
    return par;
};
#line 3 "tree/test/cartesian_tree.test.cpp"
#include <cassert>
#include <iostream>
using namespace std;

int main() {
    cin.tie(nullptr), ios::sync_with_stdio(false);
    int N;
    cin >> N;
    std::vector<int> A(N);
    for (auto &x : A) cin >> x;
    auto Ainv = A;
    for (auto &x : Ainv) x = -x;
    auto ret = cartesian_tree(A);
    auto ret2 = cartesian_tree<int, std::greater<int>>(Ainv);
    assert(ret == ret2);
    for (int i = 0; i < N; ++i) cout << (ret[i] < 0 ? i : ret[i]) << (i + 1 == N ? '\n' : ' ');
}
Back to top page