Codeforces 675D Tree Construction

D. 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.

  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
3
1 2 3
1 2
input
5
4 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模拟,同时分别记录每个结点的左右儿子。

一个结点只有可能成为比它大的最小的结点的左儿子或者是比它小的最大的结点的右儿子 

每次用lower_bound(or upper_bound)找到该结点 判断是否存在左儿子如果不存在则父结点就是它

如果存在就找比它小的最大的结点。

#include <bits/stdc++.h>
#include <cstdio>
#define ll long long
#define __max(a,b) a > b ? a : b
#define pll pair<ll, ll>
using namespace std;
const int maxn = 1e5 + 10;
int a[maxn];
set<int> q;
map<int, int> l;
map<int, int> r;
int main()
{
//    freopen("/Users/vector/Desktop/out.txt", "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n;
    cin >> n;
    for(int i = 0; i < n; i++)
        cin >> a[i];
    q.insert(a[0]);
    int ans;
    for(int i = 1; i < n; i++)
    {
        set<int>::iterator pos = q.lower_bound(a[i]);//返回大于a[i]的迭代器
        if(pos != q.end() && l[*pos] == 0)
        {
            ans = *pos;
            l[*pos] = a[i];
        }
        else
        {
            pos--;
            ans = *pos;
            r[*pos] = a[i];
        }
        cout << ans << ' ';
        q.insert(a[i]);
    }
    cout << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sinat_37158899/article/details/81436625