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
题意:这题目是想要说明一串数据中,找出它的最大值,这个最大值得保证是某一个数到另一个数的和。例如:6 -1 5 4 -7,最大值便为14,其计算过程为(6-1+5+4);0 6 -1 1 -6 7 -5,最大值便为7,其计算过程为(0+6-1+1-6+7)。这是比较简单的DP题,但是这道题最关键的,在于换行的问题:具体的输入输出应该为:
2
5
6 -1 5 4 -7
Case 1:
14 1 4
7
0 6 -1 1 -6 7 -5
5
6 -1 5 4 -7
Case 1:
14 1 4
7
0 6 -1 1 -6 7 -5
Case 2:
7 1 6
7 1 6
AC代码:
#include<stdio.h>
int dp[100005];
int main()
{
int n,m,i,num;
int sum,start,zuo,you;
m=0;
scanf("%d",&n);
while(n--)
{
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&dp[i]);
}
start=0;
zuo=0;
you=0;
sum=dp[0];
for(i=1;i<num;i++)
{
if(dp[i-1]>=0)
{
dp[i]+=dp[i-1];
}
else
{
start=i;
}
if(dp[i]>sum)
{
sum=dp[i];
zuo=start;
you=i;
}
}
if(m)
{
printf("\n");
}
printf("Case %d:\n",++m);
printf("%d %d %d\n",sum,zuo+1,you+1);
}
return 0;
}
int dp[100005];
int main()
{
int n,m,i,num;
int sum,start,zuo,you;
m=0;
scanf("%d",&n);
while(n--)
{
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&dp[i]);
}
start=0;
zuo=0;
you=0;
sum=dp[0];
for(i=1;i<num;i++)
{
if(dp[i-1]>=0)
{
dp[i]+=dp[i-1];
}
else
{
start=i;
}
if(dp[i]>sum)
{
sum=dp[i];
zuo=start;
you=i;
}
}
if(m)
{
printf("\n");
}
printf("Case %d:\n",++m);
printf("%d %d %d\n",sum,zuo+1,you+1);
}
return 0;
}