题解:CF2205D Simons and Beating Peaks

· · 题解

\Large\text{Solution}

法一:笛卡尔树

和之前 ABC 一道猫爬架子题等价。发现最大的数肯定要选,两边的数只能选一边的。

建树,从最大点连向左右部分的最大点,然后递归下去,树高就是最多能选多少个。

法二:单调栈

同学 @Rikka_Master 的赛场做法。

发现答案肯定是长一个单谷的性质,不然肯定还能再删。

单调栈在求两边最近的更大的数时,栈中刚好是这个点为谷底时两边的单增序列,把栈的大小取出来即可。

\Large\text{Code}
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int a[N], st[N][20], maxn;
int query(int l, int r)
{
    int k = __lg (r - l + 1);
    if (a[st[l][k]] > a[st[r - (1 << k) + 1][k]]) return st[l][k];
    else return st[r - (1 << k) + 1][k];
}
void dfs(int l, int r, int h)
{
    if (l > r) return;
    if (l == r)
    {
        maxn = max (maxn, h);
        return;
    }
    int x = query (l, r);
    dfs (l, x - 1, h + 1);
    dfs (x + 1, r, h + 1);  
}
int main()
{
    cin.tie (0);
    ios :: sync_with_stdio (false);
    int t;
    cin >> t;
    while (t--)
    {
        int n;
        cin >> n;
        for (int i = 1; i <= n; i++)
            cin >> a[i], st[i][0] = i;
        for (int j = 1; j <= 19; j++)
            for (int i = 1; i + (1 << j) - 1 <= n; i++)
                if (a[st[i][j - 1]] > a[st[i + (1 << j - 1)][j - 1]]) st[i][j] = st[i][j - 1];
                else st[i][j] = st[i + (1 << j - 1)][j - 1];
        maxn = 0;
        dfs (1, n, 1);
        cout << n - maxn << "\n";
    }
    return 0;
}