算法导论中用活动选择问题引出对贪心算法的讨论,并与动态规划做比较,将的很不错,下面这篇博客同样做了很不错的论述
传送门:http://www.cnblogs.com/Anker/archive/2013/03/16/2963625.html
我只贴出我的贪心算法的代码:
#include<iostream>
#include<vector>
using namespace std;
int s[12] = { 0,1,3,0,5,3,5,6,8,8,2,12 };
int f[12] = { 0,4,5,6,7,9,9,10,11,12,14,16 };
vector<int> Greedy_Activity_Selector(int s[], int f[])
{
int n = 12;
vector<int> A;
A.push_back(1);
int k = 1;
for (int m = 2; m <= n; m++)
{
if (s[m] >= f[k])
{
A.push_back(m);
k = m;
}
}
return A;
}
void printf_vector(vector<int> A)
{
for (unsigned a = 0; a != A.size(); ++a) //输出A
{
cout << A[a] << " ";
}
cout << endl;
}
int main()
{
vector<int> A = Greedy_Activity_Selector(s, f);
printf_vector(A);
return 0;
}
贪心算法和动态规划有着重要的联系与区别,正像上面的博客提到的,动态规划解决问题时全局最优解中一定包含某个局部最优解,但不一定包含前一个局部最优解,因此需要记录之前的所有最优解。贪心算法的主要思想就是对问题求解时,总是做出在当前看来是最好的选择,产生一个局部最优解。
总结的很好
算法之路异常艰辛,我等前行且珍惜。
夜深了,我该走了