01-复杂度1 最大子列和问题 (20分)
给定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
//求最大子列和三种方法用时比较
//1.穷举法 2.在线处理 3.分而治之
//the time complexity of the first is O(n2), the second is O(n), the third is O(nlgn).
#include <iostream>
#include <time.h>
#define NUM 100
using namespace std;
int list[NUM];
int compare(int a, int b, int c);
int maxSequence1(int list[], int num);
int maxSequence2(int list[], int num);
int maxSequence3(int list[], int left, int right);
clock_t start, end;
double duration;
int main(){
int max;
int num, n = 0;
while(cin>>num){
list[n] = num;
n++;
}
method_1:
start = clock();
for(int count = 0; count<=1e6; count++){
max = maxSequence1(list, n);
}
cout<<"max1="<<max<<endl;
end = clock();
duration = ((double)(end - start))/CLK_TCK;
cout<<"method 1 lasts "<<duration<<"s"<<endl;
method_2:
start = clock();
for(int count = 0; count<=1e6; count++){
max = maxSequence2(list, n);
}
cout<<"max2="<<max<<endl;
end = clock();
duration = ((double)(end - start))/CLK_TCK;
cout<<"method 2 lasts "<<duration<<"s"<<endl;
mehtod_3:
start = clock();
for(int count = 0; count<=1e6; count++){
max = maxSequence3(list, 0, n);
}
cout<<"max3="<<max<<endl;
end = clock();
duration = ((double)(end - start))/CLK_TCK;
cout<<"method 3 lasts "<<duration<<"s"<<endl;
return 0;
}
int compare(int a, int b, int c){
return a > b ? a > c ? a : c : b > c ? b : c;
}
int maxSequence1(int list[], int num){
int max = 0;
for(int i = 0; i < num; i++){
int tempMax = 0;
for(int j = i; j < num; j++){
tempMax += list[j];
if(tempMax > max){
max = tempMax;
}
}
}
return max;
}
int maxSequence2(int list[], int num){
int tempMax = 0;
int max = 0;
for(int i = 0; i < num; i++){
tempMax += list[i];
if(tempMax < 0){
tempMax = 0;
}
else if(tempMax > max){
max = tempMax;
}
}
return max;
}
int maxSequence3(int list[], int left, int right){
int leftMax, rightMax;
if(left == right){
// if(list[left] == 0){
// return list[left];
// }
// else{
// return 0;
// }
return list[left];
}
int middle;
middle = (left + right) / 2;
leftMax = maxSequence3(list, left, middle);
rightMax = maxSequence3(list, middle+1, right);
int tempLeft = 0, tempRight = 0;
int leftBorderMax = 0, rightBorderMax = 0;
for(int i = middle; i >= left; i--){
tempLeft += list[i];
if(tempLeft > leftBorderMax){
leftBorderMax = tempLeft;
}
}
for(int i = middle+1; i<= right; i++){
tempRight += list[i];
if(tempRight > rightBorderMax){
rightBorderMax = tempRight;
}
}
int middleMax = rightBorderMax + leftBorderMax;
return compare( leftMax, rightMax, middleMax);
}