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
题解:总体感觉4道题就这道简单些
#include <iostream>
#include <vector>
using namespace std;
const int N = 33;
int n;
int ct[N], level[N];
void DFS(int l, int r, int d) {
if (l > r) return;
if (l == r) {
level[l] = d;
return;
}
int k = l;
for (int i = l; i <= r; i++)
if (ct[k] > ct[i]) k = i;
level[k] = d;
DFS(l, k - 1, d + 1);
DFS(k + 1, r, d + 1);
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) cin >> ct[i];
DFS(0, n - 1, 1);
int maxdeep = 1;
for (int i = 0; i < n; i++)
if (level[i] > maxdeep) maxdeep = level[i];
for (int i = 1; i <= maxdeep; i++)
{
for (int j = 0; j < n; j++)
{
if (level[j] == i)
{
if (i == 1) cout << ct[j];
else cout << ' ' << ct[j];
}
}
}
return 0;
}