#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <limits.h>
using namespace std;
typedef struct Max_info
{
int low;
int high;
int max_sum;
}; //0 //7 15
int a[20] = {13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
Max_info getCrossMaxSubarray(int low,int mid,int high)
{
Max_info max_info;
//max_info.max_sum = -1000;
max_info.max_sum = _I32_MIN;//头文件limits.h中定义的 32bit数的最小值
int i,j,sum = 0;
for(i = mid;i>=low;i--)
{
sum += a[i];
if(sum > max_info.max_sum)
{
max_info.max_sum = sum;
max_info.low = i;
}
}
max_info.high = mid+1;
sum = max_info.max_sum + a[mid+1];
max_info.max_sum += a[mid+1];
for(j = mid+2;j<=high;j++)
{
sum += a[j];
if(sum > max_info.max_sum)
{
max_info.max_sum = sum;
max_info.high = j;
}
}
return max_info;
}
Max_info getMaxSubarray(int low,int high)
{
if(low == high)
{
Max_info max_info;
max_info.low = low;
max_info.high = high;
max_info.max_sum = a[low];
return max_info;
}
int mid = (low+high)/2;
Max_info Max_left = getMaxSubarray(low,mid);
Max_info Max_right = getMaxSubarray(mid+1,high);
Max_info Max_cross = getCrossMaxSubarray(low,mid,high);
if(Max_left.max_sum >= Max_right.max_sum && Max_left.max_sum >= Max_cross.max_sum)
return Max_left;
if(Max_right.max_sum >= Max_left.max_sum && Max_right.max_sum >= Max_cross.max_sum)
return Max_right;
else
return Max_cross;
}
int main()
{
Max_info result = getMaxSubarray(0,15);
cout<<"left:"<<result.low<<" high:"<<result.high<<" sum:"<<result.max_sum<<endl;
}
算法导论-求最大子数组-分治策略 c++版本
最新推荐文章于 2020-10-21 11:45:10 发布