最大子陣列問題--分治法的思想
國外經典教材《演算法導論》P67頁提到了最大子陣列的問題,書中給出兩種解答方法,分別是暴力求解的方法,分治策略的求解方法。在杭電 ACM OJ 中也有一條類似的題目,連線如下:http://acm.hdu.edu.cn/showproblem.php?pid=1003
Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 255763 Accepted Submission(s): 60795
Problem Description Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.
Input The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000).
Output For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases.
Sample Input 2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
Sample Output Case 1: 14 1 4 Case 2: 7 1 6
Author Ignatius.L 題目分析:若用暴力求解的方法去做,時間複雜度會是O(n^2),會出現時間超限的問題。暴力求解程式碼如下: #include<stdio.h>
int main()
{
int T;
int n;
int i;
scanf("%d",&T);
for(i=0;i<T;i++){
scanf("%d",&n);
int *p = new int [n];
int j;
for(j=0;j<n;j++){
scanf("%d",&p[j]);
}
int best;
int sum;
int first;
int end;
int k;
best = p[0];
first = end = 0; //關鍵求解過程
for(j=0;j<n;j++){
sum = 0;
for(k=j;k<n;k++){
sum += p[k];
if(best<sum){
best = sum;
first = j;
end = k;
}
}
}
printf("Case %d:\n",i+1);
printf("%d %d %d\n",best,first+1,end+1);
delete []p;
}
return 0;
}
分治策略思想: 1.把問題儘可能劃分為規模相等的子問題。 2.遞迴求解子問題 3.合併子問題的解得到原問題的解 #include<stdio.h>
struct node{
int first;
int end;
int summax;
node(int a,int b,int c):first(a),end(b),summax(c){}
};
node maxsum(int *p,int x,int y)
{
if(y-x==1||y==x){
return node(x+1,x+1,p[x]); //只有一個數
}
int mid = (x+y)/2; //分治第一步:劃分[x,mid)和[mid,y)
node maxsl = maxsum(p,x,mid);
node maxsr = maxsum(p,mid,y); //分治第二步:遞迴求解
node maxs = maxsl.summax>=maxsr.summax?maxsl:maxsr;
int L,R,sum,i,a=mid-1,b=mid;
L = p[mid-1];
sum = 0; //分治第三步:合併(1)——從分界點開始往左求最大連續和L
for(i=mid-1;i>=x;i--){
sum+=p[i];
if(sum>=L){
L = sum;
a = i;
}
}
R = p[mid];
sum = 0; //分治第三步:合併(2)——從分界點開始往右求最大連續和R
for(i=mid;i<y;i++){
sum+=p[i];
if(sum>R){
R = sum;
b = i;
}
}
if(maxs.summax>L+R){
return maxs;
}
else{
return node(a+1,b+1,L+R);
}
}
int main()
{
int T,i;
scanf("%d",&T);
for(i=0;i<T;i++){
int n,j;
int *p;
scanf("%d",&n);
p = new int [n];
for(j=0;j<n;j++){
scanf("%d",&p[j]);
}
node maxs = maxsum(p,0,n);
printf("Case %d:\n",i+1);
printf("%d %d %d\n",maxs.summax,maxs.first,maxs.end);
if(i!=T-1){
printf("\n");
}
}
return 0;
}
另外網上對於該題還有動態規劃(dp)等的求解方法,連結如下:http://blog.csdn.net/hcbbt/article/details/10454947