Codeforces 675D Tree Construction【构造,BST】

来源:互联网 发布:电脑小白编程软件 编辑:程序博客网 时间:2024/06/03 02:27

题目链接:

http://codeforces.com/contest/675/problem/D

题意:

给定数列,依次插入二叉树,求子节点的父节点。

分析:

根据二叉树的性质,我们可以找到大于这个数的最小值和小于这个数的最大值,这两个数即为该数的父节点,那么如果结点对应的儿子结点为空,直接放进去即可。注意由于这两个数的性质不存在两个结点都没有空的子节点的情况。

代码:

/*On a hill is a tree, on a tree is a bough;My heart for the Lord, but he never knows.--Created by jiangyuzhu--2016/5/17*/#include<cstdio>#include<iostream>#include<queue>#include<cstring>#include<stack>#include<vector>#include<algorithm>#include<map>#include<set>#include<cmath>using namespace std;#define pr(x) cout << #x << ": " << x << "  "#define pl(x) cout << #x << ": " << x << endl;#define sa(x) scanf("%d",&(x))#define sal(x) scanf("%I64d",&(x))#define mdzz cout<<"mdzz"<<endl;typedef long long ll;const int maxn = 1e5 + 5, mod = 1e9 + 7;int a[maxn];map<int, int> lson, rson;int main(void){   int n;sa(n);   set<int>s;   int x;   set<int>::iterator pos;   for(int i = 0; i < n; i++){        scanf("%d", &x);        if(i == 0){            s.insert(x);            continue;        }        pos = s.lower_bound(x);        if(pos != s.end() && lson[*pos]== 0 ){            lson[*pos] = x;        }else{            pos--;            rson[*pos] = x;        }        printf("%d ", *pos);        s.insert(x);   }    return 0;}
0 0
原创粉丝点击