自己写了半个小时没有耐心写下去了就查了查这个算法到底是怎么写的,刚开始看伪代码能看的懂,但是就是写不出来代码这是我原来写的代码刚开始写的第一个函数但是写到递归就开始乱了。
//#include<iostream>
//#include<vector>
//using namespace std;
//typedef std::vector<int> npt;
//void FIND_MAX_CROSSING_SUBARRAY(const npt &A,int low,int high,int &max_left,int &max_right) {
//
// int sum = A[0];
// int mid = (low + high) / 2;
// int left_sum = A[0];
// max_left = 0;
// for (int i = 1; i < mid; i++)
// {
// sum += A[i];
// if (sum > left_sum)
// {
// left_sum = sum;
// max_left = i;
// }
// }
// int sum = A[mid];
// int right_sum = A[mid];
// max_right = mid;
// for (int i = mid; i < high; i++)
// {
// sum += A[i];
// if (sum > right_sum)
// {
// right_sum = sum;
// max_right = i;
// }
// }
//
//}
//
//void FIND_MAXIMUM_SUMARRAY(npt &A, int &cross_low, int &cross_high) {
//
//
// if (A.size() == 1)
// {
// cout << "base case : only one element" << endl;
// cross_low = 1;
// cross_high = 1;
// }
// else
// {
// int mid = (A.size + 1) / 2;
// int left_low = 0;
// int left_high = 0;
// int left_sum = 0;
// FIND_MAXIMUM_SUMARRAY()
// }
//}
这是人家写的代码
#include<iostream>
using namespace std;
//寻找跨越中点的最大子数组;
void find_crossing_subarray(int*a, int low, int mid, int high, int& start, int& end, int& max_sum) {
int left_sum = INT32_MIN;
int sum = 0;
for (int i = mid; i >= low; i--) {
sum += a[i];
if (sum>left_sum) {
start = i;
left_sum = sum;
}
}
int right_sum = INT32_MIN;
sum = 0;
for (int i = mid + 1; i <= high; i++) {
sum += a[i];
if (sum > right_sum) {
end = i;
right_sum = sum;
}
}
max_sum = left_sum + right_sum;
}
void find_maximum_subarray(int*a, int low, int high, int&start, int&end, int&max_sum) {
if (high == low) {
start = low;
end = high;
max_sum = a[high];
}
else {
int mid = (high + low) / 2;
//查找中点左侧的最大子数组;
int left_start, left_end, left_sum;
find_maximum_subarray(a, low, mid, left_start, left_end, left_sum);
//寻找中点右侧的最大子数组;
int right_start, right_end, right_sum;
find_maximum_subarray(a, mid + 1, high, right_start, right_end, right_sum);
int cross_start, cross_end, cross_sum;
//寻找跨越中点的最大子数组;
find_crossing_subarray(a, low, mid, high, cross_start, cross_end, cross_sum);
//将三种情况的最大值设为当前数组的最大子数组;
if ((left_sum >= cross_sum) && (left_sum >= right_sum)) {
start = left_start;
end = left_end;
max_sum = left_sum;
}
else if ((cross_sum >= left_sum) && (cross_sum >= right_sum)) {
start = cross_start;
end = cross_end;
max_sum = cross_sum;
}
else {
start = right_start;
end = right_end;
max_sum = right_sum;
}
}
}
int main() {
int n;
cin >> n;
int a[1000];
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
int max = 0, start = 0, end = 0;
find_maximum_subarray(a, 0, n - 1, start, end, max);
cout << max << endl;
}
希望后来会慢慢的好起来
转自https://www.cnblogs.com/lif323/p/7397756.html