Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 237978 Accepted Submission(s): 56166
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
Author
Ignatius.L
Recommend
这道题目写的时候WA了很多次
最开始用结构体写的,写了两层循环,然后自己琢磨的瞎改,一直都是两层循环
#include#include #include #include #include
后来我师傅指导了我,直接用一层循环就解决了。。
就是用sum不停累加,如果sum小于0了,就重置sum等于当前的a[i],同时更新起始,结束位置
(注意sum最大时有可能为负数,所以定义maxn时要注意maxn取值要为最小--1001 )
#include#include #include #include #include
这段时间学dp学到的dp解法
#include#include #include #include using namespace std;int a[100010],sum[100010],s[100010];int main(){ int T; cin >> T; for(int k=1;k<=T;k++){ int n; cin >> n; for(int i=0;i > a[i]; } int ans = 0; sum[0] = a[0]; s[0] = 0; for(int i=0;i = 0){ //只要不是小于零就可以继续加,记下每次加后得到的值 sum[i] = sum[i-1] + a[i]; s[i] = s[i-1]; } else{ //小于零重新开始累加 sum[i] = a[i]; s[i] = i; } if(sum[ans] < sum[i]){ //求出记录中的最大值 ans = i; } } cout << "Case " << k << ":" << endl; cout << sum[ans] << " " << s[ans]+1 << " " << ans + 1 << endl; if(k!=T){ cout << endl; } } return 0;}