During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.
You are given a sequence a, consisting of n distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process.
- First element a1 becomes the root of the tree.
- Elements a2, a3, ..., an are added one by one. To add element ai one needs to traverse the tree starting from the root and using the following rules:
- The pointer to the current node is set to the root.
- If ai is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node.
- If at some point there is no required child, the new node is created, it is assigned value ai and becomes the corresponding child of the current node.
The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the length of the sequence a.
The second line contains n distinct integers ai (1 ≤ ai ≤ 109) — the sequence a itself.
Output n - 1 integers. For all i > 1 print the value written in the node that is the parent of the node with value ai in it.
3 1 2 3
1 2
5 4 2 3 1 6
4 2 2 4
Picture below represents the tree obtained in the first sample.
Picture below represents the tree obtained in the second sample.
二叉平衡树的相关操作,排成二叉排序树,按照输入顺序输出当前节点的父亲节点的值,当然根节点不算。
#include<stdio.h>
#include<iostream>
#include <algorithm>
#include<string.h>
#include<vector>
#include<math.h>
#include<queue>
#include<deque>
#include<map>
#include<set>
#define ll long long
#define INF 0x3f3f3f3f
const int mod = 1e9+7;
using namespace std;
int KGCD(int a,int b){if(a==0)return b;if(b==0)return a;if(~a&1){ if(b&1) return KGCD(a>>1,b);else return KGCD(a>>1,b>>1) <<1; } if(~b & 1) return KGCD(a, b>>1); if(a > b) return KGCD((a-b)>>1, b);return KGCD((b-a)>>1, a);}
int LCM(int a,int b){ return a/KGCD(a,b)*b; }
inline ll qpow(ll n,ll m){n%=mod;ll ans=1;while(m){if(m%2) ans=(ans*n)%mod;m/=2;n=(n*n)%mod;}return ans;}
inline ll inv(ll b){return b==1?1:(mod-mod/b)*inv(mod%b)%mod;}
inline ll inv2(ll b){return qpow(b,mod-2);}
int dir[5][2]={0,1,0,-1,1,0,-1,0};
set<int>s;
map<int,int>l,r;
int main()
{
int n,temp;
scanf("%d",&n);
scanf("%d",&temp);
s.insert(temp);
for(int i=1;i<n;i++)
{
if(i>=2)
printf(" ");
scanf("%d",&temp);
set<int>::iterator it=s.lower_bound(temp);
if(it==s.end())//如果没有比他大的
{
set<int>::iterator it1=--it;
printf("%d",*it1);
r[*it]=1;
}
else
{
int vla=*it;
if(l[*it]==1)
{
set<int>::iterator it2=--it;
printf("%d",*it2);
r[*it2]=1;
}
else
{
printf("%d",*it);
l[*it]=1;
}
}
s.insert(temp);
}
printf("\n");
return 0;
}
如果当前这个数是最大的,它就变成了已经放好点的右子树。
如果存在有比这个数大和小的(最小默认空),就先判断放到大的那个数的左子树行不行,不行放到大的那个右子树。