codeforces 675D (STL set)

来源:互联网 发布:jvcs500知乎 编辑:程序博客网 时间:2024/05/22 07:57

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

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.

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



一开始以为要构造二叉树,但是发现数据量太大了 1e5,如果是单链的话会退化成 1e5*1e5

其实只需要找到它前面最后一个比它小和最后一个比它大的 比较哪个出现的时间晚即可

#include <bits/stdc++.h>using namespace std;int fa[101010];set<int> s;map<int,int> mp;int main(){    int n;    scanf("%d",&n);    int d;    scanf("%d",&d);    s.insert(d);    mp[d]=1;    for(int i=2;i<=n;i++)    {        scanf("%d",&d);        set<int>::iterator it=s.lower_bound(d);//s.lower_bound(d) 比lower_bound(s.begin(),s.end())快        if(it==s.begin()) fa[i]=*it;        else if(it==s.end()) it--,fa[i]=*it;        else {            set<int>::iterator it2 = it;            it--;            if(mp[*it]>mp[*it2])                fa[i]=*it;            else fa[i]=*it2;        }        mp[d]=i;        s.insert(d);    }    for(int i=2;i<=n;i++)    printf("%d ",fa[i] );}