hdoj 1003

来源:互联网 发布:淘宝那个助手好 编辑:程序博客网 时间:2024/05/29 18:52

Max Sum

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


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>int main(){int n, star, end, i, j, t, x, temp, now, sum,count = 1;scanf("%d", &t);for(i = 1; i <= t; i++){scanf("%d %d", &n, &temp);star = end = x = 1;now = sum = temp;for(j = 2; j <= n; j++){scanf("%d", &temp);if(now + temp < temp){now = temp;x = j;}else{now += temp;}if(now > sum){sum = now;star = x;end = j;}}printf("Case %d:\n%d %d %d\n", count++, sum, star, end);if(i != t){printf("\n");}}return 0; }
 
这题代码是看了别人的。。很简单的一道题  
总体思路就是先把第一个数当做最大子序列   初始化各个变量
然后输入下一个数,将其加入到子序列中,如果now+temp<temp 就说明
这一串子序列加起来还没有temp大 所以now=temp  此时更改起始位置的下标
否则的话就说明加入后子序列的值变大  所以将其加入到子序列中去。
如果加入后的值大于max则更新max的值,
   各变量的含义如下
 
star          子序列的起始位置
end          子序列的最后一个位置
now          加入一个数后的当前最大值
max          保存子序列的最大值
x               子序列的起始位置
原创粉丝点击