杭电 hdoj 1003 动态规划 c语言题解
来源:互联网 发布:公务员培训老师知乎 编辑:程序博客网 时间:2024/05/17 04:58
Max Sum
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
25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5
Sample Output
Case 1:14 1 4Case 2:7 1 6
很明显是一道动态规划的题目,还有种特别的方法,不过这种方法对于新手可能会比较难理解:
#include <stdio.h>#include <stdlib.h>int main(){ int t,i,n; int temp,rear,head,j,maxrear,maxhead,sum,max; scanf("%d",&t); for(i=1;i<=t;i++){ scanf("%d",&n); for(maxrear=0,maxhead=0,sum=max=-21000,j=1,head=1,rear=1;j<=n;j++){ scanf("%d",&temp); //关键是判断当前的sum的值是否小于0 if(sum<0){ head=j; rear=j; sum=temp; } else { sum+=temp; } if(sum>max){ max=sum; maxhead=head; maxrear=rear; } rear++; } printf("Case %d:\n",i); printf("%d %d %d\n",max,maxhead,maxrear); if(i!=t)printf("\n"); } return 0;}
思路:将各个数依次相加,若和小于零则从当前加的数重新开始。
为什么?
因为题目中要求是连续的子序列,若是有一部分数的和小于零了,那这一部分的和肯定不可能包括在最大和里面,因为(前面的一部分和小于零的数)+(后面一部分加的数)肯定小于(后面一部分加的数),因而不可能是最优解,也就可以直接忽略(前面的一部分和小于零的数)。这是这种算法的关键所在。
0 0
- 杭电 hdoj 1003 动态规划 c语言题解
- 杭电HDOJ 5586 SUM(dp)(动态规划)
- 动态规划C++::杭电ACM1003
- 动态规划C++::杭电ACM1003
- 杭电OJ(HDOJ)1003题:Max Sum(动态规划)
- 杭电动态规划
- 杭电动态规划
- HDOJ 1003 动态规划
- 杭电1003 MaxSum动态规划
- 杭电动态规划习题
- 杭电动态规划习题
- 动态规划 杭电2571
- 动态规划 杭电 1087
- 动态规划 杭电1231
- 动态规划 杭电1069
- 动态规划 杭电1176
- 动态规划 杭电1257
- 杭电 2881 动态规划
- Oracle SQL性能优化
- LXC之namespace模块学习-小结
- oc 的 runtime机制(一)
- C语言常用面试题_2015.5.6(2)
- jconcole
- 杭电 hdoj 1003 动态规划 c语言题解
- iOS uitextFiled输入框被软键盘遮盖怎么办
- 第一个JAVA程序-HelloWorld
- SpringMVC入门示例教程(一)
- 漫谈数据库索引
- 关于继承parent="Theme.AppCompat"错误:This Activity already has an action bar supplied by the window decor
- 天气接口
- 信号量 互斥锁 条件变量的区别(讲的很好,值得收藏)
- shiro jdbcRealm