笛卡尔树的构造 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;
}