首页 > 代码库 > 分治法求最大子段和
分治法求最大子段和
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 else31 {32 //from middle to left33 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 right41 temp = 0;//temp 归042 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 }
分治法求最大子段和
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。