hdu 1003

来源:互联网 发布:淘宝在线云客服门户 编辑:程序博客网 时间:2024/05/22 16:21

Max Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 202042    Accepted Submission(s): 47222


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

//经典Dp,一开始我先把所有数记录下来,然后从后面向前扫描,然后错了,发现它是要最先出现的哪一组数据,所以又从头扫描,然后发现,从头扫描就不需要用数组存储了

//思路是这样:先把第一个扫描的值先记录下来为max=now=temp(temp为输入值),然后到下一个就比较temp和now+temp的值谁大,如果temp大就把now给扔掉,

//让now=temp,更新索引,如果temp小,就让now+=temp,更新索引,每一步,让now跟max比较,若max比当前的now要小,则把索引更新为当前索引,思路还是挺简单的

源代码如下:

#include <stdio.h>int main(){int i, j;int n, m, now, max, temp, x;int findex, lindex;scanf("%d", &n);for(i=1; i<=n; i++){scanf("%d", &m);for(j=0; j<m; j++){scanf("%d", &temp);if(j == 0) {findex=lindex=x=j;now=max=temp;}else{if(temp>now+temp){now=temp;x=j;}else{now=now+temp;}if(max < now){max=now;findex=x;lindex=j;}}}printf("Case %d:\n", i);printf("%d %d %d\n", max, findex+1, lindex+1);if(i != n) printf("\n");}return 0;}


0 0