题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1003
题目:
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 139023 Accepted Submission(s): 32286
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
Author
Ignatius.L
Recommend
这个题目的动态转移方程式dp[i]=max(dp[i-1]+a[i],a[i]);
然后就是题目中的pos相当于炮灰,其实。。
它是去试探的,真正的大boss是max_figure,max_figure始终保存最大值,还有就是要用两个变量start,end来保存开始的和结束的下标。。
只有在dp[i-1]+a[i]<a[i]的时候那个位置坐标temp就需要改变。。max _figure始终保存最大值。。
代码为:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=100000+10;
int a[maxn],dp[maxn];
int main()
{
int t,n,st,en,ans,Cas=1;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
ans=dp[1]=a[1];
st=en=1;
for(int i=2;i<=n;i++)
{
if(dp[i-1]+a[i]>=a[i]) dp[i]=dp[i-1]+a[i];
else dp[i]=a[i];
if(dp[i]>=ans)
{
ans=dp[i];
en=i;
}
}
int kcc=ans;
for(int i=en;i>=1;i--)
{
if(kcc-a[i]==0)
{
st=i;
break;
}
else kcc-=a[i];
}
printf("Case %d:\n",Cas++);
printf("%d %d %d\n",ans,st,en);
if(t) printf("\n");
}
return 0;
}