Introduction To Greedy Algorithms
Introduction To Greedy Algorithms
Algorithms
https://usaco.guide/bronze/intro-greedy
CP
Initiative
joincpi.org
Greedy Algorithms
A greedy algorithm constructs a solution to the problem by always
making a choice that looks the best at the moment.
A greedy algorithm never takes back its choices, but directly constructs
the final solution. For this reason, greedy algorithms are usually very
efficient.
CP
joincpi.or
Initiative g
Greedy Algorithms
Greedy does not refer to a single algorithm, but rather a way of
thinking that is applied to problems; there's no one way to do greedy
algorithms.
CP
joincpi.or
Initiative g
Coin Problem
Consider the following problem:
We have N coins of the denominations {1, 2, 5, 10, 20, 50, 100, 200},
and we need to pick the minimum number of coins that add up to some
sum, S.
CP
joincpi.or
Initiative g
Coin Problem Solution
For this problem, the greedy algorithm of “keep picking the largest coin
as long as it does not exceed S” works.
CP
joincpi.or
Initiative g
Coin Problem Note
However, this greedy algorithm does not work for the general case, or
coins of any denominations.
Try to figure out for yourself when this algorithm works, and why it
does.
CP
joincpi.or
Initiative g
Proof by AC
Note that not all greedy problems necessarily require mathematical
proofs of correctness. It is often sufficient to intuitively convince
yourself your algorithm is correct.
CP
joincpi.or
Initiative g
Practice
The best way to get better at greedy problems is to see a lot of greedy
ideas.
There is a list of practice problems you can try on the USACO Guide.
CP
joincpi.or
Initiative g
Example Problem
USACO - Mad Scientist
CP
joincpi.or
Initiative g
Solution Code (with Video Editorial)
CP
joincpi.or
Initiative g
Challenge Problem
USACO - Rest Stops
CP
joincpi.or
Initiative g
Challenge Problem Solution
CP
joincpi.or
Initiative g