ZOJ 2452

笛卡尔树的构造  key 和 aux ( 与treap 相同 , 不同在于aux 是给定的)

#include <cstring>
#include <cstdio>
#include <utility>
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
typedef pair<int, int> PII;
const int maxn = 111111;
struct TreeNode {
	int key, aux, id;
	TreeNode *father, *left, *right;
	TreeNode(int _key = 0, int _aux = 0, int _id = 0) :
			key(_key), aux(_aux), id(_id) {
		father = left = right = NULL;
	}
} tb[maxn];
int tot;
TreeNode *root;
struct node {
	int key, aux, id;
	node(int key = 0, int aux = 0, int id = 0) :
			key(key), aux(aux), id(id) {
	}
	bool operator<(const node& t) const {
		return key < t.key;
	}
} p[maxn];
TreeNode* go(TreeNode* t = NULL, int aux = 0) {
	while (t->aux > aux && t->father != NULL) {
		t = t->father;
	}
	return t;
}
int x[maxn], y[maxn], z[maxn];
void get(TreeNode &tmp) {
	TreeNode* rt = &tmp;
	int id = rt->id;
	x[id] = y[id] = z[id] = -1;
	if (rt->father != NULL)
		x[id] = rt->father->id;
	if (rt->left != NULL) {
		y[id] = rt->left->id;
	}
	if (rt->right != NULL) {
		z[id] = rt->right->id;
	}
}
int main() {

	int n, i, key, aux;
	while (~scanf("%d", &n)) {
		root = NULL;
		for (i = 0; i < n; ++i) {
			scanf("%d%d", &key, &aux);
			p[i] = node(key, aux, i);
		}
		sort(p, p + n);
		tb[0] = TreeNode(p[0].key, p[0].aux, p[0].id);
		root = &tb[0];
		TreeNode *tmp, *pre = root, *now;
		tot = 0;
		for (i = 1; i < n; ++i) {
			tmp = go(pre, p[i].aux);

			tb[i] = TreeNode(p[i].key, p[i].aux, p[i].id);

			now = &tb[i];

			if (tmp->father == NULL && tmp->aux > p[i].aux) {
				tmp->father = now;
				now->left = tmp;
				root = now;
			} else {
				if (tmp->right != NULL) {
					now->left = tmp->right;
					tmp->right->father = now;
				}

				tmp->right = now;
				now->father = tmp;
			}
			pre = now;
		}
		for (i = 0; i < n; ++i) {
			get(tb[i]);
		}
		puts("YES");
		for (i = 0; i < n; ++i) {
			printf("%d %d %d\n", x[i] + 1, y[i] + 1, z[i] + 1);
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值