**Max Sum(难度:1)
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65536/32768 K (Java/Others)
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了导致想了很久,最开始的代码设想是用一个数组a[i]来记录串中的数,dp[a][b]来储存从a到b处的最大子串和,使用递推公式dp[a][b]=max(dp[a+1][b],dp[a][b-1],num],其中num为从a到b的子串的和,使用两个数组be[a][b]和en[a][b]记录从a到b的最大子串的开头与结尾,这是代码:
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXMUM 100000
int a[MAXMUM];
int b[MAXMUM][MAXMUM];
int be[MAXMUM][MAXMUM];
int en[MAXMUM][MAXMUM];
void dp(int length){
for(int i=0;i<length;i++){
b[i][i] = a[i];
be[i][i] = i;
en[i][i] = i;
}
for(int k=2;k<=length;k++){
for(int first=0;first+k-1<=length;first++){
int last = first+k-1;
int number = 0;
for(int i=first;i<=last;i++)
number+=a[i];
b[first][last] = max(max(b[first+1][last],b[first][last-1]),number);
if(b[first][last]==b[first+1][last]){
be[first][last] = be[first+1][last];
en[first][last] = en[first+1][last];
}
else if(b[first][last]==b[first][last-1]){
be[first][last] = be[first][last-1];
en[first][last] = en[first][last-1];
}
else{
be[first][last] = first;
en[first][last] = last;
}
}
}
cout<<b[0][length-1]<<" "<<be[0][length-1]+1<<" "<<en[0][length-1]+1<<endl;
}
int main(){
int T,n;
cin>>T;
for(int time=1;time<=T;time++){
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
cout<<"Case "<<time<<":"<<endl;
dp(n);
cout<<endl;
}
return 0;
}
后来发现该题要求有多个答案时需要输出子串开头和结尾最小的结果,但是这样的实现方法及其难以实现查找最小结果,故后来借鉴了别人的思路。
思路如下:
使用a[i]记录串中的数字,dp[i]记录以a[i]为结尾的子串的最大和,此时a[i]比为开头或结尾。使用递推公式dp[i] = max(dp[i-1]+a[i],a[i]),即可得出结果。通过end记录最大子串的结尾,再后通过累加计算出begin即可。
代码如下:
```cpp
#include<iostream>
#include<algorithm>
using namespace std;
#define MAXMUM 100005
int a[MAXMUM];
int dp[MAXMUM];
int main(){
int T,n;
cin>>T;
for(int time=1;time<=T;time++){
cin>>n;
int max0 = -1001;
int begin,end;
for(int i=1;i<=n;i++){
cin>>a[i];
dp[i] = max(dp[i-1]+a[i],a[i]);
if(max0<dp[i]){
max0 = dp[i];
end = i;
}
}
int number = 0;
for(int i=end;i>0;i--){
number+=a[i];
if(number==dp[end]) begin = i;
}
cout<<"Case "<<time<<":"<<endl;
cout<<dp[end]<<" "<<begin<<" "<<end<<endl;
if(time!=T)
cout<<endl;
}
return 0;
}