算法导论(implement the 4.1 alogrithm)
来源:互联网 发布:电子商务美工方向 编辑:程序博客网 时间:2024/06/05 06:52
#include<iostream>#include<vector>#include<string>#include<set>#include<map>#include<unordered_set>#include<unordered_map>#include<algorithm>#include<xfunctional>using namespace std;vector<int> GetMax(vector<int>& diff,int start,int end){vector<int> res;if (start >= end){res.push_back(start);res.push_back(end);res.push_back(diff[start]);return res;}int mid = (start + end) / 2;vector<int> left = GetMax(diff,start,mid);vector<int> right = GetMax(diff,mid+1,end);int max_left = INT_MIN;int left_index;int temp = 0;for (int i = mid; i >= start; i--){temp += diff[i];if (temp > max_left){max_left = temp;left_index = i;}}temp = 0;int max_right = INT_MIN;int right_index;for (int j = mid + 1; j <= end; j++){temp += diff[j];if (temp > max_right){right_index = j;max_right = temp;}}vector<int> middle;middle.push_back(left_index);middle.push_back(right_index);middle.push_back(max_left+max_right);if (middle[2] > left[2] && middle[2] > right[2]) return middle;else if (left[2] > middle[2] && left[2] > right[2]) return left;else return right;}int main(){int n;cout << "The amount of the share:";cin >> n;vector<int> share(n,0);for (int i = 0; i < n; i++){cin >> share[i];}vector<int> diff(n-1,0);for (int i = 0; i < n - 1; i++){diff[i] = share[i+1] - share[i];}vector<int> res = GetMax(diff,0,diff.size()-1);cout << res[0] << " " << res[1] << " " << res[2] << endl;system("pause");return 0;}
When you read my code,you shoule be carefull about the relationship between the index of share and the index of diff
0 0
- 算法导论(implement the 4.1 alogrithm)
- 算法导论(Exercise 6.5-9 implement the k-way merge by using heap)
- 【Alogrithm】迪杰斯特拉算法
- 算法导论 Exercise2.3-5(implement binary search iteratively)
- 算法导论 Exercise 2.3-5 (implement binary serach recursively)
- 射线和轴对齐包围盒相交检测-简洁算法(ray-aabb overlap test alogrithm)
- 11/7/3 vector<T> 算法<alogrithm>
- Majority Vote Alogrithm 多数投票算法
- 算法导论(build the heap recursively 递归建堆)
- 算法导论(build the heap iteratively 迭代建堆)
- 算法导论(Exercise 4.1-2)
- 算法导论(Exercise 4.1-5)
- 算法导论 4.1-1
- 算法导论 4.1-2
- 算法导论 4.1-3
- 算法导论 4.1-4
- 算法导论 4.1-5
- 算法导论 4.1-6
- Windows系统功能模拟 C++(EasyX插件)—— 2nd 基础设施
- 【OpenCV学习笔记】四十、运动物体检测(二)
- 8、uboot移植——使用三星官方的uboot进行移植
- 数字组合
- 模拟先来先服务调度算法(C++)
- 算法导论(implement the 4.1 alogrithm)
- Redis 和 I/O 多路复用
- sklearn系列之----线性回归
- Add Strings问题及解法
- JS实现二叉查找树的建立以及一些遍历方法
- 大话设计模式读书笔记(十一) 观察者模式
- Day-2
- 【整理收集】那些神器级别的BT磁力搜索网站
- Lua-nginx-module的安装