7-4 Sorted Cartesian Tree

Sorted Cartesian tree is a tree of (key, priority) pairs. The tree is heap-ordered according to the priority values, and an inorder traversal gives the keys in sorted order. For example, given the pairs { (55, 8), (58, 15), (62, 3), (73, 4), (85, 1), (88, 5), (90, 12), (95, 10), (96, 18), (98, 6) }, the increasing min-heap Cartesian tree is shown by the figure.

Your job is to do level-order traversals on an increasing 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 lines follow, each gives a pair in the format key priority. All the numbers are in the range of int.

Output Specification:

For each test case, print in the first line the level-order traversal key sequence and then in the next line the level-order traversal priority 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
88 5
58 15
95 10
62 3
55 8
98 6
85 1
90 12
96 18
73 4

Sample Output:

85 62 88 55 73 98 58 95 90 96
1 3 5 8 4 6 15 10 12 18
#include<iostream>
#include<unordered_map>
#include<algorithm>
using namespace std;
const int N = 40;
int n;
struct Node{
  int x,y;
  bool operator<(const Node &node)const{
      return x<node.x;
  }
}in[N];
unordered_map<int,int> l,r;
Node pos[N];
int q[N];
int find_min(int il,int ir){
    int res = il;
    for(int i = il;i<=ir;i++){
        if(in[res].y>in[i].y){
            res = i;
        }
    }
    return res;
}
int build(int il,int ir){
    int k = find_min(il,ir);
    if(il<k) l[k] = build(il,k-1);
    if(k<ir) r[k] = build(k+1,ir);
    return k;
}
void bfs(int u){
    int hh = 0,tt = 0;
    q[0] = u;
    while(hh<=tt){
        auto t = q[hh++];
        if(l.count(t)) q[++tt] = l[t];
        if(r.count(t)) q[++tt] = r[t];
    }
    cout<<in[q[0]].x;
    for(int i = 1;i<=tt;i++){
        cout<<" "<<in[q[i]].x;
    }
    cout<<endl<<in[q[0]].y;
    for(int i = 1;i<=tt;i++){
        cout<<" "<<in[q[i]].y;
    }
}
int main(){
    cin>>n;
    for(int i =0;i<n;i++){
        int key,pri;
        cin>>key>>pri;
        in[i] = {key,pri};
    }
    sort(in,in+n);
    int root = build(0,n-1);
    bfs(root);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值