1. 程式人生 > >1003 Max Sum(水題)

1003 Max Sum(水題)

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

雖然是道水題…..但剛看題還以為用線段樹做….想了想線段樹…..後來發現什麼鬼啊,直接從頭遍歷一遍,如果遇到這個時候的總和小於0就將此節點更新為起點,如果這個時候的總和大於遍歷過的值的最大和,就將max更新為sum,然後把這個點設為結束點,注意的是剛開始不能把max設為0,因為更新的最大值可能為負值
AC程式碼:

#include<bits/stdc++.h>
using namespace
std; const int INF=0x3f3f3f3f; int main() { ios::sync_with_stdio(0); cin.tie(0); int T,temp,n; cin>>T; for(int k=1;k<=T;k++) { cin>>n; int max=-INF,sum=0; int start=1,end=1,start_t=1; for(int i=1;i<=n;i++) { cin>>temp; sum+=temp; if(sum>max) { max=sum; end=i; start=start_t; } if(sum<0) { sum=0; start_t=i+1; } } if(k!=1) cout<<endl; cout<<"Case "<<k<<":"<<endl; cout<<max<<" "<<start<<" "<<end<<endl; } return 0; }

四級考完….該好好準備期末和刷題了