首页 > 学院 > 开发设计 > 正文

1003.Max Sum

2019-11-06 07:19:01
字体:
来源:转载
供稿:网友
PRoblem DescriptionGiven 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.InputThe 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).OutputFor 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 Input25 6 -1 5 4 -77 0 6 -1 1 -6 7 -5Sample OutputCase 1:14 1 4Case 2:7 1 6

求每一位置的最大连续和,取最大的就好了

#include<iostream>using namespace std;int main(){ int N; cin >> N; for (int t = 1;t <= N;t++) { if (t != 1) putchar('/n'); printf("Case %d:/n", t); int M; cin >> M; int s_min=0, s_v=1; int s_max=-1001, s_h,s_l; int sum = 0; for (int i = 1;i <= M;i++) { int te;cin >> te; sum += te; if (sum - s_min >= s_max) { s_max = sum - s_min;s_h = i;s_l = s_v; } if (sum < s_min) { s_min = sum;s_v = i + 1; } } printf("%d %d %d/n", s_max, s_l, s_h); }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表