hdu1024 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 ≤ iy ≤ 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, S2, 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
Hint
Huge input, scanf and dynamic programming is recommende
解题思路:
首先定义各个数组,尽量易懂,
a[i] 储存输入的数据
now[j],表示以第j个元素为结尾的i个子段的最大和,必须包含a[j]。
pre[j],表示前j个元素i个子段的最大和,不一定包含a[j]。
dp[i][j],表示前j个元素i个子段的最大和,包含a[j]。
原始状态转移方程:
dp[i][j]=max(dp[i][j-1]+a[j],dp[i-1][k]+a[j]) (i-1<=k<=j-1)
有两种情况:
1.直接将第j个元素加在第i个子段之后。
2.第j个元素单独作为一个子段,那么前面必须是i-1个子段。
状态转移方程就是比较这两种情况较大值
实现代码:
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> using namespace std; #define M 1000002 int a[M],now[M],pre[M]; int main() { int m,n,i,j,Max; while(scanf("%d%d",&m,&n)==2) { for(i=1;i<=n;i++) scanf("%d",&a[i]); memset(now,0,sizeof(now)); memset(pre,0,sizeof(pre)); for(i=1;i<=m;i++) { Max = -999999999; //此处max值尽量开大,max是和,开小了就WA, for(j=i;j<=n;j++) { now[j]=max(now[j-1]+a[j],pre[j-1]+a[j]); //now[j]有两种来源,一种是直接在第i个子段之后添加a[j] //一种是是a[j]单独成为1个子段 pre[j-1]=Max; //更新pre使得pre是前j-1个中最大子段和 if(now[j]>Max) Max=now[j]; } } printf("%d\n",Max); } return 0; }