HDU 1003 MAX SUM
Max Sum
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
这是早前就训练过的题,所以没什么难度。
列出状态转移方程,用ans[i]记录以data[i]为子列终点的最大值;
ans[i]+=(ans[i-1]>0)?ans[i-1]:0;
dp水题,只要在找出MAX_SUM后找出始末下标就可,注意输出格式。
代码:
#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<iostream>
#include<stack>
#include<queue>
#include<limits>
using namespace std;
#define debug 0
const int maxn=100000+5;
int data[maxn],ans[maxn],caseSum,numberNum,caseNum,maxSum,startPos,endPos;
void Do()
{
int j;
for(int i=1;i<=numberNum;i++)
{
if(ans[i]>maxSum)
{
maxSum=ans[i];
startPos=endPos=i;
}
}
for(j=endPos-1;ans[j]>=0&&j>0;j--);
startPos=j+1;
if(caseNum>1)
{
putchar('\n');
}
printf("Case %d:\n%d %d %d\n",caseNum,maxSum,startPos,endPos);
}
int main()
{
#if debug
freopen("in.txt","r",stdin);
#endif // debug
while(~scanf("%d",&caseSum))
{
for(caseNum=1;caseNum<=caseSum;caseNum++)
{
maxSum=INT_MIN;
memset(data,0,sizeof(data));
scanf("%d",&numberNum);
for(int i=1;i<=numberNum;i++)
{
scanf("%d",&data[i]);
ans[i]=data[i];
if(ans[i-1]>0)
ans[i]+=ans[i-1];
}
Do();
}
}
return 0;
}