1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| #include <iostream> #include <vector> #include <algorithm> using namespace std; #define INFTY -10000000;
struct state{ int left; int right; int sum; };
state Maxsoncrossarray(vector<int>& A, int l, int r, int mid){ state ans; int max_left, max_right, left_sum, right_sum, sum; left_sum = INFTY; sum = 0; max_left = mid; for (int i = mid; i >= l; i--){ sum += A[i]; if(sum >= left_sum){ left_sum = sum; max_left = i; } } max_right = mid + 1; right_sum = INFTY; sum = 0; for (int i = mid+1; i <= r; ++i){ sum += A[i]; if(sum >= right_sum){ right_sum = sum; max_right = i; } } ans.left = max_left; ans.right = max_right; ans.sum = left_sum + right_sum; return ans; } state Maxsonarray(vector<int>& A, int l, int r){ state ans, tmp1, tmp2, tmp3; if(l == r){ ans.left = l; ans.right = r; ans.sum = A[l]; return ans; }else{ int mid = (l + r)/2; tmp1 = Maxsonarray(A, l, mid); tmp2 = Maxsonarray(A, mid+1, r); tmp3 = Maxsoncrossarray(A, l, r, mid); } if(tmp1.sum >= tmp2.sum && tmp1.sum > tmp3.sum) return tmp1; else if(tmp2.sum >= tmp1.sum && tmp2.sum > tmp3.sum) return tmp2; else return tmp3; }
int main(){ vector<int> A; int n; scanf("%d", &n); for (int i = 0; i < n; ++i){ int tmp; scanf("%d", &tmp); A.push_back(tmp); } state ans = Maxsonarray(A, 0, n - 1); printf("%d\n%d\n%d", ans.left, ans.right, ans.sum); return 0; }
|
This is copyright.