HDU-1024-Max Sum Plus Plus

来源:互联网 发布:暮光女 出柜 知乎 编辑:程序博客网 时间:2024/06/07 13:23

题目网址:Max Sum Plus Plus

Max Sum Plus Plus

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)


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 32 6 -1 4 -2 3 -2 3
 

Sample Output
68
Hint
Huge input, scanf and dynamic programming is recommended.
 

Author
JGShining(极光炫影)
 

Recommend
 
题意:每一行前两个数m,n表示要从这n个数字中挑m个子段,要求这些子段不相交,求最大这m段的最大和

思路:dp[i][j]表示前j项含有i个子段的最大和,那么dp[i][j]可以由哪些状态的到呢,首先有dp[i][j-1]+num[j],j-1个元素分为i段的最大值+num[j],这种情况num[j]属于第i个子段也就是原来的第i个子段加了一个num[j]元素,然后是dp[i-1][j-1]+num[j],j-1个元素分为i-1段的最大值+num[j],这种情况num[j]自己成为新的一段即第i段。所以就得到了动态转移方程

动态转移方程:dp[i][j]=max(dp[i][j-1]+num[j],dp(i-1,t)+num[j]),其中i-1<=t<=j-1

由于题目数据量太大(m*n)我们开不了这么大的数组,所以我们得对空间进压缩,可以发现我们只用到两个时候的dp数组即dp[i][j]dp[i-1][t],i-1<=t<=j-1而i-1之前的用过了都用不到了,所以我们可以开两个一维数组dp表示分为i段的状态,Max[j-1]表示i-1到j-1元素分为i-1段的状态的最大值。

然后还有一个很巧妙的地方就是Max数组的更新,当j元素添加到了第i段,等到推j元素分成i+1段时,Max数组也要跟着i更新。

卡了好长时间的一道题,一直想不明白,后来才明白,其中那个Max用的很巧妙,大家理解理解。

#include<bits/stdc++.h>using namespace std; const int maxn=1000005;const int INF=1<<29;int n,m,num[maxn],dp[maxn],pre[maxn],Max;int main()  {      while(~scanf("%d%d",&m,&n))      {          for(int i=1;i<=n;i++)          {              scanf("%d",&num[i]);          }        memset(dp,0,sizeof(dp));memset(pre,0,sizeof(pre));       for(int i=1;i<=m;i++)     {     Max=-INF;      for(int j=i;j<=n;j++)     {     dp[j]=max(dp[j-1]+num[j],pre[j-1]+num[j]);     pre[j-1]=Max;     Max=max(dp[j],Max);}}        printf("%d\n",Max);      }      return 0;  }

 
原创粉丝点击