K - Max Sum Plus Plus

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

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 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(im, 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

Hint

 

Huge input, scanf and dynamic programming is recommended.

//题意是:第一行 m ,n (n<=1000000) 两个整数,然后第二行 n 个数,求 m 段不相交连续序列最大和。

这篇博客写得十分详细

http://www.cnblogs.com/kuangbin/archive/2011/08/04/2127085.html

dp[i][j]代表的状态是 i 段连续序列的最大和,并且最后一段一定包含 num[j]

所以写出状态转移方程 dp[i][j]=max{dp[i][j-1]+a[j],max{dp[i-1][t]}+a[j]} 0<t<j-1

dp[i][j-1]代表接上上一个元素,后面代表自己独立成一组

n很大,只能用滚动数组

不断更新状态,用一个数据 big 保存 i - 1 段最大的和,最后直接输出,就是答案

436ms

 #include <stdio.h>
#include <string.h> #define inf 0x7ffffff
#define MAXN 1000005
int num[MAXN];
int dp[MAXN];
int pre[MAXN]; int max(int a,int b)
{
return a>b? a:b;
} int main()
{
int m,n;
int i,j,big;
while (scanf("%d%d",&m,&n)!=EOF)
{
for (i=;i<=n;i++)
{
scanf("%d",&num[i]);
pre[i]=;
} pre[]=;
dp[]=; for (i=;i<=m;i++)
{
big=-inf;
for (j=i;j<=n;j++)
{
dp[j]=max(dp[j-],pre[j-])+num[j];//连续的最大和,或者不连续的最大和
pre[j-]=big; //保存 i - 1 段 最大和
big=max(big,dp[j]);//保证是 i 段最大的和
}
}
printf("%d\n",big);
}
return ;
}

最新文章

  1. const指针
  2. 解决yum报错集
  3. 点击每个li输出里面的内容(前端很常问的面试题之一)
  4. smarty中math函数的用法
  5. 帝国CMS常见问题记录
  6. 老老实实学WCF[第一篇] Hell wcf
  7. web项目设计中框架的数据流
  8. [转]iOS之浅谈纯代码控制UIViewController视图控制器跳转界面的几种方法
  9. CentOS Linux修改系统时区
  10. js事件的方法
  11. MySQL能够承受上亿万条的数据量的架构
  12. .Net MVC4笔记之js css引用与压缩
  13. 【Django】学习资料
  14. 724. Find Pivot Index
  15. 如何在Eclipse中快速添加main方法
  16. Sublime Text3时间戳查看转换插件的开发
  17. SQL语句(理论)
  18. PHP字符串处理 单引号 双引号 heredoc nowdoc 定界符
  19. Ubuntu修改系统时间
  20. 学 shell (1/5)

热门文章

  1. 矩阵压缩写法 scipy spark.ml.linalg里都有,CRS,CCS
  2. JS中的柯里化及精巧的自动柯里化实现
  3. 配置Linux系统实现dhcp功能
  4. 2017.7.14 使用case when和group by将多条数据合并成一行,并且根据某些列的合并值做条件判断来生成最终值
  5. caffe卷积层代码阅读笔记
  6. linux 设置时间
  7. Sencha Test Futures API 探秘
  8. Loadrunner中对中文进行UTF-8转码的探索
  9. &amp;lt;!DOCTYPE&amp;gt;奇葩的问题
  10. css 温故而知新 select-option 文字方向居右