笛卡尔树模版

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    
    int n;
    std::cin >> n;
    
    std::vector a(n);
    for (int i = 0; i < n; i++) {
        std::cin >> a[i];
    }
    
    //构建笛卡尔树
    std::vector stk;
    std::vector lc(n, -1), rc(n, -1);
    for (int i = 0; i < n; i++) {
        while (!stk.empty() && a[i] > a[stk.back()]) {
            int x = stk.back();
            rc[x] = lc[i];
            lc[i] = x;
            stk.pop_back();
        }
        stk.push_back(i);
    }
    
    while (stk.size() > 1) {
        int x = stk.back();
        stk.pop_back();
        rc[stk.back()] = x;
    }
    //笛卡尔树的使用
    auto dfs = [&](auto &&self, int x, int l, int r) -> int {
        if (x == -1) {
            return inf;
        }
        int mn = std::min({self(self, lc[x], l, x), self(self, rc[x], x + 1, r), a[x]});
        //mn连续区间最小值,a[x]连续区间最大值
        return mn;
    };
    dfs(dfs, stk[0], 0, n);
    
    
    return 0;
}

你可能感兴趣的:(笛卡尔树)