A 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);
}