標籤:over ret back sed htm iostream 線性 cin 設計
覺得還是先從簡單例子程式著手,先瞭解各個演算法的基本思想。
目錄:
- 貪心演算法
- 分治法
- 動態規劃
- 回溯法
- 分支限界法
- 線性規劃網路流
演算法是指對特定問題求解步驟 的一種描述
演算法的評價標準:時間複雜度與空間複雜度。
時間複雜度:考慮給定的資料數目n,關於演算法的執行次數。漸進上界用O()表示,最壞情況對衡量演算法的好壞具有實際的意義。
空間複雜度:演算法佔用的空間大小。一般將演算法的輔助空間作為衡量標準。
1.貪心演算法
演算法思想:一個貪心演算法總是做出當前最好的選擇,也就是說,它期望通過局部最優選擇從而得到全域最優的解決方案。
小插曲: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;}View Code
請輸入載重量c以及古董個數n:
30 8
請輸入每個古董的重量
4 10 7 11 3 5 14 2
最大裝載數目:5
擴充:如何知道裝入了那些寶貝呢??
引入結構體數組,增加寶貝的編號屬性,具體程式如下
1 #include<iostream> 2 using namespace std; 3 #include<algorithm> 4 5 const int N = 100; 6 struct two { 7 int n; //寶物標號 8 double w; //寶物重量 9 }s[N];10 //double w[N]; //古董 的重量數組11 bool cmp(two a, two b)12 {13 return a.w < b.w;14 }15 16 int main()17 {18 double c;19 int n;20 cout << "請輸入載重量c以及古董個數n:" << endl;21 cin >> c >> n;22 23 cout << "請輸入每個古董的重量" << endl;24 25 for (int i = 0; i < n; i++)26 {27 cin >> s[i].w;28 s[i].n = i + 1;29 }30 sort(s, s + n, cmp);31 32 double temp = 0;33 int ans = 0;34 35 for (int i = 0; i < n; i++)36 {37 temp += s[i].w;38 if (temp <= c)39 {40 ans++;41 cout << "選擇第" << s[i].n << "個寶貝" << endl;42 }43 else44 break;45 }46 cout << "最大裝載數目:" << ans << endl;47 48 49 cin.ignore();50 cin.ignore();51 cin.ignore();52 return 0;53 }View Code
請輸入載重量c以及古董個數n:
30 8
請輸入每個古董的重量
4 10 7 11 3 5 14 2
選擇第8個寶貝
選擇第5個寶貝
選擇第1個寶貝
選擇第6個寶貝
選擇第3個寶貝
最大裝載數目:5
《趣學演算法》,陳小玉