标签:
对于最优化的子数组问题,一名话,就是从给你的数组中寻找一个子数组,使得它的和是最优的(最大/最小)如果数组中元素全是正的,那么好办,整个数组的和就是了。如果数组中元素全是负的,那么也好办,找最小的那个。但是如果正负相间呢???
#include<iostream>
#define MIN -255;
struct returnVal{
int left;
int right;
int sum;
};
struct returnVal*findMaxCrossingSubarray(int left,int mid ,int right,int *arr);
struct returnVal *findMaxSubarray(int left,int right ,int *arr);
struct returnVal*findMaxCrossingSubarray(int left,int mid ,int right,int *arr){
int leftMaxSum=MIN;
int sum=0;
int maxLeft=0;
int i,j;
for(i=mid ; i>=left; i--){
sum+=arr[i];
if(sum>leftMaxSum){
leftMaxSum=sum;
maxLeft=i;
}
}
sum=0;
int rightMaxSum=MIN;
int maxRight=0;
for(int j=mid+1; j<=right; j++){
sum+=arr[j];
if(sum>rightMaxSum){
rightMaxSum=sum;
maxRight=j;
}
}
struct returnVal *val=new returnVal;
val->left=maxLeft;
val->right=maxRight;
val->sum=rightMaxSum+leftMaxSum;
return val;
}
inline struct returnVal* maxThree_returnVal(struct returnVal *left,struct returnVal *mid,struct returnVal *right){
if(left->sum>=mid->sum&&left->sum>=right->sum){
return left;
}
if(right->right>=left->sum&&right->sum>=mid->sum){
return right;
}
if(mid->sum>=left->sum&&mid->sum>=right->sum){
return mid;
}
}
struct returnVal *findMaxSubarray(int left,int right ,int *arr){
if(left==right){
struct returnVal *val=new returnVal;
val->left=left;
val->right=right;
val->sum=arr[left];
return val;
}
struct returnVal *valRight;
struct returnVal *valCross;
struct returnVal *valLeft;
int mid=(left+right)/2;
valLeft=findMaxSubarray(left,mid,arr);
valRight=findMaxSubarray(mid+1,right,arr);
valCross=findMaxCrossingSubarray(left,mid,right,arr);
return maxThree_returnVal(valLeft,valCross,valRight);
}
int arr[16]={13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
int main(){
struct returnVal *val=new returnVal;
val=findMaxSubarray(0,15,arr);
std::cout<<val->left<<","<<val->right<<","<<val->sum<<std::endl;
}
标签:
原文地址:http://www.cnblogs.com/yml435/p/4655522.html