思路
不难发现,正常枚举下标根本没法设计 dp 状态。
于是我们套路地将 排序,升序枚举数值。
表示排序后的 , 表示 在 中的下标,设计状态 表示前 个数的最大保留长度,转移方程为:
人话:要么 ,要么 , 能向 转移。
我们开一个变量维护前半部分(),再开个树状树组维护后半部分(),就做完了。
注意要按值升序,下标降序双关键字排序。
实现
#include <bits/stdc++.h>
#define N 300005
using namespace std;
struct BitIndexTree
{
vector<int> tr;
BitIndexTree(int n) { tr.resize(n); }
void modify(int x, int d)
{
for (; x; x -= x & -x)
tr[x] = max(tr[x], d);
}
int query(int x)
{
int rsl = 0;
for (; x < tr.size(); x += x & -x)
rsl = max(rsl, tr[x]);
return rsl;
}
};
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
while (t--)
{
int n;
cin >> n;
vector<pair<int, int>> a(n + 5);
for (int i = 1; i <= n; ++i)
cin >> a[i].first, a[i].second = i;
sort(a.begin() + 1, a.begin() + n + 1,
[](pair<int, int> &x, pair<int, int> &y)
{ return x.first != y.first ? x.first < y.first : x.second > y.second; });
vector<int> f(n + 5);
BitIndexTree bit(n + 5);
for (int i = 1, j = 0, v = 0; i <= n; ++i)
{
while (j < n && a[j + 1].first < a[i].first - 1)
v = max(v, f[++j]);
f[i] = max(v, bit.query(a[i].second + 1)) + 1;
bit.modify(a[i].second, f[i]);
}
int rsl = 0;
for (int i = 1; i <= n; ++i)
rsl = max(rsl, f[i]);
cout << n - rsl << '\n';
}
return 0;
}