Swipe to navigate through the chapters of this book
It’s not a question of enough, pal.
Please log in to get access to this content
To get access to this content you need the following product:
No, it’s not to run away and buy comic books.
The idea for this version of the problem comes from Michael Soltys (see references in Chapter 4).
To be on the safe side, just let me emphasize that this greedy solution would not work in general, with an arbitrary set of weights. The distinct powers of two are key here.
If we view each object individually, this is often called 0-1 knapsack because we can take 0 or 1 of each object.
Not only is it unimportant whether zero means left or right, it is also unimportant which subtrees are on the left and which are on the right. Shuffling them won’t matter to the optimality of the solution.
If a future version of the heapq library lets you use a key function, such as in list.sort, you’d no longer need this tuple wrapping at all, of course.
They might also have equal weights/frequencies; that doesn’t affect the argument.
By the way, did you know that the ZIP code of Huffman, Texas, is 77336?
You can, in fact, combine Borůvka’s algorithm with Prim’s to get a faster algorithm.
Do you see why the result cannot contain any cycles, as long as we assume positive edge weights?
Going back and forth between this representation and one where you have edges both ways isn’t really hard, but I’ll leave the details as an exercise for the reader.
We’re sorting m edges, but we also know that m is O( n 2), and (because the graph is connected), m is Ω( n). Because Θ(lg n 2) = Θ(2.lg n) = Θ(lg n), we get the result.
Actually, the difference is deceptive. Prim’s algorithm is based on traversal and heaps—concepts we’ve already dealt with—while Kruskal’s algorithm introduced a new disjoint set mechanism. In other words, the difference in simplicity is mostly a matter of perspective and abstraction.
As I mentioned when discussing Kruskal’s algorithm, adding and removing such redundant reverse edges is quite easy, if you need to do so.
Because the intervals don’t overlap, sorting by starting and finishing times is equivalent.
Versions of this problem can be found in Soltys’ book (see “References” in Chapter 4) and that of Cormen et al. (see “References” in Chapter 1). My proof closely follows Soltys’s, while Cormen et al. choose to prove that the problem forms a matroid, which means that a greedy algorithm will work on it.
- Greed Is Good? Prove It!
Magnus Lie Hetland
- Sequence number
- Chapter number
- Chapter 7