题解:CF2161D Locked Out
xiangixuan
·
·
题解
思路
不难发现,正常枚举下标根本没法设计 dp 状态。
于是我们套路地将 a 排序,升序枚举数值。
$$
f_i=\max\limits_j^{b_j\lt b_i-1 \vee p_j\gt p_i}\{f_j+1\}
$$
人话:要么 $j \gt i$,要么 $a_j \lt a_i-1$,$j$ 能向 $i$ 转移。
我们开一个变量维护前半部分($b_j\lt b_i-1$),再开个树状树组维护后半部分($p_j\gt p_i$),就做完了。
注意要按值升序,下标降序双关键字排序。
### 实现
```cpp
#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;
}
```