[每日N题] 4.3 Max Sum Plus Plus HDU - 1024 [动态规划]

题目: Max Sum Plus Plus HDU - 1024

这道题最基本的思路其实一下子就出来了,就是这有两种可能挑第i个数进入第j个串中,或者直接跳过第i个数,直接进入第j+1个串。
但具体实现,却想了很久,然后看了别人的代码才写出来。

我的代码:

#include<cstdio>
#include<cstring>
#include<algorithm>

using namespace std;

const int MAXN = 1000000;
const int INFINITE = 32768000;

int p[MAXN+10], d[MAXN+10], maxV[MAXN+10]; 
// maxV[i]记录前i个数字中m个串的和的最大值 
int N, M;

int main () {
  while (~scanf("%d %d", &M, &N)) {
    for (int i = 1; i <= N; i++) {
      scanf("%d", &p[i]);
    }
    memset(d, 0, sizeof(d));
    memset(maxV, 0, sizeof(maxV));
		d[0] = -INFINITE;
    for (int m = 0; m < M; m++) {
    	int mmax = -INFINITE; 
			// mmax记录第需要被更新的值,到i时才更新maxV[i-1]避免影响d的值 
      for (int i = 1; i <= N; i++) {
        d[i] = max(maxV[i-1] + p[i], d[i-1] + p[i]);
        // maxV[i-1] + p[i] 是将i作为一个新串,和前i-1中m个串的和的最大值相加 
				// d[i-1] + p[i] 是和i-1继续连成一个串 
        maxV[i-1] = mmax; // 更新maxV[i-1] 
        mmax = max(d[i], mmax); // 记录,等待下次更新 
      }
    }
    int ans = -INFINITE;
    for (int i = 1; i <= N; i++) {
      ans = max(ans, d[i]);
    }
    printf("%d\n", ans);
  }
  return 0;
}

猜你喜欢

转载自blog.csdn.net/AdamAndTina/article/details/88992734