觉得还是先从简单例子程序着手,先了解各个算法的基本思想。
目录:
算法是指对特定问题求解步骤 的一种描述
算法的评价标准:时间复杂度与空间复杂度。
时间复杂度:考虑给定的数据数目n,关于算法的执行次数。渐进上界用O()表示,最坏情况对衡量算法的好坏具有实际的意义。
空间复杂度:算法占用的空间大小。一般将算法的辅助空间作为衡量标准。
算法思想:一个贪心算法总是做出当前最好的选择,也就是说,它期望通过局部最优选择从而得到全局最优的解决方案。
小插曲:c++中有排序函数sort,可以直接利用
#include<iostream> using namespace std; #include<algorithm> int main() { int a[4] = { 4,7,3,5 }; for (int i = 0; i < 4; i++) cout << a[i] << " "; cout << endl << "排序后::::" << endl; sort(a, a + 3); //可以只对某几项进行排列 for (int i = 0; i < 4; i++) cout << a[i] << " "; cin.ignore(); return 0; }
4 7 3 5
排序后::::
3 4 7 5
举列1:最优装载问题
描述:海盗们截获一批财宝,海盗船载重有限,如何尽可能多的获取宝贝??
算法设计:每次选择重量最小的,直到不能再装为止。
代码:
#include<iostream> using namespace std; #include<algorithm> const int N = 100; double w[N]; //古董 的重量数组 int main() { double c; int n; cout << "请输入载重量c以及古董个数n:" << endl; cin >> c >> n; cout << "请输入每个古董的重量" << endl; for (int i = 0; i < n; i++) { cin >> w[i]; } sort(w, w + n); double temp = 0; int ans = 0; for (int i = 0; i < n; i++) { temp += w[i]; if (temp <= c) ans++; else break; } cout << "最大装载数目:" << ans << endl; cin.ignore(); cin.ignore(); cin.ignore(); return 0; }