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;
}
发布了8 篇原创文章 · 获赞 0 · 访问量 598

猜你喜欢

转载自blog.csdn.net/qq_36993032/article/details/103823991