hdu-1003 Max Sum
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu-1003 Max Sum相关的知识,希望对你有一定的参考价值。
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1003
题目:
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 241930 Accepted Submission(s): 57107
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的童鞋们成就感的题,大概题意是,给你一个T,代表T组样例,然后每组样例给你一个数N,然后后面有N个数,问这N个数当中,那个区间的和最大,输出最大和 最大和的区间左下标 最大和的有下标
注:下标是从1开始的
解题思路:
dp的经典解题思路,利用循环,查找当前位置与之前记录的和是否比当前值还小(之前的和是否为负数),如果是,则将和赋值为当前值,记录当前值的下标,然后对记录的最大值进行比较,如果当前值更大,则更新最大区间左右下标和最大值。
AC代码:
# include <stdio.h> int a[100010]; int main () { int t,n,ret,sum,max,i,sta,end,flag=1; scanf("%d",&t); while(t--) { scanf("%d",&n); for(i=0;i<n;i++) scanf("%d",&a[i]); sta=0; end=0; ret=0; max=a[0]; sum=a[0]; for(i=1;i<n;i++) { if(sum+a[i]<a[i]) { ret=i; sum=a[i]; } else sum+=a[i]; if(max<sum) { max=sum; sta=ret; end=i; } } printf("Case %d:\n",flag); printf("%d %d %d\n",max,++sta,++end); flag++; if(t) printf("\n"); } }
易出错分析:
第一次提交RE了一次,当时没有看清题,结果数组开小了。然后根据题意,数组开大之后,将数组放入全局变量(数组大概在1000,000左右要放入全局变量,不能放入主函数中),便AC了
以上是关于hdu-1003 Max Sum的主要内容,如果未能解决你的问题,请参考以下文章