GREEDY
戴瑢溱
Index
簡介
簡介
貪婪演算法(greedy algorithm)
是一種在每一步中都選擇當前狀態下最有利的選擇
不回頭也不考慮之後的選擇
以期導致結果為最佳或最理想的演算法

17 元
先拿面額大的硬幣 !!
簡介
1
2
5
1
2
1
1
2
1
2
1
1
1
1
1
1
1
1
1
1
1
1
1
決策樹(decision tree)

7 元
貪婪演算法(greedy algorithm)
是一種在每一步中都選擇當前狀態下最有利的選擇
不回頭也不考慮之後的選擇
以期導致結果為最佳或最理想的演算法
簡介
1
2
5
1
2
1
1
2
1
2
1
1
1
1
1
1
1
1
1
1
1
1
1
決策樹(decision tree)

7 元
貪婪演算法(greedy algorithm)
是一種在每一步中都選擇當前狀態下最有利的選擇
不回頭也不考慮之後的選擇
以期導致結果為最佳或最理想的演算法
簡介
為什麼硬幣是1元、5元、10元與50元?

有另外一個硬幣系統 面額為1元、3元與4元
簡介
假設我們要購買一個6元的物品

6 元
簡介
如果結果不一定正確
那為什麼我們還要使用貪婪演算法?
-
速度極快:通常只需要 O(N log N) 或 O(N),對於海量數據(例如大數據分析),我們不追求找到保證最佳解,而是在可接受的時間內找到「足夠好」的解。
-
近似解:結果不一定會是最佳解,但接近最佳解。在難題中,Greedy 可以穩定提供一個「不完美但可接受」的結果。
-
基礎:它是許多複雜演算法的核心,在這些特定的規則下,Greedy 保證是正確的。
題目
題目

題目

bool compareLargest(string a, string b) {
return a + b > b + a;
// 如果 a+b 接起來比 b+a 大,回傳 true (代表 a 優先)
}int main() {
int n;
while (cin >> n) {
vector<string> v(n); // 使用 string 才能讓數字與數字拼在一起
for (int i = 0; i < n; i++) {
cin >> v[i];
}
sort(v.begin(), v.end(), compareLargest); // 用自訂函式排序
for (int i = 0; i < n; i++) {
cout << v[i];
}
cout << endl;
}
return 0;
}#include <bits/stdc++.h>
using namespace std;
bool compareLargest(string a, string b) {
return a + b > b + a;
}
int main() {
int n;
while (cin >> n) {
vector<string> v(n);
for (int i = 0; i < n; i++) {
cin >> v[i];
}
sort(v.begin(), v.end(), compareLargest);
for (int i = 0; i < n; i++) {
cout << v[i];
}
cout << endl;
}
return 0;
}題目

#include <iostream>
#include <string>
using namespace std;
int main() {
int T, N;
cin >> T;
for (int t = 1; t <= T; t++) {
string field;
cin >> N >> field;
int count = 0; // 紀錄稻草人數量
for (int i = 0; i < N; ) {
if (field[i] == '.') { // 遇到農作物
count++;
i += 3;
} else { // 遇到荒地
i++;
}
}
cout << "Case " << t << ": " << count << endl;
}
return 0;
}kahoot !
Greedy
By ariel tai
Greedy
- 91