杭电acm 1003 不知为何通不过(WRONG ANSWER)

题目:ProblemDescriptionGivenasequencea[1],a[2],a[3]......a[n],yourjobistocalculatethema... 题目:
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 main()
{
int a[100000],n,i,T,t;
cin>>T;
t=1;
long this_sum,sum,last_sum,best_from,best_to;
while (t<=T){
cin>>n;
for (i=0;i<n;i++)
cin>>a[i];
this_sum=last_sum=sum=a[0];
best_from=best_to=1;
for (i=1;i<n;i++){
if (this_sum>=0){
this_sum+=a[i];
last_sum=this_sum;
}
else
{
this_sum=a[i];
if (this_sum>last_sum)
best_from=i+1;
}
if (sum<this_sum){
sum=this_sum;
best_to=i+1;
}
}
cout<<"Case "<<t<<':'<<endl;
cout<<sum<<' '<<best_from<<' '<<best_to<<endl;
if (t<T)
cout<<endl;
t++;
}
return 0;
}
代码改了:
#include <iostream>
using namespace std;
int main()
{
int a[100000],n,i,T,t;
cin>>T;
t=1;
long sum,this_sum,best_from,best_to,max;
while (t<=T){
cin>>n;
for (i=0;i<n;i++)
cin>>a[i];
this_sum=sum=max=a[0];
best_from=best_to=1;
for (i=1;i<n;i++){
if (this_sum>=0){
this_sum+=a[i];
if (this_sum>max)
max=this_sum;
}
else
{
bool flag=0;
this_sum=a[i];
if (this_sum>max){
max=this_sum;
flag=1;
}
if (flag)
best_from=i+1;
}
if (sum<this_sum){
sum=this_sum;
best_to=i+1;
}
}
cout<<"Case "<<t<<':'<<endl;
cout<<sum<<' '<<best_from<<' '<<best_to<<endl;
if (t<T)
cout<<endl;
t++;
}
return 0;
}
还是不行
展开
 我来答
百度网友c438d1ee3
2010-04-11 · TA获得超过930个赞
知道小有建树答主
回答量:294
采纳率:0%
帮助的人:200万
展开全部
你的程序有点烦琐,给你个参考下,

#include <iostream>
using namespace std;

int a[100001];
int main()
{
int i,k,t,n;
scanf("%d",&t);
for(k=1;k<=t;k++)
{
int start=1,end,temp=1,sum=0,ans=-9999;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<=n;i++)
{
sum+=a[i];
if(sum>ans)
{
ans=sum;
start=temp;
end=i;
}
if(sum<0)
{
sum=0;
temp=i+1;
}
}
printf("Case %d:\n",k);
printf("%d %d %d\n",ans,start,end);
if(k!=t)
printf("\n");
}
return 0;
}
stomachcao
2010-04-12 · TA获得超过6261个赞
知道大有可为答主
回答量:2276
采纳率:75%
帮助的人:710万
展开全部
做任务中 ,一会回来回答
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式