读算法导论当中的最大子数组当中的分治算法,涉及到的问题是怎么从FIND_MAX_SUBARRAY()函数当中返回三个参数,所以用了vector来返回,总感觉不是太好,太浪费空间了,但也没想到其他办法。
int max_left,max_right,sum;
int FIND_MAX_CROSSING_SUBARRAY(int a[],int low,int mid,int high)
{int sum1=0;
int left_sum=-1000;
sum1=0;
for(int i=mid;i>=low;i--)
{sum1=sum1+a[i];
if(sum1>left_sum)
{left_sum=sum1;
max_left=i;}
}
int right_sum=-1000;
sum1=0;
for(int j=mid+1;j<=high;j++)
{ sum1=sum1+a[j];
if(sum1>right_sum)
{right_sum=sum1;
max_right=j;}
}
sum1=left_sum+right_sum;
return sum1;
}
vector<int> FIND_MAX_SUBARRAY(int a[],int low,int high)
{int middle;
int left_sum=0;
int right_sum=0;
int left_low,left_high;
int right_low,right_high;
int cross_low,cross_high;
int cross_sum=0;
//vector<int> vec;
if(high==low)
{
vector<int> t1;t1.push_back(low);t1.push_back(high);t1.push_back(a[low]);
return t1;}
else
{middle=(low+high)/2;
vector<int>left;
left=FIND_MAX_SUBARRAY(a,low,middle);
left_low=left[0];left_high=left[1];left_sum=left[2];
vector<int> right;
right=FIND_MAX_SUBARRAY(a,middle+1,high);
right_low=right[0];right_high=right[1];right_sum=right[2];
cross_sum=FIND_MAX_CROSSING_SUBARRAY(a,low,middle,high);
if((left_sum>=right_sum)&&(left_sum>=cross_sum))
{vector<int> l;l.push_back(left_low);l.push_back(left_high);l.push_back(left_sum);
return l;
}
if((right_sum>=left_sum)&&(right_sum>=cross_sum))
{vector<int> r;r.push_back(right_low);r.push_back(right_high);r.push_back(right_sum);
return r;
}
else
{vector<int> cm;
cm.push_back(max_left);cm.push_back(max_right);cm.push_back(cross_sum);
return cm;}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
cout<<"2\t\115\n";
int b[]={4,-2,3,1,-90,-2,9,-7,5};vector<int> zonghe;
zonghe=FIND_MAX_SUBARRAY(b,0,8);
//int sum4=FIND_MAX_CROSSING_SUBARRAY(b,0,2,4);
cout<<zonghe[0]<<" "<< zonghe[1]<<" "<< zonghe[2]<<endl;
return 0;
}