数据结构与算法分析——分治法
#include<stdio.h> int bigger(int a,int b) { return (a>b?a:b); } int max(int a,int b,int c) { return bigger(a,bigger(b,c)); } int maxsubsequencesum(const int A[],int left,int right) { int maxleftsum,maxrightsum; int maxleftbordersum,maxrightbordersum; int leftbordersum,rightbordersum; int centre; if(left==right) { if(A[left]>0) return A[left]; else return 0; } centre = (left+right)/2; maxleftsum=maxsubsequencesum(A,left,centre); maxrightsum=maxsubsequencesum(A,centre+1,right); maxleftbordersum=0;leftbordersum=0; for (int i = centre; i >= left; --i) { leftbordersum+=A[i]; if(leftbordersum>maxleftbordersum) maxleftbordersum=leftbordersum; } maxrightbordersum=0;rightbordersum=0; for (int i = centre+1; i<=right;++i) { rightbordersum+=A[i]; if(rightbordersum>maxrightbordersum) maxrightbordersum=rightbordersum; } return max(maxleftsum,maxrightsum,maxrightbordersum+maxleftbordersum); } int main() { int n; scanf("%d",&n); int A[100]; for (int i = 0; i < n; ++i) { scanf("%d",&A[i]); } printf("%d\n",maxsubsequencesum(A,0,n-1)); }
看了一下午,终于把算法时间复杂度看完!
然后学着来敲这个O(NlogN)的分治法找最大连续和,这堆代码主要是找4,-3,5,-2,-1,2,6,-2的最大连续和(当然也适用于其他数列)。
主要感想和问题:
首先遇到了scope的问题,没搞清楚const和extern,intern,auto,register,static的区别!
然后是日常的敲错了代码运动不起来,模仿了两次都不行,然后最后一下自己推倒重来!果然看书上代码不能照搬,一定要彻底理解了再动手自己亲自敲。