• 沒有找到結果。

Most graphics hardware includes support for a low-level operation called blit, or block

在文檔中 1.1Reductions Recursion C 1 (頁 34-41)

Homework

Exam: (b)(d)(e) transfer, which quickly copies a rectangular chunk of a pixel map (a two-dimensional array of pixel values) from one location to another. This is a two-dimensional version of the standard C library functionmemcpy().

Suppose we want to rotate an n × n pixel map 90clockwise. One way to do this, at least when n is a power of two, is to split the pixel map into four n/2 × n/2 blocks, move each block to its proper position using a sequence of five blits, and then recursively rotate each block. (Why five? For the same reason the Tower of Hanoi puzzle needs a third peg.) Alternately, we could first recursively rotate the blocks and then blit them into place.

A B C D

A BC D ABCD A

B C D

Figure 1.23. Two algorithms for rotating a pixel map.

(a) Prove that both versions of the algorithm are correct when n is a power of 2.

(b) Exactly how many blits does the algorithm perform when n is a power of 2?

(c) Describe how to modify the algorithm so that it works for arbitrary n, not just powers of 2. How many blits does your modified algorithm perform?

(d) What is your algorithm’s running time if a k × k blit takes O(k2) time?

(e) What if a k × k blit takes only O(k) time?

Exercises

Figure 1.24. The first rotation algorithm (blit then recurse) in action.

30. An array A[0 .. n − 1] of n distinct numbers is bitonic if there are unique indices i Exam

and j such that A[(i − 1) mod n] < A[i] > A[(i + 1) mod n] and A[(j − 1) mod n] >

A[j] < A[(j + 1) mod n]. In other words, a bitonic sequence either consists of an increasing sequence followed by a decreasing sequence, or can be circularly shifted to become so. For example,

4 6 9 8 7 5 1 2 3 is bitonic, but 3 6 9 8 7 5 1 2 4 is not bitonic.

Describe and analyze an algorithm to find the smallest element in an n-element bitonic array in O(log n) time. You may assume that the numbers in the input array are distinct.

31. Suppose we are given an array A[1 .. n] of n distinct integers, which could be positive, Exam

negative, or zero, sorted in increasing order so that A[1] < A[2] < · · · < A[n].

(a) Describe a fast algorithm that either computes an index i such that A[i] = i or correctly reports that no such index exists.

(b) Suppose we know in advance that A[1] > 0. Describe an even faster algorithm that either computes an index i such that A[i] = i or correctly reports that no such index exists. [Hint: This is really easy.]

32. Suppose we are given an array A[1 .. n] with the special property that A[1] ≥ A[2] and Exam

A[n − 1] ≤ A[n]. We say that an element A[x] is a local minimum if it is less than or equal to both its neighbors, or more formally, if A[x − 1] ≥ A[x] and A[x] ≤ A[x + 1].

For example, there are six local minima in the following array:

9

Î

7 7 2

Î

1 3 7 5

Î

4 7

Î

3

Î

3 4 8

Î

6 9

We can obviously find a local minimum in O(n) time by scanning through the array.

Describe and analyze an algorithm that finds a local minimum in O(log n) time.

[Hint: With the given boundary conditions, the array must have at least one local minimum. Why?]

33. Suppose you are given a sorted array of n distinct numbers that has been rotated k

Exam

steps, for some unknown integer k between 1 and n − 1. That is, you are given an array A[1 .. n] such that some prefix A[1 .. k] is sorted in increasing order, the corresponding suffix A[k + 1 .. n] is sorted in increasing order, and A[n] < A[1].

For example, you might be given the following 16-element array (where k = 10):

9 13 16 18 19 23 28 31 37 42 −4 0 2 5 7 8

(a) Describe and analyze an algorithm to compute the unknown integer k.

(b) Describe and analyze an algorithm to determine if the given array contains a given number x.

34. You are a contestant on the hit game show “Beat Your Neighbors!” You are presented with an m × n grid of boxes, each containing a unique number. It costs $100 to open a box. Your goal is to find a box whose number is larger than its neighbors in the grid (above, below, left, and right). If you spend less money than any of your opponents, you win a week-long trip for two to Las Vegas and a year’s supply of Rice-A-Ronitm, to which you are hopelessly addicted.

(a) Suppose m = 1. Describe an algorithm that finds a number that is bigger than

Exam

either of its neighbors. How many boxes does your algorithm open in the worst case?

ª(b) Suppose m = n. Describe an algorithm that finds a number that is bigger than

Homework

any of its neighbors. How many boxes does your algorithm open in the worst case?

¨ª(c) Prove that your solution to part (b) is optimal up to a constant factor. (See

Homework

Chapter••Lower Bounds••.)

35. (a) Let n = 2`− 1 for some positive integer `. Suppose someone claims to hold an

Homework

unsorted array A[1 .. n] of distinct `-bit strings; thus, exactly one `-bit string does notappear in A. Suppose further that the only way we can access A is by calling the function FetchBit(i, j), which returns the jth bit of the string A[i] in O(1) time. Describe an algorithm to find the missing string in A using only O(n) calls to FetchBit.

ª(b) Now suppose n = 2`− k for some positive integers k and `, and again we are

Homework

given an array A[1 .. n] of distinct `-bit strings. Describe an algorithm to find the kstrings that are missing from A using only O(n log k) calls to FetchBit.

Exercises

Trees

36. For this problem, a subtree of a binary tree means any connected subgraph. A binary

Exam

tree is complete if every internal node has two children, and every leaf has exactly the same depth. Describe and analyze a recursive algorithm to compute the largest complete subtreeof a given binary tree. Your algorithm should return both the root and the depth of this subtree.

Figure 1.25. The largest complete subtree of this binary tree has depth 2.

37. (a) Professor George O’Jungle has a 27-node binary tree, in which every node is HW0

labeled with a unique letter of the Roman alphabet or the character&. Preorder and postorder traversals of the tree visit the nodes in the following order:

• Preorder: I Q J H L E M V O T S B R G Y Z K C A & F P N U D W X

• Postorder: H E M L J V Q S G Y R Z B T C P U D N F W & X A K O I Draw George’s binary tree.

(b) Recall that a binary tree is full if every non-leaf node has exactly two children. Exam

i. Describe and analyze a recursive algorithm to reconstruct an arbitrary full binary tree, given its preorder and postorder node sequences as input.

ii. Prove that there is no algorithm to reconstruct an arbitrary binary tree from its preorder and postorder node sequences.

(c) Describe and analyze a recursive algorithm to reconstruct an arbitrary binary Exam

tree, given its preorder and inorder node sequences as input.

(d) Describe and analyze a recursive algorithm to reconstruct an arbitrary binary Exam

searchtree, given only its preorder node sequence.

ª(e) Describe and analyze a recursive algorithm to reconstruct an arbitrary binary Homework

searchtree, given only its preorder node sequence, in O(n) time.

In parts (b)–(e), assume that all keys are distinct and that the input is consistent with at least one binary tree.

38. Suppose we have n points scattered inside a two-dimensional box. A kd-tree10 Homework

recursively subdivides the points as follows. First we split the box into two smaller

10The term “kd-tree” (pronounced “kay dee tree”) was originally an abbreviation for “k-dimensional tree”, but more modern usage ignores this etymology, in part because nobody in their right mind would

boxes with a vertical line, then we split each of those boxes with horizontal lines, and so on, always alternating between horizontal and vertical splits. Each time we split a box, the splitting line partitions the rest of the interior points as evenly as possible by passing through a median point inside the box (not on its boundary). If a box doesn’t contain any points, we don’t split it any more; these final empty boxes are called cells.

Figure 1.26. A kd-tree for 15 points. The dashed line crosses the four shaded cells.

(a) How many cells are there, as a function of n? Prove your answer is correct.

(b) In the worst case, exactly how many cells can a horizontal line cross, as a function of n? Prove your answer is correct. Assume that n = 2k− 1 for some integer k.

[Hint: There is more than one function f such that f (16) = 4.]

(c) Suppose we are given n points stored in a kd-tree. Describe and analyze an algorithm that counts the number of points above a horizontal line (such as the dashed line in the figure) as quickly as possible. [Hint: Use part (b).]

(d) Describe an analyze an efficient algorithm that counts, given a kd-tree containing npoints, the number of points that lie inside a rectangle R with horizontal and vertical sides. [Hint: Use part (c).]

39. Let T be a binary tree with n vertices. Deleting any vertex v splits T into at most

Exam

three subtrees, containing the left child of v (if any), the right child of v (if any), and the parent of v (if any). We call v a central vertex if each of these smaller trees has at most n/2 vertices.

Describe and analyze an algorithm to find a central vertex in an arbitrary given binary tree. [Hint: First prove that every tree has a central vertex.]

everuse the letter k to denote dimension instead of the obviously superior d. Etymological consistency would require calling the data structure in this problem a “2d-tree”, or even a “2-d tree”, but the standard nomenclature is now “two-dimensional kd-tree”. See also: B-tree (maybe), alpha shape, beta skeleton, epsilon net, Potomac River, Mississippi River, Lake Michigan, Lake Tahoe, Manhattan Island, the La Brea Tar Pits, Sahara Desert, Mount Kilimanjaro, South Vietnam, East Timor, the Milky Way Galaxy, the City of Townsville, and self-driving automobiles.

Exercises

34 14

7 12

Figure 1.27. Deleting a central vertex in a 34-node binary tree, leaving subtrees with 14, 7, and 12 nodes.

ª40. Let T be a binary tree whose nodes store distinct numerical values. Recall that T is a Fun Homework

binary search treeif and only if either (1) T is empty, or (2) T satisfies the following recursive conditions:

• The left subtree of T is a binary search tree.

• All values in the left subtree of T are smaller than the value at the root of T.

• The right subtree of T is a binary search tree.

• All values in the right subtree of T are larger than the value at the root of T.

Describe and analyze an algorithm to transform an arbitrary binary tree T with distinct node values into a binary search tree, using only the following operations:

• Rotate an arbitrary node upward, as shown in Figure1.28.11

• Swap the left and right subtrees of an arbitrary node, as shown in Figure1.29.

y x

A B

C

x y

C B A right left

Figure 1.28. Left to right: right rotation at x. Right to left: left rotation at y.

x

A B

swap

x

A B

Figure 1.29. Swapping the subtrees of x

For both of these operations, some, all, or none of the subtrees A, B, and C shown in Figures1.28and1.29may be empty. Figure1.30shows a sequence of eight operations transforming a five-node binary tree into a binary search tree.

Your algorithm cannot directly modify parent or child pointers, and it cannot allocate new nodes or delete old nodes; the only way it can modify T is using

11Rotations preserve the inorder sequence of nodes in a binary tree. Partly for this reason, rotations are used to maintain several types of balanced binary search trees, including AVL trees, red-black trees, splay trees, scapegoat trees, and treaps. Some of these data structures are described in later chapters.

4

2 5

1 3 4

2 5

1 3

4 2

5 1

3

4 2

5 1 3 4

2

5 1

3 4

2 5 1

3

4 2

5 1

3

4

2 5

1 3

4 2 5

1 3

Figure 1.30. “Sorting” a binary tree: rotate 2, rotate 2, swap 3, rotate 3, rotate 4, swap 3, rotate 2, swap 4.

rotations and swaps. On the other hand, you may compute anything you like for free, as long as that computation does not modify T. In other words, the running time of your algorithm is defined to be the number of rotations and swaps that it performs.

For full credit, your algorithm should use as few rotations and swaps as possible in the worst case. [Hint: O(n2) operations is not too difficult, but we can do better.]

ª41. Bob Ratenbur, a new student in CS 225, is trying to write code to perform preorder,

Fun Homework

inorder, and postorder traversals of binary trees. Bob understands the basic idea behind the traversal algorithms, but whenever he tries to implement them, he keeps mixing up the recursive calls. Five minutes before the deadline, Bob frantically submits code with the following structure:

PreOrder(v):

if v = Null return elseprint label(v)

Order(left(v)) Order(right(v))

InOrder(v):

if v = Null return

else Order(left(v)) print label(v)

Order(right(v))

PostOrder(v):

if v = Null return

else Order(left(v)) Order(right(v)) print label(v)

Each in this pseudocode hides one of the prefixes Pre, In, or Post. Moreover, each of the following function calls appears exactly once in Bob’s submitted code:

PreOrder(left(v)) PreOrder(right(v)) InOrder(left(v)) InOrder(right(v)) PostOrder(left(v)) PostOrder(right(v))

Thus, there are precisely 36 possibilities for Bob’s code. Unfortunately, Bob acciden-tally deleted his source code after submitting the executable, so neither you nor he knows which functions were called where.

Now suppose you are given the output of Bob’s traversal algorithms, executed on some unknown binary tree T. Bob’s output has been helpfully parsed into three arrays Pre[1 .. n], In[1 .. n], and Post[1 .. n]. You may assume that these traversal sequences are consistent with exactly one binary tree T; in particular, the vertex labels of the unknown tree T are distinct, and every internal node in T has exactly two children.

(a) Describe an algorithm to reconstruct the unknown tree T from the given traversal sequences.

在文檔中 1.1Reductions Recursion C 1 (頁 34-41)

相關文件