hdu 1024 Max Sum Plus Plus

Max Sum Plus Plus

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13213    Accepted Submission(s): 4355


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
Hint
Huge input, scanf and dynamic programming is recommended.
 

 

Author
JGShining(极光炫影)
题意大致就是说给n个数,求出m个子串和的最大值。
此题确实有点难想,但是找到啦状态转移方程就比较好想,假设dp[i][j]为前j个数n个串的和的最大值,所以dp[i][j]=max{dp[i][j-1]+a[j],dp[i-1][j-1]+a[i]}(a[i]为第i个数)。
 1 #include<stdio.h>
 2 #include<string.h>
 3 #define Max(a,b) (a>b?a:b)
 4 #define size 1000100
 5 #define INF 1<<30
 6 int dp[2][size];//这儿只用啦一个dp[0],d[1]表示,可以减少内存的浪费,关键是这题我们只需要知道在j-1个数的i和i-1个子串和的最大值
 7 int num[size];
 8 int main()
 9 {
10     int n,m,i,j,max;
11     while(scanf("%d%d",&m,&n)!=EOF)
12     {
13         memset(dp,0,sizeof(dp));
14         for(i=1;i<=n;i++)
15         {
16             scanf("%d",&num[i]);
17             dp[1][i]=dp[0][i]=0;
18         }
19         for(i=1;i<=m;i++)//表示有i个子串
20         {
21             max=-INF;//令一个很小的数,好把在第i个子串是第一次的值保存下来
22             for(j=i;j<=n;j++)
23             {
24                 dp[1][j]=Max(dp[1][j-1],dp[0][j-1])+num[j];//此时的dp[1][j-1]代表前j-1个数有i个子串和的最大值,dp[0][j-1]代表前j-1个数i-1个子串的最大值(注意:i-1个子串中得最后一个子串都是以a[j-1]结尾的),并且还有一种特殊情况就是j=i时,因为也可用这方程表示就用啦一个方程表示;
25                 dp[0][j-1]=max;//记录当前状态(即i个子串)前j-1个数的最大值,以便在求前j个i+1子串是用
26                 if(max<dp[1][j])
27                 {
28                     max=dp[1][j];//比较得出前j个数i个子串和的最大值
29                 }
30             }
31         }
32         printf("%d\n",max);
33     }
34     return 0;
35 }

 

 
posted @ 2013-07-29 21:46  ゐ星落★孤晨ね  阅读(136)  评论(0编辑  收藏  举报