笛卡尔树板子求助
查看原帖
笛卡尔树板子求助
817044
cjwdyzxfblzs楼主2023/10/25 21:33

不知道是哪里有问题啊?但是确实会WA诶。

是建树的问题还是对a数组操作有问题呢???

#include <bits/stdc++.h>
#define int long long
inline int rd(void) {
    int x = 0, f = 1; char ch = getchar();
    while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); }
    while (isdigit(ch)) { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); }
    return x * f;
}
inline void wt(int x) {
    if (x < 0) putchar('-'), x = -x;
    if (x > 9) wt(x / 10);
    putchar(x % 10 + 48);
}
const int MAXN = 1e6;
int n, a[MAXN], lc[MAXN], rc[MAXN];
void bd(void) {
    std::stack<int> stk;
    for (int i = 1; i <= n; i ++ ) {
        int lst_pop = 0;
        while (!stk.empty() && a[i] < a[stk.top()]) {
            lst_pop = stk.top();
            stk.pop();
        }
        if (!stk.empty()) {
            rc[stk.top()] = i;
        }
        lc[i] = lst_pop;
        stk.push(i);
    }
}
void dfs(int u) {
    if (u) std::cout << u << ' ';
    if (lc[u]) dfs(lc[u]);
    if (rc[u]) dfs(rc[u]);
}
auto main() -> signed
{
    n = rd();
    for (int i = 1; i <= n; i ++ ) {
        int x = rd();
        a[x] = i;
    }
    bd(), dfs(1);
    std::cout << std::endl;
    return 0;
}
2023/10/25 21:33
加载中...