POJ-2201 Cartesian Tree(笛卡尔树)

笛卡尔树是一棵二叉树,树的每个节点有两个值,一个为key,一个为value。光看key的话,笛卡尔树是一棵二叉搜索树,每个节点的左子树的key都比它小,右子树都比它大;光看value的话,笛卡尔树有点类似堆,根节点的value是最小(或者最大)的,每个节点的value都比它的子树要大。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <stack>
#include <queue> 
#define maxn 50005
#define INF 1e9
typedef long long ll;
using namespace std;

struct Node{
    int l1, r1, pre, p, l2, r2;
    int k, v;
}node[maxn];
int n, Stack[maxn];
void Build(){

    Stack[1] = 1;
    int t = 1;
    for(int i = 2; i <= n; i++){
        while(t > 0 && node[Stack[t]].v > node[i].v)
         t--;
        if(t){
            int d = Stack[t];
            node[i].l1 = node[d].r1;
            node[i].pre = node[d].p;
            node[d].r1 = node[i].p;
            node[i].l2 = node[d].r2;
            node[d].r2 = i;
            node[node[i].l2].pre = node[i].p;
            Stack[++t] = i;
        }
        else{
            node[i].l1 = node[Stack[1]].p;
            node[Stack[1]].pre = node[i].p;
            node[i].l2 = Stack[1];
            Stack[++t] = i;
        }
    }
}
int cmp(const Node&a, const Node&b){
    return a.k < b.k;
}
int temp(const Node&a, const Node&b){
    return a.p < b.p;
}
int main(){

//  freopen("in.txt", "r", stdin);
    while(scanf("%d", &n) == 1){

        for(int i = 1; i <= n; i++){
            scanf("%d%d", &node[i].k, &node[i].v);
            node[i].l1 = node[i].r1 = node[i].pre = 0;
            node[i].p = i;
        }
        sort(node+1, node+1+n, cmp);
        Build(); 
        sort(node+1, node+1+n, temp);
        puts("YES");
        for(int i = 1; i <= n; i++){
            printf("%d %d %d\n", node[i].pre, node[i].l1, node[i].r1);
        }
    }
    return 0;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值