book-notes

Chapter 8 - Greedy algorithms

Greedy algorithm

Knapsack problem

Untitled

Untitled

Untitled

Set-covering problem

Suppose you’re starting a radio show. You want to reach listeners in all 50 states. Each station covers a region and there is overlap. What is the smallest set of stations you can play to cover all 50 states?

Brute force solution

  1. List every possible subset of stations. This is called the power set. There are 2^n possible subsets.
  2. From these, pick the set with the smallest number of stations that covers all 50 states.
    • The problem with brute force is that it takes a long time to calculate every possible set of stations. It takes O(2^n) time, because there are 2^n subsets.
    # of stations # of subsets O(2^n)
    5 32 2^5
    10 1024 2^10
    32 4 billion 2^32

Greedy algorithm solution

  1. Pick the station that covers the most states that haven’t been covered yet. It’s ok if the station covers some states that have been covered already.
  2. Repeat until all the states are covered.
    • This is called an approximation algorithm. When calculating the exact solution will take too much time, an approximation algorithm will work.
    • Approximation algorithms are judged by:
    • how fast they are
    • how close they are to the optimal solution - In this case, greedy algorithm runs in O(n^2) time where n is the number of stations.

Sets

Untitled

Untitled

NP-complete problems

# of cities # of routes  
1 1 1!
2 2 2!
3 6 3!
4 24 4!
5 120 5!
6 720 6!
7 5040 7!
8 40320 8!

How do you tell if a problem is NP-complete?

There’s no easy way to tell if the problem you’re working on is NP-complete. Here are some giveaways:

Untitled