[模板]笛卡尔树

很好理解,也很好写,只要知道它的两个性质就可以自己yy了
1.堆性质
2.中序遍历序列就是原序列
代码如下:

#include <bits/stdc++.h>

using namespace std;

#define N 100000

int n, a[N+5], fa[N+5], ch[N+5][2];
int stk[N+5], tp;

void build() {
    for(int i = 1; i <= n; ++i) {
        int last = 0;
        while(tp) {
            if(a[stk[tp]] <= a[i]) {
                if(ch[stk[tp]][1]) ch[i][0] = ch[stk[tp]][1], fa[ch[stk[tp]][1]] = i;
                ch[stk[tp]][1] = i, fa[i] = stk[tp];
                break;
            }
            last = stk[tp--];
        }
        if(!tp && last) ch[i][0] = last, fa[last] = i;
        stk[++tp] = i;
    }
}

bool d(int x) {
    return ch[fa[x]][1] == x;
}

int queryLeft(int x) {
    while(fa[x] && d(x) == 0) x = fa[x]; 
    return fa[x];
}

int queryRight(int x) {
    while(fa[x] && d(x) == 1) x = fa[x];
    return fa[x];
}

int main() {
    cin >> n;
    for(int i = 1; i <= n; ++i) cin >> a[i];
    build();
    for(int i = 1; i <= n; ++i)
        printf("%d %d\n", queryLeft(i), queryRight(i));
    return 0;
}

转载于:https://www.cnblogs.com/dummyummy/p/10322579.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值