Divide-and-conquer law is generally divided into three steps.
Partitioning Issues : divides an instance of the problem into sub-problems.
Recursive Solution: Solving sub-problems recursively.
Merging problem: The solution of the merging sub-problem gets the solution of the original problem.
1#include <stdio.h>2#include <string.h>3#include <algorithm>4 using namespacestd;5 6 Const intMAXN =10000+5;7 8 intA[MAXN];9 Ten intMaxsum (intAintXintY) {//returns the maximum contiguous and continuous array in the left closed right open interval [x, y) One intV, L, R; A if(Y-x = =1)returnA[X];//only one element, directly returning - intm = x + (y-x)/2;//Divide and conquer the first step: Divided into [x,m] and [M,y] - intMAXS = Max (Maxsum (A, X, M), Maxsum (A, M, y));//Divide and conquer the second step: recursive solution thev =0; L = a[m-1];//Divide and conquer step Three: Merge (1)--from the dividing point to the left of the largest continuous and L - for(inti = m1; I >= x; i--) L = max (L, v + =a[i]); -v =0; R = A[m];//Divide and conquer step three: Merge (2)--maximum continuous and r from the dividing point to the right - for(inti = m; i < Y; i++) R = Max (r, v + =a[i]); + returnMax (MAXS, l+r);//the solution of the problem of the handle L and R comparison - } + A intMain () { at intT, N; -scanf"%d", &T); - while(t--){ -scanf"%d", &n); - for(inti =0; I < n; i++){ -scanf"%d", &a[i]); in } - intMaxs = Maxsum (A,0, n); toprintf"%d\n", MAXS); + } -}
Divide and conquer the method to seek maximum continuous and.