7-4 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
Solution:
一看名字差点吓尿,这不是Treap的父类笛卡尔树吗?!
认真读题发现只要根据序列建树+遍历,这也太水了吧==
P.S. 其实也可以不用建树,在递归的时候给各节点打上层次标记即可~
#include <bits/stdc++.h>
using namespace std;
const int maxn = 50;
const int inf = 0x3f3f3f3f;
int inOrder[maxn];
struct node
{
int val;
node *ls, *rs;
node(int v)
{
this->val = v;
this->ls = this->rs = nullptr;
}
};
inline const int read()
{
int x = 0, f = 1; char ch = getchar();
while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + ch - '0'; ch = getchar(); }
return x * f;
}
node* build(int l, int r)
{
if (l > r) return nullptr;
int rtid = 0, rtval = inf;
for (int i = l; i <= r; i++)
{
if (inOrder[i] < rtval)
{
rtval = inOrder[i];
rtid = i;
}
}
node* now = new node(rtval);
int nl = rtid - l + 1, nr = r - rtid + 1;
if (nl > 0) now->ls = build(l, rtid - 1);
if (nr > 0) now->rs = build(rtid + 1, r);
return now;
}
void print(node* root)
{
queue<node*> q;
q.push(root);
bool flag = false;
while (!q.empty())
{
node* now = q.front();
q.pop();
printf("%s%d", flag ? " " : "", now->val);
flag = true;
if (now->ls) q.push(now->ls);
if (now->rs) q.push(now->rs);
}
}
int main()
{
int n = read();
for (int i = 1; i <= n; i++) inOrder[i] = read();
node* root = build(1, n);
print(root);
return 0;
}