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
解题思路:
根据简单的dp思想可以很快求出最大值,所以只要根据变化来保存一下他的最大的区间的位置就可以了
dp方程: dp[i] = max( a[i], dp[i-1]+a[i] )
代码如下:
1 #include<bits/stdc++.h> 2 #define mem(a) memset(a,0,sizeof(a)) 3 #define forn(i,n) for(int i=0;i<n;++i) 4 #define for1(i,n) for(int i=1;i<=n;++i) 5 #define IO std::ios::sync_with_stdio(false); std::cin.tie(0) 6 using namespace std; 7 typedef long long ll; 8 const int maxn=1e5+5; 9 const int mod=10007; 10 const int inf=0x3f3f3f3f; 11 12 int n,m,t,k; 13 int a[maxn]; 14 int dp[maxn]; 15 16 17 int main() 18 { 19 IO; 20 cin>>m; 21 int k=1; 22 while(k<=m) 23 { 24 mem(a); 25 mem(dp); 26 if(k!=1) 27 cout<<endl; 28 cin>>n; 29 forn(i,n) 30 { 31 cin>>dp[i]; 32 } 33 int maxs=dp[0]; 34 int l=0,r=0,head=0; 35 for(int i=1;i<n;++i) 36 { 37 if(dp[i-1]>=0) 38 { 39 dp[i]=dp[i]+dp[i-1]; 40 } 41 else 42 { 43 head=i; 44 } 45 if(dp[i]>maxs) 46 { 47 maxs=dp[i]; 48 l=head; 49 r=i; 50 } 51 } 52 cout<<"Case "<<k<<":"<<endl; 53 cout<<maxs<<" "<<l+1<<" "<<r+1<<endl; 54 k++; 55 } 56 return 0; 57 }