一道DP好题。
一开始容易想到用表示前个积木删除个 的最大价值。则
时间复杂度 可以过36分
优化上述方法,将第一维滚动掉,第二维反向枚举则有
代码
For(i , 1 , n) {
for(int j = i ; j >= 0 ; -- j) {
f[j] = max(f[j] + (a[i] == i - j ? 1 : 0) , f[j - 1]);
}容易发现第二重循环每次更新的数比较少,可以把要更新的数放到队列里,减少计算次数。这样可以水60分。
好了,以上都是扯淡,下面是正解。
我们有一个更好的状态定义是第i个积木在自己的位置上时,前i个积木中最多能归位的数目。
则有
然后以 为关键字排序,树状数组统计的最大值,这就是的值。
#include<bits/stdc++.h>
using namespace std;
#define I inline
#define ri register int
#define ll long long
#define For(i , x , y) for(ri i = x ; i <= y ; ++ i)
#define Next(i , u) for(ri i = head[u] ; i ; i = e[i].nxt)
#define lowbit(x) x & -x
I int read() {
int s = 0 , w = 1; char ch = getchar();
while(ch < 48 || ch > 57) {if(ch == '-') w = -1 ; ch = getchar();}
while(ch >= 48 && ch <= 57) s = (s << 1) + (s << 3) + (ch ^ 48) ,ch = getchar();
return s * w;
}
const int N = 2e5 + 5;
int n , Ans , c[N] , f[N];
struct node {
int x , id;
} a[N];
I void modify(int x , int val) {
while(x <= n) c[x] = max(c[x] , val) , x += lowbit(x);
}
I int query(int x) {
int res = 0;
while(x > 0) res = max(res , c[x]) , x -= lowbit(x);
return res;
}
I bool cmp(node A , node B) {
return (A.id - A.x == B.id - B.x) ? (A.id < B.id) : (A.id - A.x< B.id - B.x );
}
signed main() {
n = read();
For(i , 1 , n) a[i].x = read() , a[i].id = i;
sort(a + 1 , a + n + 1 , cmp);
For(i , 1 , n) {
if(a[i].id - a[i].x < 0) continue;
int res = query(a[i].x - 1) + 1 ; modify(a[i].x , res);
Ans = max(Ans , res);
}
cout << Ans << endl;
return 0;
}