id stringlengths 6 26 | chapter stringclasses 36
values | section stringlengths 3 5 | title stringlengths 3 27 | source_file stringlengths 13 29 | question_markdown stringlengths 17 6.29k | answer_markdown stringlengths 3 6.76k | code_blocks listlengths 0 9 | has_images bool 2
classes | image_refs listlengths 0 7 |
|---|---|---|---|---|---|---|---|---|---|
12-12.4-5 | 12 | 12.4 | 12.4-5 $\star$ | docs/Chap12/12.4.md | Consider $\text{RANDOMIZED-QUICKSORT}$ operating on a sequence of $n$ distinct input numbers. Prove that for any constant $k > 0$, all but $O(1 / n^k)$ of the $n!$ input permutations yield an $O(n\lg n)$ running time. | Let $A(n)$ denote the probability that when quicksorting a list of length $n$, some pivot is selected to not be in the middle $n^{1 - k / 2}$ of the numberes. This doesn't happen with probability $\frac{1}{n^{k / 2}}$. Then, we have that the two subproblems are of size $n_1, n_2$ with $n_1 + n_2 = n - 1$, then
$$A(n) ... | [] | false | [] |
12-12-1 | 12 | 12-1 | 12-1 | docs/Chap12/Problems/12-1.md | Equal keys pose a problem for the implementation of binary search trees.
**a.** What is the asymptotic performance of $\text{TREE-INSERT}$ when used to insert $n$ items with identical keys into an initially empty binary search tree?
We propose to improve $\text{TREE-INSERT}$ by testing before line 5 to determine whet... | **a.** Each insertion will add the element to the right of the rightmost leaf because the inequality on line 11 will always evaluate to false. This will result in the runtime being $\sum_{i = 1}^n i \in \Theta(n^2)$.
**b.** This strategy will result in each of the two children subtrees having a difference in size at m... | [] | false | [] |
12-12-2 | 12 | 12-2 | 12-2 | docs/Chap12/Problems/12-2.md | Given two strings $a = a_0a_1 \ldots a_p$ and $b = b_0b_1 \ldots b_q$, where each $a_i$ and each $b_j$ is in some ordered set of characters, we say that string $a$ is **_lexicographically less than_** string $b$ if either
1. there exists an integer $j$, where $0 \le j \le \min(p, q)$, such that $a_i = b_i$ for all $i ... | (Removed) | [] | false | [] |
12-12-3 | 12 | 12-3 | 12-3 | docs/Chap12/Problems/12-3.md | In this problem, we prove that the average depth of a node in a randomly built binary search tree with $n$ nodes is $O(\lg n)$. Although this result is weaker than that of Theorem 12.4, the technique we shall use reveals a surprising similarity between the building of a binary search tree and the execution of $\text{RA... | (Removed) | [] | false | [] |
12-12-4 | 12 | 12-4 | 12-4 | docs/Chap12/Problems/12-4.md | Let $b_n$ denote the number of different binary trees with $n$ nodes. In this problem, you will find a formula for $b_n$, as well as an asymptotic estimate.
**a.** Show that $b_0 = 1$ and that, for $n \ge 1$,
$$b_n = \sum_{k = 0}^{n - 1} b_k b_{n - 1 - k}.$$
**b.** Referring to Problem 4-4 for the definition of a ge... | **a.** A root with two subtree.
**b.**
$$
\begin{aligned}
B(x)^2 & = (b_0 x^0 + b_1 x^1 + b_2 x^2 + \cdots)^2 \\\\
& = b_0^2 x^0 + (b_0 b_1 + b_1 b_0) x^1 + (b_0 b_2 + b_1 b_1 + b_2 b_0) x^2 + \cdots \\\\
& = \sum_{k = 0}^0 b_k b_{0 - k} x^0 + \sum_{k = 0}^1 b_k b_{1 - k} x^1 + \sum_{k = 0}^2 b_k b_{2 -... | [] | false | [] |
13-13.1-1 | 13 | 13.1 | 13.1-1 | docs/Chap13/13.1.md | In the style of Figure 13.1(a), draw the complete binary search tree of height $3$ on the keys $\\{1, 2, \ldots, 15\\}$. Add the $\text{NIL}$ leaves and color the nodes in three different ways such that the black-heights of the resulting red-black trees are $2$, $3$, and $4$. | - Complete binary tree of $height = 3$:

- Red-black tree of $black\text-heights = 2$:

- Red-black tree of $black\text-heights = 3$:

- Red-black tree of $black\text-heights = 4$:
 | [] | true | [
"../img/13.1-1-1.png",
"../img/13.1-1-2.png",
"../img/13.1-1-3.png",
"../img/13.1-1-4.png"
] |
13-13.1-2 | 13 | 13.1 | 13.1-2 | docs/Chap13/13.1.md | Draw the red-black tree that results after $\text{TREE-INSERT}$ is called on the tree in Figure 13.1 with key $36$. If the inserted node is colored red, is the resulting tree a red-black tree? What if it is colored black? | - If the inserted node is colored red, the tree doesn't satisfy property 4 because $35$ will be the parent of $36$, which is also colored red.
- If the inserted node is colored black, the tree doesn't satisfy property 5 because there will be two paths from node $38$ to $T.nil$ which contain different numbers of black n... | [] | true | [
"../img/13.1-2-1.png"
] |
13-13.1-3 | 13 | 13.1 | 13.1-3 | docs/Chap13/13.1.md | Let us define a **_relaxed red-black tree_** as a binary search tree that satisfies red-black properties 1, 3, 4, and 5. In other words, the root may be either red or black. Consider a relaxed red-black tree $T$ whose root is red. If we color the root of $T$ black but make no other changes to $T$, is the resulting tree... | Yes, it is.
- Property 1 is trivially satisfied since only one node is changed and it is not changed to some mysterious third color.
- Property 3 is trivially satisfied since no new leaves are introduced.
- Property 4 is satisfied since there was no red node introduced, and root is in every path from the root to the l... | [] | false | [] |
13-13.1-4 | 13 | 13.1 | 13.1-4 | docs/Chap13/13.1.md | Suppose that we "absorb" every red node in a red-black tree into its black parent, so that the children of the red node become children of the black parent. (Ignore what happens to the keys.) What are the possible degrees of a black node after all its red children are absorbed? What can you say about the depths of the ... | The degree of a node in a rooted tree is the number of its children (see Section B.5.2). Given this definition, the possible degrees are $0$, $2$, $3$ and $4$, based on whether the black node had zero, one or two red children, each with either zero or two black children. The depths could shrink by at most a factor of $... | [] | false | [] |
13-13.1-5 | 13 | 13.1 | 13.1-5 | docs/Chap13/13.1.md | Show that the longest simple path from a node $x$ in a red-black tree to a descendant leaf has length at most twice that of the shortest simple path from node $x$ to a descendant leaf. | Suppose we have the longest simple path $(a_1, a_2, \dots, a_s)$ and the shortest simple path $(b_1, b_2, \dots, b_t)$. Then, by property 5 we know they have equal numbers of black nodes. By property 4, we know that neither contains a repeated red node. This tells us that at most $\left\lfloor \frac{s - 1}{2} \right\rf... | [] | false | [] |
13-13.1-6 | 13 | 13.1 | 13.1-6 | docs/Chap13/13.1.md | What is the largest possible number of internal nodes in a red-black tree with black-height $k$? What is the smallest possible number? | - The largest is a path with half black nodes and half red nodes, which has $2^{2k} - 1$ internal nodes.
- The smallest is a path with all black nodes, which has $2^k - 1$ internal nodes. | [] | false | [] |
13-13.1-7 | 13 | 13.1 | 13.1-7 | docs/Chap13/13.1.md | Describe a red-black tree on $n$ keys that realizes the largest possible ratio of red internal nodes to black internal nodes. What is this ratio? What tree has the smallest possible ratio, and what is the ratio? | - The largest ratio is $2$, each black node has two red children.
- The smallest ratio is $0$. | [] | false | [] |
13-13.2-1 | 13 | 13.2 | 13.2-1 | docs/Chap13/13.2.md | Write pseudocode for $\text{RIGHT-ROTATE}$. | ```cpp
RIGHT-ROTATE(T, y)
x = y.left
y.left = x.right
if x.right != T.nil
x.right.p = y
x.p = y.p
if y.p == T.nil
T.root = x
else if y == y.p.right
y.p.right = x
else y.p.left = x
x.right = y
y.p = x
``` | [
{
"lang": "cpp",
"code": "RIGHT-ROTATE(T, y)\n x = y.left\n y.left = x.right\n if x.right != T.nil\n x.right.p = y\n x.p = y.p\n if y.p == T.nil\n T.root = x\n else if y == y.p.right\n y.p.right = x\n else y.p.left = x\n x.right = y\n y.p = x"
}
] | false | [] |
13-13.2-2 | 13 | 13.2 | 13.2-2 | docs/Chap13/13.2.md | Argue that in every $n$-node binary search tree, there are exactly $n - 1$ possible rotations. | Every node can rotate with its parent, only the root does not have a parent, therefore there are $n - 1$ possible rotations. | [] | false | [] |
13-13.2-3 | 13 | 13.2 | 13.2-3 | docs/Chap13/13.2.md | Let $a$, $b$, and $c$ be arbitrary nodes in subtrees $\alpha$, $\beta$, and $\gamma$, respectively, in the left tree of Figure 13.2. How do the depths of $a$, $b$, and $c$ change when a left rotation is performed on node $x$ in the figure? | - $a$: increase by $1$.
- $b$: unchanged.
- $c$: decrease by $1$. | [] | false | [] |
13-13.2-4 | 13 | 13.2 | 13.2-4 | docs/Chap13/13.2.md | Show that any arbitrary $n$-node binary search tree can be transformed into any other arbitrary $n$-node binary search tree using $O(n)$ rotations. ($\textit{Hint:}$ First show that at most $n - 1$ right rotations suffice to transform the tree into a right-going chain.) | Consider transforming an arbitrary $n$-node binary tree into a right-going chain as follows:
Let the root and all successive right children of the root be the elements of the chain initial chain. For any node $x$ which is a left child of a node on the chain, a single right rotation on the parent of $x$ will add that n... | [] | false | [] |
13-13.2-5 | 13 | 13.2 | 13.2-5 $\star$ | docs/Chap13/13.2.md | We say that a binary search tree $T_1$ can be **_right-converted_** to binary search tree $T_2$ if it is possible to obtain $T_2$ from $T_1$ via a series of calls to $\text{RIGHT-ROTATE}$. Give an example of two trees $T_1$ and $T_2$ such that $T_1$ cannot be right-converted to $T_2$. Then, show that if a tree $T_1$ ca... | We can use $O(n)$ calls to rotate the node which is the root in $T_2$ to $T_1$'s root, then use the same operation in the two subtrees. There are $n$ nodes, therefore the upper bound is $O(n^2)$. | [] | false | [] |
13-13.3-1 | 13 | 13.3 | 13.3-1 | docs/Chap13/13.3.md | In line 16 of $\text{RB-INSERT}$, we set the color of the newly inserted node $z$ to red. Observe that if we had chosen to set $z$'s color to black, then property 4 of a red-black tree would not be violated. Why didn't we choose to set $z$'s color to black? | If we chose to set the color of $z$ to black then we would be violating property 5 of being a red-black tree. Because any path from the root to a leaf under $z$ would have one more black node than the paths to the other leaves. | [] | false | [] |
13-13.3-2 | 13 | 13.3 | 13.3-2 | docs/Chap13/13.3.md | Show the red-black trees that result after successively inserting the keys $41, 38, 31, 12, 19, 8$ into an initially empty red-black tree. | - insert $41$:

- insert $38$:

- insert $31$:

- insert $12$:

- insert $19$:

- insert $8$:
 | [] | true | [
"../img/13.3-2-1.png",
"../img/13.3-2-2.png",
"../img/13.3-2-3.png",
"../img/13.3-2-4.png",
"../img/13.3-2-5.png",
"../img/13.3-2-6.png"
] |
13-13.3-3 | 13 | 13.3 | 13.3-3 | docs/Chap13/13.3.md | Suppose that the black-height of each of the subtrees $\alpha, \beta, \gamma, \delta, \epsilon$ in Figures 13.5 and 13.6 is $k$. Label each node in each figure with its black-height to verify that the indicated transformation preserves property 5. | (Removed) | [] | false | [] |
13-13.3-4 | 13 | 13.3 | 13.3-4 | docs/Chap13/13.3.md | Professor Teach is concerned that $\text{RB-INSERT-FIXUP}$ might set $T.nil.color$ to $\text{RED}$, in which case the test in line 1 would not cause the loop to terminate when $z$ is the root. Show that the professor's concern is unfounded by arguing that $\text{RB-INSERT-FIXUP}$ never sets $T.nil.color$ to $\text{RED}... | First observe that $\text{RB-INSERT-FIXUP}$ only modifies the child of a node if it is already $\text{RED}$, so we will never modify a child which is set to $T.nil$. We just need to check that the parent of the root is never set to $\text{RED}$.
Since the root and the parent of the root are automatically black, if $z$... | [] | false | [] |
13-13.3-5 | 13 | 13.3 | 13.3-5 | docs/Chap13/13.3.md | Consider a red-black tree formed by inserting $n$ nodes with $\text{RB-INSERT}$. Argue that if $n > 1$, the tree has at least one red node. | - **Case 1:** $z$ and $z.p.p$ are $\text{RED}$, if the loop terminates, then $z$ could not be the root, thus $z$ is $\text{RED}$ after the fix up.
- **Case 2:** $z$ and $z.p$ are $\text{RED}$, and after the rotation $z.p$ could not be the root, thus $z.p$ is $\text{RED}$ after the fix up.
- **Case 3:** $z$ is $\text{RE... | [] | false | [] |
13-13.3-6 | 13 | 13.3 | 13.3-6 | docs/Chap13/13.3.md | Suggest how to implement $\text{RB-INSERT}$ efficiently if the representation for red-black trees includes no storage for parent pointers. | Use stack to record the path to the inserted node, then parent is the top element in the stack.
- **Case 1:** we pop $z.p$ and $z.p.p$.
- **Case 2:** we pop $z.p$ and $z.p.p$, then push $z.p.p$ and $z$.
- **Case 3:** we pop $z.p$, $z.p.p$ and $z.p.p.p$, then push $z.p$. | [] | false | [] |
13-13.4-1 | 13 | 13.4 | 13.4-1 | docs/Chap13/13.4.md | Argue that after executing $\text{RB-DELETE-FIXUP}$, the root of the tree must be black. | - **Case 1:** transform to 2, 3, 4.
- **Case 2:** if terminates, the root of the subtree (the new $x$) is set to black.
- **Case 3:** transform to 4.
- **Case 4:** the root (the new $x$) is set to black. | [] | false | [] |
13-13.4-2 | 13 | 13.4 | 13.4-2 | docs/Chap13/13.4.md | Argue that if in $\text{RB-DELETE}$ both $x$ and $x.p$ are red, then property 4 is restored by the call to $\text{RB-DELETE-FIXUP}(T, x)$. | Suppose that both $x$ and $x.p$ are red in $\text{RB-DELETE}$. This can only happen
in the else-case of line 9. Since we are deleting from a red-black tree, the other child of y.p which becomes $x$'s sibling in the call to $\text{RB-TRANSPLANT}$ on line 14 must be black, so $x$ is the only child of $x.p$ which is red. ... | [] | false | [] |
13-13.4-3 | 13 | 13.4 | 13.4-3 | docs/Chap13/13.4.md | In Exercise 13.3-2, you found the red-black tree that results from successively inserting the keys $41, 38, 31, 12, 19, 8$ into an initially empty tree. Now show the red-black trees that result from the successive deletion of the keys in the order $8, 12, 19, 31, 38, 41$. | - initial:

- delete $8$:

- delete $12$:

- delete $19$:

- delete $31$:

- delete $38$:

- delete $41$:
 | [] | true | [
"../img/13.4-3-1.png",
"../img/13.4-3-2.png",
"../img/13.4-3-3.png",
"../img/13.4-3-4.png",
"../img/13.4-3-5.png",
"../img/13.4-3-6.png",
"../img/13.4-3-7.png"
] |
13-13.4-4 | 13 | 13.4 | 13.4-4 | docs/Chap13/13.4.md | In which lines of the code for $\text{RB-DELETE-FIXUP}$ might we examine or modify the sentinel $T.nil$? | When the node $y$ in $\text{RB-DELETE}$ has no children, the node $x = T.nil$, so we'll examine the line 2 of $\text{RB-DELETE-FIXUP}$.
When the root node is deleted, $x = T.nil$ and the root at this time is $x$, so the line 23 of $\text{RB-DELETE-FIXUP}$ will draw $x$ to black. | [] | false | [] |
13-13.4-5 | 13 | 13.4 | 13.4-5 | docs/Chap13/13.4.md | In each of the cases of Figure 13.7, give the count of black nodes from the root of the subtree shown to each of the subtrees $\alpha, \beta, \ldots, \zeta$, and verify that each count remains the same after the transformation. When a node has a $color$ attribute $c$ or $c'$, use the notation $\text{count}\(c\)$ or $\t... | Our count will include the root (if it is black).
- **Case 1:** For each subtree, it is $2$ both before and after.
- **Case 2:**
- For $\alpha$ and $\beta$, it is $1 + \text{count}\(c\)$ in both cases.
- For the rest of the subtrees, it is from $2 + \text{count}\(c\)$ to $1 + \text{count}\(c\)$.
This de... | [] | false | [] |
13-13.4-6 | 13 | 13.4 | 13.4-6 | docs/Chap13/13.4.md | Professors Skelton and Baron are concerned that at the start of case 1 of $\text{RB-DELETE-FIXUP}$, the node $x.p$ might not be black. If the professors are correct, then lines 5–6 are wrong. Show that $x.p$ must be black at the start of case 1, so that the professors have nothing to worry about. | At the start of case 1 we have set $w$ to be the sibling of $x$. We check on line 4 that $w.color == red$, which means that the parent of $x$ and $w$ cannot be red. Otherwise property 4 is violated. Thus, their concerns are unfounded. | [] | false | [] |
13-13.4-7 | 13 | 13.4 | 13.4-7 | docs/Chap13/13.4.md | Suppose that a node $x$ is inserted into a red-black tree with $\text{RB-INSERT}$ and then is immediately deleted with $\text{RB-DELETE}$. Is the resulting red-black tree the same as the initial red-black tree? Justify your answer. | No, the red-black tree will not necessarily be the same.
- Example 1:
- initial:

- insert $1$:

- delete $1$:

- Example 2:
- initial:

- insert $1$:
!... | [] | true | [
"../img/13.4-7-1.png",
"../img/13.4-7-2.png",
"../img/13.4-7-3.png",
"../img/13.4-7-4.png",
"../img/13.4-7-5.png",
"../img/13.4-7-6.png"
] |
13-13-1 | 13 | 13-1 | 13-1 | docs/Chap13/Problems/13-1.md | During the course of an algorithm, we sometimes find that we need to maintain past versions of a dynamic set as it is updated. We call such a set **_persistent_**. One way to implement a persistent set is to copy the entire set whenever it is modified, but this approach can slow down a program and also consume much spa... | (Removed) | [] | false | [] |
13-13-2 | 13 | 13-2 | 13-2 | docs/Chap13/Problems/13-2.md | The **_join_** operation takes two dynamic sets $S_1$ and $S_2$ and an element $x$ such that for any $x_1 \in S_1$ and $x_2 \in S_2$, we have $x_1.key \le x.key \le x_2.key$. It returns a set $S = S_1 \cup \\{x\\} \cup S_2$. In this problem, we investigate how to implement the join operation on red-black trees.
**a.**... | **a.**
- Initialize: $bh = 0$.
- $\text{RB-INSERT}$: if in the last step the root is red, we increase $bh$ by $1$.
- $\text{RB-DELETE}$: if $x$ is root, we decrease $bh$ by $1$.
- Each node: in the simple path, decrease $bh$ by $1$ each time we find a black node.
**b.** Move to the right child if the node has a right... | [
{
"lang": "cpp",
"code": "RB-JOIN'(T[y], x, T[2])\n TRANSPLANT(T[y], x)\n x.left = T[y]\n x.right = T[2]\n T[y].parent = x\n T[2].parent = x"
}
] | false | [] |
13-13-3 | 13 | 13-3 | 13-3 | docs/Chap13/Problems/13-3.md | An **_AVL tree_** is a binary search tree that is **_height balanced_**: for each node $x$, the heights of the left and right subtrees of $x$ differ by at most $1$. To implement an AVL tree, we maintain an extra attribute in each node: $x.h$ is the height of node $x$. As for any other binary search tree $T$, we assume ... | **a.** Let $T(h)$ denote the minimum size of an AVL tree of height $h$. Since it is height $h$, it must have the max of it's children's heights is equal to $h - 1$. Since we are trying to get as few nodes total as possible, suppose that the other child has as small of a height as is allowed. Because of the restriction ... | [
{
"lang": "cpp",
"code": "BALANCE(x)\n while |UNBAL(x)| > 1\n if UNBAL(x) > 0\n RIGHT-ROTATE(T, x)\n else\n LEFT-ROTATE(T, x)\n BALANCE(x.left)\n BALANCE(x.right)"
},
{
"lang": "cpp",
"code": "AVL-INSERT(x, z)\n w = x\n while w !... | false | [] |
13-13-4 | 13 | 13-4 | 13-4 | docs/Chap13/Problems/13-4.md | If we insert a set of $n$ items into a binary search tree, the resulting tree may be horribly unbalanced, leading to long search times. As we saw in Section 12.4, however, randomly built binary search trees tend to be balanced. Therefore, one strategy that, on average, builds a balanced tree for a fixed set of items wo... | **a.** The root is the node with smallest priority, the root divides the sets into two subsets based on the key. In each subset, the node with smallest priority is selected as the root, thus we can uniquely determine a treap with a specific input.
**b.** For the priority of all nodes, each permutation corresponds to e... | [] | false | [] |
14-14.1-1 | 14 | 14.1 | 14.1-1 | docs/Chap14/14.1.md | Show how $\text{OS-SELECT}(T.root, 10)$ operates on the red-black tree $T$ of Figure 14.1. | - $26: r = 13, i = 10$, go left.
- $17: r = 8, i = 10$, go right.
- $21: r = 3, i = 2$, go left.
- $19: r = 1, i = 2$, go right.
- $20: r = 1, i = 1$, choose $20$. | [] | false | [] |
14-14.1-2 | 14 | 14.1 | 14.1-2 | docs/Chap14/14.1.md | Show how $\text{OS-RANK}(T, x)$ operates on the red-black tree $T$ of Figure 14.1 and the node $x$ with $x.key = 35$. | - $35: r = 1$.
- $38: r = 1$.
- $30: r = r + 2 = 3$.
- $41: r = 3$.
- $26: r = r + 13 = 16$. | [] | false | [] |
14-14.1-3 | 14 | 14.1 | 14.1-3 | docs/Chap14/14.1.md | Write a nonrecursive version of $\text{OS-SELECT}$. | ```cpp
OS-SELECT(x, i)
r = x.left.size + 1
while r != i
if i < r
x = x.left
else x = x.right
i = i - r
r = x.left.size + 1
return x
``` | [
{
"lang": "cpp",
"code": "OS-SELECT(x, i)\n r = x.left.size + 1\n while r != i\n if i < r\n x = x.left\n else x = x.right\n i = i - r\n r = x.left.size + 1\n return x"
}
] | false | [] |
14-14.1-4 | 14 | 14.1 | 14.1-4 | docs/Chap14/14.1.md | Write a recursive procedure $\text{OS-KEY-RANK}(T, k)$ that takes as input an order-statistic tree $T$ and a key $k$ and returns the rank of $k$ in the dynamic set represented by $T$. Assume that the keys of $T$ are distinct. | ```cpp
OS-KEY-RANK(T, k)
if k == T.root.key
return T.root.left.size + 1
else if T.root.key > k
return OS-KEY-RANK(T.left, k)
else return T.root.left.size + 1 + OS-KEY-RANK(T.right, k)
``` | [
{
"lang": "cpp",
"code": "OS-KEY-RANK(T, k)\n if k == T.root.key\n return T.root.left.size + 1\n else if T.root.key > k\n return OS-KEY-RANK(T.left, k)\n else return T.root.left.size + 1 + OS-KEY-RANK(T.right, k)"
}
] | false | [] |
14-14.1-5 | 14 | 14.1 | 14.1-5 | docs/Chap14/14.1.md | Given an element $x$ in an $n$-node order-statistic tree and a natural number $i$, how can we determine the $i$th successor of $x$ in the linear order of the tree in $O(\lg n)$ time? | The desired result is $\text{OS-SELECT}(T, \text{OS-RANK}(T, x) + i)$. This has runtime $O(h)$, which by the properties of red black trees, is $O(\lg n)$. | [] | false | [] |
14-14.1-6 | 14 | 14.1 | 14.1-6 | docs/Chap14/14.1.md | Observe that whenever we reference the size attribute of a node in either $\text{OS-SELECT}$ or $\text{OS-RANK}$, we use it only to compute a rank. Accordingly, suppose we store in each node its rank in the subtree of which it is the root. Show how to maintain this information during insertion and deletion. (Remember t... | First perform the usual BST insertion procedure on $z$, the node to be inserted. Then add $1$ to the rank of every node on the path from the root to $z$ such that $z$ is in the left subtree of that node. Since the added node is a leaf, it will have no subtrees so its rank will always be $1$.
When a left rotation is pe... | [] | false | [] |
14-14.1-7 | 14 | 14.1 | 14.1-7 | docs/Chap14/14.1.md | Show how to use an order-statistic tree to count the number of inversions (see Problem 2-4) in an array of size $n$ in time $O(n\lg n)$. | The runtime to build a red-black tree is $O(n\lg n)$, so we need to calculate inversions while building trees.
Every time $\text{INSERT}$, we can use $\text{OS-RANK}$ to calculate the rank of the node, thus calculating inversions. | [] | false | [] |
14-14.1-8 | 14 | 14.1 | 14.1-8 $\star$ | docs/Chap14/14.1.md | Consider $n$ chords on a circle, each defined by its endpoints. Describe an $O(n\lg n)$-time algorithm to determine the number of pairs of chords that intersect inside the circle. (For example, if the $n$ chords are all diameters that meet at the center, then the correct answer is $\binom{n}{2}$.) Assume that no two ch... | Sort the vertices in clock-wise order, and assign a unique value to each vertex. For each chord its two vertices are $u_i$, $v_i$ and $u_i < v_i$. Add the vertices one by one in clock-wise order, if we meet a $u_i$, we add it to the order-statistic tree, if we meet a $v_i$, we calculate how many nodes are larger than $... | [] | false | [] |
14-14.2-1 | 14 | 14.2 | 14.2-1 | docs/Chap14/14.2.md | Show, by adding pointers to the nodes, how to support each of the dynamic-set queries $\text{MINIMUM}$, $\text{MAXIMUM}$, $\text{SUCCESSOR}$, and $\text{PREDECESSOR}$ in $O(1)$worstcase time on an augmented order-statistic tree. The asymptotic performance of other operations on order-statistic trees should not be affec... | - **MINIMUM:** A pointer points to the minimum node, if the node is being deleted, move the pointer to its successor.
- **MAXIMUM:** Similar to $\text{MINIMUM}$.
- **SUCCESSOR:** Every node records its successor, the insertion and deletion is similar to that in linked list.
- **PREDECESSOR:** Similar to $\text{MAXIMUM}... | [] | false | [] |
14-14.2-2 | 14 | 14.2 | 14.2-2 | docs/Chap14/14.2.md | Can we maintain the black-heights of nodes in a red-black tree as attributes in the nodes of the tree without affecting the asymptotic performance of any of the redblack tree operations? Show how, or argue why not. How about maintaining the depths of nodes? | Since the black height of a node depends only on the black height and color of its children, Theorem 14.1 implies that we can maintain the attribute without affecting the asymptotic performance of the other red-black tree operations. The same is not true for maintaining the depths of nodes. If we delete the root of a t... | [] | false | [] |
14-14.2-3 | 14 | 14.2 | 14.2-3 $\star$ | docs/Chap14/14.2.md | Let $\otimes$ be an associative binary operator, and let $a$ be an attribute maintained in each node of a red-black tree. Suppose that we want to include in each node $x$ an additional attribute $f$ such that $x.f = x_1.a \otimes x_2.a \otimes \cdots \otimes x_m.a$, where $x_1, x_2, \ldots ,x_m$ is the inorder listing ... | $x.f = x.left.f \otimes x.a \otimes x.right.f$. | [] | false | [] |
14-14.2-4 | 14 | 14.2 | 14.2-4 $\star$ | docs/Chap14/14.2.md | We wish to augment red-black trees with an operation $\text{RB-ENUMERATE}(x, a, b)$ that outputs all the keys $k$ such that $a \le k \le b$ in a red-black tree rooted at $x$. Describe how to implement $\text{RB-ENUMERATE}$ in $\Theta(m+\lg n)$ time, where $m$ is the number of keys that are output and $n$ is the number ... | - $\Theta(\lg n)$: Find the smallest key that larger than or equal to $a$.
- $\Theta(m)$: Based on Exercise 14.2-1, find the $m$ successor. | [] | false | [] |
14-14.3-1 | 14 | 14.3 | 14.3-1 | docs/Chap14/14.3.md | Write pseudocode for $\text{LEFT-ROTATE}$ that operates on nodes in an interval tree and updates the $max$ attributes in $O(1)$ time. | Add 2 lines in $\text{LEFT-ROTATE}$ in 13.2
```cpp
y.max = x.max
x.max = max(x.high, x.left.max, x.right.max)
``` | [
{
"lang": "cpp",
"code": " y.max = x.max\n x.max = max(x.high, x.left.max, x.right.max)"
}
] | false | [] |
14-14.3-2 | 14 | 14.3 | 14.3-2 | docs/Chap14/14.3.md | Rewrite the code for $\text{INTERVAL-SEARCH}$ so that it works properly when all intervals are open. | ```cpp
INTERVAL-SEARCH(T, i)
x = T.root
while x != T.nil and i does not overlap x.int
if x.left != T.nil and x.left.max > i.low
x = x.left
else x = x.right
return x
``` | [
{
"lang": "cpp",
"code": "INTERVAL-SEARCH(T, i)\n x = T.root\n while x != T.nil and i does not overlap x.int\n if x.left != T.nil and x.left.max > i.low\n x = x.left\n else x = x.right\n return x"
}
] | false | [] |
14-14.3-3 | 14 | 14.3 | 14.3-3 | docs/Chap14/14.3.md | Describe an efficient algorithm that, given an interval $i$ , returns an interval overlapping $i$ that has the minimum low endpoint, or $T.nil$ if no such interval exists. | Consider the usual interval search given, but, instead of breaking out of the loop as soon as we have an overlap, we just keep track of the overlap that has the minimum low endpoint, and continue the loop. After the loop terminates, we return the overlap stored. | [] | false | [] |
14-14.3-4 | 14 | 14.3 | 14.3-4 | docs/Chap14/14.3.md | Given an interval tree $T$ and an interval $i$, describe how to list all intervals in $T$ that overlap $i$ in $O(\min(n, k \lg n))$ time, where $k$ is the number of intervals in the output list. ($\textit{Hint:}$ One simple method makes several queries, modifying the tree between queries. A slightly more complicated me... | ```cpp
INTERVALS-SEARCH(T, x, i)
let list be an empty array
if i overlaps x.int
list.APPEND(x)
if x.left != T.nil and x.left.max > i.low
list = list.APPEND(INTERVALS-SEARCH(T, x.left, i))
if x.right != T.nil and x.int.low ≤ i.high and x.right.max ≥ i.low
list = list.APPEND(INTERV... | [
{
"lang": "cpp",
"code": "INTERVALS-SEARCH(T, x, i)\n let list be an empty array\n if i overlaps x.int\n list.APPEND(x)\n if x.left != T.nil and x.left.max > i.low\n list = list.APPEND(INTERVALS-SEARCH(T, x.left, i))\n if x.right != T.nil and x.int.low ≤ i.high and x.right.max ≥ i.... | false | [] |
14-14.3-5 | 14 | 14.3 | 14.3-5 | docs/Chap14/14.3.md | Suggest modifications to the interval-tree procedures to support the new operation $\text{INTERVAL-SEARCH-EXACTLY}(T, i)$, where $T$ is an interval tree and $i$ is an interval. The operation should return a pointer to a node $x$ in $T$ such that $x.int.low = i.low$ and $x.int.high = i.high$, or $T.nil$ if $T$ contains ... | Search for nodes which has exactly the same low value.
```cpp
INTERVAL-SEARCH-EXACTLY(T, i)
x = T.root
while x != T.nil and i not exactly overlap x
if i.high > x.max
x = T.nil
else if i.low < x.low
x = x.left
else if i.low > x.low
x = x.right
... | [
{
"lang": "cpp",
"code": "INTERVAL-SEARCH-EXACTLY(T, i)\n x = T.root\n while x != T.nil and i not exactly overlap x\n if i.high > x.max\n x = T.nil\n else if i.low < x.low\n x = x.left\n else if i.low > x.low\n x = x.right\n else x = T.nil\n... | false | [] |
14-14.3-6 | 14 | 14.3 | 14.3-6 | docs/Chap14/14.3.md | Show how to maintain a dynamic set $Q$ of numbers that supports the operation $\text{MIN-GAP}$, which gives the magnitude of the difference of the two closest numbers in $Q$. For example, if $Q = \\{1, 5, 9, 15, 18, 22 \\}$, then $\text{MIN-GAP}(Q)$ returns $18 - 15 = 3$, since $15$ and $18$ are the two closest numbers... | Store the elements in a red-black tree, where the key value is the value of each number itself. The auxiliary attribute stored at a node $x$ will be the min gap between elements in the subtree rooted at $x$, the maximum value contained in subtree rooted at $x$, and the minimum value contained in the subtree rooted at $... | [] | false | [] |
14-14.3-7 | 14 | 14.3 | 14.3-7 $\star$ | docs/Chap14/14.3.md | VLSI databases commonly represent an integrated circuit as a list of rectangles. Assume that each rectangle is rectilinearly oriented (sides parallel to the $x$- and $y$-axes), so that we represent a rectangle by its minimum and maximum $x$ and $y$-coordinates. Give an $O(n\lg n)$-time algorithm to decide whether or no... | Let $L$ be the set of left coordinates of rectangles. Let $R$ be the set of right coordinates of rectangles. Sort both of these sets in $O(n\lg n)$ time. Then, we will have a pointer to $L$ and a pointer to $R$. If the pointer to $L$ is smaller, call interval search on $T$ for the up-down interval corresponding to this... | [] | false | [] |
14-14-1 | 14 | 14-1 | 14-1 | docs/Chap14/Problems/14-1.md | Suppose that we wish to keep track of a **_point of maximum overlap_** in a set of intervals—a point with the largest number of intervals in the set that overlap it.
**a.** Show that there will always be a point of maximum overlap that is an endpoint of one of the segments.
**b.** Design a data structure that efficie... | (Removed) | [] | false | [] |
14-14-2 | 14 | 14-2 | 14-2 | docs/Chap14/Problems/14-2.md | We define the **_Josephus problem_** as follows. Suppose that $n$ people form a circle and that we are given a positive integer $m \le n$. Beginning with a designated first person, we proceed around the circle, removing every $m$th person. After each person is removed, counting continues around the circle that remains.... | (Removed) | [] | false | [] |
15-15.1-1 | 15 | 15.1 | 15.1-1 | docs/Chap15/15.1.md | Show that equation $\text{(15.4)}$ follows from equation $\text{(15.3)}$ and the initial condition $T(0) = 1$. | - For $n = 0$, this holds since $2^0 = 1$.
- For $n > 0$, substituting into the recurrence, we have
$$
\begin{aligned}
T(n) & = 1 + \sum_{j = 0}^{n - 1} 2^j \\\\
& = 1 + (2^n - 1) \\\\
& = 2^n.
\end{aligned}
$$ | [] | false | [] |
15-15.1-2 | 15 | 15.1 | 15.1-2 | docs/Chap15/15.1.md | Show, by means of a counterexample, that the following "greedy" strategy does not always determine an optimal way to cut rods. Define the **_density_** of a rod of length $i$ to be $p_i / i$, that is, its value per inch. The greedy strategy for a rod of length $n$ cuts off a first piece of length $i$, where $1 \le i \l... | The counterexample:
$$
\begin{array}{c|cccc}
\text{length $i$} & 1 & 2 & 3 & 4 \\\\
\hline
\text{price $p_i$} & 1 & 20 & 33 & 36 \\\\
p_i / i & 1 & 10 & 11 & 9
\end{array}
$$ | [] | false | [] |
15-15.1-3 | 15 | 15.1 | 15.1-3 | docs/Chap15/15.1.md | Consider a modification of the rod-cutting problem in which, in addition to a price $p_i$ for each rod, each cut incurs a fixed cost of $c$. The revenue associated with a solution is now the sum of the prices of the pieces minus the costs of making the cuts. Give a dynamic-programming algorithm to solve this modified p... | We can modify $\text{BOTTOM-UP-CUT-ROD}$ algorithm from section 15.1 as follows:
```cpp
MODIFIED-CUT-ROD(p, n, c)
let r[0..n] be a new array
r[0] = 0
for j = 1 to n
q = p[j]
for i = 1 to j - 1
q = max(q, p[i] + r[j - i] - c)
r[j] = q
return r[n]
```
We need to accou... | [
{
"lang": "cpp",
"code": "MODIFIED-CUT-ROD(p, n, c)\n let r[0..n] be a new array\n r[0] = 0\n for j = 1 to n\n q = p[j]\n for i = 1 to j - 1\n q = max(q, p[i] + r[j - i] - c)\n r[j] = q\n return r[n]"
}
] | false | [] |
15-15.1-4 | 15 | 15.1 | 15.1-4 | docs/Chap15/15.1.md | Modify $\text{MEMOIZED-CUT-ROD}$ to return not only the value but the actual solution, too. | ```cpp
MEMOIZED-CUT-ROD(p, n)
let r[0..n] and s[0..n] be new arrays
for i = 0 to n
r[i] = -∞
(val, s) = MEMOIZED-CUT-ROD-AUX(p, n, r, s)
print "The optimal value is" val "and the cuts are at" s
j = n
while j > 0
print s[j]
j = j - s[j]
```
```cpp
MEMOIZED-CUT-ROD-AUX(p, ... | [
{
"lang": "cpp",
"code": "MEMOIZED-CUT-ROD(p, n)\n let r[0..n] and s[0..n] be new arrays\n for i = 0 to n\n r[i] = -∞\n (val, s) = MEMOIZED-CUT-ROD-AUX(p, n, r, s)\n print \"The optimal value is\" val \"and the cuts are at\" s\n j = n\n while j > 0\n print s[j]\n j = j... | false | [] |
15-15.1-5 | 15 | 15.1 | 15.1-5 | docs/Chap15/15.1.md | The Fibonacci numbers are defined by recurrence $\text{(3.22)}$. Give an $O(n)$-time dynamic-programming algorithm to compute the nth Fibonacci number. Draw the subproblem graph. How many vertices and edges are in the graph? | ```cpp
FIBONACCI(n)
let fib[0..n] be a new array
fib[0] = 1
fib[1] = 1
for i = 2 to n
fib[i] = fib[i - 1] + fib[i - 2]
return fib[n]
```
There are $n + 1$ vertices in the subproblem graph, i.e., $v_0, v_1, \dots, v_n$.
- For $v_0, v_1$, each has $0$ leaving edge.
- For $v_2, v_3, \dots, v_... | [
{
"lang": "cpp",
"code": "FIBONACCI(n)\n let fib[0..n] be a new array\n fib[0] = 1\n fib[1] = 1\n for i = 2 to n\n fib[i] = fib[i - 1] + fib[i - 2]\n return fib[n]"
}
] | false | [] |
15-15.2-1 | 15 | 15.2 | 15.2-1 | docs/Chap15/15.2.md | Find an optimal parenthesization of a matrix-chain product whose sequence of dimensions is $\langle 5, 10, 3, 12, 5, 50, 6 \rangle$. | $$((5 \times 10)(10 \times 3))(((3 \times 12)(12 \times 5))((5 \times 50)(50 \times 6))).$$ | [] | false | [] |
15-15.2-2 | 15 | 15.2 | 15.2-2 | docs/Chap15/15.2.md | Give a recursive algorithm $\text{MATRIX-CHAIN-MULTIPLY}(A, s, i, j)$ that actually performs the optimal matrix-chain multiplication, given the sequence of matrices $\langle A_1, A_2, \ldots ,A_n \rangle$, the $s$ table computed by $\text{MATRIX-CHAIN-ORDER}$, and the indices $i$ and $j$. (The initial call would be $\t... | ```cpp
MATRIX-CHAIN-MULTIPLY(A, s, i, j)
if i == j
return A[i]
if i + 1 == j
return A[i] * A[j]
b = MATRIX-CHAIN-MULTIPLY(A, s, i, s[i, j])
c = MATRIX-CHAIN-MULTIPLY(A, s, s[i, j] + 1, j)
return b * c
``` | [
{
"lang": "cpp",
"code": "MATRIX-CHAIN-MULTIPLY(A, s, i, j)\n if i == j\n return A[i]\n if i + 1 == j\n return A[i] * A[j]\n b = MATRIX-CHAIN-MULTIPLY(A, s, i, s[i, j])\n c = MATRIX-CHAIN-MULTIPLY(A, s, s[i, j] + 1, j)\n return b * c"
}
] | false | [] |
15-15.2-3 | 15 | 15.2 | 15.2-3 | docs/Chap15/15.2.md | Use the substitution method to show that the solution to the recurrence $\text{(15.6)}$ is $\Omega(2^n)$. | Suppose $P(n) \ge c2^n$,
$$
\begin{aligned}
P(n) & \ge \sum_{k = 1}^{n - 1} c2^k \cdot c2^{n - k} \\\\
& = \sum_{k = 1}^{n - 1} c^2 2^n \\\\
& = c^2 (n - 1) 2^n \\\\
& \ge c^2 2^n & (n > 1) \\\\
& \ge c 2^n. & (c \ge 1)
\end{aligned}
$$ | [] | false | [] |
15-15.2-4 | 15 | 15.2 | 15.2-4 | docs/Chap15/15.2.md | Describe the subproblem graph for matrix-chain multiplication with an input chain of length $n$. How many vertices does it have? How many edges does it have, and which edges are they? | The vertices of the subproblem graph are the ordered pair $v_{ij}$, where $i \le j$.
- If $i = j$, the vertex $v_{ij}$ has no output edge.
- If $i < j$, for each $k$, s.t. $i \le k < j$, the subproblem graph contains edges $(v_{ij}, v_{ik})$ and $(v_{ij}, v_{k+1, j})$, and these edges indicate that to solve the subpro... | [] | false | [] |
15-15.2-5 | 15 | 15.2 | 15.2-5 | docs/Chap15/15.2.md | Let $R(i, j)$ be the number of times that table entry $m[i, j]$ is referenced while computing other table entries in a call of $\text{MATRIX-CHAIN-ORDER}$. Show that the total number of references for the entire table is
$$\sum_{i = 1}^n \sum_{j = i}^n R(i, j) = \frac{n^3 - n}{3}.$$
($\textit{Hint:}$ You may find equ... | We count the number of times that we reference a different entry in $m$ than the one we are computing, that is, $2$ times the number of times that line 10 runs.
$$
\begin{aligned}
\sum_{l = 2}^n \sum_{i = 1}^{n - l + 1} \sum_{k = i}^{i + l - 2} 2
& = \sum_{l = 2}^n \sum_{i = 1}^{n - l + 1} 2(l - 1) \\\\
& = \s... | [] | false | [] |
15-15.2-6 | 15 | 15.2 | 15.2-6 | docs/Chap15/15.2.md | Show that a full parenthesization of an $n$-element expression has exactly $n - 1$ pairs of parentheses. | We proceed by induction on the number of matrices. A single matrix has no pairs of parentheses. Assume that a full parenthesization of an $n$-element expression has exactly $n − 1$ pairs of parentheses. Given a full parenthesization of an $(n + 1)$-element expression, there must exist some $k$ such that we first multip... | [] | false | [] |
15-15.3-1 | 15 | 15.3 | 15.3-1 | docs/Chap15/15.3.md | Which is a more efficient way to determine the optimal number of multiplications in a matrix-chain multiplication problem: enumerating all the ways of parenthesizing the product and computing the number of multiplications for each, or running $\text{RECURSIVE-MATRIX-CHAIN}$? Justify your answer. | Running $\text{RECURSIVE-MATRIX-CHAIN}$ is asymptotically more efficient than enumerating all the ways of parenthesizing the product and computing the number of multiplications for each.
Consider the treatment of subproblems by each approach:
1. For each possible place to split the matrix chain, the enumeration appro... | [] | false | [] |
15-15.3-2 | 15 | 15.3 | 15.3-2 | docs/Chap15/15.3.md | Draw the recursion tree for the $\text{MERGE-SORT}$ procedure from Section 2.3.1 on an array of $16$ elements. Explain why memoization fails to speed up a good divide-and-conquer algorithm such as $\text{MERGE-SORT}$. | Draw a recursion tree.

The $\text{MERGE-SORT}$ procedure performs at most a single call to any pair of indices of the array that is being sorted. In other words, the subproblems do not overlap and therefore memoization will not improve the running time. | [] | true | [
"../img/15.3-2.png"
] |
15-15.3-3 | 15 | 15.3 | 15.3-3 | docs/Chap15/15.3.md | Consider a variant of the matrix-chain multiplication problem in which the goal is to parenthesize the sequence of matrices so as to maximize, rather than minimize, the number of scalar multiplications. Does this problem exhibit optimal substructure? | Yes, this problem also exhibits optimal substructure. If we know that we need the subproduct $(A_l \cdot A_r)$, then we should still find the most expensive way to compute it — otherwise, we could do better by substituting in the most expensive way. | [] | false | [] |
15-15.3-4 | 15 | 15.3 | 15.3-4 | docs/Chap15/15.3.md | As stated, in dynamic programming we first solve the subproblems and then choose which of them to use in an optimal solution to the problem. Professor Capulet claims that we do not always need to solve all the subproblems in order to find an optimal solution. She suggests that we can find an optimal solution to the mat... | Suppose that we are given matrices $A_1$, $A_2$, $A_3$, and $A_4$ with dimensions such that
$$p_0, p_1, p_2, p_3, p_4 = 1000, 100, 20, 10, 1000.$$
Then $p_0 p_k p_4$ is minimized when $k = 3$, so we need to solve the subproblem of multiplying $A_1 A_2 A_3$, and also $A_4$ which is solved automatically. By her algorit... | [] | false | [] |
15-15.3-5 | 15 | 15.3 | 15.3-5 | docs/Chap15/15.3.md | Suppose that in the rod-cutting problem of Section 15.1, we also had limit $l_i$ on the number of pieces of length $i$ that we are allowed to produce, for $i = 1, 2, \ldots, n$. Show that the optimal-substructure property described in Section 15.1 no longer holds. | The optimal substructure property doesn't hold because the number of pieces of length $i$ used on one side of the cut affects the number allowed on the other. That is, there is information about the particular solution on one side of the cut that changes what is allowed on the other.
To make this more concrete, suppos... | [] | false | [] |
15-15.3-6 | 15 | 15.3 | 15.3-6 | docs/Chap15/15.3.md | Imagine that you wish to exchange one currency for another. You realize that instead of directly exchanging one currency for another, you might be better off making a series of trades through other currencies, winding up with the currency you want. Suppose that you can trade $n$ different currencies, numbered $1, 2, \l... | First we assume that the commission is always zero. Let $k$ denote a currency which appears in an optimal sequence $s$ of trades to go from currency $1$ to currency $n$. $p_k$ denote the first part of this sequence which changes currencies from $1$ to $k$ and $q_k$ denote the rest of the sequence. Then $p_k$ and $q_k$ ... | [] | false | [] |
15-15.4-1 | 15 | 15.4 | 15.4-1 | docs/Chap15/15.4.md | Determine an $\text{LCS}$ of $\langle 1, 0, 0, 1, 0, 1, 0, 1 \rangle$ and $\langle 0, 1, 0, 1, 1, 0, 1, 1, 0 \rangle$. | $\langle 1, 0, 0, 1, 1, 0 \rangle$ or $\langle 1, 0, 1, 0, 1, 0 \rangle$. | [] | false | [] |
15-15.4-2 | 15 | 15.4 | 15.4-2 | docs/Chap15/15.4.md | Give pseudocode to reconstruct an $\text{LCS}$ from the completed $c$ table and the original sequences $X = \langle x_1, x_2, \ldots, x_m \rangle$ and $Y = \langle y_1, y_2, \ldots, y_n \rangle$ in $O(m + n)$ time, without using the $b$ table. | ```cpp
PRINT-LCS(c, X, Y, i, j)
if c[i, j] == 0
return
if X[i] == Y[j]
PRINT-LCS(c, X, Y, i - 1, j - 1)
print X[i]
else if c[i - 1, j] > c[i, j - 1]
PRINT-LCS(c, X, Y, i - 1, j)
else
PRINT-LCS(c, X, Y, i, j - 1)
``` | [
{
"lang": "cpp",
"code": "PRINT-LCS(c, X, Y, i, j)\n if c[i, j] == 0\n return\n if X[i] == Y[j]\n PRINT-LCS(c, X, Y, i - 1, j - 1)\n print X[i]\n else if c[i - 1, j] > c[i, j - 1]\n PRINT-LCS(c, X, Y, i - 1, j)\n else\n PRINT-LCS(c, X, Y, i, j - 1)"
}
] | false | [] |
15-15.4-3 | 15 | 15.4 | 15.4-3 | docs/Chap15/15.4.md | Give a memoized version of $\text{LCS-LENGTH}$ that runs in $O(mn)$ time. | ```cpp
MEMOIZED-LCS-LENGTH(X, Y, i, j)
if c[i, j] > -1
return c[i, j]
if i == 0 or j == 0
return c[i, j] = 0
if x[i] == y[j]
return c[i, j] = LCS-LENGTH(X, Y, i - 1, j - 1) + 1
return c[i, j] = max(LCS-LENGTH(X, Y, i - 1, j), LCS-LENGTH(X, Y, i, j - 1))
``` | [
{
"lang": "cpp",
"code": "MEMOIZED-LCS-LENGTH(X, Y, i, j)\n if c[i, j] > -1\n return c[i, j]\n if i == 0 or j == 0\n return c[i, j] = 0\n if x[i] == y[j]\n return c[i, j] = LCS-LENGTH(X, Y, i - 1, j - 1) + 1\n return c[i, j] = max(LCS-LENGTH(X, Y, i - 1, j), LCS-LENGTH(X, Y,... | false | [] |
15-15.4-4 | 15 | 15.4 | 15.4-4 | docs/Chap15/15.4.md | Show how to compute the length of an $\text{LCS}$ using only $2 \cdot \min(m, n)$ entries in the $c$ table plus $O(1)$ additional space. Then show how to do the same thing, but using $\min(m, n)$ entries plus $O(1)$ additional space. | Since we only use the previous row of the $c$ table to compute the current row, we compute as normal, but when we go to compute row $k$, we free row $k - 2$ since we will never need it again to compute the length. To use even less space, observe that to compute $c[i, j]$, all we need are the entries $c[i − 1, j]$, $c[i... | [] | false | [] |
15-15.4-5 | 15 | 15.4 | 15.4-5 | docs/Chap15/15.4.md | Give an $O(n^2)$-time algorithm to find the longest monotonically increasing subsequence of a sequence of $n$ numbers. | Given a list of numbers $L$, make a copy of $L$ called $L'$ and then sort $L'$.
```cpp
PRINT-LCS(c, X, Y)
n = c[X.length, Y.length]
let s[1..n] be a new array
i = X.length
j = Y.length
while i > 0 and j > 0
if x[i] == y[j]
s[n] = x[i]
n = n - 1
i = i - 1
... | [
{
"lang": "cpp",
"code": "PRINT-LCS(c, X, Y)\n n = c[X.length, Y.length]\n let s[1..n] be a new array\n i = X.length\n j = Y.length\n while i > 0 and j > 0\n if x[i] == y[j]\n s[n] = x[i]\n n = n - 1\n i = i - 1\n j = j - 1\n else if c... | false | [] |
15-15.4-6 | 15 | 15.4 | 15.4-6 $\star$ | docs/Chap15/15.4.md | Give an $O(n\lg n)$-time algorithm to find the longest monotonically increasing subsequence of a sequence of $n$ numbers. ($\textit{Hint:}$ Observe that the last element of a candidate subsequence of length $i$ is at least as large as the last element of a candidate subsequence of length $i - 1$. Maintain candidate sub... | The algorithm $\text{LONG-MONOTONIC}(A)$ returns the longest monotonically increasing subsequence of $A$, where $A$ has length $n$.
The algorithm works as follows: a new array B will be created such that $B[i]$ contains the last value of a longest monotonically increasing subsequence of length $i$. A new array $C$ wil... | [
{
"lang": "cpp",
"code": "LONG-MONOTONIC(A)\n let B[1..n] be a new array where every value = ∞\n let C[1..n] be a new array\n L = 1\n for i = 1 to n\n if A[i] < B[1]\n B[1] = A[i]\n C[1].head.key = A[i]\n else\n let j be the largest index of B such ... | false | [] |
15-15.5-1 | 15 | 15.5 | 15.5-1 | docs/Chap15/15.5.md | Write pseudocode for the procedure $\text{CONSTRUCT-OPTIMAL-BST}(root)$ which, given the table $root$, outputs the structure of an optimal binary search tree. For the example in Figure 15.10, your procedure should print out the structure
$$
\begin{aligned}
& \text{$k_2$ is the root} \\\\
& \text{$k_1$ is the left chi... | ```cpp
CONSTRUCT-OPTIMAL-BST(root, i, j, last)
if i == j
return
if last == 0
print root[i, j] + "is the root"
else if j < last
print root[i, j] + "is the left child of" + last
else
print root[i, j] + "is the right child of" + last
CONSTRUCT-OPTIMAL-BST(root, i, root[i... | [
{
"lang": "cpp",
"code": "CONSTRUCT-OPTIMAL-BST(root, i, j, last)\n if i == j\n return\n if last == 0\n print root[i, j] + \"is the root\"\n else if j < last\n print root[i, j] + \"is the left child of\" + last\n else\n print root[i, j] + \"is the right child of\" + l... | false | [] |
15-15.5-2 | 15 | 15.5 | 15.5-2 | docs/Chap15/15.5.md | Determine the cost and structure of an optimal binary search tree for a set of $n = 7$ keys with the following probabilities
$$
\begin{array}{c|cccccccc}
i & 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 \\\\
\hline
p_i & & 0.04 & 0.06 & 0.08 & 0.02 & 0.10 & 0.12 & 0.14 \\\\
q_i & 0.06 & 0.06 & 0.06 & 0.06... | Cost is $3.12$.
$$
\begin{aligned}
& \text{$k_5$ is the root} \\\\
& \text{$k_2$ is the left child of $k_5$} \\\\
& \text{$k_1$ is the left child of $k_2$} \\\\
& \text{$d_0$ is the left child of $k_1$} \\\\
& \text{$d_1$ is the right child of $k_1$} \\\\
& \text{$k_3$ is the right child of $k_2$} \\\\
& \text{$d_2... | [] | false | [] |
15-15.5-3 | 15 | 15.5 | 15.5-3 | docs/Chap15/15.5.md | Suppose that instead of maintaining the table $w[i, j]$, we computed the value of $w(i, j)$ directly from equation $\text{(15.12)}$ in line 9 of $\text{OPTIMAL-BST}$ and used this computed value in line 11. How would this change affect the asymptotic running time of $\text{OPTIMAL-BST}$? | Computing $w(i, j)$ from the equation is $\Theta(j - i)$, since the loop below on lines 10-14 is also $\Theta(j - i)$, it wouldn't affect the asymptotic running time of $\text{OPTIMAL-BST}$ which would stay $\Theta(n^3)$. | [] | false | [] |
15-15.5-4 | 15 | 15.5 | 15.5-4 $\star$ | docs/Chap15/15.5.md | Knuth [212] has shown that there are always roots of optimal subtrees such that $root[i, j - 1] \le root[i, j] \le root[i + 1, j]$ for all $1 \le i < j \le n$. Use this fact to modify the $\text{OPTIMAL-BST}$ procedure to run in $\Theta(n^2)$ time. | Change the **for** loop of line 10 in $\text{OPTIMAL-BST}$ to
```cpp
for r = r[i, j - 1] to r[i + 1, j]
```
Knuth's result implies that it is sufficient to only check these values because optimal root found in this range is in fact the optimal root of some binary search tree. The time spent within the **for** loo... | [
{
"lang": "cpp",
"code": " for r = r[i, j - 1] to r[i + 1, j]"
}
] | false | [] |
15-15-1 | 15 | 15-1 | 15-1 | docs/Chap15/Problems/15-1.md | Suppose that we are given a directed acyclic graph $G = (V, E)$ with real-valued edge weights and two distinguished vertices $s$ and $t$ . Describe a dynamic-programming approach for finding a longest weighted simple path from $s$ to $t$. What does the subproblem graph look like? What is the efficiency of your algorith... | First, we clarify the question. We define the weight of a path to be the sum of the weights of the edges in the path. Then, our task is to find the path from $s$ to $t$ that has the largest weight.
$\textbf{Dynamic-programming approach}$
From a given vertex, we try all outgoing edges and take the max over the weights... | [] | false | [] |
15-15-10 | 15 | 15-10 | 15-10 | docs/Chap15/Problems/15-10.md | Your knowledge of algorithms helps you obtain an exciting job with the Acme Computer Company, along with a $\$10,000$ signing bonus. You decide to invest this money with the goal of maximizing your return at the end of 10 years. You decide to use the Amalgamated Investment Company to manage your investments. Amalgamate... | **a.** Without loss of generality, suppose that there exists an optimal solution $S$ which involves investing $d_1$ dollars into investment $k$ and $d_2$ dollars into investement $m$ in year $1$. Further, suppose in this optimal solution, you don't move your money for the first $j$ years. If $r_{k1} + r_{k2} + \ldots +... | [
{
"lang": "cpp",
"code": "INVEST(d, n)\n let I[1..10] and R[1..10] be new tables\n for k = 10 downto 1\n q = 1\n for i = 1 to n\n if r[i, k] > r[q, k] // i now holds the investment which looks best for a given year\n q = i\n if R[k + 1] + dr_{I[k + 1]k}... | false | [] |
15-15-11 | 15 | 15-11 | 15-11 | docs/Chap15/Problems/15-11.md | The Rinky Dink Company makes machines that resurface ice rinks. The demand for such products varies from month to month, and so the company needs to develop a strategy to plan its manufacturing given the fluctuating, but predictable, demand. The company wishes to design a plan for the next $n$ months. For each month $i... | Our subproblems will be indexed by and integer $i \in [n]$ and another integer $j \in [D]$. $i$ will indicate how many months have passed, that is, we will restrict ourselves to only caring about $(d_i, \dots, d_n)$. $j$ will indicate how many machines we have in stock initially. Then, the recurrence we will use will t... | [] | false | [] |
15-15-12 | 15 | 15-12 | 15-12 | docs/Chap15/Problems/15-12.md | Suppose that you are the general manager for a major-league baseball team. During the off-season, you need to sign some free-agent players for your team. The team owner has given you a budget of $\$X$ to spend on free agents. You are allowed to spend less than $\$X$ altogether, but the owner will fire you if you spend ... | We will make an $N + 1$ by $X + 1$ by $P + 1$ table. The runtime of the algorithm is $O(NXP)$.
```cpp
BASEBALL(N, X, P)
initialize a table B of size (N + 1) by (X + 1)
initialize an array P of length N
for i = 0 to N
B[i, 0] = 0
for j = 1 to X
B[0, j] = 0
for i = 1 to N
for ... | [
{
"lang": "cpp",
"code": "BASEBALL(N, X, P)\n initialize a table B of size (N + 1) by (X + 1)\n initialize an array P of length N\n for i = 0 to N\n B[i, 0] = 0\n for j = 1 to X\n B[0, j] = 0\n for i = 1 to N\n for j = 1 to X\n if j < i.cost\n B[... | false | [] |
15-15-2 | 15 | 15-2 | 15-2 | docs/Chap15/Problems/15-2.md | A **_palindrome_** is a nonempty string over some alphabet that reads the same forward and backward. Examples of palindromes are all strings of length $1$, $\text{civic}$, $\text{racecar}$, and $\text{aibohphobia}$ (fear of palindromes).
Give an efficient algorithm to find the longest palindrome that is a subsequence ... | Let $A[1..n]$ denote the array which contains the given word. First note that for a palindrome to be a subsequence we must be able to divide the input word at some position $i$, and then solve the longest common subsequence problem on $A[1..i]$ and $A[i + 1..n]$, possibly adding in an extra letter to account for palind... | [] | false | [] |
15-15-3 | 15 | 15-3 | 15-3 | docs/Chap15/Problems/15-3.md | In the **_euclidean traveling-salesman problem_**, we are given a set of $n$ points in the plane, and we wish to find the shortest closed tour that connects all n points. Figure 15.11(a) shows the solution to a $7$-point problem. The general problem is NP-hard, and its solution is therefore believed to require more tha... | First sort all the points based on their $x$ coordinate. To index our subproblem, we will give the rightmost point for both the path going to the left and the path going to the right. Then, we have that the desired result will be the subproblem indexed by $v$, where $v$ is the rightmost point.
Suppose by symmetry that... | [] | false | [] |
15-15-4 | 15 | 15-4 | 15-4 | docs/Chap15/Problems/15-4.md | Consider the problem of neatly printing a paragraph with a monospaced font (all characters having the same width) on a printer. The input text is a sequence of $n$ words of lengths $l_1, l_2, \ldots, l_n$, measured in characters. We want to print this paragraph neatly on a number of lines that hold a maximum of $M$ cha... | First observe that the problem exhibits optimal substructure in the following way: Suppose we know that an optimal solution has $k$ words on the first line. Then we must solve the subproblem of printing neatly words $l_{k + 1}, \dots, l_n$. We build a table of optimal solutions solutions to solve the problem using dyna... | [
{
"lang": "cpp",
"code": "PRINT-NEATLY(n)\n let P[1..n] and C[1..n] be new tables\n for k = n downto 1\n if sum_{i = k}^n l_i + n - k < M\n C[k] = 0\n q = ∞\n for j = 1 to n - k\n cost = sum_{m = 1}^j l_{k + m} + m - 1\n if cost < M and (M - cost)^... | false | [] |
15-15-5 | 15 | 15-5 | 15-5 | docs/Chap15/Problems/15-5.md | In order to transform one source string of text $x[1..m]$ to a target string $y[1..n]$, we can perform various transformation operations. Our goal is, given $x$ and $y$, to produce a series of transformations that change $x$ to $y$. We use an array $z$—assumed to be large enough to hold all the characters it will need—... | **a.** We will index our subproblems by two integers, $1 \le i \le m$ and $1 \le j \le n$. We will let $i$ indicate the rightmost element of $x$ we have not processed and $j$ indicate the rightmost element of $y$ we have not yet found matches for. For a solution, we call $\text{EDIT}(x, y, i, j)$.
**b.** We will set
... | [
{
"lang": "cpp",
"code": "EDIT(x, y, i, j)\n let m = x.length\n let n = y.length\n if i == m\n return (n - j)cost(insert)\n if j == n\n return min{(m - i)cost(delete), cost(kill)}\n initialize o1, ..., o5 to ∞\n if x[i] == y[j]\n o1 = cost(copy) + EDIT(x, y, i + 1, j +... | false | [] |
15-15-6 | 15 | 15-6 | 15-6 | docs/Chap15/Problems/15-6.md | Professor Stewart is consulting for the president of a corporation that is planning a company party. The company has a hierarchical structure; that is, the supervisor relation forms a tree rooted at the president. The personnel office has ranked each employee with a conviviality rating, which is a real number. In order... | The problem exhibits optimal substructure in the following way: If the root $r$ is included in an optimal solution, then we must solve the optimal subproblems rooted at the grandchildren of $r$. If $r$ is not included, then we must solve the optimal subproblems on trees rooted at the children of $r$. The dynamic progra... | [] | false | [] |
15-15-7 | 15 | 15-7 | 15-7 | docs/Chap15/Problems/15-7.md | We can use dynamic programming on a directed graph $G = (V, E)$ for speech recognition. Each edge $(u, v) \in E$ is labeled with a sound $\sigma(u, v)$ from a finite set $\Sigma$ of sounds. The labeled graph is a formal model of a person speaking a restricted language. Each path in the graph starting from a distinguish... | **a.** Our substructure will consist of trying to find suffixes of s of length one less starting at all the edges leaving $v_0$ with label $\sigma_0$. if any of them have a solution, then, there is a solution. If none do, then there is none. See the algorithm $\text{VITERBI}$ for details.
```cpp
VITERBI(G, s, v[0])
... | [
{
"lang": "cpp",
"code": "VITERBI(G, s, v[0])\n if s.length = 0\n return v[0]\n for edges(v[0], v[1]) in V for some v[1]\n if sigma(v[0], v[1]) = sigma[1]\n res = VITERBI(G, (sigma[2], ..., sigma[k]), v[1])\n if res != NO-SUCH-PATH\n return (v[0], res... | false | [] |
15-15-8 | 15 | 15-8 | 15-8 | docs/Chap15/Problems/15-8.md | We are given a color picture consisting of an $m \times n$ array $A[1..m, 1..n]$ of pixels, where each pixel specifies a triple of red, green, and blue (RGB) intensities. Suppose that we wish to compress this picture slightly. Specifically, we wish to remove one pixel from each of the $m$ rows, so that the whole pictur... | **a.** If $n > 1$ then for every choice of pixel at a given row, we have at least $2$ choices of pixel in the next row to add to the seam ($3$ if we're not in column $1$ or $n$). Thus the total number of possibilities is bounded below by $2^m$.
**b.** We create a table $D[1..m, 1..n]$ such that $D[i, j]$ stores the di... | [
{
"lang": "cpp",
"code": "SEAM(A)\n let D[1..m, 1..n] be a table with zeros\n let S[1..m, 1..n] be a table with empty lists\n for i = 1 to n\n S[1, i] = (1, i)\n D[1, i] = d_{1i}\n for i = 2 to m\n for j = 1 to n\n if j == 1 // left-edge case\n if D... | false | [] |
15-15-9 | 15 | 15-9 | 15-9 | docs/Chap15/Problems/15-9.md | A certain string-processing language allows a programmer to break a string into two pieces. Because this operation copies the string, it costs $n$ time units to break a string of $n$ characters into two pieces. Suppose a programmer wants to break a string into many pieces. The order in which the breaks occur can affect... | The subproblems will be indexed by contiguous subarrays of the arrays of cuts needed to be made. We try making each possible cut, and take the one with cheapest cost. Since there are $m$ to try, and there are at most $m^2$ possible things to index the subproblems with, we have that the m dependence is that the solution... | [
{
"lang": "cpp",
"code": "CUT-STRING(L, i, j, l, r)\n if l == r\n return (0, [])\n minCost = ∞\n for k = i to j\n if l + r + CUT-STRING(L, i, k, l, L[k]).cost + CUT-STRING(L, k, j, L[k], j).cost < minCost\n minCost = r - l + CUT-STRING(L, i, k, l, L[k]).cost + CUT-STRING(L,... | false | [] |
16-16.1-1 | 16 | 16.1 | 16.1-1 | docs/Chap16/16.1.md | Give a dynamic-programming algorithm for the activity-selection problem, based on recurrence $\text{(16.2)}$. Have your algorithm compute the sizes $c[i, j]$ as defined above and also produce the maximum-size subset of mutually compatible activities.
Assume that the inputs have been sorted as in equation $\text{(16.1)... | ```cpp
DYNAMIC-ACTIVITY-SELECTOR(s, f, n)
let c[0..n + 1, 0..n + 1] and act[0..n + 1, 0..n + 1] be new tables
for i = 0 to n
c[i, i] = 0
c[i, i + 1] = 0
c[n + 1, n + 1] = 0
for l = 2 to n + 1
for i = 0 to n - l + 1
j = i + l
c[i, j] = 0
k = j -... | [
{
"lang": "cpp",
"code": "DYNAMIC-ACTIVITY-SELECTOR(s, f, n)\n let c[0..n + 1, 0..n + 1] and act[0..n + 1, 0..n + 1] be new tables\n for i = 0 to n\n c[i, i] = 0\n c[i, i + 1] = 0\n c[n + 1, n + 1] = 0\n for l = 2 to n + 1\n for i = 0 to n - l + 1\n j = i + l\n ... | false | [] |
16-16.1-2 | 16 | 16.1 | 16.1-2 | docs/Chap16/16.1.md | Suppose that instead of always selecting the first activity to finish, we instead select the last activity to start that is compatible with all previously selected activities. Describe how this approach is a greedy algorithm, and prove that it yields an optimal solution. | This becomes exactly the same as the original problem if we imagine time running in reverse, so it produces an optimal solution for essentially the same reasons. It is greedy because we make the best looking choice at each step. | [] | false | [] |
16-16.1-3 | 16 | 16.1 | 16.1-3 | docs/Chap16/16.1.md | Not just any greedy approach to the activity-selection problem produces a maximum-size set of mutually compatible activities. Give an example to show that the approach of selecting the activity of least duration from among those that are compatible with previously selected activities does not work. Do the same for the ... | As a counterexample to the optimality of greedily selecting the shortest, suppose our activity times are $\\{(1, 9), (8, 11), (10, 20)\\}$ then, picking the shortest first, we have to eliminate the other two, where if we picked the other two instead, we would have two tasks not one.
As a counterexample to the optimali... | [] | false | [] |
16-16.1-4 | 16 | 16.1 | 16.1-4 | docs/Chap16/16.1.md | Suppose that we have a set of activities to schedule among a large number of lecture halls, where any activity can take place in any lecture hall. We wish to schedule all the activities using as few lecture halls as possible. Give an efficient greedy algorithm to determine which activity should use which lecture hall.
... | Maintain a set of free (but already used) lecture halls $F$ and currently busy lecture halls $B$. Sort the classes by start time. For each new start time which you encounter, remove a lecture hall from $F$, schedule the class in that room, and add the lecture hall to $B$. If $F$ is empty, add a new, unused lecture hall... | [] | false | [] |
16-16.1-5 | 16 | 16.1 | 16.1-5 | docs/Chap16/16.1.md | Consider a modification to the activity-selection problem in which each activity $a_i$ has, in addition to a start and finish time, a value $v_i$. The objective is no longer to maximize the number of activities scheduled, but instead to maximize the total value of the activities scheduled. That is, we wish to choose a ... | Easy and straightforward solution is to run a dynamic programming solution based on the equation $\text{(16.2)}$ where the second case has "1" replaced with "$v_k$". Since the subproblems are still indexed by a pair of activities, and each calculation requires taking the minimum over some set of size $\le |S_{ij}| \in ... | [] | false | [] |
16-16.2-1 | 16 | 16.2 | 16.2-1 | docs/Chap16/16.2.md | Prove that the fractional knapsack problem has the greedy-choice property. | Let $I$ be the following instance of the knapsack problem: Let $n$ be the number of items, let $v_i$ be the value of the $i$th item, let $w_i$ be the weight of the $i$th item and let $W$ be the capacity. Assume the items have been ordered in increasing order by $v_i / w_i$ and that $W \ge w_n$.
Let $s = (s_1, s_2, \ld... | [] | false | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.