题解:CF2161D Locked Out

· · 题解

先将 a 数组按 a_i 从小到大排序,a_i 相同的按下标从大到小的顺序放,且令 b_i 为排好序后第 i 项的值,c_i 为排好序后第 i 项在原数组中的下标。
考虑动态规划,令 f_i 为考虑了排好序后前 i 项,能保留的最多数目。
转移如下:

f_i \leftarrow \max\left(1, \max_{\substack{1 \le j < i \\ (b_j \neq b_i - 1 \lor c_i < c_j)}} (dp_j + 1)\right)

直接做时间复杂度是 \mathcal{O(n^2)} 的。我们来优化这个转移。
这个转移可以分为 2 部分来优化:

这样,我们就解决了此问题。下面是代码。 AC link

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define unll unsigned long long
#define bint __int128
#define set_q priority_queue
#define unmp unordered_map
#define ldouble long double
mt19937_64 mrand((unll) std::chrono::steady_clock::now().time_since_epoch().count());

inline int in() {
    unsigned int x = 0ll; bool f = false; char ch = getchar();
    while (ch < '0' || ch > '9') {f |= ch == '-'; ch = getchar();}
    while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
    return f ? -(int)x : x;
}

inline ll inll() {
    unll x = 0ll; bool f = false; char ch = getchar();
    while (ch < '0' || ch > '9') {f |= ch == '-'; ch = getchar();}
    while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}
    return f ? -(ll)x : x;
}

const ll inf = 1ll << 59ll;
const ll infless = -inf;

const int N = 300100;

int test, n, s[N], f[N];
array<int, 2> a[N];
ll ans = 0ll, res = 0ll;

inline int lowbit (const int &x) {
    return x & (-x);
}

inline int query (const int &x) {
    int sum = 0;
    for (int y = x; y; y -= lowbit(y)) {
        sum = max(sum, s[y]);
    }
    return sum;
}

inline void modify (const int &x, const int &d) {
    for (int y = x; y <= n; y += lowbit(y)) {
        s[y] = max(s[y], d);
    }
}

inline void solve () {
    ans = 0ll;
    n = in();
    for (int i = 1; i <= n; i++) {
        a[i] = {in(), n + 1 - i};
        f[i] = s[i] = 0;
    }
    sort(a + 1, a + n + 1);
    int j = 0;
    res = 0ll;
    for (int i = 1; i <= n; i++) {
        while (j + 1 < i && a[j + 1][0] + 1 < a[i][0]) {
            j++;
            res = max(res, 1ll * f[j]);
        }
        f[i] = 1 + max((int)res, query(a[i][1]));
        modify(a[i][1], f[i]);
        ans = max(ans, 1ll * f[i]);
        //printf("x%d %d %d\n", i, j, f[i]);
    }
    printf("%lld\n", n - ans);
    return;
}

int main() {
    for (test = in(); test--; solve());
    return 0;
}