要注意边界条件的判断(第一次写的麻烦了。。)
# include <cstdio> # include <cstring> # include <iostream> # define inf 0x8fffffff; using namespace std; int max(int a,int b) { return a>b?a:b; } int dp[2][4000][2],v[4000]; int main() { int n,b,i,j,ans = 0; scanf("%d%d",&n,&b); for (i=1;i<=n;++i) scanf("%d",&v[i]); memset(dp,0,sizeof(dp)); dp[1][1][0] = inf; for (i=2;i<=n;++i) for (j=0;j<b;++j) { dp[i%2][j][1] = max(dp[(i-1)%2][j-1][0],dp[(i-1)%2][j-1][1]+v[i]); dp[i%2][j][0] = max(dp[(i-1)%2][j][0],dp[(i-1)%2][j][1]); if (!j) dp[i%2][j][1] = inf; } ans = max(dp[n%2][b-1][0],dp[n%2][b-1][1]+v[1]); memset(dp,0,sizeof(dp)); dp[0][0][1] = inf; for (i=3;i<=n;++i) for (j=0;j<=b;++j) { dp[i%2][j][1] = max(dp[(i-1)%2][j-1][0],dp[(i-1)%2][j-1][1]+v[i]); dp[i%2][j][0] = max(dp[(i-1)%2][j][0],dp[(i-1)%2][j][1]); if (!j) dp[i%2][j][1] = inf; } ans = max(ans,max(dp[n%2][b][1],dp[n%2][b][0])); printf("%d ",ans); return 0; }