sotanishy's competitive programming library

sotanishy's code snippets for competitive programming

View the Project on GitHub sotanishy/cp-library-cpp

:heavy_check_mark: Cartesian Tree
(tree/cartesian_tree.hpp)

Description

Cartesian tree は,数列から定まる二分木で,以下の条件を満たすものである.

Operations

Reference

Verified with

Code

#pragma once
#include <stack>
#include <vector>

template <typename T>
std::vector<int> cartesian_tree(const std::vector<T>& a) {
    const int n = a.size();
    std::vector<int> par(n, -1);
    std::stack<int> st;
    for (int i = 0; i < n; ++i) {
        int j = -1;
        while (!st.empty() && a[st.top()] >= a[i]) {
            j = st.top();
            st.pop();
        }
        if (!st.empty()) par[i] = st.top();
        if (j != -1) par[j] = i;
        st.push(i);
    }
    return par;
}
#line 2 "tree/cartesian_tree.hpp"
#include <stack>
#include <vector>

template <typename T>
std::vector<int> cartesian_tree(const std::vector<T>& a) {
    const int n = a.size();
    std::vector<int> par(n, -1);
    std::stack<int> st;
    for (int i = 0; i < n; ++i) {
        int j = -1;
        while (!st.empty() && a[st.top()] >= a[i]) {
            j = st.top();
            st.pop();
        }
        if (!st.empty()) par[i] = st.top();
        if (j != -1) par[j] = i;
        st.push(i);
    }
    return par;
}
Back to top page