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

分治法求最大子段和

时间:2014-12-03 14:09:54      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   div   

 1 // sumsub.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <vector>
 7 using namespace std;
 8 int sumsub(vector<int> v, size_t left, size_t right);
 9 int _tmain(int argc, _TCHAR* argv[])
10 {
11     vector<int> v;
12     int temp,sum;
13     cout << "please input some integer" << endl;
14     while (cin >> temp)
15         v.push_back(temp);
16     sum=sumsub(v, 0, v.size()-1);
17     cout << sum<< endl;
18     return 0;
19 }
20 int sumsub(vector<int> v,size_t left,size_t right)
21 {
22     int sum1, sum2, sum3, middle;
23     if (left == right)
24         return v[left];
25     middle = floor((right + left) / 2);
26     sum1=sumsub(v, left, middle);
27     sum2=sumsub(v, middle+1, right);
28     if (left + 1 == right)
29         return sum1 > sum2 ? sum1 : sum2;
30     else
31     {
32         //from middle to left
33         int ls = 0, rs = 0, temp = 0;
34         for (size_t i = 0; i <= middle; ++i)
35         {
36             temp = temp + v[middle-i];
37             if (temp > ls)
38                 ls = temp;
39         }
40         //from middle to right
41         temp = 0;//temp 归0
42         for (size_t i =middle+1; i < v.size(); ++i)
43         {
44             temp = temp + v[i];
45             if (temp > rs)
46                 rs = temp;
47         }
48         sum3 = ls + rs;
49         sum1 = sum1 > sum2 ? sum1 : sum2;
50         sum1 = sum1 > sum3 ? sum1 : sum3;
51         return sum1;
52     }
53 }

 

分治法求最大子段和

标签:style   blog   io   ar   color   os   sp   for   div   

原文地址:http://www.cnblogs.com/ccode/p/4139771.html

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