本系列是网易云课堂浙大数据结构课程的一些笔记。课程配套了一些编程练习,以加深理解与编程能力。提高编程的方法无他,唯多看,多练,多思考。
首先介绍了一些基本的算法概念,分析。
然后给出了一个求最大子序列和的例子,给出了四种时间复杂度不同算法实现,可以体会到算法的有效设计对程序效率的影响是很大的,特别是数据集很大的时候。
#include <iostream>
#include <stack>
#include <time.h>
#include <vector>
#define MAX 100001
using namespace std;
int p = 0, q = 0;
/*求最大子序列和问题*/
/*算法一:蛮力法:找出所有子序列和,比较取最大的,时间复杂度O(N^3)*/
int MaxSubseqSum1(int A[], int N) {
int ThisSum, MaxSum = 0;
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
ThisSum = 0;
for (int k = i; k < j; k++) {
ThisSum += A[k];
if (ThisSum > MaxSum)
MaxSum = ThisSum;
}
}
}
return MaxSum;
}
/*算法二:蛮力法的改进,每次循环一遍不用从头开始加,时间复杂度O(N^2)*/
int MaxSubseqSum2(int A[], int N) {
int ThisSum, MaxSum = 0;
for (int i = 0; i < N; i++) {
ThisSum = 0;
// p = i;
for (int j = i; j < N; j++) {
ThisSum += A[j]; //加一项即可
if (ThisSum > MaxSum) {
MaxSum = ThisSum;
p = i;
q = j;
}
}
}
return MaxSum;
}
int MAX3(int A, int B, int C) { return A > B ? A > C ? A : C : B > C ? B : C; }
int DivedAndConquer(int List[], int left, int right) {
int MaxLeftSum = 0, MaxRightSum = 0, LeftBorderSum = 0, RightBorderSum = 0,
MaxLeftBorderSum = 0, MaxRightBorderSum = 0;
int certer = 0, i;
//递归终止条件
if (left == right) {
if (List[left] > 0)
return List[left];
else
return 0;
}
//分
certer = (left + right) / 2;
MaxLeftSum = DivedAndConquer(List, left, certer);
MaxRightSum = DivedAndConquer(List, certer + 1, right);
//寻找跨边界的最大
for (i = certer; i < left; i--) {
LeftBorderSum += List[i];
if (LeftBorderSum > MaxLeftBorderSum)
MaxLeftBorderSum = LeftBorderSum;
}
for (i = certer + 1; i < right; i++) {
RightBorderSum += List[i];
if (RightBorderSum > MaxRightBorderSum)
MaxRightBorderSum = RightBorderSum;
}
//治
return MAX3(MaxLeftSum, MaxRightSum, MaxLeftBorderSum + MaxRightBorderSum);
}
/*算法三:分而治之:时间复杂度O(N*logN)*/
int MaxSubseqSum3(int List[], int N) { return DivedAndConquer(List, 0, N - 1); }
/*算法四:在线处理。时间复杂度O(N)*/
int MaxSubseqSum4(int A[], int N) {
int ThisSum = 0, MaxSum = 0;
for (int i = 0; i < N; i++) {
ThisSum += A[i];
if (ThisSum > MaxSum)
MaxSum = ThisSum;
else if (ThisSum < 0)
ThisSum = 0;
}
return MaxSum;
}
int main() {
int A[MAX], MaxSum = 0;
int x, N, i, j = 0;
cin >> N;
for (i = 0; i < N; i++) {
cin >> A[i];
}
for (i = 0; i < N; i++) {
if (A[i] < 0)
j++;
}
if (j == N) {
MaxSum = 0;
p = 0, q = N;
cout << MaxSum << " " << p << " " << q << endl;
} else {
MaxSum = MaxSubseqSum2(A, N);
cout << MaxSum << " " << p << " " << q << endl;
}
}