zoukankan      html  css  js  c++  java
  • STL---Codeforces675D Tree Construction(二叉树节点的父亲节点)

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

    Sample Input

    Input
    3
    1 2 3
    Output
    1 2
    Input
    5
    4 2 3 1 6
    Output
    4 2 2 4

    题意:将n个节点依次插入到二叉树中,第一个数作为根节点,输出2~n节点的父亲节点的值;

    思路:对于插入的节点i,它的父节点一定是距离它最近的点,比它大的那个点和比它小的点出现最晚的就是父亲节点,可以用pos[]数组来记录个点出现的次序;

    代码如下:
    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <cstring>
    #include <set>
    #include <map>
    using namespace std;
    set<int>t;
    map<int,int>pos;
    
    int main()
    {
        int n,x;
        int times=1;
        cin>>n;
        scanf("%d",&x);
        t.insert(0);
        t.insert(x);
        pos[x]=times++;
        while(times<=n)
        {
            scanf("%d",&x);
            set<int>::iterator it = t.lower_bound(x);
            set<int>::iterator it1=it--;
            set<int>::iterator it2=it;
            if(pos[*it1]<pos[*it2])
                printf("%d ",*it2);
            else printf("%d ",*it1);
            t.insert(x);
            pos[x]=times++;
        }
        return 0;
    }
  • 相关阅读:
    Java实现 蓝桥杯 历届试题 城市建设
    Java实现 蓝桥杯 历届试题 城市建设
    Java实现 蓝桥杯 历届试题 城市建设
    Java实现 蓝桥杯 历届试题 城市建设
    MYSQL创建数据库时候直接指定编码和排序规则
    Eclipse 安装插件(aptana、svn 、git、Java EE、JSHint)
    (转)CentOS无损调整磁盘分区大小的实现方法
    Linux(centos)系统各个目录的作用详解
    Ecplise插件安装方法
    Fedora25 将eclipse的快捷方式添加到Applications中
  • 原文地址:https://www.cnblogs.com/chen9510/p/5538113.html
Copyright © 2011-2022 走看看