码迷,mamicode.com
首页 > 其他好文 > 详细

最大子序列-algorithms_3th

时间:2015-02-28 16:20:45      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void FIND_MAX_CROSSING_SUBARRAY(int * const A,const int &low,const int &mid,const int &high,int &max_left,int &max_right,int &max_sum){
 5     int sum = 0;
 6     int left_sum = A[mid];
 7     max_left=mid;
 8     for (auto i = mid; i > low; --i){
 9         sum += A[i];
10         if (sum > left_sum){
11             left_sum = sum;
12             max_left = i;
13         }
14     }
15 
16     int right_sum = A[mid+1];
17     sum = 0;
18     max_right=mid+1;
19     for (auto i = mid + 1; i < high; ++i){
20         sum += A[i];
21         if (sum > right_sum){
22             right_sum = sum;
23             max_right = i;
24         }
25     }
26     max_sum = left_sum + right_sum;
27 }
28 
29 void FIND_MAXISUM_SUBARRAY(int *const A,const int &low,const int &high,int &left_bd,int &right_bd,int &max_sum){
30     if (high == low){
31         left_bd = low;
32         right_bd = high;
33         max_sum = A[low];
34     }
35     else{
36         int mid = (low + high) / 2;
37         int left_low, left_high, left_sum;
38         int right_low, right_high, right_sum;
39         int cross_low, cross_high, cross_sum;
40         FIND_MAXISUM_SUBARRAY(A, low, mid, left_low, left_high, left_sum);
41         FIND_MAXISUM_SUBARRAY(A, mid + 1, high, right_low, right_high, right_sum);
42         FIND_MAX_CROSSING_SUBARRAY(A, low, mid, high, cross_low, cross_high,cross_sum);
43         if (left_sum >= right_sum && left_sum >= cross_sum){
44             left_bd = left_low;
45             right_bd = left_high;
46             max_sum = left_sum;
47         }
48         else if(right_sum>=left_sum && right_sum>=cross_sum){
49             left_bd = right_low;
50             right_bd = right_high;
51             max_sum = cross_sum;
52         }
53         else{
54             left_bd = cross_low;
55             right_bd = cross_high;
56             max_sum = cross_sum;
57         }
58     }
59 }
60 
61 int main(void)
62 {
63     int a[] = { -2, 11, -4, 13, -5, 2, -5, -3, 12, -9 };
64     int _start,_end,_max;
65 
66     FIND_MAXISUM_SUBARRAY(a, 0, end(a) - begin(a), _start, _end, _max);
67     for (auto i = _start; i <= _end; ++i){
68         cout << a[i] << " ";
69     }
70     cout << "\n max sum of sub array:" << _max << " ";
71     cout << endl;
72     system("pause");
73     return 0;
74 }

 

最大子序列-algorithms_3th

标签:

原文地址:http://www.cnblogs.com/lhyz/p/4305576.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!