Max Sum
http://acm.hdu.edu.cn/showproblem.php?pid=1003
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[i]表示以i为结尾的子串的最大和,再用sta数组保存其起始下标即可,进行状态转移
刚开始对sta数组也开了一个数组存储下标,但是发现cur只用一次,如果及时更新答案就不用数组保存了,然后就换成curSta表示当前子串的起始下标(其实dp数组也可以不需要,但是为了符合习惯,就不省略了)
过了这么久再写一次,发现写的方法还是一样(总想着减少时间和空间)
#include <cstdio>
using namespace std;
int dp[100005],curSta,ansSum,ansSta,ansDes;//dp[i]表示以i为结尾的子串的最大和,curSta表示其起始下标
int n;
int main() {
int T,kase=0;
scanf("%d",&T);
while(kase<T) {
if(kase!=0)
printf("\n");
printf("Case %d:\n",++kase);
scanf("%d%d",&n,dp+1);
curSta=ansSta=ansDes=1;
ansSum=dp[1];
for(int i=2;i<=n;++i) {
scanf("%d",dp+i);
if(dp[i-1]<0) {
curSta=i;
}
else {
dp[i]+=dp[i-1];
}
if(ansSum<dp[i]) {
ansSum=dp[i];
ansSta=curSta;
ansDes=i;
}
}
printf("%d %d %d\n",ansSum,ansSta,ansDes);
}
return 0;
}