这是二叉搜索树吗?
#include <bits/stdc++.h> #define sc(x) scanf("%lld", &(x)) #define pr(x) printf("%lld\n", (x)) #define rep(i, l, r) for (int i = l; i <= r; ++i) using namespace std; typedef long long ll; const int N = 1e3 + 7; const int mod = 1e9 + 7; ll a[N], tr[N]; ll n, p = 0; bool err = 0; void build(int idx, int rt, int L, int R) { if (err) return; int lson = L, rson = L; while (rson <= R) { if (a[rson] >= a[rt]) break; ++rson; } rep(i, rson, R) if (a[i] < a[rt]) { err = 1; return; } if (lson < rson && a[lson] < a[rt]) { build(idx * 2, lson, lson + 1, rson - 1); } if (rson <= R and a[rson] >= a[rt]) { build(idx * 2 + 1, rson, rson + 1, R); }if (rt >= 1 && rt <= n) tr[++p] = a[rt]; } void build2(int idx, int rt, int L, int R) { if (err) return; int lson = L, rson = L; while (rson <= R) { // change if (a[rson] < a[rt]) break; ++rson; } // cout << rt << ' ' << L << ' ' << R << ' ' << lson << ' ' << rson << endl; rep(i, rson, R) if (a[i] >= a[rt]) { err = 1; return; } if (lson < rson && a[lson] >= a[rt]) { build2(idx * 2, lson, lson + 1, rson - 1); } if (rson <= R and a[rson] < a[rt]) { build2(idx * 2 + 1, rson, rson + 1, R); }if (rt >= 1 && rt <= n) tr[++p] = a[rt]; } int main() { sc(n); rep(i, 1, n) sc(a[i]); build(1, 1, 2, n); // rep(i, 1, p) printf("%lld%c", tr[i], i == p ? '\n' : ' '); if (p == n && !err) { puts("YES"); // post(1); rep(i, 1, n) printf("%lld%c", tr[i], i == n ? '\n' : ' '); } else { p = 0; err = 0; memset(tr, 0, sizeof tr); build2(1, 1, 2, n); if (p == n && !err) { puts("YES"); p = 0; // post(1); rep(i, 1, n) printf("%lld%c", tr[i], i == n ? '\n' : ' '); } else { puts("NO"); } } return 0; }
算法竞赛之路 文章被收录于专栏
整理、记录算法竞赛的好题