Codeforces Round #353 (Div. 2)D. Tree Construction

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

题意:按二叉搜索树的方法插入n个互不相等的数,然后要求输出除根以外n-1个点的父亲的权值。

分析:当我们建好整棵树后,我们会知道这棵二叉树的中序遍历就是这些数从小到大排列,那么每个数的父亲就是比它小的中最大的那个数或者比它大的数中最小的。知道了这些之后我们随便用点结构或者stl里面的容器都行啦。我用的是线段树。

代码:

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<bitset>
#include<math.h>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int N=100010;
const int MAX=1000000100;
const int mod=100000000;
const int MOD1=1000000007;
const int MOD2=1000000009;
const double EPS=0.00000001;
typedef long long ll;
const ll MOD=998244353;
const int INF=1000000010;
typedef double db;
typedef unsigned long long ull;
struct node {
    int x,id;
    bool operator < (const node a) const{
        return x<a.x;
    }
}b[N];
int n,a[N],ans[N];
node mi[4*N];
void build(int x,int l,int r) {
    if (l==r) { mi[x]=b[l];return ; }
    int mid=(l+r)>>1;
    build(2*x,l,mid);
    build(2*x+1,mid+1,r);
    if (mid+1>r||mi[2*x].id<mi[2*x+1].id) mi[x]=mi[2*x];
    else mi[x]=mi[2*x+1];
}
node get(int x,int l,int r,int L,int R) {
    if (l==L&&r==R) return mi[x];
    int mid=(L+R)>>1;
    if (r<=mid) return get(2*x,l,r,L,mid);
    else if (l>mid) return get(2*x+1,l,r,mid+1,R);
        else {
            node kk=get(2*x,l,mid,L,mid);
            node gg=get(2*x+1,mid+1,r,mid+1,R);
            if (kk.id<gg.id) return kk;
            return gg;
        }
}
void div(int l,int r,int x) {
    if (l>r) return ;
    node w=get(1,l,r,1,n);
    ans[w.id]=x;
    div(l,a[w.id]-1,w.x);div(a[w.id]+1,r,w.x);
}
int main()
{
    int i;
    scanf("%d", &n);
    for (i=1;i<=n;i++) {
        scanf("%d", &a[i]);
        b[i].x=a[i];b[i].id=i;
    }
    sort(b+1,b+n+1);
    for (i=1;i<=n;i++) a[b[i].id]=i;
    build(1,1,n);
    div(1,n,0);
    for (i=2;i<=n;i++) printf("%d ", ans[i]);
    printf("\n");
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值