dp好想。bit的优化好想。还有细节:
(1)从k->0,这样才不会被本身转移。
(2)这个dp表示的是以i结尾的最长的长度,所以随时max。
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; int n,k,tab[5550][550],dp[10050][550],h[10050],mx=0,ans=0; int lowbit(int x) {return (x&(-x));} int ask(int x,int y) { int ret=0; for (int i=x;i>=1;i-=lowbit(i)) for (int j=y;j>=1;j-=lowbit(j)) ret=max(ret,tab[i][j]); return ret; } void insert(int x,int y,int val) { for (int i=x;i<=mx;i+=lowbit(i)) for (int j=y;j<=k+1;j+=lowbit(j)) tab[i][j]=max(tab[i][j],val); } int main() { scanf("%d%d",&n,&k); for (int i=1;i<=n;i++) scanf("%d",&h[i]); for (int i=1;i<=n;i++) mx=max(mx,h[i]);mx+=k; for (int i=1;i<=n;i++) for (int j=k;j>=0;j--) { dp[i][j]=ask(h[i]+j,j+1)+1; insert(h[i]+j,j+1,dp[i][j]); ans=max(ans,dp[i][j]); } printf("%d\n",ans); return 0; }