1.问题描述
算法导论上38页,最大子数组给出一组数组来,然后求出使得从i到j的数组值的和最大的边界i与j。如果不用分治的方法的话,需要通过暴力方法来寻找n(n-1)/2种。
方法:
2代码:
#include<iostream>
using namespace std;
typedef struct maximum
{
int left;
int right;
int sum;
}Maximum;
Maximum* FIND_MAX_CROOSING_SUBARRAY(int *A,int low,int mid,int high);
Maximum* FIND_MAXIMUM_SUBARRAY(int *A,int low,int high);
Maximum* FIND_MAX_CROOSING_SUBARRAY(int *A,int low,int mid,int high)
{
Maximum *mymaximum=new Maximum;
int left_sum=INT_MIN;
int right_sum=INT_MIN;
int i,j;
int sum=0;
for(i=mid;i>=low;i--)
{
sum=sum+A[i];
if(sum>left_sum)
{
left_sum=sum;
mymaximum->left=i;
}
}
sum=0;
for(j=mid+1;j<=high;j++)
{
sum=sum+A[j];
if(sum>right_sum)
{
right_sum=sum;
mymaximum->right=j;
}
}
mymaximum->sum=left_sum+right_sum;
return mymaximum;
}
Maximum* FIND_MAXIMUM_SUBARRAY(int *A,int low,int high)
{
int mid;
Maximum *leftmymaximum=new Maximum;;
Maximum *rightmymaximum=new Maximum;
Maximum *mycross=new Maximum;
if(low!=high)
{
mid=(low+high)/2;
leftmymaximum=FIND_MAXIMUM_SUBARRAY(A,low,mid);
rightmymaximum=FIND_MAXIMUM_SUBARRAY(A,mid+1,high);
mycross=FIND_MAX_CROOSING_SUBARRAY(A,low,mid,high);
}
if(((leftmymaximum->sum)>=(rightmymaximum->sum))&&((leftmymaximum->sum)>=(mycross->sum)))
return leftmymaximum;
else if((rightmymaximum->sum)>=(leftmymaximum->sum)&&(rightmymaximum->sum)>=(mycross->sum))
return rightmymaximum;
else
return mycross;
}
int main(void)
{
int totalnum;
int i=1;
int t;
int *A=new int;
Maximum *mymaximum=new Maximum;
printf("您的数组一共有多少个数字?\n");
scanf("%d",&totalnum);
printf("请输入您要输入的数组?以-123\n");
for(i=1;i<=totalnum;i++)
scanf("%d",&A[i]);
mymaximum=FIND_MAXIMUM_SUBARRAY(A,1,totalnum);
printf("最大子数组的左边界是%d\n",mymaximum->left);
printf("最大子数组的右边界是%d\n",mymaximum->right);
printf("最大子数组的和是%d\n",mymaximum->sum);
return 0;
}
结果: