ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

PTA 1167 Cartesian Tree (30 分)

2022-03-03 02:01:08  阅读:150  来源: 互联网

标签:Cartesian sequence int tree Tree 1167 heap line


1167 Cartesian Tree (30 分)

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

感悟

好多人这题拿去建树做,其实没什么必要,bfs遍历一下最小根堆,每次找到当前区间内的最小值,这个最小值就是当前区间的子树的根,用一个数组存下该元素数组下标,并且记下当前的层数,最后用以排序.

#include <iostream>
#include <algorithm>

using namespace std;

typedef pair<int, int> PII;
const int N = 40;
int a[N];
int cnt = 1;
PII b[N];

void find(int l,int r, int level)
{
    if(l>r)return;
    int root = l;
    for(int i = l; i <= r; i++)
        if(a[i] <= a[root]) root = i;
    b[cnt++] = {level,root};
    find(l,root-1,level+1);
    find(root+1,r,level+1);
}

int main()
{
    int n;
    cin >> n;
    for(int i = 1; i <= n; i++)
        cin >> a[i];
    find(1,n,0);
    sort(b+1,b+n+1);
    for(int i = 1; i <= n; i++)
        printf("%d%c",a[b[i].second], i == n ? '\n' : ' ');

    return 0;
}

标签:Cartesian,sequence,int,tree,Tree,1167,heap,line
来源: https://www.cnblogs.com/sherluoke/p/15957953.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有