1 /*分治法找最大子串*/ 2 #include<iostream> 3 #include<vector> 4 using namespace std; 5 #define M -99999999 6 7 struct Node 8 { 9 int low; 10 int high; 11 int sum; 12 }; 13 14 Node find_max_crossing_subsequence(vector<int> A, int low, int mid, int high) 15 { 16 int left_sum = M; 17 int max_left; 18 int sum = 0; 19 for(int i=mid; i>=low; --i) 20 { 21 sum+=A[i]; 22 if(sum >= left_sum) 23 { 24 left_sum = sum; 25 max_left = i; 26 } 27 } 28 int right_sum = M; 29 int max_right; 30 sum = 0; 31 for(int i=mid+1; i <= high; ++i) 32 { 33 sum += A[i]; 34 if(sum > right_sum) 35 { 36 right_sum = sum; 37 max_right = i; 38 } 39 } 40 Node n={max_left, max_right, left_sum+right_sum}; 41 return n; 42 } 43 44 Node find_max_subsequence(vector<int> A, int low, int high) 45 { 46 if(low == high) 47 { 48 Node n={low, low, A[low]}; 49 return n; 50 } 51 else 52 { 53 int mid = (low + high)/2; 54 Node ln = find_max_subsequence(A, low, mid); 55 Node cn = find_max_crossing_subsequence(A, low, mid, high); 56 Node rn = find_max_subsequence(A, mid+1, high); 57 if(ln.sum >= cn.sum && ln.sum >= rn.sum) 58 return ln; 59 else if(cn.sum >= ln.sum && cn.sum >= rn.sum) 60 return cn; 61 else 62 return rn; 63 /*比较顺序决定了当最大子串不止一个时返回子串的位置*/ 64 } 65 } 66 67 int main() 68 { 69 int num; 70 while(cin>>num) 71 { 72 int minus_num(0); 73 vector<int> A(num,0); 74 for(int i=0; i < num; ++i) 75 { 76 cin>>A[i]; 77 if(A[i] < 0) 78 ++minus_num; 79 } 80 if(minus_num == num) 81 cout<<0<<" "<<A[0]<<" "<<A[num-1]<<endl; 82 else 83 { 84 Node n = find_max_subsequence(A, 0, num-1); 85 cout<<n.sum<<" "<<A[n.low]<<" "<<A[n.high]<<endl; 86 } 87 } 88 return 0; 89 }