题解:CF2205D Simons and Beating Peaks

· · 题解

注意到,数组的最大值必须置于两端。否则,我们必须将其左侧或右侧的所有元素全部删除,然后得到一个新的子数组。每次都会导致区间的缩小,因而可以递归求解。

具体地,对于区间 [l, r],如果 a_x = \max_{l \le i \le r} a_i,那么我们有两种选择:

因此,递推式为

f_{l,r} = \min(r - x + f_{l,x-1}, x - l + f_{x+1,r})

如果暴力求解区间最大值,那么平均复杂度为 \mathcal O(n \log n),但若原数组单调,则会被卡成 \mathcal O(n^2)

故考虑用 ST 表维护区间最大值,递归过程可优化至 \mathcal O(n)

时间复杂度 \mathcal O(\sum n \log n),瓶颈在 ST 表初始化。

#include <bits/stdc++.h>
using namespace std;
int t, n, a[500001], pos[500001], st[500001][19];
int query(int l, int r) {
    int j = __lg(r - l + 1);
    return max(st[l][j], st[r-(1<<j)+1][j]);
}
int solve(int l, int r) {
    if (r - l <= 1) return 0;
    int x = pos[query(l,r)];
    return min(r - x + solve(l, x - 1), x - l + solve(x + 1, r));
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin >> t;
    while (t--) {
        cin >> n;
        for (int i = 1; i <= n; i++) {
            cin >> a[i];
            pos[a[i]] = i;
        }
        for (int i = 1; i <= n; i++) st[i][0] = a[i];
        for (int j = 1; (1 << j) <= n; j++)
            for (int i = 1; i + (1 << j) - 1 <= n; i++) 
                st[i][j] = max(st[i][j-1], st[i+(1<<(j-1))][j-1]);
        cout << solve(1, n) << '\n';
    }
    return 0;
}