#C++初学记录(ACM试题2)
Max Sum **
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>
#include<cstdio>
using namespace std;
int a[200];
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
int t,resmax=0,sursum=0,curleft=1,temp=0,resleft=0,resright,ressum=0;
cin>>t;
for(int i=1;i<=t;i++)
{
cin>>temp;
sursum+=temp;
if(sursum>resmax)
{
resmax=sursum;
resright=i;
resleft=curleft;
}
if(sursum<0)
{
sursum=0;
curleft=i+1;
}
}
printf("Case %d:\n%d %d %d\n",i, resmax, resleft, resright);
printf(i==t?"":"\n");
}
}
}
题意理解
题意是按照顺序进行不停的相加,假设每一次加一个数所得到的数据都另外储存在一个数组里面,则到最后进行每一步加法的大小比较,输出三组数据,第一个数据是不停相加过程中出现的最大值,第二个数据是相加过程中的起始点,注意,这里相加时若出现负数可以进行清零,然后起始点赋值成变成负值位置的下一个位置。假设中的数据实际不会用到只是为了方便解释题意,用数组进行储存每一步的相加数据太麻烦。第三个数据则是相加过程中的结束点。
对于最大值的判断:如何判断最大值是完成这个题目的首要问题,则需要一个累加的代码进行不断相加输入的数据,还需要一个判断程序,即if条件语句,进行判断是否大于“历届”最大值,最后需要一个空间储存最大值。首先定义一个空间resmax,进行初始化为零,接着对不停累加的变量sursum进行比较,与resmax进行比较,当前值大于结果值时更新resmax, resleft, resright,当前值小于0时更新curleft, cursum;。