Codeforces Round #353 (Div. 2) D. Tree Construction 模拟

D. Tree Construction

题目连接:

http://www.codeforces.com/contest/675/problem/D

Description

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.

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.

Sample Input

3
1 2 3

Sample Output

1 2

Hint

题意

给你平衡树的节点,每个节点都依次插进去的,问你每个节点插进去之后,他的父亲是谁

题解:

没必要真的写个平衡树,直接用stl模拟就好了……

代码

#include<bits/stdc++.h>
using namespace std;
set<int> s;
map<int,int> ls,rs;
int x;
int main()
{
    int n;
    scanf("%d",&n);
    scanf("%d",&x);
    s.insert(x);
    for(int i=1;i<n;i++)
    {
        scanf("%d",&x);
        auto it=s.lower_bound(x);
        if(it==s.end())
        {
            it--;
            rs[*it]=x;
            printf("%d ",*it);
        }
        else if(ls[*it]==0)
        {
            ls[*it]=x;
            printf("%d ",*it);
        }
        else
        {
            it--;
            rs[*it]=x;
            printf("%d ",*it);
        }
        s.insert(x);
    }
    printf("\n");
}
    原文作者:qscqesze
    原文地址: https://www.cnblogs.com/qscqesze/p/5503453.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞