贪心
贪心算法每步选眼前最好的、选了不回头:很快,但不一定对,硬币 1、3、4 凑 6 它用 3 枚,其实 2 枚就够;用 sort 按最早结束做区间调度,则能证明一定对。
收银员找 63 美分,硬币有 25、10、5、1 美分:先拿两个 25,剩 13;拿一个 10,剩 3;再拿三个 1。一共 6 枚,而且这就是最少的。这个办法叫贪心:每一步都拿眼前最好的(能拿的最大的硬币),拿了就不回头。它简单、快,很多时候就是对的;但换一套硬币,同样的办法就会给出错的答案。
每一步拿眼前最好的
1#include <iostream>2#include <vector>3using namespace std;4 5vector<int> coins = {25, 10, 5, 1};6 7void change(int amount) {8 int count = 0;9 cout << amount << " = ";10 for (int c : coins)11 while (amount >= c) { // 能拿最大的就拿最大的12 amount -= c;13 cout << c << ' ';14 count++;15 }16 cout << "(" << count << " 枚)\n";17}18 19int main() {20 change(63);21 change(41);22 change(99);23 return 0;24}
63 = 25 25 10 1 1 1 (6 枚) 41 = 25 10 5 1 (4 枚) 99 = 25 25 25 10 10 1 1 1 1 (9 枚)
现在换一套硬币:1、3、4。凑 6,贪心先拿 4,剩下的 2 只能拿两个 1,一共 3 枚。可是 3 + 3 只要 2 枚。
4 + 1 + 13 枚拿了 4 以后,剩下的 2 只能用两个 13 + 32 枚第一步拿「小一点」的 3,后面更省把 1 到 10 都跑一遍,贪心和真正的最少(试遍所有拿法)对比:
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6vector<int> coins = {4, 3, 1};7 8int greedy(int amount) {9 int count = 0;10 for (int c : coins)11 while (amount >= c) { amount -= c; count++; }12 return count;13}14 15int best(int amount) { // 试遍:第一枚拿哪个,剩下的再求最少16 if (amount == 0) return 0;17 int m = 1000;18 for (int c : coins)19 if (amount >= c) m = min(m, best(amount - c) + 1);20 return m;21}22 23int main() {24 for (int a = 1; a <= 10; a++) {25 int g = greedy(a), b = best(a);26 cout << "凑 " << a << ":贪心 " << g << " 枚,最少 " << b << " 枚"27 << (g == b ? "" : " ← 贪心错了") << '\n';28 }29 return 0;30}
凑 1:贪心 1 枚,最少 1 枚 凑 2:贪心 2 枚,最少 2 枚 凑 3:贪心 1 枚,最少 1 枚 凑 4:贪心 1 枚,最少 1 枚 凑 5:贪心 2 枚,最少 2 枚 凑 6:贪心 3 枚,最少 2 枚 ← 贪心错了 凑 7:贪心 2 枚,最少 2 枚 凑 8:贪心 2 枚,最少 2 枚 凑 9:贪心 3 枚,最少 3 枚 凑 10:贪心 4 枚,最少 3 枚 ← 贪心错了
best 把所有拿法都试一遍,是对的,但它是指数级的(同一个剩余金额会被算很多遍);下一课「动态规划入门」会把它改成 O(金额 × 硬币种数)。贪心只看眼前,它之所以对 25、10、5、1 有效,是因为这套面值有特别的性质,不是因为「每步最好」本身就保证了整体最好。
硬币有 25、20、10、5、1,贪心凑 40 用几枚?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> coins = {25, 20, 10, 5, 1};7 int amount = 40, count = 0;8 for (int c : coins)9 while (amount >= c) {10 amount -= c;11 count++;12 }13 cout << count << '\n';14 return 0;15}
硬币有 1、5、6、9,要凑 11。贪心用几枚?最少要几枚?
补上 while 里的比较符号:只要还够拿这一枚,就一直拿。程序要显示 6(63 = 25 + 25 + 10 + 1 + 1 + 1)。
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> coins = {25, 10, 5, 1};7 int amount = 63, count = 0;8 for (int c : coins)9 while (amount c) {10 amount -= c;11 count++;12 }13 cout << count << "\n";14 return 0;15}
>=。写成 >,最后剩 1 时拿不了那个 1,只显示 5;写成 <=,一枚都拿不了。区间调度:按最早结束选
一间会议室,一天有一堆会议申请,每个有开始和结束时间,同一时间只能开一个。最多能安排几个?
可以想出好几种「贪心」:先选开始最早的?先选最短的?先选结束最早的?只有最后一种总是对的。直觉是:选结束最早的那个,留给后面的时间最多。
把三种选法都写出来,在同一组会议上跑。三种选法只差 sort 的第三个参数:一个比较器,a 该排在 b 前面就返回 true。
1#include <iostream>2#include <vector>3#include <algorithm>4#include <functional>5#include <string>6using namespace std;7 8struct Meet { char name; int s, e; };9 10vector<Meet> m = {{'A', 0, 10}, {'B', 1, 4}, {'C', 4, 7}, {'D', 3, 5},11 {'E', 7, 10}, {'F', 6, 8}, {'G', 10, 12}, {'H', 9, 11}};12 13void pick(const string& rule, function<bool(const Meet&, const Meet&)> cmp) {14 sort(m.begin(), m.end(), cmp);15 vector<Meet> chosen;16 for (const Meet& x : m) {17 bool ok = true;18 for (const Meet& y : chosen) // 和已选的每一个都不重叠19 if (x.s < y.e && y.s < x.e) ok = false;20 if (ok) chosen.push_back(x);21 }22 cout << rule << ":" << chosen.size() << " 个,";23 for (const Meet& y : chosen) cout << y.name;24 cout << '\n';25}26 27int main() {28 pick("结束最早", [](const Meet& a, const Meet& b) {29 return a.e != b.e ? a.e < b.e : a.s < b.s;30 });31 pick("开始最早", [](const Meet& a, const Meet& b) {32 return a.s != b.s ? a.s < b.s : a.e < b.e;33 });34 pick("最短的先", [](const Meet& a, const Meet& b) {35 int la = a.e - a.s, lb = b.e - b.s;36 return la != lb ? la < lb : a.s < b.s;37 });38 return 0;39}
结束最早:4 个,BCEG 开始最早:2 个,AG 最短的先:3 个,DFH
「开始最早」先选了从 0 点开到 10 点的 A,一下子占掉一大段;「最短的先」先选了 D(只有 2 小时),可它正好横跨 B 和 C 的交界,把两个都挡掉了。按结束时间排好以后,其实不用和每一个已选的比,只要和最后选的那个比:s >= 上一个的结束时间 就选(练习 1)。
5 个会议:A [1, 3)、B [2, 5)、C [3, 6)、D [5, 7)、E [6, 9)。按「最早结束」选,选中的是哪几个?
n 个会议,先按结束时间排序,再从头扫一遍(每个只和最后选的那个比)。整个算法的时间复杂度是多少?
最多能开几个会
✓m 里的会议是乱序的,每个是一对 {开始, 结束}。先用 sort 加 lambda 按结束时间排好,再用一个变量 end 记最后选的那个会的结束时间:开始时间 ≥ end 就选,并更新 end。打印选了几个。
4
1#include <iostream>2#include <vector>3#include <algorithm>4#include <utility>5using namespace std;6 7int main() {8 vector<pair<int, int>> m = {{5, 9}, {1, 4}, {8, 12}, {0, 6}, {12, 16}, {3, 5},9 {6, 10}, {2, 14}, {5, 7}, {8, 11}, {3, 9}};10 int count = 0, end = -1;11 // 按 second(结束时间)从小到大排序;再依次看每个会议:first >= end 就选12 cout << count << '\n';13 return 0;14}
为什么「每步最好」要证明
贪心每一步只看眼前,选了不改。它对不对,不能靠「感觉每一步都很好」,要证明:第一步这样选,不会把最好的答案丢掉。常用的办法叫交换论证,说白了是这样:
- 随便拿一个最好的安排(会议最多的那个),看它的第一个会议 X;
- 贪心的第一个是 B,B 是所有会议里结束最早的,所以 B 结束得不比 X 晚;
- 把这个最好的安排里的 X 换成 B:B 结束得不比 X 晚,不会和后面的会议冲突,会议个数也没变,所以换了以后还是一个最好的安排;
- 现在这个最好的安排和贪心的第一步一样了。去掉 B 和与它冲突的,剩下的是同一个问题,同样的道理一步步换下去,最后就和贪心选的一模一样。
所以贪心选出来的个数,不少于任何一个安排:它就是最多的。
用同样的办法检查硬币 1、3、4 凑 6:最好的拿法是 3 + 3,贪心第一步拿的是 4。想把 3 换成 4,剩下的 2 就凑不成一个硬币了,换不过去。交换不成立,就是贪心可能出错的地方。实在证明不了,就举反例试试;找到一个反例,就要换成动态规划或者回溯。
交换论证里,把最好安排的第一个会议 X 换成 B(所有会议里结束最早的)。为什么换了以后不会和后面的会议冲突?
三个会议:[0, 5)、[4, 7)、[6, 10)。按「最短的先」选,能选几个?最多其实能选几个?
你已经见过的贪心
| 算法 | 每一步贪什么 | 在哪一课 |
|---|---|---|
| 哈夫曼树 | 合并当前最小的两个权值 | 第 4 章(树) |
| Prim | 把离已选部分最近的顶点加进来 | 第 5 章(图) |
| Kruskal | 选最短的、不会成环的边 | 第 5 章(图) |
| Dijkstra | 定下当前离起点最近的顶点 | 第 5 章(图) |
| 区间调度 | 选结束最早的、不冲突的 | 这一课 |
| 分数背包(可以拿一部分) | 先拿「价值 / 重量」最高的 | 练习 2 |
这些都有各自的证明。比如 Dijkstra 的证明要用到「边权不为负」:有负权边时,「当前最近的」以后还可能被一条负边改得更近,贪心的前提就不成立了。
考试里: 408 很少单独考「贪心」两个字,而是藏在哈夫曼树、Prim、Kruskal、Dijkstra 的题里:按贪心的规则一步步画出过程。面试里常见的是区间调度(会议室、射气球、无重叠区间)、跳跃游戏、分发饼干;拿不准能不能贪的时候,先试几个小反例。
这几个算法里,哪一个不是贪心?
分数背包
✓东西可以只拿一部分(比如一袋米倒出一半)。先把物品按「价值 / 重量」从高到低排好(比较 a.v * b.w > b.v * a.w,不用除法),再依次拿:装得下就整个拿,装不下就拿能装下的那一部分,然后停。打印容量 50 和 25 时最多的价值。
240.0 135.0
1#include <cstdio>2#include <vector>3#include <algorithm>4using namespace std;5 6struct Item { int w, v; };7 8double fill(vector<Item> items, int cap) {9 double total = 0;10 // 1. sort 按 v / w 从高到低11 // 2. 依次看每个物品:w <= cap 就整个拿(cap 减少);否则拿 cap / w 那么多,然后停12 return total;13}14 15int main() {16 vector<Item> items = {{30, 120}, {10, 60}, {20, 100}};17 printf("%.1f %.1f\n", fill(items, 50), fill(items, 25));18 return 0;19}
用 STL 写
贪心的代码大多是两种样子:先排序,再扫一遍;或者每一步从一堆里拿出当前最好的。前一种用 sort 加比较器,后一种用 priority_queue。
比较器有三种写法:lambda(最常用)、greater<int>() 这样现成的函数对象、或者在 struct 里写 operator<。比较器必须是「严格小于」:a 和 b 一样时要返回 false,写成 <= 会让 sort 出错甚至越界。
还是「区间调度」那一关的 8 个会议,换个问题:全部都要开,最少要几间会议室?按开始时间排好,用一个小顶堆装着每间会议室什么时候空出来:堆顶的那间最早空;它已经空了(top() <= s)就接着用,否则再开一间。
1#include <iostream>2#include <vector>3#include <queue>4#include <algorithm>5#include <functional>6using namespace std;7 8struct Meet {9 char name; int s, e;10 bool operator<(const Meet& o) const { return s < o.s; } // 默认按开始时间排11};12 13int main() {14 vector<Meet> m = {{'A', 0, 10}, {'B', 1, 4}, {'C', 4, 7}, {'D', 3, 5},15 {'E', 7, 10}, {'F', 6, 8}, {'G', 10, 12}, {'H', 9, 11}};16 sort(m.begin(), m.end()); // 用 operator<17 18 priority_queue<int, vector<int>, greater<int>> rooms; // 小顶堆:每间什么时候空19 for (const Meet& x : m) {20 if (!rooms.empty() && rooms.top() <= x.s) rooms.pop(); // 最早空的那间能接上21 rooms.push(x.e);22 cout << x.name << " " << x.s << "-" << x.e << ":在用 " << rooms.size()23 << " 间,最早 " << rooms.top() << " 点空出来\n";24 }25 cout << "最少 " << rooms.size() << " 间\n";26 27 vector<int> v = {5, 2, 8, 1, 9};28 sort(v.begin(), v.end(), greater<int>()); // 从大到小29 for (int x : v) cout << x << ' ';30 cout << '\n';31 return 0;32}
A 0-10:在用 1 间,最早 10 点空出来 B 1-4:在用 2 间,最早 4 点空出来 D 3-5:在用 3 间,最早 4 点空出来 C 4-7:在用 3 间,最早 5 点空出来 F 6-8:在用 3 间,最早 7 点空出来 E 7-10:在用 3 间,最早 8 点空出来 H 9-11:在用 3 间,最早 10 点空出来 G 10-12:在用 3 间,最早 10 点空出来 最少 3 间 9 8 5 2 1
堆里的数只增不减:一间会议室被接着用,是先 pop 再 push;开新的一间,是只 push。最后堆有几个,就开过几间。这个贪心的道理是:某一时刻同时在开的会最多有 3 个(4 点到 5 点,A、D、C 都在),无论怎么排都至少 3 间,而它正好用了 3 间。
里面是什么:sort 是内省排序(快速排序为主,递归太深换堆排序,小段用插入排序),不稳定;要保持相等元素原来的顺序用 stable_sort(归并排序)。priority_queue 是 vector 上的二叉堆,默认是大顶堆,要小顶堆写 greater<int>。
| 写法 | 做什么 | 代价 |
|---|---|---|
sort(b, e, [](const T& a, const T& b) { return …; }) | 按自己的规则排序 | O(n log n) |
sort(b, e, greater<int>()) | 从大到小 | O(n log n) |
bool operator<(const T& o) const | 让 sort、set、priority_queue 默认按它比 | 不另外花时间 |
priority_queue<int, vector<int>, greater<int>> pq | 小顶堆,pq.top() 是最小的 | push / pop O(log n),top O(1) |
面试里: 「会议室 II」就是这一关的这段程序:排序加小顶堆,O(n log n)。「无重叠区间」「用最少的箭射爆气球」都是按结束时间排序再扫一遍。比较器里两个数相减(return a.e - b.e;)是 C 的 qsort 写法,C++ 的 sort 要的是 bool,写 a.e < b.e。
greater<int> 的 priority_queue 是小顶堆。放进 4 个数、弹出一个以后,程序输出什么?
1#include <iostream>2#include <vector>3#include <queue>4using namespace std;5 6int main() {7 priority_queue<int, vector<int>, greater<int>> q;8 for (int x : {5, 2, 8, 3})9 q.push(x);10 q.pop();11 cout << q.top() << " " << q.size() << "\n";12 return 0;13}
pop 弹掉 2,新的堆顶是剩下 5 8 3 里最小的 3,还剩 3 个。不写 greater<int> 就是默认的大顶堆,堆顶会是 8,弹掉以后是 5。小结
贪心:每步选眼前最好的,选了不回头
- 快又简单,但不一定对:硬币 1 3 4 凑 6,贪心 3 枚,最少 2 枚
- 区间调度按最早结束选,一定最多
- 要证明:交换论证,把最好答案的第一步换成贪心的,不变差
- 先 sort(比较器返回 a 是否排在 b 前面)再扫,或者每步从 priority_queue 拿最好的
1sort(m.begin(), m.end(), [](const Meet& a, const Meet& b) {2 return a.e < b.e;3});4for (const Meet& x : m)5 if (x.s >= end) { count++; end = x.e; }