经典动态规划问题——最大子段和问题
来源:互联网 发布:淘宝上有正规药店吗 编辑:程序博客网 时间:2024/05/19 21:17
hud1003
问题描述
Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
问题分析:
这是一道经典的动态规划问题,动态规划是常见的算法题目,但是这道题国语经典,所以难度也不是特别的大,下来我来展示求解过程:
以dp作为动态规划数组,dp[i]表示以i结尾的最大最大子段和。
动态规划方程为:dp[i]=max(dp[i-1]+A[i],A[i])
源代码如下:
#include<iostream>#include<cstdio>#define maxn 100010#define INF 0x7fffffffusing namespace std;int A[maxn],dp[maxn],L[maxn],R[maxn];//L和R分别记录左起点和右起点int N;int main(){ int T;cin>>T; for(int kase=1;kase<=T;kase++){ cin>>N; for(int i=0;i<N;i++) scanf("%d",A+i); dp[0]=A[0];L[0]=R[0]=0; for(int i=1;i<N;i++){ if(dp[i-1]<0) L[i]=R[i]=i,dp[i]=A[i]; else L[i]=L[i-1],R[i]=i,dp[i]=dp[i-1]+A[i]; } int l,r,Max=-INF; for(int i=0;i<N;i++) if(dp[i]>Max) Max=dp[i],l=L[i],r=R[i]; printf("Case %d:\n%d %d %d\n",kase,Max,l+1,r+1); if(kase<T) printf("\n"); } return 0;}
- 经典动态规划问题——最大子段和问题
- 动态规划——最大子段和问题
- 动态规划 最大子段和问题
- 0013算法笔记——【动态规划】最大子段和问题,最大子矩阵和问题,最大m子段和问题
- 0013算法笔记——【动态规划】最大子段和问题,最大子矩阵和问题,最大m子段和问题
- 0013算法笔记——【动态规划】最大子段和问题,最大子矩阵和问题,最大m子段和问题
- 最大m子段和问题 Max Sum Plus Plus —— 动态规划
- 算法笔记——【动态规划】最大子段和问题
- 动态规划之最大子段和问题
- 动态规划之最大子段和问题总结
- 动态规划算法求最大子段和问题
- 动态规划之最大子段和问题
- (3)最大子段和问题____动态规划
- 动态规划之最大子段和问题
- C语言最大子段和问题(动态规划)
- 最大子段和问题的动态规划解法
- 动态规划-最大子段和系列问题
- 动态规划之最大子段和问题
- 简述游标的使用
- Lesson02_python3之 基础数据类型
- 【学习笔记】图论 割点 割边
- 在C和C++中NULL的区别
- PBR的优点
- 经典动态规划问题——最大子段和问题
- 解析数组
- 习题8.3
- AS开发中出现Error(十二)——Library中引用aar报错的问题
- 数据包转发处理流程
- leetcode_Two Sum II
- 深入浅出空间索引:为什么需要空间索引
- (初学者) 求最大公约数和最小公倍数之辗转相除法
- 前台接收后台传过来的list进行遍历,然后根据表格用合并rowspan列