1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
| #include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cstdlib> #include <vector> #include <stack> #include <queue> #define ll long long #define maxn 300010 #define maxm 100010 #define cn const node #define cQ const queue #define pb push_back #define INF 1000000000 #define lowbit(i) ((i) & (-i)) using namespace std;
int n, a[maxn];
int lb[maxn], ls[maxn]; stack<int> S;
#define lc i << 1 #define rc i << 1 | 1 struct Seg { int V1, V2, v1, v2, tag1, tag2; } T[maxn * 4]; inline void maintain(int i) { T[i].V1 = min(T[lc].V1, T[rc].V1); T[i].V2 = min(T[lc].V2, T[rc].V2); T[i].v1 = min(T[lc].v1, T[rc].v1); T[i].v2 = max(T[lc].v2, T[rc].v2); }
void update1(int i, int l, int r, int L, int R, int v) { if (l > R || r < L || T[i].v1 > v) return ; if (l == r) return (void) (T[i].v1 = INF, T[i].V1 = n + 1); int m = l + r >> 1; update1(lc, l, m, L, R, v); update1(rc, m + 1, r, L, R, v); maintain(i); }
void update2(int i, int l, int r, int L, int R, int v) { if (l > R || r < L || T[i].v2 < v) return ; if (l == r) return (void) (T[i].v2 = 0, T[i].V2 = n + 1); int m = l + r >> 1; update2(lc, l, m, L, R, v); update2(rc, m + 1, r, L, R, v); maintain(i); }
void update(int i, int l, int r, int k, int v) { if (l == r) return (void) (T[i].V1 = T[i].V2 = v, T[i].v1 = T[i].v2 = a[l]); int m = l + r >> 1; if (k <= m) update(lc, l, m, k, v); else update(rc, m + 1, r, k, v); maintain(i); }
int query1(int i, int l, int r, int L, int R) { if (l > R || r < L) return n + 1; if (L <= l && r <= R) return T[i].V1; int m = l + r >> 1; return min(query1(lc, l, m, L, R), query1(rc, m + 1, r, L, R)); } int query2(int i, int l, int r, int L, int R) { if (l > R || r < L) return n + 1; if (L <= l && r <= R) return T[i].V2; int m = l + r >> 1; return min(query2(lc, l, m, L, R), query2(rc, m + 1, r, L, R)); }
int f[maxn]; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
cin >> n; for (int i = 1; i <= n; ++i) cin >> a[i]; for (int i = n; ~i; --i) { while (!S.empty() && a[i] <= a[S.top()]) ls[S.top()] = i, S.pop(); S.push(i); } a[0] = INF; while (!S.empty()) S.pop(); for (int i = n; ~i; --i) { while (!S.empty() && a[i] >= a[S.top()]) lb[S.top()] = i, S.pop(); S.push(i); } update(1, 1, n, 1, 0); f[1] = 0; for (int i = 2; i <= n; ++i) { f[i] = f[i - 1]; update1(1, 1, n, 1, i - 2, a[i - 1]); update2(1, 1, n, 1, i - 2, a[i - 1]); f[i] = min(f[i], query2(1, 1, n, ls[i], i - 2)); f[i] = min(f[i], query1(1, 1, n, lb[i], i - 2)); update(1, 1, n, i, ++f[i]); } cout << f[n] << "\n"; return 0; }
|