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

185 篇文章 0 订阅
116 篇文章 0 订阅

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

 

题意:给你一个数列,让你以此构造一个排序二叉树,输出每个点的父亲。


分析:再次被智商压制,排序二叉树中一个点向左找到的第一个点(左下或左上)一定是之前序列中出现的最后一个小于等于当前节点权值得数,右边同理。


#include <set> 
#include <cstdio>
#include <iostream>
#include <unordered_map>
using namespace std;
set <int> f;
unordered_map <int,int> l,r;
int n,a[100005];
int main()
{
	cin.sync_with_stdio(false);
	cin>>n;
	for(int i = 1;i <= n;i++)
	{
		cin>>a[i];
		if(i == 1) f.insert(a[i]);
		else 
		{
			auto it = f.lower_bound(a[i]);
			if(it == f.end()) r[*--it] = a[i];
			else 
			{
				if(!l[*it]) l[*it] = a[i];
				else r[*--it] = a[i];
			}
			cout<<*it<<" ";
			f.insert(a[i]);
		}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值