错误的dp初始化代码
#include<stdio.h> #include<string.h> int a[20100]; int dp[20100]; int main() { int n,max,m; int i,j; while(scanf("%d",&n)!=EOF&&n!=0) { memset(dp,0,sizeof(dp)); memset(a,0,sizeof(a)); for(i=1;i<=n;i++) scanf("%d",&a[i]); dp[1]=1; max=1; for(i=2;i<=n;i++) { m=0; for(j=i-1;j>=1;j--) { if(a[j]+i-j<=a[i]) { if(m<dp[j])m=dp[j]; //break; } } dp[i]=m+1; //if(j==0)dp[i]=1; // //dp[i]=; } for(i=2;i<=n;i++) //printf("%d\n",dp[i]); if(dp[i]>max)max=dp[i]; printf("%d\n",max); } return 0; }
求最长递增子序列的和+小变形
Dp问题dp数组的初始化很重要!!!!!!!!!!!!!
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> using namespace std; const int maxn = 20010; int n; int data[maxn], a[maxn]; int main() { int i, j, ans ; while(cin>>n) { ans=0; for(i = 1; i <= n; i++) { scanf("%d", &a[i]); if(a[i] >= i) data[i] = 1; else data[i] = -1e9; } data[1] = 1; for(i = 2; i <= n; i++) { for(j = 1; j < i; j++) if(a[i]-a[j] >= i-j) data[i] = max(data[i], data[j]+1); ans = max(ans, data[i]); } cout<<ans<<endl; } return 0; }