CS 332: Algorithms

Homework #5

 

Assigned:        Monday, April 15 2002 (Tax day!)

Due:                Monday, April 22 2002

 

 

1.      Exercise 15.4-4 (16.3-4 in old book).  Note that you are not changing the running time of the algorithm, just the space requirements.

 

2.      Recall this problem from exam 2:

Describe how to implement a dynamic set S that efficiently supports the FIFO queue operations Enqueue (instead of Insert), Dequeue (instead of Delete), and Minimum (note: not ExtractMin, just Minimum; the node is not deleted).

 

Here is a solution to this problem that performs all operations in O(1) amortized time: keep the items in an ordinary FIFO queue N.  Keep a second queue, M, that is a subset of N, such that the minimum item in N is always at the head of M.  Enqueuing and dequeuing the items on N take O(1) time, and getting the minimum from the head of M takes only O(1) time.  But maintaining M requires additional work.

            N is an ordinary queue, in which items are inserted at the tail and removed at the head.  M is an input-restricted deque (double-ended queue), in which items are inserted only at the tail but can be deleted at both ends.  The set operations are implemented as follows (assume, without loss of generality, that the items in the set are just numbers):

 

Minimum(S)

                return head[M]

 

Dequeue(S)

                n = head[N]

                delete head of N

                if n = head[M]

                                then delete head of M

                return n

 

Enqueue(S)

                insert n at tail of N

                while tail[M] > n

                                do delete tail of M

                insert n at tail of M

 

(a)    Run an example, showing N and M after enqueuing 3,4,6, and 7, then after enqueuing 5

(b)   Argue the correctness of this algorithm by describing the invariants preserved by the above code

(c)    Use amortized analysis to argue that all operations will take O(1) time