实例1.1 最大子列和问题
分数 20
作者 DS课程组
单位 浙江大学
给定K个整数组成的序列{ N1, N2, ..., NK },“连续子列”被定义为{ Ni, Ni+1, ..., Nj },其中 1≤i≤j≤K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。
本题旨在测试各种不同的算法在各种数据情况下的表现。各组测试数据特点如下:
- 数据1:与样例等价,测试基本正确性;
- 数据2:102个随机整数;
- 数据3:103个随机整数;
- 数据4:104个随机整数;
- 数据5:105个随机整数;
输入格式:
输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。
输出格式:
在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。
输入样例:
6
-2 11 -4 13 -5 -2
输出样例:
20
代码长度限制
16 KB
时间限制
50000 ms
内存限制
64 MB
C++ (g++)
方法一:复杂度n^2。
int MaxSubseqSum1(int List[], int N) {
int thisSum, maxSum = 0;
int i, j;
for (i = 0; i < N; i++) {
thisSum = 0;
for (j = i; j < N; j++) {
thisSum += List[j];
if (thisSum > maxSum) {
maxSum=thisSum;
}
}
}
return maxSum;
}
方法二:分治法
int Max2(int A, int B, int C) {
return A > B ? A > C ? A : C : B > C ? B : C;
}//三个数最大的。
int DivideAndConquer(int List[], int left, int right) {
int maxLeftSum, maxRightSum;
int maxLeftBorderSum, maxRightBorderSum;
int leftBorderSum, rightBorderSum;
int center, i;
if (left == right) {
if (List[left] > 0) {
return List[left];
} else {
return 0;
}
}
center = (left + right) / 2;
//左、右部分的最长子串和
maxLeftSum = DivideAndConquer(List, left, center);
maxRightSum = DivideAndConquer(List, center + 1, right);
//下面开始计算中间部分的最长子串和
maxLeftBorderSum = 0;
leftBorderSum = 0;
for (i = center; i >= left; i--) {
leftBorderSum += List[i];
if (leftBorderSum > maxLeftBorderSum) {
maxLeftBorderSum = leftBorderSum;
}
}
maxRightBorderSum=0;
rightBorderSum=0;
for(i=center+1;i<=right;i++)
{
rightBorderSum+=List[i];
if(rightBorderSum>maxRightBorderSum)
{
maxRightBorderSum=rightBorderSum;
}
}
return Max2(maxLeftSum,maxRightSum,maxRightBorderSum+maxLeftBorderSum);//返回“治”结果
}
总代码如下:
#include<stdio.h>
#include <stdlib.h>
int Max2(int A, int B, int C) {
return A > B ? A > C ? A : C : B > C ? B : C;
}
int DivideAndConquer(int List[], int left, int right) {
int maxLeftSum, maxRightSum;
int maxLeftBorderSum, maxRightBorderSum;
int leftBorderSum, rightBorderSum;
int center, i;
if (left == right) {
if (List[left] > 0) {
return List[left];
} else {
return 0;
}
}
center = (left + right) / 2;
maxLeftSum = DivideAndConquer(List, left, center);
maxRightSum = DivideAndConquer(List, center + 1, right);
maxLeftBorderSum = 0;
leftBorderSum = 0;
for (i = center; i >= left; i--) {
leftBorderSum += List[i];
if (leftBorderSum > maxLeftBorderSum) {
maxLeftBorderSum = leftBorderSum;
}
}
maxRightBorderSum=0;
rightBorderSum=0;
for(i=center+1;i<=right;i++)
{
rightBorderSum+=List[i];
if(rightBorderSum>maxRightBorderSum)
{
maxRightBorderSum=rightBorderSum;
}
}
return Max2(maxLeftSum,maxRightSum,maxRightBorderSum+maxLeftBorderSum);
}
int main() {
int n;
scanf("%d", &n);
int list[n];
for (int i = 0; i < n; ++i) {
scanf("%d", &list[i]);
}
printf("%d\n", DivideAndConquer(list,0,n-1));
}