先将 数组按 从小到大排序, 相同的按下标从大到小的顺序放,且令 为排好序后第 项的值, 为排好序后第 项在原数组中的下标。
考虑动态规划,令 为考虑了排好序后前 项,能保留的最多数目。
转移如下:
直接做时间复杂度是 的。我们来优化这个转移。
这个转移可以分为 部分来优化:
- 的 最大值。这一部分可以直接动态的用一个变量来维护。也可以像我代码中写的一样用一个指针来扫,在扫的过程中动态维护。
- 的最大值。这一部分可以统一把下标转化为 ,转化后就可以用树状数组维护前缀最大值,来代替原问题的后缀最大值。
说实话我还是第一次见树状数组维护最大值的
这样,我们就解决了此问题。下面是代码。 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;
}