example1
- http://acm.hdu.edu.cn/showproblem.php?pid=1003
- 比大多数提交都要耗时
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/10f3507d2f7fa28cc28de40caa0b2821.png)
#include<iostream>
#include<string.h>
using namespace std;
void getCrossMax(int number[],int L,int mid,int R,int &LOfMax,int &ROfMax,int &max){
int tempL = mid;
int tempR = mid+1;
int LMax = -1001;
for(int sum=0;tempL>=L;--tempL){
//找左边的最大
sum += number[tempL];
if(sum >= LMax){
LOfMax = tempL;
LMax = sum;
}
}
int RMax = -1001;
for(int sum=0;tempR<=R;++tempR){
//找右边的最大
sum += number[tempR];
if(sum>RMax){
ROfMax = tempR;
RMax = sum;
}
}
max = LMax + RMax;
}
void getMax(int number[],int L,int R,int &LOfMax,int &ROfMax,int &max){
//分治法
if(L==R){
LOfMax = L;
ROfMax = R;
max = number[L];
}else{
int mid = (L+R)/2;
int LOfL,ROfL,LMax;
getMax(number,L,mid,LOfL,ROfL,LMax);
int LOfR,ROfR,RMax;
getMax(number,mid+1,R,LOfR,ROfR,RMax);
int LOfMid,ROfMid,MidMax;
getCrossMax(number,L,mid,R,LOfMid,ROfMid,MidMax);
if(LMax>=RMax && LMax>MidMax){
LOfMax = LOfL;
ROfMax = ROfL;
max = LMax;
}else{
if(RMax > MidMax){
LOfMax = LOfR;
ROfMax = ROfR;
max = RMax;
}else{
LOfMax = LOfMid;
ROfMax = ROfMid;
max = MidMax;
}
}
}
}
int main(){
int totalAmount,eachAmount;
cin>>totalAmount;
int number[100000];
for(int i=0;i<totalAmount;++i){
cin>>eachAmount;
for(int j=0;j<eachAmount;++j){
cin>>number[j];
}
int L,R,max;
getMax(number,0,eachAmount-1,L,R,max);
cout<<"Case "<<i+1<<":"<<endl;
cout<<max<<" "<<L+1<<" "<<R+1<<endl;//答案从1开始
if(i+1 != totalAmount){
cout<<endl;
}
}
}