解法一:二叉搜索树
思路参考:https://www.liuchuo.net/archives/2153
#include <bits/stdc++.h>
using namespace std;
vector<int> preOrder;
vector<int> postOrder;
bool isMirror = false;
void rebuild(int root, int tail) {
if (root > tail)
return;
int i = root + 1, j = tail;
if (!isMirror) {
while (i <= tail && preOrder[root] > preOrder[i])
i++;
while (j > root && preOrder[root] <= preOrder[j])
j--;
} else {
while (i <= tail && preOrder[root] <= preOrder[i])
i++;
while (j > root && preOrder[root] > preOrder[j])
j--;
}
if (i - j != 1)
return;
rebuild(root + 1, j);
rebuild(i, tail);
postOrder.emplace_back(preOrder[root]);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int N;
cin >> N;
preOrder.resize(N);
for (int i = 0; i < N; ++i) {
cin >> preOrder[i];
}
rebuild(0, N - 1);
if (postOrder.size() != N) {
postOrder.clear();
isMirror = true;
rebuild(0, N - 1);
if (postOrder.size() != N) {
cout << "NO\n";
return 0;
}
}
cout << "YES\n";
cout << postOrder[0];
for (int i = 1; i < N; ++i) {
cout << " " << postOrder[i];
}
cout << "\n";
}