Summer Training day6 codeforces 675D 二叉搜索树

来源:互联网 发布:一口价域名 编辑:程序博客网 时间:2024/05/18 03:34

D. Tree Construction
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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.

  1. First element a1 becomes the root of the tree.
  2. 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:
    1. The pointer to the current node is set to the root.
    2. 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.
    3. 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.
Input

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

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.

Examples
input
31 2 3
output
1 2
input
54 2 3 1 6
output
4 2 2 4
Note

Picture below represents the tree obtained in the first sample.

Picture below represents the tree obtained in the second sample.


题意:按要求构造一颗二叉搜索树,然后输出每个结点的父节点是谁。

我们用set维护一个有序序列,对于新插入的元素a,用lower_bound找到一个位置,如果这个位置是set.begin()的话,那么父节点就是当前找到位置的元素。

如果找到的位置不为set.begin()的话,那么现在有两种情况,可能是前一个位置的右孩子,也有可能是当前位置的做左孩子。

我们用一个数组right[MAXN]代表的是该节点是否有右孩子。我们先判断一下前一个位置有没有右孩子,没有的话就认为它是前一个位置的右孩子,否则的话就是当前位置的左孩子。


代码:

#include <iostream>#include <cstdio>#include <set>#include <map>using namespace std;const int MAXN = 1e5+10;map<int,int> rights;int n;int main(){set<int> st;scanf("%d",&n);int tmp; scanf("%d",&tmp);st.insert(tmp);for(int i = 2;i <= n;i++){int tmp;scanf("%d",&tmp);set<int> ::iterator it = st.lower_bound(tmp);if(it == st.begin()){printf("%d ",*it);}else{int pre = *(--it);if(rights[pre] == 0){rights[pre] = 1;printf("%d ",pre);}else{printf("%d ",*(++it));}}st.insert(tmp);}return 0;}/*1010 5 7 9 2 1 4 8 3 6 */