4279. 笛卡尔树

3 篇文章 0 订阅

笛卡尔树 是由一系列不同数字构成的二叉树。

树满足堆的性质,中序遍历返回原始序列。
最小笛卡尔树表示满足小根堆性质的笛卡尔树。

例如,给定序列 {8,15,3,4,1,5,12,10,18,6},则生成的最小堆笛卡尔树如图所示。

现在,给定一个长度为 N 的原始序列,请你生成最小堆笛卡尔树,并输出其层序遍历序列。

输入格式

第一行包含整数 N。

第二行包含 N 个两两不同的整数,表示原始序列。

输出格式

共一行,输出最小堆笛卡尔树的层序遍历序列。

数据范围

1≤N≤30,
原始序列中元素的取值范围 [−2147483648,2147483647]。

输入样例:

10
8 15 3 4 1 5 12 10 18 6

输出样例:

1 3 5 8 4 6 15 10 12 18

 不用BFS:

#include<bits/stdc++.h>
using namespace std;

const int N=40;
vector<int> s[N];
int  w[N];
int getmin(int l,int r)
{
    int res=l;
    for(int i=l;i<=r;i++)
    if(w[res]>w[i])
    res=i;
    return res;
}
void dfs(int l,int r,int d)
{
    if(l>r)return;
    int root=getmin(l,r);
    s[d].push_back(w[root]);
    dfs(l,root-1,d+1);
    dfs(root+1,r,d+1);
}
int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    cin>>w[i];
    dfs(0,n-1,0);
    for(int i=0;s[i].size();i++)
    for(auto x:s[i])//vector容器简便输出
    cout<<x<<' '; 
    return 0;
}

二、用BFS

#include<bits/stdc++.h>
using namespace std;

const int N=40;
int  w[N],L[N],R[N],q[N];

int getmin(int l,int r)
{
    int res=l;
    for(int i=l;i<=r;i++)
    if(w[res]>w[i])
    res=i;
    return res;
}

int dfs(int l,int r)
{
    if(l>r)return -1;
    int root=getmin(l,r);
    
    L[root]=dfs(l,root-1);
    R[root]=dfs(root+1,r);
    return root;
}

void bfs(int root)
{
    int hh=0,tt=0;
    q[0]=root;
    while(hh<=tt)
    {
        int t=q[hh++];
        cout<<w[t]<<' ';
        if(L[t]!=-1)
        q[++tt]=L[t];
        if(R[t]!=-1)
        q[++tt]=R[t];
    }
}

int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    cin>>w[i];
    int root=dfs(0,n-1);
   bfs(root);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值