天梯赛 L2-006 树的遍历

这篇文章介绍了如何使用C++编写一个区间树的构建函数和查询函数,用于处理整数数组并按给定顺序输出连续子数组。
摘要由CSDN通过智能技术生成

 

#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
typedef pair<int,int> PII;
const int N = 55;
int a[N],b[N],p[N];
int n;
vector<int> q[N];
void build(int al,int ar,int ll,int lr,int d){
    if(al>ar) return ;
    int k=a[ar];
    q[d].push_back(k);
    int root=p[k];
    build(al, root-1-ll+al, ll, k-1, d+1);
    build(root-ll+al, ar-1, root+1, lr, d+1);
}
int main(){
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    for(int i=0;i<n;i++){
        scanf("%d",&b[i]);
        p[b[i]]=i;
    }
    build(0,n-1,0,n-1,0);
    int count=1;
    for(int i=0;i<n;i++){
        for(auto x: q[i]){
            if(count<n){
                printf("%d ",x);
            }
            else{
                printf("%d",x);
            }
            
            count+=1;
            
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值