2019年12月PAT甲级 第四题 Cartesian Tree(1167)题解

题目

A Cartesian tree is a binary tree constructed from a sequence of distinct numbers. The tree is heap-ordered, and an inorder traversal returns the original sequence. For example, given the sequence { 8, 15, 3, 4, 1, 5, 12, 10, 18, 6 }, the min-heap Cartesian tree is shown by the figure.
在这里插入图片描述
Your job is to output the level-order traversal sequence of the min-heap Cartesian tree.

Input Specification:
Each input file contains one test case. Each case starts from giving a positive integer N (≤30), and then N distinct numbers in the next line, separated by a space. All the numbers are in the range of int.

Output Specification:
For each test case, print in a line the level-order traversal sequence of the min-heap Cartesian tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the beginning or the end of the line.

Sample Input:
10
8 15 3 4 1 5 12 10 18 6

Sample Output:
1 3 5 8 4 6 15 10 12 18

解释

 本题的要点是找出根结点,根结点一定是inl inr之间值最小的点,由于数值范围是int而非positive integer所以不能使用map<int, int>,index从1开始,最后对ans中的元素进行排序并输出。
:实际使用的头文件没有如此多,在考场中我选择一次性把所有都附上,以备不时之需。

正确答案

#include<iostream>
#include<climits>
#include<cctype>
#include<map>
#include<unordered_map>
#include<set>
#include<vector>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
vector<int> ins;
int maxindex = -1;
unordered_map<int, int> tree;//
struct node{
    int index, id;
};
vector<node> ans;
bool cmp(node a, node b){
    return a.index < b.index;
}
void levelorder(int inl, int inr, int root, int index){
    if(inl > inr || root < inl || root > inr) return;
    if(index > maxindex) maxindex = index;
    int i = inl, j = root + 1,minl = ins[inl], minr = ins[root + 1];
    for(int l = inl;  l<root; l++)
        if(ins[l] < minl){
            i = l;
            minl = ins[l];
        }
    for(int p = root + 1;  p<= inr; p++){
        if(ins[p] < minr){
            j = p;
            minr = ins[p];
        }
    }
    ans.push_back({index, ins[root]});
    levelorder(inl, root - 1, i, 2 * index);
    levelorder( root+ 1, inr, j, 2 * index + 1);
}
int main(){
    int n, root, minn = INT_MAX, tag;
    cin >> n;
    ins.resize(n + 1);
    for(int i = 1; i <= n; i++){
        cin >> ins[i];
        if(ins[i] < minn){
            minn = ins[i];
            root=i;
        }   
    } 
	int flag = 0;
    levelorder(1, n, root, 1);
    sort(ans.begin(),ans.end(), cmp);
    for(int i = 0 ; i < ans.size(); i++)
    printf("%d%c", ans[i].id, i < ans.size() - 1? ' ' : '\n');
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值