建树倒是会了,不知道有啥用
hdu6701 Make Rounddog Happy(笛卡尔树启发式合并)
就是一个用数组下标作为另一关键字的treap
因为这个下标作为关键字的性质,所以从左向右扫描数组建树的时候,
新节点一定靠右,即分两种情况:为右孩子或者左孩子的父亲,
所以单调栈处理一下,维护右链,每次退栈到当前元素应该插入的位置
然后处理一下这两种情况就好
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5+7;
int n;
int val[maxn] = {0,9,3,7,1,8,12,10,20,15,18,5};
int l[maxn],r[maxn],Fa[maxn],root;
int stl[maxn],top;
int deep[maxn],Mdep;
int Insert(int i){
while(top && val[stl[top]]>=val[i])
l[i] = stl[top--];
Fa[i] = stl[top];//up to father
if(Fa[i])r[Fa[i]] = i;//if father not null ,father to self
stl[++top] = i;//push stack
}
void dfs(int x,int cur){//init the deep or print aboriginal array
if(!x)return;
Mdep = max(Mdep,cur);
deep[x] = cur;
dfs(l[x],cur+1);
printf("%3d",val[x]);
dfs(r[x],cur+1);
}
int main(){
n = 11;
for(int i=1;i<=n;i++)Insert(i);
while(top)root = stl[top--];
dfs(root,1);
printf("\n");
for(int i=1;i<=n;i++)printf("%3d",i);
printf("\n");
for(int i=1;i<=Mdep;i++){
for(int j=1;j<=n;j++){
if(deep[j] == i)
printf("%3d",val[j]);
else
printf("%3c",' ');
}
putchar('\n');
}
return 0;
}