动态规划+滚动数组(最大字段和)

Max Sum Plus Plus

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 S 1, S 2, S 3, S 4 … S x, … S n (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ S x ≤ 32767). We define a function sum(i, j) = S i + … + S j (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(i 1, j 1) + sum(i 2, j 2) + sum(i 3, j 3) + … + sum(i m, j m) maximal (i x ≤ i y ≤ j x or i x ≤ j y ≤ j x 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(i x, j x)(1 ≤ x ≤ m) instead. _
Input
Each test case will begin with two integers m and n, followed by n integers S 1, S 2, S 3 … S n.
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

原题意思就是找m个不相交的子段,使子段和最大。
用dp[i][j]表示在第j个数下,前j个数的最大和。
1.第j个数加入前面的子段中dp[i-1][j-1] + a[j]。
2.第j个数自成一个子段dp[i][k] + a[j]。(j加入前面最大子段中)。

d[i][j]=max(d[i][j-1],d[i-1][k])+a[j],其中k=i-1,i,…,j-1。
这么看的话按题目要求是会爆的。

滚动数组优化且可以用一个数组记录前最大和就行b[j-1]。

d[i][j]=max(d[i][j-1],b[j-1])+a[j]。
可以降维得到新的式子为
dp[j] = max(dp[j - 1] + a[j], b[j - 1] + a[j])。

#pragma warning(disable:4996)
#include 
#include 
#include 
#include 
#define INF 0x3fffffff
using namespace std;
const int maxn = 1e6 + 10;
int a[maxn];
int b[maxn];
int dp[maxn];
int main()
{
	int n, m;
	while (scanf("%d%d", &m, &n) != EOF)
	{
		int  g = 0;
		memset(b, 0, sizeof(b));
		memset(a, 0, sizeof(a));
		memset(dp, 0, sizeof(dp));
		for (int i = 1;i <= n;i++)
		{
			scanf("%d", &a[i]);
		}
		for (int i = 1;i <= m;i++)
		{
			g = -INF;
			for (int j = i;j <= n;j++)
			{
				dp[j] = max(dp[j - 1] + a[j], b[j - 1] + a[j]);
				b[j - 1] = g;
				g = max(g, dp[j]);
			}
		}
		cout << g << endl;
	}

	return 0;
}

你可能感兴趣的:(动态规划)