const int N = 6e5 + 5, M = 22;
int a[N], f[N];
int main()
{
//freopen("in.txt", "r", stdin);
int n;
while (cin >> n)
{
f(i, 1, n)a[i] = in();
deque<int> pos, neg;
pos.push_back(1);
neg.push_back(1);
f(i, 2, n)
{
f[i] = inf;
int last=-1;
while (!pos.empty() && a[pos.back()] >= a[i])
{
//4 4:ok 4 6 4:ok
f[i] = min(f[i], f[pos.back()] + 1);
last = a[pos.back()];
pos.pop_back();
}
//1 4:ok 1 5 4:ok 1 4 4:no
if (!pos.empty() && (last == -1 || last !=a[i]))
f[i] = min(f[i], f[pos.back()] + 1);
last = -1;
while (!neg.empty() && a[neg.back()] <= a[i])
{
f[i] = min(f[i], f[neg.back()] + 1);
last = a[neg.back()];
neg.pop_back();
}
if (!neg.empty() && (last == -1 || last != a[i]))
f[i] = min(f[i], f[neg.back()] + 1);
neg.push_back(i);
pos.push_back(i);
}
cout << f[n] << endl;
}
return 0;
}
D - Discrete Centrifugal Jumps(单调栈dp)
最新推荐文章于 2022-05-27 09:37:38 发布