与杭电的max sum plus plus相同。
我用那个代码,把m改成2上交就ac了(两个字段)
代码如下:
#include<stdio.h>
#include<stdlib.h>
int maxsum(int e[], int n, int m)
{
int *curr_best;
int *prev_best;
int max_sum, i, j;
curr_best = (int*)malloc(sizeof(int) * (n + 1));//分配,不初始化
prev_best = (int*)calloc(n + 1, sizeof(int));//分配,且每个元素初始化为0
*curr_best = 0;
e--;
for(i = 1; i <= m; ++i)
{
max_sum = -2147483648;
for(j = i; j <= n; ++j)
{
if(curr_best[j - 1] < prev_best[j - 1])//prev_best中存放的是i-1阶段的最大值
curr_best[j] = prev_best[j - 1] + e[j];
else
curr_best[j] = curr_best[j - 1] + e[j];
prev_best[j - 1] = max_sum;
if(max_sum < curr_best[j])
max_sum = curr_best[j];//prev_best中存放i阶段的最大值
}
prev_best[j - 1] = max_sum;//对第n个数赋值
}
free(prev_best);
free(curr_best);
return max_sum;
}
int main()
{
int i,n;
int *data;
while(scanf("%d",&n),n)
{
data=(int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
scanf("%d",&data[i]);
printf("%d\n",maxsum(data,n,2));
free(data);
}
return 0;
}