ContinueLib

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

View the Project on GitHub Continue765/ContinueLib

:heavy_check_mark: CartesianTree
(data_structure/cartesian_tree.hpp)

CartesianTree

定义于头文件 cartesian_tree.hpp

template <typename T, bool IS_MIN = false>
struct CartesianTree;

以序列 $a$ 为键构造笛卡尔树,$O(n)$。IS_MIN = false 时为大根堆,否则为小根堆。

模板参数

参数 说明
T 键类型
IS_MIN 为 true 时根取区间最小值,否则取最大值

成员变量

成员变量 说明
n 序列长度
L[i] 结点 $i$ 的左儿子,无则 $-1$
R[i] 结点 $i$ 的右儿子,无则 $-1$
p[i] 结点 $i$ 的父结点,根为 $-1$
range[i] $[l, r)$,子树 $i$ 覆盖的下标区间
root 根结点编号

成员函数

构造

成员函数 说明
CartesianTree(vector<T>& a) 以 a 构造,$O(n)$

注解

键相等时下标小者作为祖先。

示例

vector<int> a{3, 1, 4, 1, 5};
CartesianTree<int> mx(a);
CartesianTree<int, true> mn(a);
int r = mx.root;
auto [l, rr] = mx.range[2];
int par = mx.p[2];

Depends on

Verified with

Code

#pragma once
#include <common.hpp>


template <typename T, bool IS_MIN = false>
struct CartesianTree {
    int n;
    vector<T>& a;
    vector<int> L, R, p;
    // range[i]: the interval of the subtree rooted at i

    vector<pair<int, int>> range;
    int root;

    CartesianTree(vector<T>& a_) : n(a_.size()), a(a_), root(-1) {
        L.assign(n, -1);
        R.assign(n, -1);
        p.assign(n, -1);
        range.assign(n, {0, n});
        vector<int> stk;

        auto cmp = [&](int i, int j) -> bool {
            if (a[i] == a[j]) {
                return i < j;
            }
            if constexpr (IS_MIN) {
                return a[i] < a[j];
            } else {
                return a[j] < a[i];
            }
        };

        for (int i = 0; i < n; i++) {
            while (!stk.empty() && cmp(i, stk.back())) {
                L[i] = stk.back();
                stk.pop_back();
            }
            range[i].first = (stk.empty() ? 0 : stk.back() + 1);
            if (!stk.empty()) {
                R[stk.back()] = i;
            }
            stk.push_back(i);
        }
        if (!stk.empty()) {
            root = stk.front();
        }
        stk.clear();
        for (int i = n - 1; i >= 0; i--) {
            while (!stk.empty() && cmp(i, stk.back())) {
                stk.pop_back();
            }
            range[i].second = stk.empty() ? n : stk.back();
            stk.push_back(i);
        }
        for (int i = 0; i < n; i++) {
            if (L[i] != -1) {
                p[L[i]] = i;
            }
            if (R[i] != -1) {
                p[R[i]] = i;
            }
        }
    }
};
Back to top page