首页 > 其他 > 详细

[模板]笛卡尔树

时间:2019-01-26 10:06:56      阅读:237      评论:0      收藏:0      [点我收藏+]

很好理解,也很好写,只要知道它的两个性质就可以自己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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!