HDU1024 Max Sum Plus Plus (优化线性dp)
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. ^_^
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. ^_^
InputEach 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.
OutputOutput 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.
别的博客在原理上说得很清楚了,代码里的注释解释了一下是如何进行时空优化的。
#include <bits/stdc++.h> #define INF 1<<30 using namespace std; int a[1000005]; int dp[1000005]={0};//dp[i,j]表示选取a[j]分成i段的最大子段和 dp[i][j]=max(dp[i][j-1]+a[j],dp[i-1][k]+a[j])(k:i-1~j-1) int m,n; int pre[1000005]={0}; int main() { while(scanf("%d%d",&m,&n)!=EOF) { memset(dp,0,sizeof(dp)); memset(pre,0,sizeof(pre)); int i,j; for(i=1;i<=n;i++) { scanf("%d",&a[i]); } int ans=0; for(i=1;i<=m;i++) { ans=-INF;//因为所求的最大状态一定在i=m这一轮出现,所以每轮开始把ans设为负无穷没有影响 for(j=i;j<=n;j++)//从i开始,要不然的话少于i个数分不成i段了 { dp[j]=max(dp[j-1]+a[j],pre[j-1]+a[j]);//在这里,一开始整个pre数组存储的本身就是i-1阶段里的各个最大值 pre[j-1]=ans;//当第二重循环跑起来时 ,在更新dp数组的同时也在更新pre数组,这就是这一句的含义,而在这一重循环中更新pre数组对当前是没有影响的(因为已经越过去了) ans=max(ans,dp[j]);//在开头初始化后,ans能保证一直是当前层的最大值 } } cout<<ans<<endl; } return 0; }
分类:
动态规划—线性DP/背包问题
, 题库—HDOJ
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!