• 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("
    ");
    }
  • 相关阅读:
    求一列的和,awk和perl哪个快?
    转:使用memc-nginx和srcache-nginx模块构建高效透明的缓存机制
    使用apt-get autoremove造成的系统无法开机
    因不公对待,技术销毁删除代码数据,谁对谁错?负能量文章,老板慎入。
    我曾经做过的插件
    宝石TD迷宫设计器
    VSX-5 VSXMusic 编码听音乐
    耐得住寂寞,才能守得住繁华
    VSX-4 VSXTra
    VSX-3 VSCT文件
  • 原文地址:https://www.cnblogs.com/qscqesze/p/5503453.html
Copyright © 2020-2023  润新知