笛卡尔树是一棵二叉树,树的每个节点有两个值,一个为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;
}
来源:CSDN
作者:天夏123
链接:https://blog.csdn.net/qq_26122039/article/details/51620084