HDU 1003 经典DP
来源:互联网 发布:如何变文艺知乎 编辑:程序博客网 时间:2024/06/11 11:06
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 261877 Accepted Submission(s): 62235
Problem Description
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.
Sample Input
2
5 6 -1 5 4 -7
7 0 6 -1 1 -6 7 -5
Sample Output
Case 1:
14 1 4
Case 2:
7 1 6
此题是经典的DP,求最大子序列和,转移方程为:dp[i-1]+a[i]>a[i]?dp[i]=dp[i-1]+a[i]:a[i]; 然后ans=max{dp[i]};
dp[i]表示的是以i结尾的所有子序列和的最大值,比如第一个样例:5个数 6 -1 5 4 -7 求得的dp[i]为 6 5 10 14 7 表明以i=3结尾的所有子序列[6 -1 5],[6 -1],[-1 5],[6]和的最大值为10,其他的也都是这样。终止位置为求得最大值的下标i,起始位置就从结尾位置开始往回扫并求和,等于最大值的时候就是起始位置。
AC代码:
#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#include<cmath>using namespace std;int a[100010],dp[100010];int main(){ int t,n,k=1,st,ed; scanf("%d",&t); while(t--){ scanf("%d",&n); for(int i=1;i<=n;i++){ a[i]=0; scanf("%d",&a[i]); } dp[1]=a[1],st=1,ed=1; int maxn=dp[1]; for(int i=2;i<=n;i++){ if(dp[i-1]+a[i]>a[i])dp[i]=dp[i-1]+a[i]; else dp[i]=a[i]; if(dp[i]>maxn){ maxn=dp[i]; ed=i; }; } int sum=0; for(int i=ed;i>0;i--){ sum+=a[i]; if(sum==maxn)st=i; } printf("Case %d:\n%d %d %d\n",k++,maxn,st,ed); if(t)printf("\n"); } return 0;}
阅读全文
0 0
- HDU 1003 经典DP
- HDU 1003 Max Sum (经典DP)
- HDU-1003 Max Sum(经典DP)
- hdu 1421 经典DP
- hdu 1227(经典dp)
- hdu 1421经典dp
- HDU 1069 DP 经典
- hdu 4035 经典期望dp
- hdu 2196(经典树形dp)
- dp经典题目 hdu 2084
- HDU 1003 Max Sum (经典dp入门题)
- 各类经典dp问题分讲(HDU 2084、HDU 1003、HDU 1176)
- HDU 2196 Computer 经典树形DP
- HDU——1227(经典DP)
- HDU 2196 Computer(树形dp经典)
- HDU 2196 Computer(经典树形DP)
- hdu 4616 Game ( 经典树形dp )
- hdu 4455 Substrings (经典DP)
- 关于laravel软删除
- win7安装Qt4.8.5 For Windows 详细的教程
- 【OpenCV】视频制作
- centos7与centos6区别
- java 自我知识总结(十六)匿名内部类
- HDU 1003 经典DP
- Android学习随笔(12)------持久化技术
- 1347 旋转字符串
- java 自我知识总结(十七)访问权限
- 作业3.2
- 利用码云gitee搭建个人maven仓库
- redis 与Spring Data Redis 使用
- 使用Flexible实现手淘H5页面的终端适配
- Softmax回归