#include <iostream>
#include <limits>
#include <vector>
#include <array>
#include <algorithm>
using namespace std;
array<int, 3> find_max_cross_subarray(int A[], int low, int mid, int high) {
int left_sum = numeric_limits<int>::min();
int max_left {};
int sum {};
for(int i = mid; i >= low; --i) {
sum += A[i];
if(sum > left_sum) {
left_sum = sum;
max_left = i;
}
}
int right_sum = numeric_limits<int>::min();
int max_right {};
sum = 0;
for(int i = mid + 1; i <= high; ++i) {
sum += A[i];
if(sum > right_sum) {
right_sum = sum;
max_right = i;
}
}
return array<int, 3>{ max_left, max_right, left_sum + right_sum };
}
array<int, 3> find_maximum_subarray(int A[], int low, int high) {
int mid {};
if(high == low)
return array<int, 3> { low, high, A[low] };
else {
mid = (low + high) / 2;
array<int, 3> left_maximum = find_maximum_subarray(A, low, mid);
array<int, 3> right_maximum = find_maximum_subarray(A, mid + 1, high);
array<int, 3> cross_mid_maximum = find_max_cross_subarray(A, low, mid, high);
if(left_maximum[2] >= right_maximum[2] && left_maximum[2] >= cross_mid_maximum[2])
return array<int, 3> { left_maximum[0], left_maximum[1], left_maximum[2] };
else if(right_maximum[2] >= left_maximum[2] && right_maximum[2] >= cross_mid_maximum[2])
return array<int, 3> { right_maximum[0], right_maximum[1], right_maximum[2] };
else
return array<int, 3> { cross_mid_maximum[0], cross_mid_maximum[1], cross_mid_maximum[2] };
}
}
int main(int argc, const char * argv[]) {
vector<int> input {};
cout << "please input the array :(you can input noninterger to finish your input)" << endl;
int element;
while(cin >> element) {
input.push_back(element);
}
int* A = new int[input.size()];
int index {};
for_each(input.begin(), input.end(), [=](int x)mutable{ A[index++] = x; });
array<int, 3> result = find_maximum_subarray(A, 0, static_cast<int>(input.size() - 1));
cout << "the max subarray from :" << result[0] + 1 << "th to "<< result[1] + 1 << "th, and the sum is : " << result[2] << endl;
delete []A;
}
算法导论-第四章-分治策略:最大子数组C++实现
最新推荐文章于 2021-01-12 21:29:20 发布