自己敲出来的,先把代码贴上来,晚上有时间再写总结
#include<stdio.h> #define N 10 struct Max{ int low; int high; int sum; }; int a[N]; Max Findcrossing(int* a,int low,int middle,int high); Max FindSub(int* a,int low,int high); int main() { Max m; int i; for(i=0;i<N;i++) scanf("%d",&a[i]); m=FindSub(a,0,9); printf("%d\n%d\n%d",m.sum,m.low,m.high); return 0; } Max FindSub(int* a,int low,int high) { Max max_sub; Max max_left; Max max_right; Max max_cross; if(high==low) { max_sub.high=high; max_sub.low=low; max_sub.sum=a[low]; } else { int middle=(low+high)/2; max_left=FindSub(a,low,middle); max_right=FindSub(a,middle+1,high); max_cross=Findcrossing(a,low,middle,high); if(max_left.sum>=max_right.sum&&max_left.sum>=max_cross.sum) { max_sub.high=max_left.high; max_sub.low=max_left.low; max_sub.sum=max_left.sum; } else if(max_right.sum>=max_left.sum&&max_right.sum>=max_cross.sum) { max_sub.high=max_right.high; max_sub.low=max_right.low; max_sub.sum=max_right.sum; } else { max_sub.high=max_cross.high; max_sub.low=max_cross.low; max_sub.sum=max_cross.sum; } } return max_sub; } Max Findcrossing(int* a,int low,int middle,int high) { int i,j; Max max_cross; int left_i,sum_left=0,MAX_left=-10000; for(i=middle;i>=low;i--) { sum_left+=a[i]; if(sum_left>MAX_left) { MAX_left=sum_left; left_i=i; } } int right_j,sum_right=0,MAX_right=-10000; for(j=middle+1;j<=high;j++) { sum_right+=a[j]; if(sum_right>MAX_right) { MAX_right=sum_right; right_j=j; } } max_cross.sum=MAX_left+MAX_right; max_cross.low=left_i; max_cross.high=right_j; return max_cross; }
时间: 2024-10-13 19:36:40