【Codeforces 675D】Tree Construction

【链接】 我是链接,点我呀:)
【题意】


依次序将数字插入到排序二叉树当中
问你每个数字它的父亲节点上的数字是啥

【题解】


按次序处理每一个数字
对于数字x
找到最小的大于x的数字所在的位置i
显然,x要放在这个x的左子树里面
所以如果x的左子树为空那么直接放上去就好
否则,左子树不为空的话,对于i的左儿子,从这个左儿子开始,一直往右儿子方向往下走
即未插入x之前,最大的且比i对应的数字小的数字 less
我们的x显然是要放在less的右子树上才行。
这个less和位置i对应的数字都能用java里面的lower和higher函数得到
那么根据上面的分析
如果higher对应的数字的左子树为空,那么x应该放在higher所在位置的左儿子上,因此答案就是higher
否则,如果higher对应的数字的左子树不为空,那么就应该放在less(最大的小于x的数字)的右儿子上,因此答案是less

【代码】

import java.io.*;
import java.util.*;

public class Main {
    
    
    static InputReader in;
    static PrintWriter out;
        
    public static void main(String[] args) throws IOException{
        //InputStream ins = new FileInputStream("E:\\rush.txt");
        InputStream ins = System.in;
        in = new InputReader(ins);
        out = new PrintWriter(System.out);
        //code start from here
        new Task().solve(in, out);
        out.close();
    }
    
    static int N = 50000;
    static class Task{
        
        int n;
        TreeSet<Integer> dic = new TreeSet<Integer>();
        HashMap<Integer,Integer> mymap[]= new HashMap[2];
        
        public void solve(InputReader in,PrintWriter out) {
            for (int i = 0;i < 2;i++) mymap[i] = new HashMap<Integer,Integer>();
            n = in.nextInt();
            int x;
            x = in.nextInt();
            dic.add(x);
            
            for (int i = 2;i <= n;i++) {
                x = in.nextInt();
                Integer upper = dic.higher(x);
                Integer less = dic.lower(x);
                if (upper==null) {
                    out.print(less+" ");
                    mymap[1].put(less, 1);
                }else {
                    if (mymap[0].containsKey(upper)) {
                        out.print(less+" ");
                        mymap[1].put(less, 1);
                    }else {
                        out.print(upper+" ");
                        mymap[0].put(upper, 1);
                    }
                }
                dic.add(x);
            }
        }
    }

    

    static class InputReader{
        public BufferedReader br;
        public StringTokenizer tokenizer;
        
        public InputReader(InputStream ins) {
            br = new BufferedReader(new InputStreamReader(ins));
            tokenizer = null;
        }
        
        public String next(){
            while (tokenizer==null || !tokenizer.hasMoreTokens()) {
                try {
                tokenizer = new StringTokenizer(br.readLine());
                }catch(IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }
        
        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/AWCXV/p/10569004.html