Greedy Algorithm
What is Greedy Algorithm?
The Greedy Algorithm is to make the best choice at current stage when solving the problem. That is to say, instead of considering the global optimal solution, it only makes the local optimal solution in a certain sense.
Greedy Algorithm can not get global optimal solution for all problems, but it can produce global optimal solution or approximate solution for a wide range of problems.
In a word, greedy is from the local optimal solution to the global optimal solution.
The basic way to solve the greedy problem
- Establish a mathematical model to describe the problem.
- Divide the problem into several subproblems.
- Solve each subproblem to get the local optimal solution.
- Synthesize the local optimal solution of the subproblem into a solution of the original problem.
example
Knapsack problem(背包问题)
A traveler has a backpack that can hold at most M
kg. Now there are n
items. The weight of each item is W1, W2,…, WN respectively. The value of each item is C1, C2,…, CN respectively. You need to put the items into the backpack. How can you ensure the maximum value of the items in the backpack?
Input
- The first line has two numbers. The first one describes the num of items. The second one describes your bag capacity.
- The next n lines describe item’s heavy and value.
1 | 4 50 <- N M |
Output
1 | 205 |
Solve
In the current situation, the most beneficial situation is to choose the items with more value and less weight. That is to choose the item with the highest cost performance (value / weight).
In summary, we first rank all items according to the price performance ratio from high to low.Then choose the most cost-effective item that the current backpack can hold.
Code
1 |
|