Greedy Algorithm,也就是贪心算法,局部最优化的算法,虽然可以快速得到解,但是这个解往往不会是全局最优解。不过这个算法的思想倒是挺有趣的。
Consider the following solitaire game: you are given a list of moves, x1, x2…xm, and their costs, y1, y2…ym. Moves and their costs both take the form of positive integers. Such a list of moves and their costs is called an instance of the game. To play the game, you start with a positive integer n. On each turn of the game you have two choices: subtract 1 from n incurring a cost of 1 or pick some move xi such that n is divisible by xi and divide n by xi incurring a cost of yi. The goal is to get to 0 while incurring the minimum possible cost. For instance, suppose that the set of moves is 4, 5, 7 and the corresponding penalties are 1, 3, 4. If n is 20 then the optimal strategy is as follows:
So the final cost is 4. One suboptimal strategy for this game is as follows:
which gives us a total cost of 5. One possible greedy algorithm for this game is as follows: On each turn, simply divide the current number by the legal move x of cost y which maximizes x / y - the ratio of move to cost (and subtract 1 from the current number if it is not divisible by any move). If two legal moves have the same ratio of move to cost then the greedy algorithm will take the larger move. Unfortunately, this greedy algorithm does not always give the optimal strategy. In this problem you will find counterexamples that show the greedy algorithm is not optimal in different instances of this game.
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。