HDU 1024 Max Sum Plus Plus (动态规划 最大M字段和)

Problem Description
Now I think you have got an AC in Ignatius.L's "Max Sum" problem. To be a brave ACMer, we always challenge ourselves to more difficult problems. Now you are faced with a more difficult problem.

Given a consecutive number sequence S1, S2, S3, S4 ... Sx, ... Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx ≤ 32767). We define a function sum(i, j) = Si + ... + Sj(1 ≤ i ≤ j ≤ n).

Now given an integer m (m > 0), your task is to find m pairs of i and j which make sum(i1, j1) + sum(i2, j2) + sum(i3, j3) + ... + sum(im, jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jx is not allowed).

But I`m lazy, I don't want to write a special-judge module, so you don't have to output m pairs of i and j, just output the maximal summation of sum(ix, jx)(1 ≤ x ≤ m) instead. ^_^

 
Input
Each test case will begin with two integers m and n, followed by n integers S1, S2, S3 ... Sn.
Process to the end of file.
 
Output
Output the maximal summation described above in one line.
 
Sample Input
1 3 1 2 3
2 6 -1 4 -2 3 -2 3
 
Sample Output
6
8

题目大意:有n的个数,需要你将他划分成m段互不相交的子段,求最大的子段和

 思路:在这里向大家推荐一篇大佬的博客,讲解的清晰明了,让我获益匪浅 https://blog.csdn.net/winter2121/article/details/72848482  Orz

  大佬的博客写的很清晰,而且附上图解很容易弄懂

  dp[i][j] 代表前i个数并且以第i个数为末尾划分成了j段的最大和。

  而dp[i][j] 有两种情况:1. 将第i个数划分到前面这一段取

            2.将第i个数单独拿出来作为一段的开始

  dp[i][j] = max(dp[i-1][j],max(前i个数中的最大和))+a[j];

 #include<iostream>
#include<algorithm>
#include<cstring> using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int maxn = ;
LL n, m;
LL dp[maxn][], a[maxn];//dp[i][j]代表以第i个数为结尾且分成j段的最大和
int main()
{
ios::sync_with_stdio(false);
while (/*cin>>m>>n*/scanf("%lld%lld", &m, &n) != EOF) {
for (int i = ; i <= n; i++)scanf("%lld", &a[i]);
/*cin >> a[i];*/
for (int i = ; i <= n; i++)dp[i][] = dp[i][] = ;
for (int i = , k = ; i <= m; i++, k ^= ) {
LL maxpre = -INF; dp[i - ][k] = -INF;//避免与后面for循环的影响
for (int j = i; j <= n - m + i; j++) {
maxpre = max(maxpre, dp[j-][k ^ ]);//寻找上一行第i个数之前的最大值
dp[j][k] = max(dp[j - ][k], maxpre) + a[j];
}
}
LL ans = -INF;
for (int i = m; i <= n; i++)
ans = max(ans, dp[i][m&]);
//cout << ans << endl;
printf("%lld\n", ans);
}
return ;
}
 
上一篇:codeforces 629D 树状数组+LIS


下一篇:团队作业8——第二次项目冲刺(Beta阶段)--第二天