題目來源:http://ac.jobdu.com/problem.php?pid=1011
我的代碼:超時
//c語言中,數學函數除了求整數的絕對值函數abs()之外<abs() 定義在stdlib.h中>,其餘的函數都在頭文件 math.h 中定義,包括對浮點數求絕對值的函數fabs()。
//c++中,包含的相應的頭文件爲,原則是前面加c,同時去掉.h 。
//例如:
//#include <cstdlib>對應 #include <stdlib.h>
//#include <cmath>對應 #include <math.h>
#include <iostream>
#include <cstdlib>
using namespace std;
int m;
int a[10000];
int lesss,moree;
int maxx;
//int sum=0;
int pick(int low,int high,int& les,int& mor){//總是假設序列從一個正數開始
if (low==high&&a[low]<0){
m=0;
les=0;
mor=high;
return 0;
}
if(low>high) return 0;
int ma=a[low];
int sum=0;
int less=low;
int more=low;
while(a[++more]>=0&&more<=high){
// more=low+1;
ma+=a[more];
}
more--;
int i=more+1;
while (a[more]==0&&more>low) more--;
while (a[less]==0&&(less+1)<=more) less++;
for(;i<=high;i++){
if(a[i]>=0) break;
sum+=a[i];
}
maxx=pick(i,high,lesss,moree);
int summ=abs(sum);
if(maxx>summ){
if((ma-summ+maxx)>=maxx){
ma=ma-summ+maxx;
more=moree;
}
else if((ma-summ+maxx)<maxx){
less=lesss;
more=moree;
ma=maxx;
}
}
else if(maxx<=summ)
if(ma<maxx){
less=lesss;
more=moree;
ma=maxx;
}
les=less;
mor=more;
return ma;
}
int main(){
int k;
while(cin>>k){
if (k==0) return 0;
for(int i=0;i<k;i++)
cin>>a[i];
int less=0,more=k-1;
int i;
for(i=0;i<k;i++)
if(a[i]>=0) break;
m= pick(i,k-1,less,more);
cout<<m<<" "<<a[less]<<" "<<a[more]<<endl;
}
return 0;
}
#include<stdio.h>
#define
Max 10000
int
main(){
int
maxsofar;
int
maxendinghere;
int
begin,end,temp;
int
x[Max];
int
i,n;
int
count;
while
(
scanf
(
"%d"
,&n),n>0){
for
(i=0;i<n;i++)
scanf
(
"%d"
,&x[i]);
count
= 0;
maxsofar
= maxendinghere = 0;
begin
= end = temp = 0;
for
(i=0;i<n;i++){
if
(x[i]<0)
count++;
maxendinghere
+= x[i];
if
(maxendinghere<=0){
maxendinghere
= 0;
temp
= i+1;
}
if
(maxendinghere>maxsofar){
maxsofar
= maxendinghere;
begin
= temp;
end
= i;
}
if
(maxendinghere==0&&maxsofar==0&&x[i]==0)
end
= begin = i;
}
if
(count==n)
printf
(
"0
%d %d\n"
,x[0],x[n-1]);
else
printf
(
"%d
%d %d\n"
,maxsofar,x[begin],x[end]);
}
}