题解:CF946G Almost Increasing Array
更困难的版本 P2501。
思路
考虑点对
由于所有的题解都用了数据结构来优化,这里只讲二分的做法。设
以上是处理普通的最长不降子序列的二分做法,考虑本题。由于这题加入了一个允许删不超过一个数的条件,我们显然容易重新设出一个状态
实现的一个小细节,由于我们从 0 转移到 1 时用到了
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e5 + 5;
int n, a[N], dp[N][2], idx, tot1, tot2;
int work(int x) {
int l = 0, r = tot1, ans = 1;
while(l <= r) {
int mid = l + r >> 1;
if(dp[mid][0] > x) {
r = mid - 1;
ans = mid;
}
else {
l = mid + 1;
ans = mid + 1;
}
}
return ans;
}
int work1(int x) {
int l = 0, r = tot2, ans = 1;
while(l <= r) {
int mid = l + r >> 1;
if(dp[mid][1] > x) {
r = mid - 1;
ans = mid;
}
else {
l = mid + 1;
ans = mid + 1;
}
}
return ans;
}
signed main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n;
for(int i = 1; i <= n; i ++) {
cin >> a[i];
a[i] -= i;
}
// for(int i = 1; i <= n; i ++) {
// cout << a[i] << '\n';
// }
dp[0][0] = dp[0][1] = -1e10;
for(int i = 0; i < n; i ++) {
if(a[i + 1] + 1 >= dp[tot2][1]) {//当我们的删数数组处理到 i+1 时,没有删数的数组需要处理到 i-1 方便转移。
dp[++ tot2][1] = a[i + 1] + 1;
}
else {
dp[work1(a[i + 1] + 1)][1] = a[i + 1] + 1;
}
// cout << work(a[i + 1] + 1) << '\n';
// cout << a[i + 1] + 1 << ' ' << dp[tot1][0] << '\n';
if(a[i + 1] + 1 >= dp[tot1][0]) {
if(tot1 == tot2) {
dp[++ tot2][1] = a[i + 1] + 1;
}
else {
dp[tot1 + 1][1] = min(dp[tot1 + 1][1], a[i + 1] + 1);
}
}
else {
dp[work(a[i + 1] + 1)][1] = min(dp[work(a[i + 1] + 1)][1], a[i + 1] + 1);
}
if(i) {
if(a[i] >= dp[tot1][0]) {
dp[++ tot1][0] = a[i];
}
else {
// cout << work(a[i]);
dp[work(a[i])][0] = a[i];
}
}
}
cout << max(n - tot2 - 1, 0ll);
return 0;
}