D. Tree Construction (BST)

Posted Harris-H

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了D. Tree Construction (BST)相关的知识,希望对你有一定的参考价值。

D. Tree Construction (BST)

构造BST时, l < x < r l<x<r l<x<r l l l尽可能大, r r r尽可能小。

则要么添加到 l l l的右儿子,要么是 r r r的左儿子。

但是两者不可能同时没有,因为根据 B S T BST BST的特点, l l l要么是 r r r的左儿子, r r r要么是 l l l的右儿子。

然后用一个set,两个map维护即可。

#include <iostream>
#include <set>
#include <map>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0);

    set<int> numbers;
    map<int, int> left;
    map<int, int> right;

    int n, v;
    cin >> n >> v;
    numbers.insert(v);
    for (int i = 0; i < n - 1; i++) {
        cin >> v;
        auto it = numbers.upper_bound(v);
        int result;
        if (it != numbers.end() && left.count(*it) == 0) {
            left[*it] = v;
            result = *it;
        } else {
            it--;
            right[*it] = v;
            result = *it;
        }
        numbers.insert(v);
        cout << result;
        if (i == n - 2) cout << '\\n';
        else cout << ' ';
    }
}

以上是关于D. Tree Construction (BST)的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces Round #353 (Div. 2) D. Tree Construction (二分,stl_set)

Codeforces675 D. Tree Construction(构造,二叉排序树性质)

codeforces 675D Tree Construction

CF675DTree Construction

codeforces 675D Tree Construction set

HDU 3516 Tree Construction