这个题要注意的是:右节点时大于等于根节点的。
#include#include using namespace std;const int maxn = 1e3 + 10;int pre[maxn], n;bool is;vector ss;void f(int l, int r){ if (l > r)return; int tr = l + 1; int tl = r; if (!is){ while (tr <= r&&pre[tr] < pre[l])tr++; while (tl > l&&pre[tl]>=pre[l])--tl; } else{ while (tr <= r&&pre[tr] >= pre[l])tr++; while (tl > l&&pre[tl] < pre[l])--tl; } if (tr - tl != 1)return; f(l + 1, tl); f(tr, r); ss.push_back(pre[l]);}int main(){ cin >> n; for (int i = 0; i < n; ++i)cin >> pre[i]; f(0, n - 1); if (ss.size() != n){ is = 1; ss.clear(); f(0, n - 1); } if (ss.size() != n)cout << "NO" << endl; else{ cout << "YES" << endl; cout << ss[0]; for (int i = 1; i < n; ++i) cout << " " << ss[i]; cout << endl; }}