先看题目
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 190877 Accepted Submission(s): 44442
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
暴力肯定不行,一看就是动态规划的题目。一维的动态规划,有两个点,如果遇到正数,加上去肯定是会变大的,对于一个数是这样,对于很多个数的和也是一样,第二点是如果前面的几个数的和是负数,就要把起始位置改为负数后的一点。再和前面最大的数比较,若后面有更大的数就改起始位置。
代码如下
#include <iostream>
using namespace std;
int a[100000];
typedef struct
{
int sum;
int start;
int end;
}result;
result dp(int count)
{
int i;
int max=-9999999;
int k=1;
result res;
res.sum=0;
i=1;
while(i<=count)
{
res.sum+=a[i];
if(res.sum>max)
{
max=res.sum;
res.start=k;
res.end=i;
}
if(res.sum<0)
{
res.sum=0;
k=i+1;
}
i++;
}
res.sum=max;
return res;
}
int main()
{
result res;
int i;
int j=1;
int number;
int count;
cin>>number;
while(number)
{
cin>>count;
for(i=1;i<=count;i++)
{
cin>>a[i];
}
res=dp(count);
if(j!=1)
cout<<endl;
cout<<"Case "<<j<<":"<<endl;
cout<<res.sum<<" "<<res.start<<" "<<res.end<<endl;
number--;
j++;
}
return 0;
}
ac了