HDU 1003 HDU1231 Max Sum

HDU 1003 :                                                                                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

 

解题报告:

此题为求每一个子段的最大的和,求出该子段起始位置,最末一个元素的位置,由于测试数据为1<=N<=100000,所以采取双重循环,分别求每一个子段的和,然后再相互比较,则很显然会TLE,所以双重循环式行不通的,只能考虑更为简单的方法。

可以这样考虑,如果一个<0的数加上一个数a,那么它的和肯定<a。如果a的值比开始所求得的max大,则就将起始位置e设置为a的位置。只要和比max大,则将此位置的行号赋给末尾位置,这样就是单重循环,不会TLE;

解此题的过程中间,出现了问题,就是通过比较第k+1个数的值>第k个的值,才使起始位置的值更新,花费很长时间举个例子 100 -101 2才发现错误。就是判断是否或在哪更新起始位置稍微有些问题。下面是AC代码:

#include<stdio.h>
int main()
{
int n,m,max,s,a,k,temp,j=1,e,t;
scanf("%d",&n);
while(1)
{
scanf("%d",&m);
s=0;
t=1;
temp=1;
max=-100001;
for(k=1;k<=m;k++)
{
scanf("%d",&a);

s+=a;
if(s<a)//判断大小,若成立,则说明s<0;
{
t=k; //先将此位置的值赋予t
s=a; //初始值a赋予s
}
if(s>max) //判断是否>最大值
{
e=t; // 此时只有这个条件成立时,才将t的值赋予初始值e
max=s;
temp=k; //满足s>max,即将k的值赋予末尾位置
}

}
printf("Case %d:\n%d %d %d\n",j,max,e,temp);
if(j!=n)printf("\n"); //控制格式
j++;
if(j==n+1)break; //跳出循环
}
return 0;
}

 HDU 1231同这题,差不多,AC代码:

#include<stdio.h>
int main()
{
int a[10001],i,max,p,temp,begin,end,s,n;
while(1)
{
p=0;
max=-100000;
scanf("%d",&n);
if(n==0)break;
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(a[i]>=0)p=1;
}
if(p==1)
{
s=0;
begin=a[0];
end=a[0];
temp=a[0];
for(i=0;i<n;i++)
{
s+=a[i];
if(s<a[i])
{
temp=a[i];
s=a[i];
}
if(s>max)
{
begin=temp;
end=a[i];
max=s;
}
}
}
else
{
begin=a[0];
end=a[n-1];
max=0;
}
printf("%d %d %d\n",max,begin,end);

}
return 0;
}



你可能感兴趣的:(HDU)