順序表應用7 最大子段和之分治遞迴法

2021-07-23 04:03:03 字數 1326 閱讀 2585

這個題做的我一臉懵逼。

time limit: 10ms

memory limit: 400kb

submit

statistic

problem description

給定n(1<=n<=50000)個整數(可能為負數)組成的序列a[1],a[2],a[3],…,a[n],求該序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。當所給的整數均為負數時定義子段和為0,依此定義,所求的最優值為: max,1<=i<=j<=n。 例如,當(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)時,最大子段和為20。

注意:本題目要求用分治遞迴法求解,除了需要輸出最大子段和的值之外,還需要輸出求得該結果所需的遞迴呼叫總次數。

#include

int count=0;

int main()

int fib(int n)

input

第一行輸入整數n(1<=n<=50000),表示整數序列中的資料元素個數;

第二行依次輸入n個整數,對應順序表中存放的每個資料元素值。

output

一行輸出兩個整數,之間以空格間隔輸出:

第乙個整數為所求的最大子段和;

第二個整數為用分治遞迴法求解最大子段和時,遞迴函式被呼叫的總次數。

example input

6

-2 11 -4 13 -5 -2

example output

20 11

hint

author

#include#includeusing namespace std;

int cnt;

typedef struct

list;

void initlist(list &l)

void creatlist(list &l, int n)

int maxn(list &l, int l, int r)

else

{int mid=(l+r)/2;

int lsum=maxn(l, l, mid);

int rsum=maxn(l, mid+1, r);

int sum=0, max1=0, max2=0;

for(int i=mid;i>=l;--i)

{sum+=l.data[i];

if(max1>n;

initlist(l);

creatlist(l, n);

cnt=0;

int s=maxn(l, 0, n-1);

cout<

分治演算法 順序表應用7 最大子段和之分治遞迴法

problem description 給定n 1 n 50000 個整數 可能為負數 組成的序列a 1 a 2 a 3 a n 求該序列如a i a i 1 a j 的子段和的最大值。當所給的整數均為負數時定義子段和為0,依此定義,所求的最優值為 max,1 i j n。例如,當 a 1 a 2 ...

順序表應用7 最大子段和之分治遞迴法

time limit 10ms memory limit 400kb problem description 給定n 1 n 50000 個整數 可能為負數 組成的序列a 1 a 2 a 3 a n 求該序列如a i a i 1 a j 的子段和的最大值。當所給的整數均為負數時定義子段和為0,依此定...

順序表應用7 最大子段和之分治遞迴法

problem description 給定n 1 n 50000 個整數 可能為負數 組成的序列a 1 a 2 a 3 a n 求該序列如a i a i 1 a j 的子段和的最大值。當所給的整數均為負數時定義子段和為0,依此定義,所求的最優值為 max,1 i j n。例如,當 a 1 a 2 ...