顺序表应用7:最大子段和之分治递归法
Problem Description
给定n(1<=n<=50000)个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整数均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n。 例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。
注意:本题目要求用分治递归法求解,除了需要输出最大子段和的值之外,还需要输出求得该结果所需的递归调用总次数。
递归调用总次数的获得,可以参考以下求菲波那切数列的代码段中全局变量count的用法:
#include
int count=0;
int main()
{
int n,m;
int fib(int n);
scanf("%d",&n);
m=fib(n);
printf("%d %d\n",m,count);
return 0;
}
int fib(int n)
{
int s;
count++;
if((n==1)||(n==0)) return 1;
else s=fib(n-1)+fib(n-2);
return s;
}
Input
第一行输入整数n(1<=n<=50000),表示整数序列中的数据元素个数;
第二行依次输入n个整数,对应顺序表中存放的每个数据元素值。
Output
一行输出两个整数,之间以空格间隔输出:
第一个整数为所求的最大子段和;
第二个整数为用分治递归法求解最大子段和时,递归函数被调用的总次数。
Example Input
6 -2 11 -4 13 -5 -2
Example Output
20 11
Hint
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define Maxsize 50000
using namespace std;
typedef int element;
typedef struct
{
element *elem;
int length;
int listsize;
} Sqlist;
int cnt;
int InitList(Sqlist &L)
{
L.elem = new element[Maxsize];
if(!L.elem)
return -1;
L.length = 0;
L.listsize = Maxsize;
return 1;
}
void creat(Sqlist &L, int n)
{
for(int i = 0; i < n; i++)
scanf("%d", &L.elem[i]);
L.length = n;
}
int Msum(Sqlist &L, int b, int mid, int e)
{
int s1=0,s2=0,s=0;
for(int i = mid; i >= b; i--)
{
s += L.elem[i];
if(s > s1)
s1 = s;
}
s=0;
for(int i = mid+1; i <= e; i++)
{
s += L.elem[i];
if(s > s2)
s2 = s;
}
return s1+s2;
}
int Msub(Sqlist &L, int b, int e)
{
if(b < e)
{
cnt++;
int mid=(b+e)/2;
int a = Msub(L, b, mid);
int b1 = Msub(L, mid+1, e);
int c = Msum(L, b, mid, e);
return max(c, max(a, b1));
}
if(b == e)
{
cnt++;
return L.elem[b];
}
}
int main()
{
Sqlist L;
int n;
scanf("%d", &n);
InitList(L);
creat(L, n);
cnt=0;
int ss = Msub(L, 0, n-1);
printf("%d %d\n", ss, cnt);
return 0;
}