CF1407D
题目链接
设 \(f_i\) 表示对于前 \(i\) 个,已经跳到了 \(i\) 了。
那么对于第一个条件,\(f_i=f_{i-1}+1\)
再考虑第二个,看到这个算式,可以联想到单调栈,所以维护一个严格递增的单调栈。
第三个和第二个同理。
\(\mathscr{Code:}\)
#include<bits/stdc++.h>
#define LL long long
//#define int LL
#define per(i, a, b) for (int i = a, END##i = b; i >= END##i; i--)
#define rep(i, a, b) for (int i = a, END##i = b; i <= END##i; i++)
#define repn(x) rep(x, 1, n)
#define repm(x) rep(x, 1, m)
#define pb push_back
#define e(x) for(int i = h[x], v = to[i]; i; i = nxt[i], v = to[i])
#define E(x) for(auto y : p[x])
#define PII pair<int, int>
#define i64 unsigned long long
#define YY puts("Yes"), exit(0)
#define NN puts("No"), exit(0)
using namespace std;
const int Mod = 1e9 + 7;
const int Inf = 0x3f3f3f3f;
const LL InfLL = 0x3f3f3f3f3f3f3f3f;
inline LL read() {LL s = 0, fu = 1; char ch = getchar(); while (ch < '0' || ch > '9') ch == '-' ? fu = -1 : 0, ch = getchar(); while (ch >= '0' && ch <= '9') s = (s << 1) + (s << 3) + (ch ^ 48), ch = getchar(); return s * fu;}
const int N = 3e5 + 10;
int n, h[N], f[N];
int ta, tb, sta[N], stb[N];
inline void Main() {
n = read();
repn(i) h[i] = read();
memset(f, 0x3f, sizeof(f));
sta[++ta] = stb[++tb] = 1;
f[1] = 0;
rep(i, 2, n) {
f[i] = f[i - 1] + 1;
while (ta && h[i] >= h[sta[ta]]) {
if (h[i] != h[sta[ta]])
f[i] = min(f[i], f[sta[ta - 1]] + 1);
ta--;
}
while (tb && h[i] <= h[stb[tb]]) {
if (h[i] != h[stb[tb]])
f[i] = min(f[i], f[stb[tb - 1]] + 1);
tb--;
}
sta[++ta] = stb[++tb] = i;
}
cout << f[n];
}
signed main() {
// freopen("input.in", "r", stdin);
int T = 1;
while (T--)
Main();
return 0;
}

浙公网安备 33010602011771号