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

阎淮晨
2023-12-01
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
3
1 2 3
output
1 2
input
5
4 2 3 1 6
output
4 2 2 4

题意:给你一个二叉树,输出每个子节点的父节点。
思路:给结点的大小排序,对每个结点找到最小并大于它的结点,如果找不到,该节点就放在最大结点的右子节点上,如果找到,并没有左子节点,就把 该节点就放在当前节点的左结点上,如果当前找到的结点有左子节点,就放在其左孩子的右孩子上

#include<stdio.h>
#include<set>
#include<map>
using namespace std;
int main()
{
	set<int> sorted_tree;
	map<int, int> left;
	map<int, int> right;
	int n,x;
	scanf("%d", &n);
	scanf("%d", &x);
	sorted_tree.insert(x);
	for (int i = 1; i < n; i++)
	{
		scanf("%d", &x);

        auto it = sorted_tree.upper_bound(x);
		if (it == sorted_tree.end())
		{
			printf("%d ", *(--it));
			right[*it] = x;
		}
		else
		{
			if (left[*it] == 0)
			{
				printf("%d ", *it);
				left[*it] = x;
			}
			else
			{
				printf("%d ", *(--it));
				right[*it] = x;
			}
		}
		sorted_tree.insert(x);
	}
	printf("\n");
	return 0;
}
注意:set里面的元素是不重复的,插入元素后是有序的
           
 类似资料: