Tree Construction
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 aitself.
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.
本来想着自己建一棵二叉树边输入边模拟,但是超时。看网上题解都是用set模拟。
函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置。
代码也是看了网上的博客才写出来。
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<set>
#include<map>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
set<ll>s;
map<ll,ll>pos;
int main()
{
ll n,x;
set<ll>::iterator it1,it2,it;
scanf("%lld",&n);
scanf("%lld",&x);
s.insert(0);
s.insert(x);
ll T=1;
pos[x]=T++;
for(int i=1;i<n;i++){
scanf("%lld",&x);
it=s.lower_bound(x);
it1=it--;it2=it;
if(pos[*it1]<pos[*it2])
printf("%lld ",*it2);
else
printf("%lld ",*it1);
pos[x]=T++;
s.insert(x);
}
puts("");
return 0;
}