POJ 2201 Cartesian Tree 【笛卡尔树】

89 篇文章 0 订阅
42 篇文章 0 订阅

构造笛卡尔树。

我用的是 排序+左旋 的方式,这种方式并不是最好的构造方式,先写出来再说,今天不行了,改天在学习其他的算法。

构树技巧:增加一个虚拟的根节点,根节点的value优先级最高,可以保证此节点一直是根节点。


这道题目的数据有点……,所以不需要判断不合法的,所有的数据都可以构成笛卡尔树,所以判断NO的就可以省了。。。。⊙﹏⊙b汗



排序+左旋:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

struct node {
    int key, value, idx, lson, rson, fa;
} a[50005];
struct renode {
    int fa, lson, rson, idx;
} b[50005];
int n;

bool cmp_key(const node &x, const node &y) {
    return x.key < y.key;
}
bool cmp_value(const node &x, const node &y) {
    return x.value < y.value;
}
void Insert(int now) {
    int j = now - 1;
    while (a[j].value > a[now].value) j = a[j].fa;
    a[now].lson = a[j].rson;
    a[a[j].rson].fa = now;
    a[j].rson = now;
    a[now].fa = j;
}
int main() {
    while (scanf("%d", &n) == 1) {
        for (int i=1; i<=n; i++) {
            scanf("%d %d", &a[i].key, &a[i].value);
            a[i].lson = a[i].rson = a[i].fa = 0;
            a[i].idx = i;
        }
        bool flag = true;
        sort(a+1, a+1+n, cmp_value);
        for (int i=1; i<n; i++)
            if (a[i].value == a[i+1].value) {
                flag = false;
                break;
            }
        if (!flag) {
            printf("NO\n"); continue;
        }
        sort(a+1, a+1+n, cmp_key);
        for (int i=1; i<n; i++)
            if (a[i].key == a[i+1].key) {
                flag = false;
                break;
            }
        if (!flag) {
            printf("NO\n"); continue;
        }

        a[0].lson = a[0].rson = a[0].fa = 0;
        a[0].value = -0x3f7f7f7f;
        a[0].idx = 0;

        for (int i=1; i<=n; i++) Insert(i);
        printf("YES\n");
        for (int i=1; i<=n; i++) {
            b[a[i].idx].fa = a[a[i].fa].idx;
            b[a[i].idx].lson = a[a[i].lson].idx;
            b[a[i].idx].rson = a[a[i].rson].idx;
        }
        for (int i=1; i<=n; i++)
            printf("%d %d %d\n", b[i].fa, b[i].lson, b[i].rson);
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值