算法导论第三版--动态规划与贪心算法
2017-03-20 22:11
387 查看
当我刷到动态规划这一章的时候,突然想起以前的部门研发比武,就是一道需要运用动态规划思想来处理的题目,团灭了99%的人,而我也是这99%中的一员,哈哈,只怪出题的人太狠了。
以下的代码是汽车车间装配时间最短的代码习题,懒于整理,折叠起来:
View Code
贪心算法属于动态规划的延伸。
动态规划是自底而上的,贪心算法是自顶而下的。
贪心算法能解决很多求最优解的问题。主要在于如何做出贪心选择和确定最优子结构,这个就根据具体的问题来分析了,开始有点玄学的味道了。
以下的代码是汽车车间装配时间最短的代码习题,懒于整理,折叠起来:
#include <iostream> #include <vector> #include <utility> using namespace std; struct move_time { int i; int j; move_time() : i(0), j(0) {} move_time(int x, int y) : i(x), j(y) {} }; void print_stations(const vector<int>& l, int lx, int n) { int i = lx; cout << "line " << i << ", station " << n << endl; for (int j=n-1; j>0; j--) { i = l[j]; cout << "line " << i << ", station " << j << endl; } } int main(int argc, char* argv[]) { int s1[] = {7,9,3,4,8,4}; int s2[] = {8,5,6,4,5,7}; int len = 6; vector<int> vf1_a(s1, s1+len), vf2_a(s2, s2+len); vector<int> line(len, 0); vector<int> f1(len, 0), f2(len, 0); int a_i[] = {2,3,1,3,4}; int a_j[] = {2,1,2,2,1}; vector< struct move_time > pt(5, move_time(0,0)); for (int n=0; n<pt.size(); n++) { pt .i = a_i ; pt .j = a_j ; } int e1 = 2; int e2 = 4; int x1 = 3; int x2 = 2; int fx = 0; int lx = 0; f1[0] = e1 + vf1_a[0]; f2[0] = e2 + vf2_a[0]; int l=1; for (; l<len; ++l) { if (f1[l-1]+vf1_a[l] <= f2[l-1]+pt[l-1].j+vf1_a[l]) { f1[l] = f1[l-1]+vf1_a[l]; line[l] = 1; } else { f1[l] = f2[l-1]+pt[l-1].j+vf1_a[l]; line[l] = 2; } if (f2[l-1]+vf2_a[l] <= f1[l-1]+pt[l-1].i+vf2_a[l]) { f2[l] = f2[l-1]+vf2_a[l]; line[l] = 2; } else { f2[l] = f1[l-1]+pt[l-1].i+vf2_a[l]; line[l] = 1; } } l = len-1; if (f1[l]+x1 <= f2[l]+x2) { fx = f1[l]+x1; lx = 1; } else { fx = f2[l]+x2; lx = 2; } print_stations(line, lx, len); return 0; }
View Code
贪心算法属于动态规划的延伸。
动态规划是自底而上的,贪心算法是自顶而下的。
贪心算法能解决很多求最优解的问题。主要在于如何做出贪心选择和确定最优子结构,这个就根据具体的问题来分析了,开始有点玄学的味道了。
相关文章推荐
- 算法导论小结(8)-动态规划与贪心算法
- 算法导论第16章 贪心算法-0-1背包问题—动态规划求解
- 《算法导论》读书笔记——动态规划与贪心算法【for_wind】
- 算法导论--贪心算法与动态规划(活动选择问题)
- 算法导论第三版16.1-4 贪心算法(区间图着色问题)
- 算法导论 第三版 动态规划之库存规划
- 算法导论第三版 练习2.3-5
- 算法导论-13.贪心算法
- 算法导论 动态规划 笔记
- 算法导论(第三版)练习 1.2-1 ~ 1.1-3
- 从01背包学习贪心算法和动态规划
- 五大常用算法——分治法,动态规划,回溯法,分支界限法,贪心算法
- 算法导论--动态规划(最长公共子序列)
- 算法导论第三版第四章 最大子数组和的三种解法(暴力、教材分治法、线性解法)
- 算法导论15章 动态规划 之 钢条切割
- 算法导论第三版--计数,基数排序
- 算法导论第三版--红黑树
- 算法导论学习笔记——动态规划
- 算法导论——动态规划
- 算法导论习题解-第16章贪心算法