Sie sind auf Seite 1von 10

Last Name: ............................. First Name: .............................. Email: ..............................

CS 3510 A, Spring 2015, Homework 1, 1/7/15 Due 1/14/15 in class


Page 1/8

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 1, 1/7/15 Due 1/14/15 in class
Page 2/8

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 1, 1/7/15 Due 1/14/15 in class
Page 3/8

Problem 1: Analysis of Recursive Algorithm (10 points).


Consider the function Mystery dened below.
Mystery(n)
if n > 1 then begin
print(x);
Mystery(n 1);
Mystery(n 1);
Mystery(n 1);
Mystery(n 1);
end
If we call Mystery(n), where n is an integer n > 1, how many xs (as an exact function of n) does call
Mystery(n) print? Justify your answer/show your work (solve recurrences using the substitution
method, do not use O() notation.)

Problem 2: Analysis of Recursive Algorithm (10 points).


Consider the function Mystery dened below, where T is a global variable initialized to T := 0.
Mystery(x)
begin
T := T + 1;
if x > 1 then begin
Mystery(x 1); Mystery(x 1); Mystery(x 1);
end
end
If we call Mystery(n), where n is a positive integer, what is the value of T (as an exact function
of n), at the end of the execution of Mystery(n). Justify your answer (solve recurrences using the
substitution method do not use O() notation.)

Problem 3: Analysis of Recursive Algorithm (10 points).


Consider the function Mystery dened below.
Mystery(n)
if n > 1 then begin
print(xx);
Mystery(n/3);
Mystery(n/3);
Mystery(n/3);
end
If we call Mystery(n), where n > 1 and n is a power of 3, how many xs (as a function of n) does call
Mystery(n) print? Justify your answer/show your work (solve recurrences using the substitution
method.)

Answer: If we call Mystery(1), then T will become 1. In general, whatever the value of T is, once
Mystery(1) is called, the value of T will increase by 1. If we call Mystery(x) for x > 1, then this
will cause the increase of T by 1, plus the increase caused by three recursive calls to Mystery(x 1).
If f (n) is the nal value of T as a function of n after a call to Mystery(n), or, in other words, f (n)
is the total increase of T the above imply:

Answer: Let f (n) be the number of xs Mystery(n) prints, when n is an integer n > 1. Since n
is a power of 3, this means n 3. For the base case, we see that f (3) = 2. For n > 3 we have
f (n) = 3f ( n3 ) + 2. We thus have to solve:
n
f (n) = 3f ( ) + 2 ,
with f (3) = 2.
3

Answer: Let f (n) be the number of xs Mystery(n) prints, when n is an integer n > 1. For the
base case, we see that f (2) = 1. For n > 2 we have f (n) = 4f (n 1) + 1. We thus have to solve:
f (n) = 4f (n 1) + 1

with

f (2) = 1.

We solve by substitutioon. The general form is f (x) = 4f (x 1) + 1.


for x = n 1 the general form becomes
f (n 1) = 4f (n 2) + 1
= 4 (4f (n 2) + 1) + 1
for x = n 2 the general form becomes
2
= 4 f (n 2) + 4 + 1
f (n 2) = 4f (n 3) + 1

f (n) = 4f (n 1) + 1

= 42 (4f (n 3) + 1) + 4 + 1
= 43 f (n 3) + 42 + 4 + 1
= ......
= 4k f (n k) + 4k1 + . . . + 42 + 4 + 1 guessing general term
= 4k f (n k) +

4k 1
41

4k 1
3
4n2 1
3

N +1 1

using xN + . . . + x2 + x + 1 = x
for x = 4 and N = k 1

x1

substitute k = n 2
because we know f (2) = 1

4n2 1
3
3 4n2 + 4n2 1
3
4 4n2 1
3
4n1 1
.
3

= 4n2 +
=
=
=


f (n) =
=
=
=
=
=
=
=
=
=

= 4k f (n k) +
= 4n2 f (2) +

f (n) = 3f (n 1) + 1 , with f (1) = 1 .


Lets solve f (n) by substitution. The general form is f (x) = 3f (x 1) + 1.
3f (n 1) + 1
3(3f (n 2) + 1) + 1
by substituting f (n 1) = 3f (n 2) + 1
32 f (n 2) + 3 + 1
32 (3f (n 3) + 1) + 3 + 1
by substituting f (n 2) = 3f (n 3) + 1
3
2
3 f (n 3) + 3 + 3 + 1
......
3k f (n k) + 3k1 + . . . + 32 + 3 + 1 guessing general term
N +1
k 1
using xN + . . . + x2 + x + 1 = x x11
3k f (n k) + 331
for x = 3 and N = k 1
k
3k f (n k) + 3 21
n1
by substituting k = n 1
3n1 f (1) + 3 2 1
because we know f (1) = 1
n1
3n1 + 3 2 1

=
n1
n1 1
= 23 +3
2
n1
= 33 2 1
n
= (3 1) /2

Thus f (n) = (3n 1) /2.


(You can verify that this formula gives f (1) = 1, f (2) = 4, etc, as it should.)

n
for x = n/3 the general form becomes
f (n) = 3f ( ) + 2
f ( n3 ) = 3f ( 3n2 ) + 2
3


n
= 3 3f ( 2 ) + 2 + 2
3
n
for x = n/32 the general form becomes
= 32 f ( 2 ) + 3 2 + 2
f ( 3n2 ) = 3f ( 3n3 ) + 2
3


n
= 32 3f ( 3 ) + 2 + 3 2 + 2
3
n
= 3 3 f ( 3 ) + 32 2 + 3 2 + 2
3
n
3
= 3 f ( 3 ) + 2 (32 + 3 + 1)
3
= ......
n
= 3k f ( k ) + 2 (3k1 + . . . 32 + 3 + 1) guessing general term
3
N +1
n
3k 1
using xN + . . . + x2 + x + 1 = x x11
k
= 3 f( k ) + 2
3
31
for x = 3 and N = k 1
= 3k f (

n
3k 1
)+2
3k
2

= 3k f (

n
) + 3k 1
3k

substitute 3nk = 3
because we know f (3) = 2
implying 3nk = 3 3k+1 = n
k + 1 = log3 n k = log3 n 1

= 3log3 n1 f (3) + 3log3 n1 1


= 2 3log3 n1 + 3log3 n1 1 = 3 3log3 n1 1 = 3log3 n 1 = n 1 .

Thus f (n) =
1 /3.
(You can verify that this formula gives f (2) = 1, f (3) = 5, etc, as it should.)
4n1

We solve by substitutioon. The general form is f (x) = 3f ( n3 ) + 2.

Thus f (n) = n 1, where n is a power of 3.


(You can verify that this formula gives f (3) = 2, f (9) = 8, etc, as it should.)

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 1, 1/7/15 Due 1/14/15 in class
Page 4/8

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 1, 1/7/15 Due 1/14/15 in class
Page 5/8

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 1, 1/7/15 Due 1/14/15 in class
Page 6/8

Problem 4: Analysis of Recursive Algorithm (10 points).


Consider the function Mystery dened below.
Mystery(n)
if n > 1 then begin
for i = 1 to n print(x);
Mystery(n/2);
Mystery(n/2);
end
If we call Mystery(n), where n > 1 and n is a power of 2, how many xs (as a function of n) does call
Mystery(n) print? Justify your answer/show your work (solve recurrences using the substitution
method.)

Problem 5: Mergesort Application: Counting Inversions (15 points).


Let A be an array of n distinct numbers. If for some i < j we have A(i) > A(j) then the pair (i, j)
is called an inversion of A.
a. List the ve inversions of the array 2,3,8,6,1.
b. What array with elements from the set 1, 2, . . . , n has the most inversions? How many does it
have?
c. Show how to determine the number of inversions in any array of n distinct elements in time
O(n log n). Hint: Modify mergesort. Note: If you give pseudocode, it should be very short and
very clear.

Problem 6: Divide and Conquer (15 points).


Given a sorted array of distinct integers A(1, ..., n), you want to nd out whether there is an index
i for whichA(i) = i. Give a divide-and-conquer algorithm that runs in time O(log n). You have to
justify correctness and running time. Note: If you give pseudocode, it should be very short and
very clear.

Answer: Let f (n) be the number of xs Mystery(n) prints, when n is a power of 2 with n > 1.
Thus the smallest number that Mystery is called with is Mystery(2). For the base case, we see that
f (2) = 2. For n > 2 we have f (n) = 2f ( n2 ) + n. We thus have to solve:
n
f (n) = 2f ( ) + n
2

with

f (2) = 2.

We solve by substitutioon. The general form is f (x) = 2f ( n2 ) + x.


n
for x = n/2 the general form becomes
f (n) = 2f ( ) + n
f ( n2 ) = 2f ( 2n2 ) + n2
2


n
n
= 2 2f ( 2 ) +
+n
2
2
n
n
= 22 f ( 2 ) + 2 + n
2
2
n
for x = n/22 the general form becomes
= 22 f ( 2 ) + 2n
f ( 2n2 ) = 2f ( 2n3 ) + 2n2
2


n
n
2
= 2 2f ( 3 ) + 2 + 2n
2
2
n
) + 3n
23
= ......
n
= 2k f ( k ) + (k 1)n guessing general term
2
substitute 2nk = 2
n
because we know f (2) = 2
= 2k f ( k ) + (k 1)n
implying 2nk = 2 2k+1 = n
2
k + 1 = log2 n k = log2 n 1
= 23 f (

= 2log2 n1 f (2) + (log2 n 1)n


= 2 2log2 n1 + log2 n n
= 2log2 n + n log2 n n
= n + n log2 n n
= n log2 n

Thus f (n) = n log2 n, where n is a power of 2.


(You can verify that this formula gives f (2) = 2, f (4) = 8, etc, as it should.)

Answer:
a. 2 > 1, 3 > 1, 8 > 6, 8 > 1 and 6 > 1, thus the inversions are indices (1,5) for 2 > 1, indices (2,5) for
3 > 1, indices (3,4) for 8 > 6, indices (3,5) for 8 > 1, and indices (4,5) for 6 > 1.
b. We rst argue that the maximum number of inversions that an array with n elements can have
is n(n1)/2. This is because, by denition, an inversion involves two indices i and j with i < j,
thus the rst element with index 1 can result to at most (n 1) inversions with each one of the
indices 2, . . . , n, and in general, the i-th element with index i can result to at most (ni) inversions
n1
with each one of the indices (i+1), . . . , n. The above gives a max total of i=1
(ni) = n(n1)/2.

It is now easy to see that the array n, (n1), . . . , 2, 1 indeed has n1
i=1 (ni) = n(n1)/2 inversions,
thus the above array indeed has the maximum possible number of inversions.
c. Let A be an array of n distinct numbers. We want to count the inversions of A, ie the pairs of
indices i and j with i < j and A(i) > A(j). The diculty in counting the number of inversions
in time O(n log n) is that there could be O(n2 ) inversions. Therefore, our algorithm should be
accounting for many sets of inversions in large groups (without expllicitly enumerating the members
of the group.)
Let us assume that n is a power of 2, and let us partition the pairs to three classes.
The rst class consists of indices i < j n/2 with A(i) > A(j). These inversions will be computed
recursively. The second class consists of indices ( n2 + 1) i < j with A(i) > A(j). These inversions
will be also computed recursively. The third class consists of indices i < j, with 1 i n/2,
( n2 + 1) j n, and A(i) > A(j). It is now important to notice that the number of inversions of
the third class will not change if we permute the elements in the rst half of A arbitrarily, and if we
also permute the elements in the second half of A arbitrarily. In particular, it is convenient to have
the subarrays A(1), . . . , A( n2 ) and A( n2 + 1), . . . , A(n) sorted (as in mergesort.) This is because we
can now compute the number of inversions of the third class while merging (as in mergesort) the
rst half of A with the second half of A as follows: Suppose that we have found the rst k elements
of the sorted merged array, and all the inversions involved with these elements. Suppose also that,
of these k elements, k1 come from the rst part of A and k2 come from the second part of A. Thus,
we are now comparing the i = (k1 + 1)-st element of the rst part of A with the j = (k2 + 1)-st
element of A. If A(i) < A(j) then the (k + 1)-st element of the merged sorted array is A(i) and
there are no more inversions involved with i or A(i). This is because the only possible inversions
would have to involve a j  > qj with A(i) > A(j  ), which is impossible, since the second half of
A is sorted, thus A(i) < A(j) < A(j  ) for all j  > j. On the other hand, if A(i)
> A(j) then the

(k + 1)-st element of the merged sorted array is A(j) and there are n2 i + 1 inversions involved
with j or A(j). This is because all the pairs (i, j), (i + 1, j), . . ., (n/2, j) involve inversions, since
n
j 2 + 1, while the second part of A is sorted thus A(n/2) > . . . > A(i + 1) > A(i) > A(j).
The above algorithm is a straightforward modication of mergesort and runs in time O(n log n).

Answer: Assume that n is a power of 2.


Main Fact: If A(i) < i then A(j) < j, for all j < i. (Thus there is no xed point j : A(j) = j in
the range 1 j i, and any possible xed point must be in the range (i + 1) j n.)
Proof: Since the A(j)s are distinct integers and the array A is sorted, we have A(j1) A(j)1, for
all js. It now follows immediately that for j = ik we have A(j) = A(ik) A(i)k < ik = j.
Similarly to the above Main Fact, we can argue that if A (i) > i, then A(j) > j, for all j > i.
(Thus there is no xed point j : A(j) = j in the range i j n, and any possible xed point
must be in the range 1 j (i 1).
 
Algorithm: The above leads to the following natural algorithm:
Check if A n2 = n2 . If yes, then you
 
have found a xed
point
and you are done. If no, then
if A n2 < n2 recurse looking for a possible



xed point in A n2 + 1  , . . . , A(n). If however A n2 > n2 , then recurse looking for a possible xed
point in A(1), . . . , A n2 .
Analysis:
 

n
+c
2

n
+ 2c
T
22
 
n
T
+ 3c
23
.....
 
n
T
+ kc
2k

T (n) T

= T (1) + c log2 n , for k = log2 n


= O(log n)

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 1, 1/7/15 Due 1/14/15 in class
Page 7a/8

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 1, 1/7/15 Due 1/14/15 in class
Page 7b/8

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 1, 1/7/15 Due 1/14/15 in class
Page 8/8

Problem 7: Mix and Max with very few comparisons: Ecient Design 15 points).
Let A be an array of n distinct numbers. It is clear that one can nd the maximum of these numbers
with n1 comparisons. Similarly, it is clear that one can nd the minimum of these numbers with
n1 comparisons. Thus, one can nd both the maximum and the minimum of these numbers with
2n2 comparisons. But one can do better! Show how to nd both the maximum and the minimum
of n distinct numbers with 3 n2 2 comparisons (you may assume that n is even.) Note: If you give
pseudocode, it should be very short and very clear.

Answer No 2 for Problem 7:


M and will eventually hold the maximum and minimum of the array respectively.
If n = 2 we can nd M and by comparing A(1) and A(2).
If n = 4, how can we compute the maximum of A(1), . . . , A(4)? Initially, with one comparisons,
M and are equal to the maximum and minimum of {A(1), A(2)} respectively. With one more
comparisons, we let X and x be the maximum and minimum of {A(3), A(4)} respectively. Finally,
with two more comparisons, we update M = max{M, X} and = min{, x} respectively. Thus
M and are eventually equal to the maximum and minimum of {A(1), . . . , A(4)} respectively.
Suppose that for some i < n/2, M and hold the maximum and minimum of A(1), . . . , A(2i)
respectively. How can we compute the maximum of A(1), . . . , A(2(i+1))? Suppose that M and are
equal to the maximum and minimum of {A(1), . . . , A(2i)} respectively. With one more comparisons,
we let X and x be the maximum and minimum of {A(2i+1), A(2i+2)} respectively. Next, with two
more comparisons, we update M = max{M, X} and = min{, x} respectively. Thus M and are
eventually equal to the maximum and minimum of {A(1), . . . , A(2i + 2)} = {A(1), . . . , A(2(i + 1))}
respectively.
This leads us to the following algorithm:
if A(1) < A(2) then begin := A(1); M := A(2); end
else begin := A(2); M := A(1); end

for i = 1 to n2 1 begin
if A(2i + 1) < A(2i + 2) then begin x := A(2i + 1); X := A(2i + 2); end
else begin x := A(2i + 2); X := A(2i + 1); end
if x < then := x;
if X > M then M := X;
end
The total number of comparisons is T (n) = T (n 2) + 3 with T (2) = 1.
We solve the above reccurence by substitution:

Problem 8: Exact Sum: Sorting Application (15 points).


Given a sorted array of distinct integers A(1, ..., n) and a target integer S, you want to nd if S
can be expressed as the sum of two distinct entries of A. That is, you want to nd 1 i < j n
such that A(i) + A(j) = S, if such a pair exists. If such a pair does not exist, you want to answer
NO. Give an algorithm that runs in time O(n). You have to justify correctness and running time.
Note: If you give pseudocode, it should be very short and very clear.

Answer No 1: In STEP 1 below, using n/2 comparisons, we partition the n elements of A into
two sets B and C, such that the maximum of A belongs to the set B, the minimum of A belongs
to the set C, and each one of B and C
has exactly n/2 elements.

In STEP 2 below, we use  n2 1 comparisons to nd the maximum of B, which is also the
maximum of A, and another n2 1 comparisons to nd the minimum of C, which is also the
minimum of A.


Thus, the total number of comparisons is n/2 from STEP 1 and 2 n2 1 from STEP 2, for a
total of


n
n
n
+2
1 = 3 2 .
2
2
2
STEP 1: For each successive pair of integers in A, we put the maximum of the pair in B and the
minimum of the pair in C. In particular:
for i = 1 to n/2
if A(2i 1) > A(2i) then begin
B(i) := A(2i 1);
C(i) := A(2i);
end
else begin
B(i) := A(2i);
C(i) := A(2i 1);
end
We now argue that B indeed contains the maximum of A, and C indeed contains the minimum
of A. To argue that B indeed contains the maximum of A, it suces to argue that C does not
contain the maximum of A. This is clear, since for each element of C there is one element of A
which is larger than C (if C(i) = A(2i) then A(2i 1) > A(2i) while if C(i) = A(2i 1) then
A(2i) > A(2i 1).) Similarly, we can argue
that
C indeed contains the minimum of A.


STEP2: The standard method of using n2 1 comparisons to nd the maximum of B, and another n2 1 comparisons to nd the minimum of C:
max := B(1); for i := 2 to n/2 if B(i) > max then max := B(i);
min := C(1); for i := 2 to n/2 if C(i) < min then min := C(i);

Answer:
Main Fact: If A(1) + A(n) > S then A(i) + A(n) > S for all i. (Thus we may discard A(n) as a
candidate in a pair A(i) + A(j) = S.)
Proof: The integers are distinct and sortd, thus A(i) > A(1) for all i > 1, thus A(i) + A(n) >
A(1) + A(n) > S.
Similarly, if A(1) + A(n) < S then A(1) + A(i) < S for all i. Thus we may discard A(1) as a
candidate in a pair A(i) + A(j) = S.
Algorithm: We have two pointers, initially placed on A(1) and A(n) respectivey. We will proceed
in at most (n 1) rounds until either the left pointer is on some i and the right pointer is on some j
with i < j and a(i) + a(j) = S (in which case we have found a desired pair), or the left pointer and
the right pointer coincide (in which case there is no pair with the desired property.) In each step, if
the left pointer is on i and the right pointer is on j, we compare a(i) + a(j) to S. If a(i) + a(j) > S
we move the right pointer to (j 1). If a(i) + a(j) < S we move the left pointer to (i + 1). If
a(i) + a(j) = S we have found a pair with the desired property.

T (n) = T (n 2) + 3
= T (n 4) + 3 2
= T (n 6) + 3 3
= ......
= T (n 2k) + 3 k
= T (n 2k) + 3 k


n
1
2
n
= 1+3 3
2
n
= 3 2 .
2

guessing general term


since T (2) = 1 substitute
n 2k = 2


thus k = n2 1

= T (2) + 3

Turn page to see a dierent answer.

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 2, 1/16/15 Due 1/23/15 in class
Page 1/5

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 2, 1/16/15 Due 1/23/15 in class
Page 2/5

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 2, 1/16/15 Due 1/23/15 in class
Page 3/5

Problem 1: Analysis of Recursive Algorithm (20 points).


Consider the function Mystery dened below.
Mystery(n)
for i = 1 to n print(xx);
 
if n > 16 then for i = 1 to 3 Mystery n4 ;
If we call Mystery(n), where n > 4 and n is a power of 4, how many xs (as a function of n) does call
Mystery(n) print? Justify your answer/show your work (solve recurrences using the substitution
method.)
Answer: The rst line of Mystery(n) prints 2n xs,
and the second line makes 3 calls to
 
Mystery n4 , for n > 16 = 42 . We thus have: T (n) = 3T n4 + 2n, with T (16)
= 32.

We solve by substitution.
The general form is T (x) = 3T x4 + 2x.

Problem 2: Analysis of Recursive Algorithm (20 points).


Consider the function Mystery dened below.
Mystery(n)
if n > 1 then print(xxxxxxx);  
if n > 1 then for i = 1 to 5 Mystery n3 ;
If we call Mystery(n), where n > 1 and n is a power of 3, how many xs (as a function of n) does call
Mystery(n) print? Justify your answer/show your work (solve recurrences using the substitution
method.)
Answer: The rst line of Mystery(n) prints 7 xs,
and the second line makes 5 calls to

Mystery n3 , for n 3. We thus have: T (n) = 5T n3 + 7, with T (3) = 7. 
We solve by substitution.
The general form is T (x) = 5T x3 + 7.

Problem 3: Correctness and Analysis of a Recursive Algorithm (20 points).


A startup has proposed the following elegant sorting algorithm:
STOOGE-SORT(A, i, j)
if A(i) > A(j) then exchange A(i) A(j);
if (i + 1) < j then begin
k := (j i + 1)/3
;
STOOGE-SORT(A, i, j k); Remank: First two thirds.
STOOGE-SORT(A, i + k, j); Remank: Last two thirds.
STOOGE-SORT(A, i, j k); Remank: First two thirds again.
end
a. Argue that STOOGE-SORT(A, 1, legth(A)) correctly sorts the input array A(1, . . . , n), where
n = legth(A).
b. Give a recurrence for the worst-case running time of STOOGE-SORT and a bound (in O()
notation) for the worst-case running time.
c. Compare the worse-case running time of STOOGE-SORT with that of bubblesort and mergesort.
Does the startup deserve funding?
Answer:
(a) Assume wlog (wlog=without loss of generality) that n is a multiple of 3, so n = 3k for some positive integer k.

 

T (n)

3T


n
4

3 3T

32 T

32 3T




=
=

stop when

x
42

for x =

n
+2
4

n
4

the general form gives T ( n4 ) = 3T

x
42

 

+2

T (n)

n
4

3 T

3k T

n
4k
n
4k

n
42

+2

3
4

+ 2n

+ 2n

3
+ ... + + 1
4

guessing general term


1xk
1x ,

for x < 1

3log4 n2 T

n
3log4 n
T 42 log n
32
4 4

log n
4log4 n
3 4
3log4 n  2 
T (16) log4 n
3log4 n
3
T 4 + 8n 16 log4 n 9
=
+ 8n 8 16
4
32
9
9

4log4 n2


3
4

(4log4 n2 3log4 n2 )/4log4 n2


+ 2n
1/4

x
3

+7

for x = 3n2 the general


 form gives
T ( 3n2 ) = 5T 3n3 + 7

5log3 n1 7 + 7

5log3 n1 1
4

5log3 n 5log3 n 1
7
+

5
20
4

=
=

5 5log3 n 1

20
4

Assume also wlog that all elements of A are distinct. Let S be the array A correctly sorted, that is s1 < s2 < . . . < sn
n
k
2k
and n
i=1 {ai } = i=1 {si }. Let SL = i=1 {si } be the n/3 smallest elements of A. Let SM = i=k+1 {si } be the n/3

+7 +57+7

4 5log3 n 5log3 n 1
+

7
20
20
4

=
96 log4 16
9 3

the general form gives T ( n3 ) = 5T

53 T

32 log4 n
3log4 n
96
+ 8n 8 16
3
= 8n 3log4 n = O(n)
9
9
9

log4 n (verify also that formula gives T (16) = 8 16


Hence T (n) = 8n 96
9 3
2
8 16 96
9 3 = 8 16 96 = 32 as it should.)

n
33

16

n
3

+57+7

+7 +7

52 5T

for x =

 log4 n2
3

n
32

n
32

n
+ 52 7 + 5 7 + 7
33
 
n
+ 7 (5k1 + . . . + 5 + 1)
guessing general term
=
5k T
3k

 
n
5k 1
k1 + . . . + x + 1 = xk 1 , for x > 1
=
5k T
+
7
using
x
x1
3k
51
n
n
n
stop when
= 3 = 3k log3 = k k = log3 n log3 3 k = log3 n 1
3k
3
3

5log3 n1 1
=
5log3 n1 T (3) + 7
4

using xk1 + . . . + x + 1 =

1 4
+ 2n

52 T

n
n
n
= 4k log4
= k k = log4 n log4 16 k = log4 n 2
= 16
4k
16
16

 k

34
1 34

5 5T

+7

+32

 
k1

n
3

5T

for x = 4n2 the general


  form gives
T ( 4n2 ) = 3T 4n3 + 2 4n2

+ 2n
n
+ 2n
4

+32
n
43

n
+ 2n
4
 
n
n
n
2
+
3

+
3

+ 2n
33 T
43
42
4
 

 
n
3 2 3
+
1
+
2n
+
33 T
43
4
4

n
42

+ 2n

middle elements elements of A. Let SR = n


i=2k+1 {si } be the n/3 largest elements of A. Notice that every element
z SR has less that n/3 elements that are strictly greater than z. We call this the fundamental property of SR .
After we sort the rst 2/3 of the elements of A, let X1 be the set of elements occupying the rst 1/3 positions, let
X2 be the set of elements occupying the middle 1/3 positions, and let X3 be the set of elements occupying the last
1/3 positions. It is now easy to see that X1 SR = , that is, the elements in X1 do not occupy any of the last 1/3
positions of the sorted array s1 < s2 < . . . < sn . This is because every element in x X1 has at least n/3 elements
that are strictly greater than x (namely all the elements in X2 ), thus it fails to satisfy the fundamental property of
SR . Thus, the elements of SR X2 X3 .
Thus, after we sort the last 2/3 of the elements, ie we sort X2 X3 , we are guaranteed that all elements of SR
are correctly sorted and placed in the last 1/3 positions s2k+1 , . . . , sn . Consequently, the elements of SL SM are
correctly placed in the range of positions 1, . . . , 2k, however they are not necessarily sorted.
The nal sorting of elements in positions 1, . . . , 2k guarantess that the elements of SL SM are correctly sorted and
placed rst 2/3 positions. Thus A is sorted and coincides with S.

(b)
T (n) = 3T (2n/3) + c

7 log3 n
(5
1)
4
7 log3 5 log3 n
7
1) = (nlog3 5 1) = O(nlog3 5 )
(3
4
4

= 3(3T (22 n/32 ) + c) + c = 32 T (22 n/32 ) + 3c + c


= 32 (3T (23 n/33 ) + c) + 3c + c = 33 T (23 n/33 ) + c(32 + 3 + 1)
= 3k T (2k n/3k ) + c(3k1 + ... + 3 + 1)
= 3k T (2k n/3k ) + c(3k 1)/2
= stop when

 k
2
3

n=1n=

 k
3
2

k = log1.5 n

= 3log1.5 n T (1) + c3log1.5 n c/2


= O(3

log1.5 n

log1.5 3 log1.5n

) = O(1.5

) = O(nlog1.5 3 )

(c) Mergesort is O(n log n), bubblesort is O(n2 ), Stoogesort is O(nlog1.5 3 ) O(n2.725 ), no funding!
Hence T (n) = 74 (5log3 n 1) (verify also formula gives T (3) = 47 (5log3 3 1) = 74 (5 1) = 7.)

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 2, 1/16/15 Due 1/23/15 in class
Page 4/5

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 3, 1/23/15 Due 1/27/15 in class
Page 1/2

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 2, 1/23/15 Due 1/27/15 in class
Page 2/2

Problem 4: Median nding Under Partial Sorting (20 points).


Let X(1, . . . , n) and Y (1, . . . , n) be two arrays, each containing n numbers already in sorted order.
Describe an O(log n)-comparison algorithm to nd the median of all 2n elements in arrays x and
Y . Justify your answer in correctness and running time.
Answer: Suppose S = s1 < s2 < . . . < s2n is the set of elements of X Y in sorted order. We are
looking for the two medians, sn and sn+1 .
Case 1 n is odd, thus n = 2k + 1. Thus there are altogether 2(2k + 1) = 4k + 2 elements, and we
are looking for the two medians (2k + 1)st and (2k + 2)nd elements.
Compare xk+1 and yk+1 and suppose that xk+1 < yk+1 . We then know that, for each element xi
where i = {1, . . . , k} there are at least 2(k + 1) = 2k + 2 elements that are strictly larger than xi
(namely, the elements xk+1 to x2k+1 and yk+1 to y2k+1 .) Thus, in the sorted array S every element
xi where i = {1, . . . , k} has rank at most 2n (2k + 2) = 4k + 2 2k 2 = 2k, it is smaller than
the medians, and it is belongs to the rst 2k positions of S. Similarly, for each element element
yi where i = {k + 2, . . . , 2k + 1} there are at least 2(k + 1) = 2k + 2 elements that are strictly
smaller than yi . Thus, in the sorted array S every element yi where i = {k + 2, . . . , 2k + 1} is larger
than the medians and belongs to the last 2k positions of S. We may therefore look recursively for
the medians of X(k + 1, . . . , 2k + 1) and Y (1, . . . k + 1), and with one comparison the problem is
reduced to one that is half the size. (Of course the case where xk+1 > yk+1 follows identical logic.)
Case 2 n is even, thus n = 2k. Thus there are altogether 4k elements, and we are looking for the
two medians 2kth and (2k + 1)st elements of S.
Compare xk and yk and suppose that xk < yk . We can similarly identify the (k 1) elements
x1 , . . . , xk1 as being smaller than both medians and the (k 1) elements yk+2 , . . . , yn as being
larger than both medians, and recurse on X(k, . . . , n) and Y (1, . . . , (k + 1)). Again, with one
comparison we have reduced the problem to one that is half the size.
Complexity T (n) = T (n/2) + c which solves to O(log n).

Problem 1: Weighted Median (50 points).



For n distinct elements x1 , x2 , . . . , xn with positive weights w1 , w2 , . . . , wn such that ni=1 wi = 1,
the weighted median is the element xk satisfying

Problem 2: Recursive Design/Divide and Conquer (50 points).


Diogenes Technologies have n supposedly identical integrated-circuit chips that in principle are
capable of testing each other. Their testjig accomodates two chips at a time. When the jig is
loaded, each chip tests the other and reports whether it is good or bad. A good chip always reports
accurately whether the other chip is good or bad. But the answer of a bad chip cannot be trusted.
Thus, the four possible outcomes of a test are as follows:

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 2, 1/16/15 Due 1/23/15 in class
Page 5/5
Problem 5: Numbers Closest to Median (20 points).
Describe an O(n)-comparison algorithm that, given a set S of n distinct integers and a positive
integer k n, determines the k numbers in S that are closest to the median of S. For example,
if S = {11, 14, 2, 1, 30, 20, 5, 4, 14, 10, 9} and k = 4 the median of S is 10 and the 4 numbers that
are closest to 10 are 9, 11, 12 and 14 since 10-9=1, 11-10=1, 12-10=2 and 14-10=4, while 10-5=5.
Justify your answer in correctness and running time.
Answer:
Using an O(n) median-nding algorithm we nd the median m of S.
We compute the array A, where a(i) = |s(i) m|, for all s(i) S. Thats another O(n) operations.
Using an O(n) KSelect algorithm, we nd the kth element of A, say its value is .
We scan S one more time, and for every element with |s(i) m| , we include s(i) as one of the
elements that are among the k elements closest to the median.

wi

xi <xk

1
2

and

wi

xi >xk

1
.
2

a. Show how to compute the weighted median of n elements in O(n log n) time using sorting.
b. Show how to compute the weighted median of n elements in O(n) time using a linear-time
median nding algorithm similar to KSELECT.
Answer:
(a) STEP 1: Use an O(n log n) sorting algorithm to sort the xi s. If the position of xi in sorted
order is j, then dene p(xi ) := j.
STEP 2: Scan the xi s in sorted oder, until you nd xk satisfying weighted median property:
m := 0; index := 0;
while m 12
index := index + 1;
m := m + wp(xindex ) ;
return( index );
(b) We solve a more general problem: For n distinct elements x1 , x2 , . . . , xn with positive weights

w1 , w2 , . . . , wn and a number  ni=1 wi , we want the element xk satisfying

xi <xk

wi 

and


xi >xk

wi (

n


wi ) .

i=1

EpsilonSplitter(x1 , x2 , . . . , xn , w1 , w2 , . . . , wn , )
STEP 1: Use KSELECT to nd the median s of x1 , . . . , xn .
STEP 2: Let A = {xi : xi s} and B := {xi : xi > s}.

STEP 3: compute w(A) := xi A wi ;
STEP 4: if w(A) >  then EpsilonSplitter(xi A, wi : xi A, )
else EpsilonSplitter(xi B, wi : xi B,  w(A));
in STEPS 1 through 3, we reduce the problem to one of half
Complexity: Using O(n) operations

the size. Thus T (n) = T n2 + cn which solve to O(n).

Chip A says
B is good
B is good
B is bad
B is bad

Chip B says
A is good
A is bad
A is good
A is bad

Conclusion
both are good, or both are bad
at least one is bad
at least one is bad
at least one is bad

(a) Consider the problem of nding a single good chip from among n chips, assuming that more
than n/2 of the chips are good. Show that n/2
pairwise tests are sucient to reduce the probelm
to one of nearly half the size.
(b) Show that the good chips can be identied with O(n) pairwise tests, assuming that more than
n/2 of the chips are good, as in part (a). Give and solve the recurrence that describes the number
of tests. (Avoiding code or pseudocode recommended.)
Abswer:
(a) Case 1: n is even, so n = 2k and there are at least (k + 1) good chips.
Suppose that we test the chips in k pairs.
If a pair answers {good, bad} or {bad, bad} then we know that the pair contains at least one bad
chip. Suppose there are k  such pairs, and we discard all the chips in these pairs. By discarding
these pairs, we remove exactly 2k  chips of which at least k  are bad and at most k  are good.
We are thus left with 2(k k  ) chips, at least (k + 1) k  of them are good, and when compaired
in pairs the answer of each pair is {good, good}. This means that, in each pair, either both chips
are good, or both chips are bad, and more than half of the pairs correspond to two good chips. We
may thus keep one chip from each pair, and be left with (k k  ) chips such that more than half of
these chips are good. This reduces the problem of nding a good chip from 2k to at most k (note
als0 that (k k  ) > 0 since there is at least one pair that outputs {good, good} among the rst k
comparisons, ie k  < k.)
Case 2: n is odd, so n = 2k + 1 and there are at least (k + 1) good chips.
Suppose that we test the chips in k pairs, and one last odd chip is not tested.
For the k pairs, follow the method of Case 1, and suppose that we are left with (k k  ) chips. If
(k k  ) is even (it could also be 0, which is an even number) then for the next round we use these
(k k  ) chips AND the last odd chip. If (k k  ) is then for the next roud we use these (k k  )
chips AND DO NOT use the last odd chip.
(b) The above method reduces the problem of nding a good chip to one of half the size, using n/2
comparisons. In the end we will be left with a single chip which is a good chip. The total number
of comparisons is T (n) = T (n/2) + n/2 which solves to T (n) n. Once a good chip is found, we
can use it in (n 1) pairwise tests with the remaining (n 1) chips, and determine the good and
the bad chips in the entire set.

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 4, 1/30/15 Due 2/4/15 in class
Page 1/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 4, 1/30/15 Due 2/4/15 in class
Page 2/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 4, 1/30/15 Due 2/4/15 in class
Page 3/4

Problem 1: Recursive Design, Divide and Conquer, 25 points.


You have n = 3k coins (k 1) and a pan balance. One of the coins is counterfeit and it is lighter
(in weight) than the rest. All the other (n 1) coins have the same weight. Design a divide and
conquer algorithm to nd the counterfeit coin in k rounds. In each round, you may put any number
of coins in each pan of the balance, and, it tells you either that bothe sides have the same weight,
or which side is heavier. Explain why your algorithm is correct, and justify the running time.
Answer:
If n = 3 then we nd the counterfeit as follows. We take 2 of the 3 coins and put them on the
balance. If the balance is not horizontal, then the higher side reveals the counterfeit coin. If the
balance is horzintal, then the 2 coins on the balance have equal weight, and the lighter counterfeit
is the 3rd one.
If n = 3k for some k > 1 then we reduce the problem to a problem on size 3k1 = n/3 as follows.
We partition the coins into 3 sets, each set containing 3k1 = n/3 coins. We take 2 of these 3 sets
and put them on the balance. If the balance is not horizontal, then the higher sode reveals the set
of 3k1 = n/3 coins that contain the counterfeit coin. If the balance is horizontal, then the 2 sets
on the balance have equal weight, and the lighter counterfeit coin is in the 3rd set. We recurse on
the set of size 3k1 = n/3 that contains the lighter counterfeit coin.
We thus have T (n) = T (n/3) + 1 with T (3) = 1. Lets solve it by substitution:

Problem 2: Recursive Design, Divide and Conquer, 25 points.


Suppose that you are consulting for a bank that is concerned about fraud detection, and they
come to you with the following problem. They have a collectioon of n bank cards that they have
conscated, suspecting them of being used in fraud. Each bank card is a small plastic object,
containing a magnetic stripe woth some encrypted data, and it corresponds to a unique account in
the bank. Each account can have many bank cards corresponding to it, and we will say that two
bank cards are equivalent if and only if they correspond to the same account.
It is very dicult to read the account number o the card directly, but the bank has a high
tech equivalence tester that takes two bank cards and, after performing some computations,
determines whether they are equivalent.
Their question is the following: among the collection of n cards, is there a set of more than n/2
of them that are all equivalent to one another? Assume that the only feasible operations that you
can do with the cards are to pick two of them and plug them in to the equivalence tester. Show how
to decide the answer to their question with only O(n log n) invocations of the equivalence tester.
Answer: Assume that n is a power of 2. Let c1 , . . . , cn be the cards. Say that a bank account x
is a majority
element for c1 , . . . , cn if and only if the number of cards ci corresponding to x is at


least n2 + k , for some k > 0. Clearly, if there exists a majority element x, then x is unique.
Main Lemma: If there is a majority element x for c1 , . . . , cn then
either Case 1: x is a marority element for c1 , . . . , c n2 ,
or Case 2: x is a marority element for c n2 +1 , . . . , cn ,
or Case 3: x is a majority element for both c1 , . . . , c n2 and c n2 +1 , . . . , cn . Proof: By contradition.
Suppose that x is not a majority element for neither of c1 , . . . , c n2 nor c n2 +1 , . . . , cn . That means
that the number of cards in c1 , . . . , c n2 corresponding to x is at most n/4 and the number of cards in
c n2 +1 , . . . , cn corresponding to x is also at most n/4. Thus, the total number of cards corresponding
to x in x for c1 , . . . , cn is at most n4 + n4 = n2. This, however. contradicts the fact that the total
number of cards corresponding to x is at least n2 + k , for some k > 0, since x is a majority element
for c1 , . . . , cn .

Problem 3: Application of KSelect, Median, Order Statistic, 25 points.


Let a(1), . . . , a(n) be an unsorted input array of n distinct positive integers, where n is odd. A
wigly arrangement of a is a permutation of the input such that

T (n) = T (n/3) + 1
= T (n/32 ) + 1 + 1 = T (n/32 ) + 2
= T (n/33 ) + 1 + 2 = T (n/33 ) + 3
= T (n/3k ) + k
= T (n/3log3 n1 ) + log3 n 1
= T (3) + log3 n 1
= 1 + log3 n 1
= log3 n

Algorithm: If n = 2 then check the two cards. If they are equivalent, then output one of them. If
they are not equivalent, then output nil. If n > 2 then
Recurse on c1 , . . . , c n2 . The output should be, either nil, or a card ci with 1 i n2 .
Recurse on c n2 +1 , . . . , cn . The output should be, either nil, or a card cj with ( n2 + 1) cj n.
If the output of both the above recursive calls is nil then output nil and halt.
If the output of one of the recursive calls is nil and of the other recursive call is a card ca , then
compare ca with all the cards in c1 , . . . , cn and if the number of cards found equivalent to ca is
greater than n/2 then output ca and halt.
If the output of both recursive calls is not nil, ie the rst recursive call output a card ca and the
second recursive call output a card cb then
Compare ca with all the cards in c1 , . . . , cn and
if the number of cards equivalent to ca is greater than n/2 then output ca and halt
else compare cb with all the cards in c1 , . . . , cn and
if the number of cards equivalent to cb is greater than n/2 then output cb and halt
else output nil.

a((1)) > a((2)) < a((3)) > a((4)) < a((5)) . . . a((n 2)) > a((n 1)) < a((n)).
For example, on input 100, 20, 2, 5, 200, 50, 40, 201, 300
a wigly arrangement is 100, 20, 200, 2, 50, 5, 201, 40, 300
since 100 > 20 < 200 > 2 < 50 > 5 < 201 > 40 < 300.
Give an O(n) comparison algorithm that outputs a wigly arrangement of an unsorted input array
a(1), . . . , a(n) of n distimct integers, where n is odd. You may give a simple description of the
algorithm (no pseudocode.) You should include a short argument of correctness and running time.
Answer:
Using O(n) comparisons, nd the median m of a(1), . . . , a(n).
Scanning a(1), . . . , a(n) and using n comparisons, nd the set S1 of (n 1)/2 elements that are
smaller than m, and the set S2 of (n + 1)/2 elements that are greater than or equal to m. Clearly,
every element of S1 is smaller than every element of S2 .
Place the elements of S1 on the (n 1)/2 even numbered indices a(2), a(4), . . . , a(n 1).
Place the elements of S2 on the (n + 1)/2 odd numbered indices a(1), a(3), . . . , a(n).
Since every element of S1 is smaller than every element of S2 , the nal arrangement is wigly.

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 4, 1/30/15 Due 2/4/15 in class
Page 4/4
Problem 4: Recursive Design, Divide and Conquer, 25 points.
Consider an n-node complete binary tree T , where n = 2d 1 for some d. Each node in v of T is
labelled with a distinct number xv . A node v of T is a local minimum if and only if the label xv is
less than the label xw for all nodes w that are joined to v by an edge.
You are given such a complete binary tree T , but the labeling is only specied in the following
implicit way: for each node v, you can determine the vale xv by probing the node v. Show how to
nd a local minimum of T using onlt O(log n) probes to nodes of T .
Answer: Algorithm and Reasoning:
If d = 2 then the tree has 3 nodes: the root u, the roots left child uL and the roots right child
uR . If xu < xuL and xu < xuR then u is a local minimim. Otherwise, if xu > xuL then uL is a local
minimum, or if xu < xuR then uR is a local minimum.
If d > 2 then let u be the root, uL is the roots left child and uR is the roots right child. If xu < xuL
and xu < xuR then u is a local minimim.
Otherwise, if xu > xuL we recursively look for a local minimum in the tree rooted in uL . If uL
is the local minimum of the tree rooted in uL then uL is also a local minimum of the entire tree.
This is because, by being a local minimum of the tree rooted in uL , xuL is smaller than both its
children. And since it is also smaller than its parent xu > xuL , us value is smaller than the value
of all its neighbors, hence local minimum. If uL is not the local minimum of the tree rooted in uL ,
then the local minimum of this subtree is automatically a local minimum of the entire tree.
Otherwise, if xu < xuL and xu > xuR we recursively look for a local minimum in the tree rooted in
uR .
Complexity Analysis: In all cases, the probes consist of the root u and the nodes along a sigle path
from u to a some descendant of u. So let u, u1 , . . . , uk be that path. The longest possibility for
this path is if uk is a leaf, in which case k = d and the number of nodes probed along this path is
(d+1). In addition, for u1 , . . . , ud , the sigling of these nodes was also probed, which is an additional
d probes. Thus the total number of probes is at most (2d + 1). Since d = log2 (n + 1), the total
number of probes interms of n is (2d + 1) = 2 log2 (n + 1) + 1.

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 5, 2/3/15 Due 2/18/15 in class
Page 1/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 5, 2/13/15 Due 2/18/15 in class
Page 2/4

Problem 1: Scheduling All Intervals/Interval Partition, Greedy, 25 points.


Consider requests R = {1, 2, . . . , n}. The i-th request corresponds to an interval of time starting
at s(i) and nishing at f (i). Say that a subset of intervals is compatible if and only if no two of
them overlap in time. The problem is to schedule all requests using as few resources as possible. In
particular, a partitioning of R is a collection of sets R1 , R2 , . . . , Rm with Ri Rj = , i = j, and
with m
i=1 Ri = R. Say that a partitioning of R is valid if and only if the subset Ri is a compatible
for all 1 i m (we may thus schedule all intervals using m resources, one resource for each set
Ri .) We want a valid partitioning of R which minimizes m.
(a) Suppose that the intervals in R are arranged in the time line, with interval i starting at s(i)
and nishing at f (i). Say that the depth d of R is the maximum number of intervals that pass over
any single point on the time line. Argue that any valid partitioning of R uses at least d resources
(ie m d.)
(b) Give an ecient greedy algorithm that nds a valid partitioning of R that uses exactly d
resources. Argue correctness and running time of your algorithm. Hint: Consider the intervals
ordered by their starting times.
Answer:
(a) If for some particular x we have |{i : s(i) x f (i), 1 i n}| = d, then we clearly need at
least d resources.
(b) The algorithm will consider intervals in increasing starting order. We thus assume that
s(1) s(2) . . . s(n). The rst interval will be assigned to R1 and we mark the nish
time F1 = f (1). At iteration i we will assign interval i. Throughout the algorithm we will be
maintaining all resources that have been used, together with the time until which each resource is
reserved. The resources are being maintained in a heap, so that the resource that nishes rst is
available when we consider the starting time of the next interval i.
sort the starting times, so that s(1) s(2) . . . s(n);
d := 1; R1 := {1}; F1 := f (1); Heap := {(1, R1 , F1 )};
for i := 2 to n
let (k0 , Rk0 , Fk0 ) be the root of Heap;
if s(i) > Fk0 then
Rk0 := Rk0 {i}; Fk0 := f (i); Update((k0 , Rk0 , Fk0 )Heap);
else
d := d + 1; Rd := {i}; Fd := f (i); Insert((d, Rd , Fd ), Heap);
The total running time is O(n log n). This is the time for sorting according to starting times, plus
n iterations, each of which one heap operation which is O(log n).

Problem 2: Mincost Vertex Cover, Dynamic Programming Implementation, 25 points.


Let G(V, E) be a graph with costs on its nodes. Thus, for each v V , let w(v) > 0 is the cost of
a vertex v. Say that C V is a vertex cover if an only if every edge in E has at least one of its
endpoints in the set C: |{u, v} V | 1, {u, v} E. Dene the cost of a vertex cover C as the

sum of the costs of all vertices in C: W (C) = vC w(v).
(a) Suppose that G(V, E) is a line, that is V = {1, . . . , n} and E = {{1, 2}, {2, 3}, . . . , {(n 1), n}}.
Give an ecient algorithm that nds a minimum cost vertex cover of G. Argue correctness and
running time.
(b) Suppose that G(V, E) is a cycle, that is V = {1, . . . , n} and E = {{1, 2}, {2, 3}, . . . , {(n
1), n}} {{n, 1}}. Give an ecient algorithm that nds a minimum cost vertex cover of G. Argue
correctness and running time.
Answer:
(a) Let OPT(n) be the cost of the optimal vertex cover for edges {{1, 2}, {2, 3}, . . . , {(n 1), n}},
and let C(n) be the set of vertices belonging to this cover. Let OPTout (n) be the cost of the
cheapest vertex cover for edges {{1, 2}, {2, 3}, . . . , {(n 1), n}} that does not contain vertex n, and
let Cout (n) be the set of vertices belonging to this cover. Realize that Cout (n) must contain vertex
(n 1), since edge {(n 1), n} must be covered. Let OPTin (n) be the cost of the cheapest vertex
cover for edges {{1, 2}, {2, 3}, . . . , {(n 1), n}} that contains vertex n, and let C,in (n) be the set of
vertices belonging to this cover. Clearly OPT(n) = min{OPTout (n), OPTin (n)}.
More generally, for 2 k n let OPT(k) be the cost of the optimal vertex cover for edges
{{1, 2}, {2, 3}, . . . , {(k 1), k}}, and let C(k) be the set of vertices belonging to this cover. Let
OPTout (k) be the cost of the cheapest vertex cover for edges {{1, 2}, {2, 3}, . . . , {(k 1), k}} that
does not contain vertex k, and let Cout (k) be the set of vertices belonging to this cover. Realize
that Cout (k) must contain vertex (k 1), since edge {(k 1), k} must be covered. Let OPTin (k) be
the cost of the cheapest vertex cover for edges {{1, 2}, {2, 3}, . . . , {(k 1), k}} that contains vertex
k, and let Cin (k) be the set of vertices belonging to this cover.
Clearly C2,out = {1} and OPTout (2) = w(1), while C2,in = {2} and OPTin (2) = w(2).
Now, for 3 k n, we may write:

(b) In part (a) we gave a linear time algorithm to nd the mincost vertex cover of a weighted line.
In addition, the algorithm was computing the mincost vertex covers conatining and not containing
an end vertex of the line. In this part we will nd the mincost vertex cover of a weighted cycle by
reducing this problem to three separate mincost vertex cover problems on suitably dened weighted
lines, ans taking the smaller of three suitale solutions.
In particular, for the cycle {{1, 2}, {2, 3}, . . . , {(n 1), n}} {{n, 1}}, edge {n, 1}} must be
covered by any vertex cover. There are three cases: (i)Vertex 1 belongs to the vertex cover of the
cycle and vertex n does not belong to the vertex cover of the cycle. (ii)Vertex n belongs to the
vertex cover of the cycle and vertex 1 does not belong to the vertex cover of the cycle. (iii)Both
vertices 1 and n belong to the vertex cover.
For case (i) above, we consider the line graph {{2, 3}, . . . , {(n1), n}} and compute Ci,out (n1)
and OPTi,out (n 1). We let X := w(1) + OPTi,out (n 1). For case (ii) above, we consider the
line graph {{1, 2}, {2, 3}, . . . , {(n 2), (n 1)}} (with vertices considered from higher to lower)
and compute Cii,out (n 1) and OPTii,out (n 1). We let Y := w(n) + OPTii,out (n 1). For case
(iii) above, we consider the line graph {{2, 3}, . . . , {(n 2), (n 1)}} and compute Ciii (n 2) and
w(1) + w(n) + OPTiii (n 2).
If X = max{X, Y, Z} then the mincost vertex cover of the cycle is {1} Ci,out (n 1) and has
cost w(1) + OPTi,out (n 1). If Y = max{X, Y, Z} then the mincost vertex cover of the cycle is
{n} Cii,out (n 1) and has cost w(n) + OPTii,out (n 1). If Z = max{X, Y, Z} then the mincost
vertex cover of the cycle is {1, n} Ciii (n 2) and has cost w(1) + w(n) + OPTiii (n 2).

Cout (k) = Cin (k 1)




Cin (k) =

{k} Cout (k 1) if w(k) + OPTout (k 1) w(k) + OPTin (k 1)


{k} Cin (k 1) if w(k) + OPTout (k 1) > w(k) + OPTin (k 1)

Therefore, a linear algorithm that computes OPT(n) = min{OPTout (n), OPTin (n)} is a
memoization of the above recursions that compute Cout (k) and Cin (k), for k := 2 to n.
Initialization: C2,out := {1}; OPTout (2) := w(1); C2,in := {2}; OPTin (2) = w(2);
Main Loop: for k := 2 to n begin
Cout (k) = Cin (k 1); OPT
out (k) = OPTin (k 1);
Cin (k) := {k} Cout (k 1)
if w(k) + OPTout (k 1) w(k) + OPTin (k 1) then
OPTin (k) := w(k) + OPTout (k 1)


else
end;

if OPTout (n) < OPTin (n) then


else

Cin (k) := {k} Cin (k 1)


OPTin (k) := w(k) + OPTin (k 1)

C(n) := Cout (n)


OPT(n) := OPTout (n)
C(n) := Cin (n)
OPT(n) := OPTin (n)

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 5, 2/13/15 Due 2/18/15 in class
Page 3/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 5, 2/13/15 Due 2/18/15 in class
Page 4/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 6, 2/27/15 Due 3/6/15 in class
Page 1a/6

Problem 3: Floyd-Warshall, 25 points.


Let G(V, E) be a graph where each edge (i, j) has a cost wij . Look at the pseudocode of the
Floyd-Warshall algorithm in CRLS.
(a) Assuming that G does not have a negative cycle, modify Floyd-Warshalls algorithm to compute
the predecessor matrices (k) .
(b) Modify Floyd-Warshals algorithm to decide if G has a negative cycle and, if a negative cycle
exists, output all edges of a negative cycle.
Answer:
(a) Floyd-Warshall (W ) with predecessor matrix
1 n rows(W )
2a D(0) W
2b for i 1 to n
for j 1 to n
if ((i = j) or (i, j) E) then (0) (j) i
3 for k 1 to n
4
for i 1 to n
5
j 1 to n
 (k)
(k1)
dij dij
(k1)
(k1)
(k1)
dik
+ dij
then
6
if dij
(k)
(k1)
ij ij

Problem 4: Floyd-Warshall, 25 points.


Let G(V, E), |V | = n, be a graph where each edge (i, j) has a cost wij . We know that FloydWarshall requires that G has no negative cycle. Now consider the following proposition for nding
cheapest paths in graphs whose weight matrices contain negative cycles. First nd the minimum
cost edge we = min1in,1jn {wij }. If we 0 then all edges of G have non-negative costs and
 = w w .
we may apply Floyd-Warshall. If we < 0 then dene a new cost matrix W  with wij
ij
e
Now the weight of all edges has been increases by we , thus all edges have non-negative weights
and W  does not have a negative cycle. Apply Floyd-Warshall of W  and simultaneously compute
(n)
(n)
can be used as a predecessor matrix of
the predecessor matrix . The predecessor matrix
shortest paths. Is the above algorithm correct? If yes then give a proof. If no then give a counter
example.
Answer:
The shortest paths suggested by the predecessor matrix (n) that corresponds to W  do not
necessarily correspond to shortest paths in the original graph W . Here is a counter example.
Suppose that for vertices x, y and z of W there were edges x y, x z and z y in W with
costs wxy = 3, wxz = 1 and szy = 1. Thus, the shortest path from x to y in W had cost 2 and
consisted of taking edge x z followed by edge z y. Now suppose a large weight, say 100, is
added to all the edges. In graph W  , the edge x z has cost 101, the edge z y has cost 101,
and the edge x y has cost 103. In W  the shortest path from x to y consists of the edge x y,
and it is dierent from the shortest path in the original graph W .

Problem : DFS in Directed Graph (10 points).


(a) Run DFS in the graph of le DFSDirGraph.pdf, where vertices and edges are explored in lexicographic order. For every vertex, indicate the start and nish times. Indicate DFS tree edges.
Incicate back edges, forward edges and cross edges.

else

(k)

(k1)

(k)

(k1)

dij dik

(k1)

+ dij

ij kj
(b) Floyd-Warshall (W ) detecting negative cycle
1 n rows(W )
2a D(0) W
2b for i 1 to n
for j 1 to n
if ((i = j) or (i, j) E) then (0) (j) i
2c NegCycle := false; N 0
3 for k 1 to n
4
for i 1 to n
5
j 1 to n
6a
if (NegCycle=false)
begin
 (k)
(k1)
dij dij
(k1)
(k1)
(k1)
6b
if dij
dik
+ dij
then
(k)
(k1)
ij ij


else


(k)
dij

(k)

(k1)

(k)

(k1)

dij dik

(b) Indicate how strongly connected components are identied using DFS in the reverse graph GT .

(k1)

+ dij

ij kj

6c
if (i = j) and
< 0 then {NegCycle := true;N i}
7 if (NegCycle = true) then begin
return(N
)

(n)
repeat x := N N (N ); return(N ) until (x = N )
end

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 6, 2/27/15 Due 3/6/15 in class
Page 1c/6

(c) In the strongly connected component algorithm we explore GT treating vertices in reverse than
the order that they nished when DFS run on G. Was the use of GT necessary? If we did a second
DFS on G treating vertices in reverse than the order that they nished when DFS run for the rst
time on G, would the strongly connected components be identied?
"OTXFS'PSUIFHSBQIPGUIJTQSPCMFN BTFDPOE%'4USFBUJOHWFSUJDFTJOUIFPSEFSUIBUUIFZGJOJTIFEJOUIF
GJSTU %'4 EPFT QSPEVDF USFF DPNQPOFOUT UIBU DPSSFTQPOE UP UIF TUSPOHMZ DPOOFDUFE DPNQPOFOUT PG UIF
HSBQI)PXFWFS UIJTJTOPUUSVFJOHFOFSBM BTTIPXOJOUIFHSBQIPGUIFDPVOUFSFYBNQMFCFMPX

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 6, 2/27/15 Due 3/6/15 in class
Page 2/6

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 6, 2/27/15 Due 3/6/15 in class
Page 4/6

Problem 2: Topological Sorting (10 points).


We know that, if G(V, E) is a directed acyclic graph then arranging the nodes in reverse nish
order according to any DFS produces an ordering where all edges are directed from lower to higher
nodes. Now suppose that G(V, E) is a general directed graph, thus G may have cycles, and there
is no ordering of its nodes such that all edges are directed from lower to higher nodes. However,
we still want an ordering of the nodes such that the number of edges directed from higher to lower
is minimized. Does arranging nodes in reverse nish order according to DFS produce such an
ordering? If yes then give a proof. If no then give a counter-example.

Problem 4: Testing Bipartiteness (20 points).


An undirected graph G(V, E) is bipartite if and only if V can be partitioned to VL and VR (ie
VL VR = V and VL VR = ) so that all edges in E have one endpoint in VL and the other endpoint in VR . Clearly, if a graph contains an odd length cycle then it is not bipartite, thus an odd
length cycle is a certicate of non-bipartiteness. Give an O(|V | + |E|) algorithm that determines if
G is bipartite. If the graph is not bipartite then the algorithm should output an odd length cycle.
If the graph is bipartite then the algorithm nds a partition of V to VL and VR so that all edges in
E have one endpoint in VL and the other endpoint in VR . Argue correctness and running time.

"OTXFS*UJTOPUUSVF BTTIPXOJOUIFDPVOUFSFYBNQMFCFMPX

"OTXFS
8FEP%'4BOEBTTJHOPOFPGUXPOVNCFSTUPOPEFT TBZBOE5IFSPPU JFXIFOXFBSFTUBSUJOHBOFX
DPOOFDUFEDPNQPOFOU
JTBTTJHOFEFJUIFSPS&WFSZOPEFUIBUJTOPUBSPPUOPEFJO%'4JTBTTJHOFEB
OVNCFSUIBUJTEJGGFSFOUUIBOUIFOVNCFSPGJUTQBSFOU4PGBSUIFOVNCFSJOHJTGJOF)PXFWFS JGUIFSFBSF
CBDLFEHFTJOBEEJUJPOUPUIFUSFFFEHFT UIFOBUUIFQPJOUXIFOBCBDLFEHFJTEJTDPWFSFECPUIJUT
FOEQPJOUTIBWFCFFOBTTJHOFEOVNCFST5IFSFBSFUXPDBTFT5IFGJSTUDBTFJTUIBUUIFOVNCFSTBUUIF
FOEQPJOUTPGBMMUIFCBDLFEHFTBSFEJGGFSFOU*OUIFDBTFUIFOVNCFSJOHQSPEVDFECZ%'4JNNFEJBUFMZHJWFT
BCJQBSUJUJPOPGUIFOPEFTPGUIFHSBQI TPUIBUUIFSFBSFOPFEHFTCFUXFFOQBSUJUJPODMBTTFT OPPS
FEHFT
5IFTFDPOEDBTFJTUIBUUIFOVNCFSTBUUIFFOEQPJOUTPGTPNFCBDLFEHFVWXFSFUIFTBNF5IBU
JNNFEJBUFMZJEFOUJGJFTBOPEEMFOHUIDZDMF8FDBOGJOEUIJTDZDMFTUBSUJOHGSPNUIFCBDLFEHFVW BOE
UIFOGPMMPXJOHUSFFFEHFTGSPNVUPBMMJUTBODFTUPSTJOUIF%'4USFF VOUJMWJTSFBDIFE5IFUPUBMUJNFJT
0 ]7] ]&]


Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 6, 2/27/15 Due 3/6/15 in class
Page 3/6
Problem 3: Cycles in Undirected Graphs (20 points).
Give an O(|V |) algorithm that determines if an undirected graph G(V, E) in adjacency list representation has a cycle. Your algorithm should run in time O(|V |) independent of |E|. Argue correctness
and running time. Hint: Argue that G has a cycle if and only if DFS discovers a single non-tree edge.
"OTXFS%'4JOVOEJSFDUFEHSBQITQSPEVDFTPOMUUSFFFEHFTBOECBDLFEHFT*GUIFBMHPSJUINQSPEVDFTPOMZUSFF
FEHFT UIFO TJODFUIFSFBSFBUNPTU ]7]
USFFFEHFT UIFHSBQIIBTOPUDZDMFBOE%'4IBTGJOJTIFEJO0 ]7]
*GUIF
BMHPSJUINQSPEVDFTBTJOHMFOPOUSFFFEHF UIFOUIBUJTBCBDLFEHFBOEJUJEFOUJGJFTBDZDMF8FDBOTUPQUIF
BMHPSJUINBUUIBUQPJOU SFQPSUJOHUIBUUIFSFJTBDZDMF BOEFOTVSJOHBUPUBMSVOOJOHUJNF0 ]7]

%'4( 7 &
$:$-&GBMTF
GPSBMMW V mark v unvisited;
while there exists unvisisted v V
if (CYCLE = false) then DFS-visit(v);
return(CYCLE)
DFS-visit(v)
mark v visited;
if (CYCLE = false) then
for all u A(v) if (u is visited) then CYCLE := true else DFS-visit(u)

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 6, 2/27/15 Due 3/6/15 in class
Page 5/6

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 7, 3/13/15 Due 3/25/15 in class
Page 1/6

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 7, 3/13/15 Due 3/25/15 in class
Page 2/6

Problem 5: DFS Application (20 points).


Let G(V, E) be a directed graph given in adjacency list representation. In addition, each node
v V has as associated value val(v). For each node v dene R(v) to be the set of all nodes that are
reachable from v. For each node v dene MaxVal(v) = max{val(u) : u R(v)}. Assuming G(V, E)
is acyclic, give an O(|V | + |E|) algorithm to compute MaxVal(v), for all v V . Argue correctness
and running time. Hint: Use topological sorting and compute max{val(u) : (v, u) E}.

Problem 1, MST, 20 points


Let G(V, E) be an undirected connected graph with distinct costs on its edges. Let ce be the cost
associated with every e E. Argue that the following is a mincost spanning tree algorithm for G.
Let e1 ,...,em be the edges sorted in decreasing order of cost.
T :=E;
for i:=1 to m
JG5=\FJ^JTDPOOFDUFEUIFO55=\FJ^

Problem 2, MST, 20 points


Let G(V, E) be an undirected connected graph with distinct costs on its edges. Let ce be the cost
associated with every e E. Let T be a spanning tree of G. Argue that the following is a mincost
spanning tree algorithm for G.
while (e T and e E \ T ) such that ( ce < ce and T {e } \ {e}) is a spanning tree of G
T := T {e } \ {e}
Answer:
5IFDPTUTBSFEJTUJODU UIVTUIF.45JTVOJRVF
-FU5hCFUIFVOJRVF.45
-FU5CFUIFTQBOOJOHUSFFBUUIFUFSNJOBUJPOPGUIFBCPWFMPPQ
'PSUIFQVSQPTFTPGDPOUSBEJDUJPO BTTVNFUIBU5h5
4PMFUFhCFBOFEHFPG5hUIBUEPFTOPUCFMPOHUP5
8IFOXFBEEFhUP5XFDSFBUFBVOJRVFDZDMF TBZFh F  FL XIFSFFJ5 







TFFBMTPGJHVSFCFMPX

CVUGPSBMMJJLXFIBWFDFhDFJ PSFMTFUIFMPPQXPVMEIBWFOPUUFSNJOBUFE
8FXJMMEFSJWFBDPOUSBEJDUJPOCZTIPXJOHUIBU GPSTPNFJJL

5 5h=\Fh^\FJ^JTBTQBOOJOHUSFF
#VUUIFODPTU 5 
DPTU 5h
DFh DFJDPTU 5h
XIJDIDPOUSBEJDUTUIFGBDUUIBU5hJTBO.45
5PTFFUIBUGPSTPNFJJL 5 5h=\Fh^\FJ^JTBTQBOOJOHUSFF DPOTJEFSSFNPWJOHFhGSPN5h TFF
BMTPGJHVSFCFMPX
UIVTDSFBUJOHUXPDPOOFDUFEDPNQPOFOUT TBZ5VBOE57=6PWFSWFSUJDFT TBZ 6BOE7=6
/PXDPOTJEFSUIFFEHFTPGUIFDZDMFFh F  FLUIBUDSPTTUIFDVU 6 7=6
5IFFEHFFhDSPTTFTUIFDVU UIVT
UIFSFJTBUMFBTUPOFNPSFFEHFGSPNUIFDZDMFDSPTTJOHUIFDVU UIVTFJDSPTTFTUIFDVUGPSTPNFJJL
#VUUIFOXFDPVMEBEEFJUP5VBOE57=6 UIVTDSFBUJOHBTQBOOJOHUSFF5 5657=6\FJ^5h=\Fh^\FJ^
"OEDPTU 5h
DFh DFJDPTU 5h
UIVTDPOUSBEJDUJOHUIFGBDUUIBU5hJTBO.45

"OTXFS
4JODFUIFHSBQIJTBDZDMJD JUIBTBUMFBTUPOFTJOL4JODFOPWFSUFYJTSFBDIBCMFGSPNBTJOL UIF.BY7BMPG
FWFSZTJOLJTFRVBMUPJUTPSJHJOBMWBMVF/PXTVQQPTFUIBU JOUJNF0 ]7] ]&]
XFEPUPQPMPHJDBMTPSUJOHTP
UIBUBMMFEHFTBSFEJSFDUFEGSPNMFGUUPSJHIU5IFSJHIUNPTUWFSUFYJTBTJOL TPXFNBZTFUJUT.BY7BMUPJUT
PSJHJOBMWBMVF8FXJMMQSPDFFEUPDPNQVUFUIF.BY7BMPGUIFSFNBJOJOHOPEFTQSPDFFEJOHGSPNSJHIUUP
MFGU5IFBMHPSJUINNBJOUBJOTUIFQSPQFSUZUIBUXIFOUIFOPEFJOUIFJUIQPTJUJPOJTBCPVUUPCFDPNQVUFE 
UIF.BY7BMPGBMMOPEFTUPJUTSJHIUJOQPTJUJPOT J 
 OIBWFCFFOBMSFBEZDPNQVUFE5IFSFGPSF 
.BY7BMPGUIFOPEFJOUIFJUIQPTJUJPODBOCFDPNQVUFECZMPPLJOHBUBMMJUTBEKBDFOUFEHFT XIJDIFOEJO
OPEFTJOQPTJUJPOT J 
 O
BOEUBLJOHUIFNBYJNVNPGUIFTFWBMVFT5IJTVQEBUJOHTUFQBMTPUBLFT0 ]
7] ]&]
5IFUPUBMSVOOJOHUJNFJT0 ]7] ]&]


Answer:5IFDPTUTBSFEJTUJODU UIVTUIF.45JTVOJRVF-FU&&BOEMFU&JCFUIFFEHFTUIBUSFNBJOBGUFS
JUFSBUJPOJ8FOFFEUPQSPWFUIBU&NDPOUBJOTBMMFEHFTPGUIF.45 BOEUIBU&NEPFTOPUDPOUBJOBOZFEHFUIBUJT
OPUJOUIF.45'PSUIJT JUTVGGJDFTUPQSPWFUIFGPMMPXJOH
.BJO'BDUFJJTOPUSFNPWFEBUJUFSBUJPOJ UIVTFJ&J JGBOEPOMZJGFJJTBOFEHFPGUIF.45 
*GFJJTOPU
SFNPWFEJOJUFSBUJPOJUIFOFJJTBOFEHFPGUIF.45
1300'8FVTFUIFGBDUUIBUUIFDIFBQFTUFEHFPGFWFSZDVUCFMPOHTUPUIF.458FUIFSFGPSFOFFEUPJEFOUJGZBDVU
6BOE7=6TVDIUIBUFJJTUIFDIFBQFTUFEHFBDSPTTUIJTDVU"UUIFQPJOUXIFOFJJTFYBNJOFE BMMFEHFTUIBUIBWF
CFFOSFNPWFEBSFNPSFFYQFOTJWFUIBOFJ5IVT XIFOXFSFNPWFFJBOEUIJTEJTDPOOFDUTUIFSFNBJOJOHHSBQIUPV
BOE7=6 FJJTUIFDIFBQFTUFEHFBDSPTTUIJTDVU TJODFBMMPUIFSFEHFTPGUIFPSJHJOBMHSBQIUIBUDSPTTUIJTDVUBOE
IBWFBMSFBEZCFFOSFNPWFEBSFNPSFFYQFOTJWF

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 6, 2/27/15 Due 3/6/15 in class
Page 6/6
Problem 6: (20 points).
Let G(V, E) be a directed graph in adjacency matrix representation. We say that a vertex v is a
supersink if and only if there is an edge (u, v) for every vertex u = v, and there is no edge (v, u).
Give an O(|V |) running time algorithm that decides if a graph given in its adjacency matrix representation has a supersink. (Note that the running time does not even look at all the entries of
the |V | |V | adjacency matrix representation of the graph.) Argue correctness and running time.
Hint: Suppose that a21 = 1, a31 = 1, a41 = 1, but a51 = 0. What can you infer about nodes 1, 2,
3, 4 and 5?
"OTXFS

5IFBMHPSJUINXJMMCFLFFQJOHBTJOHMFWFSUFYJBTBDBOEJEBUFGPSTVQFSTJOL

*OJUJBMMZJ8FBSFFYBNJOJOHFOUSJFTBLWFSJGZJOHUIBUUIFDPSSFTQPOEJOHFEHFTBSFQSFTFOU
8IFOUIFFEHFBLJTQSFTFOU UIJTLFFQTBTBTVQFSTJOLDBOEJEBUF BOEBMTPFYDMVEFTWFSUFYLBTFWFSCFJOH
BTVQFSTJOLDBOEJEBUF*GBMMFEHFTBL LO BSFQSFTFOU UIFBMHPSJUINGJOJTIFTBOEJTTVQFSTJOL

*GIPXFWFSGPSTPNFKXFGJOEBLJTBCTFOU UIFOXFFYDMVEFGSPNCFJOHBTVQFSTJOLDBOEJEBUF
"UUIJTQPJOU BMMWFSUJDFT    L
IBWFCFFOFYDMVEFEGSPNCFJOHTVQFSTJOLDBOEJEBUFT8FNBZUIVT
QSPDFFEXJUILBTBTVQFSTJOLDBOEJEBUF BOEXJUIDIFDLJOHUIFTVCNBUSJYBJKXIFSFLJ KO

5IFBCPWFTUBHFUBLFT0 ]7]


*GBUUIFFOETPNFWFSUFYYIBTTVSWJWFEBTBTVQFSTJOLDBOEJEBUF UIFOXFIBWFUPWFSJGZUIBUBJY
GPSBMMJY BOEUIBUBYKGPSBMMK5IJTBMTPUBLFT0 ]7]



*GFJJTSFNPWFEJOJUFSBUJPOJUIFOFJJTOPUBOFEHFPGUIF.45
1300'8FBSHVFUIBUUIFBMHPSJUINFOETXJUIBTQBOOJOHUSFF4JODFJOQBSU B
XFBSHVFEUIBUBMMLFQUFEHFT
CFMPOHFEUPUIF.45 BMMSFNPWFEFEHFTEJEOPUCFMPOHUPUIF.45
8IZEPFTUIJTBMHPSJUINFOEXJUIBTQBOOJOHUSFF $MFBSMZUIFHSBQIFOETXJUIBDPOOFDUFEDPNQPOFOUUIBUTQBOT
UIFHSBQI5PTFFUIBUUIJTDPNQPOFOUEPFTOPUDPOUBJOBDZDMF TVQQPTF GPSDPOUSBEJDUJPO UIBUUIFBMHPSJUINFOET
XJUIBDPOOFDUFEHSBQIUIBUDPOUBJOTBDZDMF XJUIFEHFTTBZFJ F  FJL XIFSFJJJL5IVTFJLJTUIFNPTU
FYQFOTJWFFEHFPGUIFBCPWFDZDMF BOEUIFGJSTUFEHFFYBNJOFECZUIFBMHPSJUIN#VUUIFO CFDBVTFPGUIFFYJTUFODF
PGUIFBCPWFDZDMF XIFOFJLXBTFYBNJOFECZUIFBMHPSJUINFJLXBTOPUEJTDPOOFDUJOHUIFHSBQI4PFJLTIPVMEIBWF
CFFOSFNPWFE XIJDIDPOUSBEJDUTUIFGBDUUIBUBDZDMFFYJTUT5IVT UIFBMHPSJUINFOETXJUIBTQBOOJOHUSFF

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 7, 3/13/15 Due 3/25/15 in class
Page 3/6

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 7, 3/13/15 Due 3/25/15 in class
Page 4/6

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 7, 3/13/15 Due 3/25/15 in class
Page 5/6

Problem 3, Bottleneck Spanning Tree, 20 points


The bottleneck spanning tree of G is a spanning tree of G whose largest cost edge is minimum over
all spanning trees of G. We say that the value of a bottleneck spanning tree is the cost of the
largest cost edge.
(a) Argue that the mincost spanning tree of G is also a bottleneck spanning tree of G.
(b) Give an O(|V|+|E|) algorithm that, given an integer b, decides if the value of a bottleneck
spanning tree is at most b.
Answer:
B
8FBSHVFCZDPOUSBEJDUJPO4VQQPTFUIBU5.45JTUIFNJODPTUTQBOOJOHUSFF CVUJUJTOPUBCPUUMFOFDL
TQBOOJOHUSFF5IBUNFBOTUIBUUIFSFJTBTQBOOJOHUSFF5CPUUMFXIPTFNBYJNVNDPTUFEHF TBZF JTNPSF
FYQFOTJWFUIBOFWFSZFEHFPG5CPUUMF
8FXJMMTIPXUIBUXFDBODPOTUSVDUBUSFF5hXIPTFDPTUJTTNBMMFSUIBOUIFDPTUPG5.45
*OQBSUJDVMBS MFUVTBEEFUP5CPUUMF UIVTDSFBUJOHBDZDMFF F FL
4JODFFJTNPSFFYQFOTJWFUIBOFWFSZFEHFPG5CPUUMF FJTNPSFFYQFOTJWFUIBOFWFSZFJ JL
/FYU SFNPWFFGSPN5.45 UIVTDSFBUJOHUXPDPOOFDUFEDPNQPOFOUT TBZ56BOE57=6PWFSWFSUJDFT TBZ 6
BOE7=6/PXDPOTJEFSUIFFEHFTPGUIFDZDMFF F FLUIBUDSPTTUIFDVU 6 7=6
5IFFEHFFDSPTTFTUIFDVU 
UIVTUIFSFJTBUMFBTUPOFNPSFFEHFGSPNUIFDZDMFDSPTTJOHUIFDVU UIVTFJ DSPTTFTUIFDVU GPSTPNF
JJL#VUUIFOXFDPVMEBEEFJUP56BOE57=6 UIVTDSFBUJOHBTQBOOJOHUSFF5h5657=6\FJ^
5.45=\F^\FJ^"OEDPTU 5h
DPTU 5.45
Fh DFJDPTU 5.45
UIVTDPOUSBEJDUJOHUIFGBDUUIBU5.45JTBO
.45

Problem 4, Dijkstra, 20 points


Let G(V, E) be a directed graph G(V, E) with costs on its edges and let s V be a source vertex. In
general, Dijkstras algorithm nds shortest paths out of s when all the edge costs are non-negative.
(a) Give a counter-example of a graph with an edge of negative cost where Dijkstras algorithm
fails.
(b) Argue that Dijkstras algorithm works if the cost of some of the edges leaving s have negative
costs, and all other edges have non-negative costs.
Answer:

Problem 5, Review Question, Dynamic Programming, 10 points


Let G(V, E), |V | = n, be an acyclic directed graph. Give an O(|V | + |E|) algorithmm that determines if there is a path of length (n 1) in G.
Answer:

B
(SBQIXJUITPVSDFWFSUFYT BOEUXPBEEJUJPOBMWFSUJDFTVBOEW&EHFTWXJUIDPTU FEHFTV
XJUIDPTU BOEFEHFVWXJUIDPTU%JKLTUSBGJSTUFTUJNBUFTEJTUBODFTE W
BOEE V
5IFO
%JKLTUSBGJOETUIBUTWJTUIFTIPSUFTUQBUIGSPNTUPWBOEJUIBTDPTU"GUFSUIJTQPJOUE W
JTOFWFS
BHBJOVQEBUFE5IFO%JKLTUSBGJOETUIBUTVJTUIFTIPSUFTUQBUIGSPNTUPVBOEJUIBTDPTU5IF
BMHPSJUINUFSNJOBUFT XJUIPVUEJTDPWFSJOHUIFQBUITWVUIBUIBTDPTU

C
3FDBMMUIFGPSNPG%JKLTUSB

C
8FTDBOUIFFEHFTPODF BOELFFQUIFFEHFTXIPTFDPTUJTBUNPTUC5IJTUBLFT0 ]7] ]&]
-FU&CCFUIF
TFUPGFEHFTUIBUIBWFDPTUBUNPTUC6TJOH%'4XIJDIUBLFTUJNF0 ]7] ]&]
XFDIFDLJGUIFHSBQI
( 7 &C
JTDPOOFDUFE*G:&4 UIFOUIFSFJTBTQBOOJOHUSFFXIPTFNPTUFYQFOTJWFFEHFIBTDPTUBUNPTUC 
UIVTUIFWBMVFPGUIFCPUUMFOFDLTQBOOJOHUSFFJTBUNPTUC*G/0 UIFOUIFSFJTOPTQBOOJOHUSFFBMMPG
XIPTFFEHFTIBWFDPTUBUNPTUC UIVTFWFSZTQBOOJOHUSFFIBTBUMFBTUPOFFEHFXIPTFDPTUJTNPSFUIBOC 
UIVTUIFWBMVFPGUIFCPUUMFOFDLTQBOOJOHUSFFJTTUSJDUMZHSFBUFSUIBOC

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 8, 3/27/15 Due 4/03/15 in class
Page 1/5
Problem1,ISPCLIQUE,20points
RecallthatIS(IndependetSet)isthefollowingproblem.OninputanundirectedgraphG(V,E)andaninteger
kwith1k|V|,doesGhaveanindependentsetcontainingatleastkvertices?NextwedenetheCLIQUE
problem.WhereG(V,E)isanundirectedgraph,wesaythatasubsetofitsnodesCVisacliqueifanonlyif
betweeneverypairofvericesinCthereisanedge(ofE).Thesizeofthecliqueis|C|.Now,theCLIQUEisthe
followingproblem.OninputanundirectedgraphG(V,E)andanintegerkwith1k|V|,doesGhavea
CLIQUEofsizeatleastk?ShowthatISPCLIQUE.
Answer:Wehavetoshowthat,ifthereisapolytimealgorithmforCLIQUE,thenthereisapolytime
algorithmsforIS.ThereductionwillbebasedonthefactbelowthatrelatesthestructureofGwiththe
structureofitscomplement.Inparticular,thecomplementofG(V,E)isthegraphG(V,E)whichhasthe
samesetofverticesasG,and{u,v}Eifandonlyif{u,v}E.Thatis,if{u,v}isnotanedgeinEthen{u,
v}isanedgeinE,andif{u,v}isanedgeinEthen{u,v}isnotanedgeinE.
Fact:LetG(V,E)beanundirectedgraphandletG(V,E)bethecomplementofG.LetXVbeasubsetof
thevertices.ThenXisanindependentsetinGifandonlyifXisacliqueinG.Proof.Followsimmediately
fromthedenitionofindependentset,clique,andcomplementgraph.
Thereductionfrom(IS)to(CLIQUE)isnowobvious.Foraninstanceof(IS)wheretheinputisagraphG(V,
E) and an integer k (and the question is if G has an independent set of size at least k) we constrcut the
complementgraphG(V,E)whichhasthesamesetofverticesasG,and{u,v}E ifandonlyif{u,v}E.
WenowaskifG(V,E)hasaCLIQUEofsizeatleastk.Inparticular,ifG(V,E)hasaCLIQUEofsizeat
leastk,thenGhasanISofsizeatleastk.IfG(V,E)doesnothaveaCLIQUEofsizeatleastk,thenGdoes
nothaveanISofsizeatleastk.
Last Name: ............................. First Name: .............................. Email: ..............................
CS 3510 A, Spring 2015, Homework 8, 3/27/15 Due 4/03/15 in class
Page 2/5
Problem 2, Hamilton Cycles and Hamilton Paths, 20 points
RecallthataHamiltonCycleinadirectedgraphG(V,E)isacyclethatusesedgesinEandgoesthrougheach
vertexinVexactlyonce.Recallthat,intheDirectedHamiltonCycleproblemHC(Dir),oninputadirected
graphG(V,E)wewanttoknowifGhasaHamiltonCycle.Inlectureweshowedthat3SATPHC(Dir).
Now,foradirectedgraphG(V,E),aHamiltonPathisasimplepaththatusesedgesinEandvisitseachvertex
inVexactlyonce.TheDirectedHamiltonPathproblemHP(Dir)isdenedasfollows.Oninputadirected
graphG(V,E),doesGhaveaHamiltonPath?
Showthat3SATPHP(Dir).
Answer:Weusetheexactsamegraphconstructionfromthereduction3SATPHC(Dir),exceptwedonot
connecttheterminalvertextbackwiththesourcevertexs.
Last Name: ............................. First Name: .............................. Email: ..............................
CS 3510 A, Spring 2015, Homework 8, 3/27/15 Due 4/03/15 in class
Page 3/5
Problem 3, Hamiltonicity: Directed and Undirected, 20 points
Recall that a Hamilton Cycle in a directed graph G(V,E) is a cycle that uses edges in E andgoes
through each vertex in V exactly once. Recall that, in the Directed Hamilton Cycle problemHC(Dir), on
input a directed graph G(V,E) we want to know if G has a Hamilton Cycle.
AHamiltonCycleinanundirectedgraphG(V,E)isacyclethatusesedgesinE andgoesthrougheach
vertex in V exactly once. In the Hamilton Cycle problem HC, on input an undirected graphG(V,E) we
want to know if G has a Hamilton Cycle.
ShowthatHC(Dir)PHC.
Answer:
We need to show that if we can decide HC in polynomial time, then we can decide HD(Dir) in
polynomial time.
LetG(V,E)beadirectedgraphforwhichwewanttodecideifithasaHamiltoncycle.Wecon-structan
undirectedgraphG(V,E)asfollows.
ForeveryvertexvVweintroducethreeverticesvin,vo,andvoutinV.
ForeveryvertexvoVweintroducetwoedges:{vin,vo}Eand{vo,vout}E.
Foreveryedge(u,v)Eweintroduceedge{uout,vin}E.
ItisnowobviousthatG(V,E)hadaHamiltoncycleifandonlyifG(V,E)hasaHamiltoncycle.

5IFNBJOJOWBSJBODFJTUIBU XIFOBWFSUFYWFOUFSTUIFTFU4 UIFOE W


JTUIFDPTUPGUIFDIFBQFTUQBUIGSPN
TUPWBOE W
JTUIFMBTUTUFQPGUIFTIPSUFTUQBUIGSPNTUPW5IJTJOWBSJBODFJTNBJOUBJOFEXIFOTPNFPG
UIFFEHFTPVUPGTIBWFOFHBUJWFDPTU

( 7 &
JTBEJSFDUFEBDZDMJDHSBQI5IVT JO0 ]7] ]&]
XFDBOGJOEBUPQPMPHJDBMTPSUJOHPG(-FUW W  WO
CFUIFWFSUJDFTJOUPQPMPHJDBMMZTPSUFEPSEFS UIVTBMMFEHFTHPGSPNMPXFSOVNCFSFEWFSUJDFTUPIJHIFS
OVNCFSFEWFSUJDFT5IVT UIFSFJTBQBUIPGMFOHUI O
JGBOEPOMZJGUIFSFJTBQBUIPGMFOHUI O

TUBSUJOHFOEJOH<TJD>BUWO8FDPVMEVTFEZOBNJDQSPHSBNNJOHUPGJOEUIFMFOHUIPGUIFMPOHFTUQBUI
TUBSUJOHJOWBOEFOEJOHJOWO BTJO2VJ[
#VUJOUIJTDBTF XFBSFMPPLJOHGPSBQBUIPGMFOHUI O

BOEUIBUDBOPOMZCFUIFQBUIWWWOWO8FDBOUIVTPOMZDIFDLJGWJWJ JTBOFEHFJO& 
GPSBMMJ O

Last Name: ............................. First Name: .............................. Email: ..............................
CS 3510 A, Spring 2015, Homework 7, 3/13/15 Due 3/25/15 in class
Page 6/6
Problem 6, Review Question, Strong Majority, 10 points
Let a(1), a(2), . . . , a(n) be an array of n integers. We say that an integer x is a strong majority
element if and only if |{i : a(i) = x}| > n2 . Argue that the linear algorithm below correctly decides
if the input array has a strong majority element.
Count:=0;
for i := 1 to n
if (Count= 0) then Candidate := a(i);
if (a(i) = Candidate) then (Count := Count + 1) else (Count := Count 1);
m := 0;
if (Count > 0) then for i := 1 to n
if (a(i) = Candidate) then m := m + 1;
if m > n2 then return(Candidate) else return(Nil)
Answer:
-FU$06/5 J
CFUIFWBMVFPG$06/5BGUFSUIFFYFDVUJPOPGUIFJUIJUFSBUJPO BOE$06/5 

-FU$"/%*%"5& J
CFUIFWBMVFPG$"/%*%"5&BGUFSUIFFYFDVUJPOPGUIFJUIJUFSBUJPO
3FBMJ[FUIBU$"/%*%"5&DIBOHFTWBMVFPOMZBGUFS$06/5IBTCFDPNF[FSPJOUIFQSFWJPVTTUFQ
JF  $"/%*%"5& J 
$"/%*%"5& J
 $06/5 J


$BTF*G$06/5 J
GPSBMMJO UIFO BUUIFFOEPGUIFBMHPSJUIN $"/%*%"5&B 
BOEB 
JT
TUSPOHNBKPSJUZ XIJDIXJMMCFWFSJGJFEJOUIFMBTUUFTU
$BTF-FUJJJLCFUIFJUFSBUJPOTBUUIFFOEPGXIJDI$06/5 JK
 KL
$"/%*%"5& J
B 
JTUIFWBMVFPGFYBDUMZIBMGPGUIFFMFNFOUT\B 
B 
 B J
^
4JNJMBSMZ $"/%*%"5& JK
B JK 
JTUIFWBMVFPGFYBDUMZIBMGPGUIFFMFNFOUT



\B JK 
B JK 
 B JK
^ KL
$BTFB*GJLO UIFOUIFSFJTOPTUSPOHNBKPSJUZFMFNFOUJOBOZPGUIFTVCBSSBZT B 
B J


B J 
B 

  B JL 
BLBO
UIFOUIFSFJTOPTUSPOHNBKPSJUZFMFNFOUJOUIFFOUJSFBSSBZ 
BOE$06/5DPSSFDUMZGJOJTIFTXJUIUIFWBMVF
$BTFC*GJLO UIFOUIFSFJTOPTUSPOHNBKPSJUZFMFNFOUJOBOZPGUIFTVCBSSBZT B 
B J


B J 
B 

  B JL 
BL
5IVT UIFSFJTOPTUSPOHNBKPSJUZFMFNFOUJOUIFTVCBSSBZ
B 
B JL

*G IPXFWFS UIFFOUJSFBSSBZ B 


B O

IBTBTUSPOHNBKPSJUZFMFNFOU UIFOUIJTNVTU
OFDFTTBSJMZNBOJGFTUJUTFMGJOUIFTVCBSSBZ B JL 
BO
5IFSFGPSF JGUIFFOUJSFBSSBZIBTBTUSPOH
NBKPSJUZFMFNFOU UIFOUIJTWBMVFXJMMOFDFTTBSJMZCFUIFGJOBMWBMVFPG$"/%*%"5&5IJTXJMMCFWFSJGJFEJO
UIFMBTUWFSJGJDBUJPOTUFQ /PUFUIBUUIFMBTUWFSJGJDBUJPOTUFQJTOFDFTTBSZ CFDBVTFBOFMFNFOUUIBU
NBOJGFTUTBT$"/%*%"5&GSPNUIFMBTUQBSUPGUIFBSSBZ B JL 
BO
JTOPUOFDFTTBSJMZBTUSPOHNBKPSJUZ
FMFNFOUPGUIFFOUJSFBSSBZ$PVOUFSFYBNQMF           UIFGJOBM$"/%*%"5&JT CVUUIJTJT
OPUBTUSPOHNBKPSJUZFMFNFOUPGUIFFOUJSFBSSBZ

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 8, 3/27/15 Due 4/03/15 in class
Page 4/5

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 9, 4/8/15 Due 4/15/15 in class
Page 1/5

Problem 4, Hardness of Long Paths, 20 points


The Long Path Problem (LongP) is dened as follows. On input an undirected, unweighted graph
G(V, E), does G have a simple path of legth at least |V2 |
?
Show that HPP LongP.
Answer:
Let G(V, E) be a graph for which we wan to decide if it has a path of length (|V | 1).
We constrcut a graph G (V  , E  ) as follows.
Let X be a new set of |X| = x isolated vertices (ie, every vertex in X will never be connected to
any other vertex.) Set V  = V X and set E  = E.
Clearly, if l is the length of the longest path in G then l is also the length of the longest path in G .
We therefore need x to satisfy:
|V |+x
l < (|V | 1) l < |V |+x
2
(1) and l (|V | 1) l 2
(2).
For (1) we have: if l < (|V | 1) then the maximum value of l is (|V | 2)
and (1) becomes (|V | 2) < |V |+x
2
.
For (2) we have: if l (|V | 1) then the minimum value of l is (|V | 1)
and (2) becomes (|V | 1) |V |+x
2
.
(1) and (2) combined imply (|V | 2) < |V |+x
2
(|V | 1)

=
(|V
|

1).
which implies |V |+x
2
We may now set x = |V |2 and realize that for this value of x we have, indeed, |V |+x
2
= (|V |1).

Problem 1, VCp Set Cover, 20 points


Recall the unweighted Set Cover problem. X = {e1 , e2 , . . . , en } is a ground set of n elements.
F = {S1 , S2 , . . . , Sm } is a collection of subsets of X, ie Sj X, for 1 j m. A set cover C is a
subset of F such that every element of X belongs to a set in C. Given k, such that 1 k m, we
want to know if there exists a set cover that has at most k sets.
Recall the unweighted Vertex Cover (VC) problem. G(V, E) is an undirected graph. A vertex cover
CV is a subset of V such that every edge in E has at least one of its endpoints in CV . Given k,
such that 1 k |V |, we want to know if there exists a vertex cover that has at most k vertices.
Show that VCP Set-Cover.
Answer:
Let G(V, E) be an undirected graph and let k be an integer, with 1 k |V |.
We construct an instance of set cover (X, F, k  ) as follows:
For every edge ei E we have a point ei X.
For every vertex v V we have a set Sv F which contains all points ei X corresponding to
edges ei E that are incident to v.
We may now set k  = k, and observe that G(V, E) has a vertex cover of size at most k if and only
if (X, F, k) has a set cover of size at most k.

Therefore, if we want to decide if G(V, E) has a Hamilton path, we construct G (V  , E  ), where


V  = V X with |X| = (|V | 2), and E  = E. Thus the number of vertices of G is |V  | = 2|V | 2,
and the length of the longest path in G is the same as the length of the lonest path in G. Thus,
G has a path of length (|V | 1) if and only if G has a path of length |V  |/2.
Last Name: ............................. First Name: .............................. Email: ..............................
CS 3510 A, Spring 2015, Homework 8, 3/27/15 Due 4/03/15 in class
Page 5/5
Problem 5, Euler Cycles, 20 points
Let G(V, E) be a directed strongly connected graph. An Euler Cycle of G is a sequence of consecutive edges of E that (a)starts and nishes on the same vertex and (b)every edge of the graph
appears in the sequence exactly once.
(a) Prove that G is Eulerial (ie G has an Euler Cycle) if and only if every vertex v V has the
same number of incoming and outgoing edges.
(b) Give an ecient time algorithm that, on input an Eulerian directed graph G(V, E) nds an
Euler Cycle. Justify correctness and running time.
Answer:
(a) Clearly, if there exists a single vertex where the out degree is dierent than the in degree, the
graph cannot have an Euler Cycle. For the other direction, namely that if for every vertex, the
in degree is equal to the out degree, then the graph has an Euler Cycle, we give a DFS based
algorithm in part (b).
(b) Since the graph is strongly connected, DFS starting fro any vertex results in a single tree on
all V vertices. Starting from a vertex v0 V , we construct such a tree T rooted at v0 . That is,
all edges of T are directed from the leaves to the root v0 , and every vertex v = v0 has a unique
outgoing edge in the tree T . We may now construct an Euler Cycle by strating at v0 and, when we
are at any vertex v, we choose the next vertex u as follows:
If there exists an edge v u that is untraversed and does not belong to T , then the next vertex is
u. Otherwise, if the only untraversed vertex v u belongs to T , then the next vertex is u.
The running time to construct T in O(E + V ). The rest of the execution is just a scanning through
the edges which is O(E).

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 9, 4/8/15 Due 4/15/15 in class
Page 2/5
Problem 2, Weigheted Set Cover, 20 points
The weighted set cover problem is as follows. X = {e1 , e2 , . . . , en } is a ground set of n elements.
F = {S1 , S2 , . . . , Sm } is a collection of subsets of X, ie Sj X, for 1 j m. Each set Sj has a
positive cost cost(Sj ), for 1 j m. A set cover C is a subset of F such that every element of X

belongs to a set in C. The cost of a set cover C is cost(C) = SC cost(S). Let OPT be the cost of
a set cover whose cost in minimized oved all possible set covers. Give a polynomial time algorithm
that nds a set cover C such that cost(C) Hn OPT. Justify correctness of the approximation
bound.
Hint: Straightforward extension of unweighted set cover algorithm given in lecture.
Answer:
APPROX-SET-COVER
initialization: U := X; (all elements are uncovered)
C := ; (no set has been added to the set cover)
while U = (while there exist uncovered elements)
|U S|
;
for every set S F \ C dene eectiveness(S) = cost(S)
(the eectiveness of an unpicked set S for the current iteration
is the number of uncovered elements that belong to S divided by the cost of the set )
pick S F \ C that minimizes eectiveness(S);
for all elements that belong to U S set price(e) := cost(S)
|U S| ;
for all elements that belong to U S set f irst(e) := S;
C := C {S}; (add S to the set cover)
U := U \ S; (elements that belong to S are no longer uncovered)
return(C);
Theorem: cost(C) Hn OPT.
Proof of Theorem. Let COPT be a set cover with cost(COPT ) = OPT. We combine Facts 1 and
2 (stated in the next page) and get:
Hn OP T

= Hn

Fact 1: cost(C) =
Proof of Fact 1.
cost(C) =

eS

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 9, 4/8/15 Due 4/15/15 in class
Page 3/5

price(e).

cost(S)

SC

SC

eX
f irst(e) = S

price(e)

price(e) .

eX

Fact 2: If COPT is a set cover with cost(COPT ) = OPT and S COPT



then eS price(e) Hn cost(S).
Proof of Fact 2.

Let e1 , e2 , . . . , ek be the elements of S in the order in which they were covered when sets were
added to C by the APPROX-SET-COVER algorithm. Now |S | = k n and realize that:
)
)
= cost(S
, since e1 was the rst element of S that was covered, hence, at that
price(e1 ) cost(S
k
|S |

point S itself could have covered it with eectiveness


cost(S )
|S |1
S itself

price(e2 )
that point

cost(S )
k1 ,

price(ek )

k(k1)

SCOPT

cost(S )
1

all i k, and nally

The above combined imply




price(e) =

k


|ECROSS | |EIN |

price(ei )

We alse have

i=1

cost(S)

|E| = |ECROSS | + |EIN |

k

cost(S )
i=1

Hn cost(S)
price(e)

cost(S )
|S |(i1)

eS

|S |1
cost(S ) .
cost(S )
k(i1) , for

could have covered it with eectiveness at least

Continuing this arguing, we see that price(ei )


cost(S )

|S |
cost(S ) .

since e2 was the second element of S that was covered, hence, at

SCOPT

notice that the price of each element e appears


exactly once in this double summation,
namely with the set S = f irst(e)

k (i 1)

= cost(S )
, by Fact 2 below

Thus

|E|
|ECROSS |
2
Finally, since the maximum cut may, in the best case, involve all edges in E (but, clearly, no more)

k

cost(S )
i=1

k (i 1)

1
1
1
+
+ ... + + 1
k k1
2

1
1
1
= cost(S ) 1 + + . . . +
+
2
k1 k


1
1
1
+
cost(S ) 1 + + . . . +
2
n1 n
= cost(S )Hn

= cost(S )

SCOPT eS

because the price of each element e


may appear more than once

price(e)
eX
in the double summation above
= cost(C) , byF act1below.

Problem 3, MAX CUT, Factor 2 Approximation, 20 points


Let G(V, E) be an undirected, unweighted graph. A cut is a partition of V to S V and V \ S.
The size of the cut is the number of edges that have one endpoint in S and the other endpoint in
V \ S. Let OPT be the size of a cut whose size is maximized over all cuts. Cosider the following
greedy algorithm that tries to construct a cut of large size:
Initially A := ; B := ;
Initially all vertices in v V are undecided;
Initially, for some {u, v} E add v to A and u to B,
A := A {v} and B := B {u}, and mark u and v decided;
while undecided vertices
let u be an undecided vertex;
let dA (u) := |{v A : {u, v} E}| and dB (u) := |{v B : {u, v} E}|;
if dA (u) dB (u) then B := B {u} else A := A {u};
mark u decided;
output ( S := A; V \ S := B ) ;
Argue that this is a factor 1/2 approximation algorithm.
That is, argue that |{{u, v} E : u A, v B}| OPT
2 .
Hint: Argue that |{{u, v} E : u A, v B}| |E|
2 .
Answer:
Let ECROSS = {{u, v} E : u A and v B}.
Let EIN = {{u, v} E : either (u A and v A) or (u B and v B)}.
For the rst edge, the algorithm places its endpoints in dierent sets, so the rst edge belongs to
ECROSS . When a new vertex comes it is placed in one of A or B so that it introduces at least as
many edges in ECROSS than in EIN . Thus, at the end of the algorithm, we have

OPT |E|

The last two bounds combined give us


|ECROSS |

|E|
OPT

2
2

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Homework 9, 4/8/15 Due 4/15/15 in class
Page 5/5

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 1, 2/6/15
Page 1/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 1, 2/6/15
Page 2/4

Problem 5 Independent Set, Special Case in Polynomial Time, 20 points


Let G(V, E) be an undirected, unweighted graph that is a tree. That is, G is connected and has no
cycles. Give a polynomial time algorithm that nds a maximum cardinality independent set for G.
Justify your answer.
Answer:
Fact 1: If the graph consists of a single edge, then the maximum cardinality independent set consists of exactly one of the endpoits (either one.)
Fact 2: If the graph has a non leaf v connected to a leaves u1 , u2 , . . . , uk , then there is a maximum
independent set that does not contain v and contains all of u1 , u2 , . . . , uk .
Proof: It is obvious that a maximum independent set must contain either v or the entire set
u1 , u2 , . . . , uk . If the maximum independent set contains v, then k = 1 (or else removing v and
adding u1 , u2 , . . . , uk would result in an independent set of larger size.) But then, we can remove v
from the maximum independent set, add the leaf v1 , and the size of the independent set does not
change, thus we still have a maximum independent set.

Problem 1: 30 points.
Consider the function Mystery dened below.
Mystery(n)
if n > 1 then begin
print(x);
Mystery(n 1);
Mystery(n 1);
Mystery(n 1);
end
If we call Mystery(n), where n is an integer n > 1, how many xs (as a function of n) does
call Mystery(n) print? Justify your answer/show your work (ie give recurrence and solve by
substitution.)
Answer:
(10 points for writing correct recursion and base case, 20 points for correct solution to recursion.)
We have to solve T (n) = 3T (n 1) + 1 with T (2) = 1. We will solve it by substitution:

Problem 2: 30 points.
Consider the function Mystery dened below.
Mystery(n)
if n > 1 then begin
print(x);
Mystery( n2 );
Mystery( n2 );
Mystery( n2 );
Mystery( n2 );
end
If we call Mystery(n), where n is an integer n > 2 and n is a power of 2, how many xs, as a
polynomial function of n, does call Mystery(n) print? Justify your answer/show your work (ie give
recurrence and solve by substitution.)
Answer:
(10 points for writing correct recursion and base case, 20 points for correct solution to recursion.)
We have to solve T (n) = 4T ( n2 ) + 1 with T (4) = T (22 ) = 5 (since 4 = 22 is the smallest integer for
which we may call Mystery. We will solve it by substitution:

MAX-IND-SET-for-TREE G(V, E)
IS := ;
while exists node u with a single neighbor v; (a leaf)
let u1 , u2 , . . . , uk be all the leafs incident to v;
IS := IS {u1 , u2 , . . . , uk };
remove {u1 , v}, {u2 , v}, . . ., {uk , v} from E;
if v is connected to other vertices x1 , . . . , xk that are non leaves then
remove {v, x1 }, . . ., {v, xk } from E;
if we ar left with a set of isolated vertices Y , then add them all to the ind set IS := IS Y ;

T (n)

3T (n 1) + 1

3(3T (n 2) + 1) + 1

32 T (n 2) + 3 + 1

3 (3T (n 3) + 1) + 3 + 1

33 T (n 3) + 32 + 3 + 1

T (n)

3k T (n k) + (3k1 + . . . + 32 + 3 + 1)
3k 1
3k 1
=
3k T (n k) +
= 3k T (n k) +
31
2
stop when n k = 2 k = n 2
3n2 1
n2
=
3
T (2) +
2
3n2 1
=
3n2 +
2


=
2 3n2 + 3n2 + 1 /2
=

=
=





3 3n2 1 /2
n1

1 /2


So T (n) = 3n1 1 /2 (which is also consistent with 2 = T (2) = 321 1 /2 = 2.)

n
4T ( ) + 1
 2

n
4 4T ( 2 ) + 1 + 1
2
n
42 T ( 2 ) + 4 + 1
2


n
)+1 +4+1
23
n
=
4 T ( 3 ) + 42 + 4 + 1
2
n
=
4k T ( k ) + 4k1 + . . . + 42 + 4 + 1
2
n
4k 1
=
4k T ( k ) +
2
41
n
4k 1
=
4k T ( k ) +
2
3
n
n
stop when
= 22 2 = 2k k = log2 n 2
2k
2
4log2 n2 1
=
4log2 n2 T (4) +
3

log
n
354 2
4log2 n
=
+
1 /3
42
42
=

42 T (
3

=
=

16 4log2 n
1 /3
42


4log2 n 1 /3 = 22 log2 n 1 /3 = n2 1 /3 .





So T (n) = n2 1 /3 (which is also consistent with 5 = T (4) = 42 1 /3 = 5.)

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 1, 2/6/15
Page 3/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 1, 2/6/15
Page 4/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 2, Sample
Page 1/4

Problem 3: 30 points.
Suppose that you are given an array A with n distinct unsorted integer entries, where n = 2m for
some integer m 1. Let S(1) be the set containing the smallest n/2 elements of A.
For example, if n = 16 = 24 and the array A is (100, 40, 120, 20, 50, 30, 85, 80, 150, 200, 60, 70, 2, 3, 101, 102),
then S(1) = {40, 20, 50, 30, 60, 70, 2, 3}.
In general, for positive integer k with 1 k m, let S(k) be the set containing the smallest n/2k
elements of A.
For example, if n = 16 = 24 and the array A is (100, 40, 120, 20, 50, 30, 85, 80, 150, 200, 60, 70, 2, 3, 101, 102),
S(1) = {40, 20, 50, 30, 60, 70, 2, 3}, S(2) = {20, 30, 2, 3}, S(3) = {2, 3} and S(4) = {2}.
(a, 10 points) Argue that for any integer m 1, if n = 2m , then on input an array A of n distinct
unsorted integers, the elements of S(1) can be identied using O(n) comparisons.
(b, 20 points) Argue that for any integer m 1, if n = 2m , then on input an array A of n distinct
unsorted integers, the elements of all the sets S(k), for all 1 k m, can be identied and listed
using O(n) comparisons.
Answer:
Main Fact: There is a constant c such that KSelect with input any array X which has N elements
looking for the K-th element, 1 K N runs using at most cN comparisons. Stressing here that
c is independent on N .
Corollary: There is a constant c such that on input any arrayX which has N elements can nd
the N/2 smallest elements of A using at most (c + 1)N comparisons. To see this, use at most cN
comparisons to nd the middle element, and use an additional scanning of X to nd all elements
that are smaller than the middle element.
(a) It follows from the above Corollary that we can nd S(1) using at most (c + 1)n comparisons.
(b) We may now recurse on S(1) and nd S(2) using at most (c + 1)n/2, and so on, recurse on
S(k) to nd S(k + 1) using at most (c + 1)n/2k comparisons. We may thus nd all of the sets S(k),
for all 1 k m = log2 n, with number of comparisons bounded by:

Problem 4: 10 points.
Let S1 , . . . , Sn be an array of n distinct integers, where n > 2 is a positive even integer.
The pseudocode below rst updates two arrays A1 , . . . , A n2 and B1 , . . . , B n2 .
Then, a variable Alice is updated using the array A,
and a variable Bob is updated using array B.
Characterize the values that variables Alice and Bob have, at the end of the execution of the
pseudocode. Give a short justication of your answer.

Problem 1, Recursion, 25 points.


Consider the function Mystery dened below.
Mystery(n)
if n > 1 then begin
1
for i := 1 to n 2 print(x);
Mystery( n4 );
end
If we call Mystery(n), where n is a power of 4 and n > 1, how many xs (as a function of n)
does call Mystery(n) print? Justify your answer/show your work (ie give recurrence and solve by
substitution.)
Answer: n is a power of 4, so n = 4m for some m 1. We observe that T (4) = 2 and
1
T (n) = T ( n4 ) + n 2 for all n 42 . We will solve this recurrence by substitution.

m


n
(c + 1) k
2
k=1

= (c + 1)n

m

1
k=1

= (c + 1)n

= (c + 1)n

2k

1
1

= 2(c + 1)n 1

n
2

begin
Ai := max{Si , S n2 +i };
Bi := min{Si , S n2 +i };
end;

Alice := A1 ;
Bob := B1 ;
for i := 1 step 1 to n2
if (Ai > Alice) then Alice := Ai ;
for i := 1 step 1 to n2
if (Bi < Bob) then Bob := Bi ;
Answer: Alice is the value of the maximum element of the array S1 , ..., Sn and Bob is the value
of the minimum element of the array S1 , ..., Sn . We argue this in two steps:
First notice that A1 , ..., A n2 contains the maximum element of the array S1 , ..., Sn and B1 , ..., B n2
contains the value of the minimum element of the array S1 , ..., Sn . This is obvious, since for some
i, the maximum value element must have been placed in Ai := max{Si , S n2 +i }, while for some i ,
the minimum value element must have been placed in Bi := min{Si , S n2 +i }.
Next notice that Alice takes the value of the maximum element of A1 , ..., A n2 using the standard
method of scanning the array once from left to right and updating the max as necessary, and BoB
takes the value of the minimum element of B1 , ..., B n2 also using the standard method of scanning
the array once from left to right and updating the max as necessary.

T (n)

=
=
=
=
=
=
=

2k+1
1
2
1
2k+1
1
2

for i := 1 to

1
n
T( ) + n2
4
 1
1
n 2
n
T( 2) +
+ n2
4
4

T(

n
)+
43

n
42

1
2

 1

1

n
4

1
2k+1

=
=

2n 2 2

< 2(c + 1)n


= O(n)

1
2

1

 1

2
1
n
n
n 2
n 2
)+
+ ... 2
+
+ n2
4k
4k1
4
4


1
n
1
1
1
T( k ) + n2
2 +
1 + 1
k1 + . . . +
4
2
42
42 
4
1
1
n
1
1
2
T( k) + n
+ ... + 2 + + 1
4
2k1
2
2

1 21k
1
n
T( k ) + n2
4
1 12


1
n
1
T ( k ) + 2n 2 1 k
4
2

1
n
1
4
=4 k =
4k
4
n
4k


1
2
T (4) + 2n 2 1 1
n2
1
2
2 + 2n 4 =

stop when

+ n2

T(

1
2

 1

4
n

1
2
= 1
2k
n2

.
1

So Mystery prints 2n 2 xs (which is consistent with T (4) = 2 since 2 4 2 2 = 2.)

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 2, Sample
Page 2/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 2, Sample
Page 3/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 2, Sample
Page 4/4

Problem 2, Dynamic Programming, 25 points.


Let G(V, E) be a directed acyclic graph given in adjacency list representation and in topologically
sorted order. That is, where the set of vertices is V = {1, 2, . . . , n}, all edges i j E have
i < j. Let L(k) be the length of the longest path that starts at k, 1 k n. Give an O(|V | + |E|)
algorithm that computes L(k) for all k, 1 k n.
Answer:
Sinks do not have outgoing edges, so no path starts at a sink, so for all sinks s we have L(s) = 0.
For every non-sink vertex k, the maximum length path starting at k is a path whose rst
edge is k j E. Therefore, the maximum length path starting at k is determined as
L(k) = 1 + max{L(j) : k j E}. For the correct computation of L(k) it is necessary that, for all
edges k j E, the value L(j) has been computed before the computation of L(k) starts. Since
the graph is acyclic and presented topologically sorted, we know that all edges L(j) : k j E
have k < j. Therefore, if we compute the L(k)s in reverse order n, (n 1), . . . , 1, we are guaranteed
that when the computation of L(k) is about to start, for all edges k j E, the value L(j) has
been already computed.
Initialization: for k := 1 to n set L(k) := 0;
Main Loop: for k := n downto 1
for all j Adj(k) do L(k) := max{L(k), 1 + L(j)};
The running time of the above algorithm is O(|V | + |E|). To see this, realize that each edge is
used exactly once at the second line of the main loop, in particular, when updating the value of its
starting point.

Problem 3, DFS, 25 points.


(a) An undirected graph G(V, E) is bipartite if and only if V can be partitioned to VL and VR (ie
VL VR = V and VL VR = ) so that all edges in E have one endpoint in VL and the other
endpoint in VR . Describe an O(|V | + |E|) algorithm that decides if an undirected graph given in
its adjacency list representation is bipartite.
(b) An undirected graph G(V, E) is near-bipartite if and only if there exists e E such that
removing e gives a bipartite graph Ge (V, E \ {e}). Describe a polynomial time algorithm that that
decides if an undirected graph given in its adjacency list representation is near-bipartite. Argue
correctness and running time.
Answer:
(a) We give an algorithm that decides if a graph is bipartite by doing one of the following:
Either the algorithm nds a partitioning of V to VL and VR such that all edges have one endpoint
in VL and the other point in VR .
Or the algorithm nds an odd length cycle, thus establishing that no such partitioning exists and
the graph is not bipartite.
The algorithm achieves the above as follows:
First we do DFS in G, color each root of each tree in the DFS forest VL , and as new vertices are
discovered, color each vertex a dierent color than the color of its parent (if the parent is colored
VL then the vertex is colored VR , while if the parent is colored VR then the vertex is colored VL .)
Next we examine all edges {u, v} that were not tree edges.
If the endpoints of every such edges have dierent colors, then the coloring assigned by DFS gives
a proper bipartition of vertices, and the graph is bipartite.
If there is a non-tree-edge whose endpoints u and v have the same color, and assuming wlog that
v is an ancestor of u in the DFS tree, then there is a path from u to v that has an odd number of
vertices (starting from u, following parents of the DFS tree until we reach v.) Together with the
edge {u, v}, this gives a cycle of odd length. This cycle is proof that G is not bipartite.
Since the complexity of DFS is O(|V |+|E|), the running time of the entire algorithm is O(|V |+|E|).
(b) We consider each one of the graphs Ge (V, E \{e}) and test them for bipartiteness in O(|V |+|E|).
If, for some e E, Ge is bipartite then G is near-bipartite.
If, for all e E, Ge is not bipartite then G is not near-bipartite.
The total running time is O(|E|(|V | + |E|)).

Problem 4, DFS, 25 points.


Let G(V, E) be a directed graph. The component graph GSCC (V SCC , E SCC ) is dened as follows.
Suppose that G has strongly connected components C1 , C2 , . . . , Ck . The vertex set of GSCC is
V SCC = {v1 , v2 , . . . , vk }. There is an edge vi vj E SCC if and only if for some x Ci and for
some y Cj we have x y E.
(a) Given G in its adjacency list representation, describe an O(|V | + |E|) running time algorithm
to compute the adjacency list representation of GSCC .
(b) The adjacency list representation of GSCC may contain redundancies. In particular, for an edge
vi vj E SCC , vj may be appearing several times in the adjacency list of vi . Give an ecient
method to eliminate all such redundancies. Analyze the running timeof your method.
Answer:
(a) First compute the strongly connected components C1 , C2 , . . . , Ck .
This can be done is O(|V | + |E|) running two DFS as follows: The rst DFS is on G. The second
DFS is on the reverse of G, where vertices are visited in order reverse than their nish times in the
rst DFS. The vertices of each tree component of the second DFS correspond to a distinct strongly
connected component of G.
We now have the vertex-set V SCC = {v1 , v2 , . . . , vk }, one vertex for each strongly connected
component. To nd the edges in E SCC we scan the edges in E once. For each edge u v E, if u
and v belong to dierent strongly connected components, say v Ci and v Cj with i = j, then
we add an edge vi vj to E SCC .
The complexity of this algorithm is O(|V | + |E|).
(b) We may eliminate redundancies by sorting the nodes in the adjacency list of each vi V SCC .
Then, multiple occurrences of an incident node vj will appear in consecutive positions. We can
eliminate such multiplicities with a secong pass of the adjacency lists. There are at most |V |
adjacency lists. Each list has length at most |V |. Sorting each adjacency list takes O(|V | log |V |)
and the total running time is O(|V |2 log |V |).
We get a better running time if we keep the adjacency lists of GSCC sorted as we are inserting new
vertices. Each insertion will take O(log |V |) (using binary search), and we avoid multiplicities. We
have to examine |E| edges of G, each edge takes O(log |V |) to update the corresponding adjacency
list of GSCC , and the total running time becomes O(|V | + |E|) for the identication of the strongly
connected components, and O(|E| log |V |) for the construction of GSCC without edge multiplicities.
Thus the total running time becomes O(|V | + |E| log |V |).

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 2, 3-11-15
Page 1/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 2, 3-11-15
Page 2/4

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 2, 3-11-15
Page 4/4

Problem 1, Recursion, 25 points.


Consider the function Mystery dened below.
Mystery(n)
if n 1 then begin
1
for i := 1 to n 2 print(x);
Mystery( n4 );
n
Mystery( 4 );
end
(a) How many xs does Mystery(1) print? How many xs does Mystery(4) print?
(b) If we call Mystery(n), where n is a power of 4 and n 1, how many xs (as a function of n)
does call Mystery(n) print? Justify your answer/show your work (ie give recurrence and solve by
substitution.) Hint: Using 4k = 22k and taking logs base 2 makes calculations easier.
Answer: (a) Mystery(1) prints one x. Mystery(4) prints four xs.
1
(b) We have to solve T (n) = 2T ( n4 ) + n 2 for all n 1, with T (1) = 1. Solve by substitution.

Problem 2, Graph Representation, 25 points.


Let G(V, E) be an undirected graph given in adjacency list representation (without redundancies,
ie each vertex appears at most once in an adjacency list.) The degree of a vertex v V is the
number of vertices u that are adjacent to v: deg(v) = |{u : u Adj(v)}|. The twodegree of a vertex

v V is the sum of the degrees of the vertices that are adjacent to v: twodeg(v) = uAdj(v) deg(u).
(a) Give an O(|V | + |E|) time algorithm that computes deg(v), for all v V .
(b) Give an O(|V | + |E|) time algorithm that computes twodeg(v), for all v V .
Answer:
(a) To compute degrees scan the adjacency lists of all vertices. Since there are no redundancies,
every vertex in an adjacency list of a vertex v adds one to the degree of v.
for all v V set deg(v) := 0;
for all v V
for all u Adj(v) set deg(v) := deg(v) + 1;
The total time is O(|V | + |E|), each vertex is considered once in the rst and second lines, and each
edge {u, v} is considered twice in the second line, once in the adjacency list of u and once in the
adjacency list of v.
(b) To compute twodegrees, after the degrees have been computed in part (a), again scan the
adjacency lists of all vertices. For every vertex u in an adjacency list of a vertex v add deg(u) to
the twodegree of v.
for all v V set twodeg(v) := 0;
for all v V
for all u Adj(v) set twodeg(v) := twodeg(v) + deg(u);
The total running time is O(|V | + |E|), arguing exactly as in part (a).

Problem 4, Dynamic Programming, 25 points.


Let G(V, E), V = {1, 2, . . . , n}, be a directed acyclic graph given in adjacency list representation
and in topologically sorted order (that is, if i j E then i < j.) Describe an O(|V | + |E|) time
algorithm that nds the length of the longest path from 1 to n. If there is no path from 1 to n
then your algorithm should output Nil. Justify correctness and running time of your algorithm.
Hint: Consider nding the length of the longest path from every vertex k to n, 1 k n.
Answer:
Let L(k) be the length of the longest path from node k to node n, 1 k n.
L(n) = 0 and if, for some k < n, there is no path from k to n then L(k) = Nil.
Suppose that, for some k n, L(j) has been correctly computed for all j > k.
Since the graph is acyclic and presented topologically sorted order, all edges out of k (which are
the possible rst steps of a path from k to n) are of the form k j, j > k.
So we can update L(k) by looking at all of ks neighbors, say j, and the corresponding L(j)s:

 

T (n)

2T

n
4

2 2T


n
42

22 T

22 2T

23 T

2k T

n
42

 1

n
4

+ 2n

+ n2

n
43

+ n2

1
2

n
42

1

+ 2n 2

1
n
+ 3n 2
43

1
n
2
+
kn
4k

So Mystery prints n 2 1 +
1

log2 n
2 
log2 4
2

Nil
if L(j) = Nil for all k j E
max{1 + L(j) : k j E and L(j) = Nil} if L(j) = Nil for some k j E

The memoization algorithm is then straightforward:


Initialization: L(n) := 0; for all 1 k n set L(k) := Nil;
Main Loop: for k := (n 1) down to 1
for all j Adj(k)

1 + L(j)
if L(k) = Nil
if L(j) = Nil then L(k) :=
max{L(k), 1 + L(j)} if L(k) = Nil
Each vertex is examined once in initialization and in the rst line of the main loop. and each edge
is examined once in the second line of the main loop. Thus the running time is O(|V | + |E|).

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 2, 3-11-15
Page 3/4

n
log2 n
stop when
= 1 n = 4k n = 22k 2k = log2 n k =
4k
2
log2 n
log2 n 1
2
2
T (1) +
=
2
n
2
1
1
log2 n
=
n2 +
n2
2


1
log2 n
=
n2 1 +
.
2

and T (4) = 4 since 4 2 1 +

L(k) =

xs (which is consistent with T (1) = 1 since 1 2 1 +

log2 1
2

=1

= 4 .)

Problem 3, DFS, 25 points.


Give an O(|V | + |E|) algorithm which takes as input a directed graph G = (V, E), and determines
whether or not there exists a vertex v V from which all other vertices are reachable. Justify
correctness and running time. Hint: First solve the problem for the case where G is acyclic.
Answer:
If G(V, E) is acyclic, then it has a topological sorting. The only vertex of V that can possibly
reach all other vertices is the vertex that is rst in topologically sorted order, say r (since all other
vertices are ahead of r in topological order and thus cannot have an edge to reach r.) We may thus
do DFS starting at r. We know that all vertices reacheble from r will belong to the tree rooted
at r. So we just check if the DFS tree rooted at r contains all of V . If yes, then all vertices can
be reached from r. If no, then there is no vertex from which all vertices in V can be reached.
The total running time involves two runs of DFS (one for topological sorting and one for checking
reachability from r thus the total running time is O(|V | + |E|).
For general G(V, E) we rst nd the strongly connected components of G and the component
graph GSCC (V SCC , E SCC ). This can be done in O(|V | + |E|) using DFS. It is now obvious that,
since GSCC is acyclic, there exists a vertex v V from which all other vertices are reachable if
and only if all of V SCC can be reached from the vertex r V SCC that is rst in a topological
sorting of V SCC . The approach involves a constant number of DFS calls, so the total running time
is O(|V | + |E|).

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 3, Sample
Page 3/4

Problem 1, MST, Dijkstra, 25 points.


(a) Let G(V, E) be a directed weighted graph, where the weights of all edges are positive: wuv > 0,
for all u v E. Let s V be a source vertex. Dijkstras algorithm with source s nds the
cheapest path from s to every other vertex v V . In particular, for every vertex v V , Dijkstra
computes a predecessor vertex (v) such that v (v) E, and such that the collection of edges
T = vV {v (v)} form a tree rooted at s with the list of ancestors of v in the tree giving a
cheapest path from v to s. Consider a graph G (V, E) on the same set of vertices as G and with the
 = w + c. Now
same set of edges as G. However, for some c > 0, the weights of edges of G are wuv
uv
suppose that we apply Dijkstras algorithm with source s to the graph G , and let T  be resulting
tree. Is T = T  ? If yes, then give a proof. If no, then give a counter-example.
Answer:No.
Counterexample: Graph on the three nodes {s, a, b} with directed edges e1 = s a, e2 = s b
and e3 = b a. The costs are w(e1 ) = 3, w(e2 ) = 1 and w(e3 ) = 1. The cheapest path from s to
a is s b a at cost 2.
Now add 10 to the costs of all edges to get w (e1 ) = 13, w (e2 ) = 11 and w (e3 ) = 11. The cheapest
path from s to a is s a at cost 13 (the path s b a has new cost 22 and is no longer shortest
path.)

Problem 3, Hardness Reductions, 25 points.


SomewhatLongPath is the following decision problem. On input an undir
ected, unweighted graph
path of G is at least |V |, while the output is
G(V, E), the output is YES if the length of the longest 
NO if all paths of G have length strictly smaller than |V |. Show that HPP SomewhatLongPath.
(HP is the standard Hamilton Path problem. On input an undirected, unweighted graph G(V, E),
the output is YES if the length of the longest path of G is (|V | 1), while the output is NO if all
paths of G have length strictly smaller than (|V | 1).
Answer:
Let G(V, E) be the graph for which we want to decide if the longest path is of length (|V | 1).
We construct G (V  , E  ) as follows:
V  is V together with X isolated vertices, where x = |X|, and E  = E.
Let L be the length of the longest path in G.
Of course, L is also the length of the longest path in G .
We need
 x such that:





L < |V | 1 L < |V | + x and L = |V | 1 L |V | + x .
The second condition implies (|V | 1)2 |V | x, so we may pick x = (|V | 1)2 |V |.
It is easy to verify that this coice of x also satises the rst condition. In particular, if L < |V | 1
2
then the maximum val
ue that L can take is (|V | 2). For x = (|V | 1) |V |, the rst condition
becomes (|V | 2) < |V | + (|V | 1)2 |V | = (|V | 1), obviously always true.

(b) Let G(V, E) be an undirected connected weighted graph, where the weights of all edges are
distinct and positive: we > 0, for all e = {u, v} E. Let T be the mincost spanning tree of G.
Consider a graph G (V, E) on the same set of vertices as G and with the same set of edges as G.
However, for some c > 0, the weights of edges of G are we = we + c. Is T still a mincost spanning
tree of G ? If yes, then give a proof. If no, then give a counter-example.
Answer: Yes.
Every spanning tree has (n 1) edges. Thus, if we add the same c to the costs of all edges, the
cost of every spanning tree will increase by the same amount, namely c(n 1).
Last Name: ............................. First Name: .............................. Email: ..............................
CS 3510 A, Springl 2015, Quiz 3, Sample
Page 2/4
Problem 2, Maxcost Spanning Tree, 25 points.
Let G(V, E) be an undirected connected weighted graph, where the weights of all edges are distinct
and positive: we > 0, for all e = {u, v} E. Give an ecient algorithm that nds a spanning tree
of maximum cost (ie the sum of the weights of the edges of the spanning tree is maximized, over
all spanning trees of the graph.) Justify correctness and running time.
Answer:
STEP 1: Construct G on the same set of vertices and edges as G (thus the same set of spanning
trees), but with new costs of edges we = we .
STEP 2: T = MST in G using Kruskal or Prim (note: they work for arbitraty costs on the edges.)
STEP 3: Output T as maxcost spanning tree of G.
Correctness follows because Kruskal and Prims algorithms work for arbitraty costs on the edges,
these costs can be positive or negative.
Eciency follows because the main computational task in the above algorithm is one call of an
MST algorithm (in STEP 2).

2
1

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Springl 2015, Quiz 3, Sample
Page 1/4

6
A

5
G

H
3

6
A

2
E

H
3

6
Last Name: ............................. First Name: .............................. Email: ..............................
CS 3510 A, Springl 2015, Quiz 3, Sample
Page 4/4
Problem 4, Approximation Algorithm, 25 points.
Let G(V, E) be a directed unweighted graph, |V | = n. Let be a total ordering of V , that is, each
vertex v V is assigned a unique integer (v) in the range 1 to n.
Let BACK() be the number of edges directed from higher order vertices to lower order vertices:
BACK() = |{u v E : (u) > (v)}|.
Let OPT=max{BACK() : is a total ordering of V }.
Now let be an arbitrary total ordering of V , and let  be the reverse ordering,
ie ((v) = 1  (v) = n), ((v) = 2  (v) = n 1), . . ., ((v) = n  (v) = 1).
Argue that max{BACK(), BACK(  )} OPT
2 .
Answer:
Let BACK = max{BACK(), BACK(  )}.
Let FORWARD = |E| BACK, the rest of the edges.
By choice, BACK > FORWARD, thus BACK |E|
2 .
But |E| is the total number of edges of the graph, thus OPT |E|.
The last two bounds combined give
BACK

OPT
|E|

2
2

2
1

2
E

F
1

D
5

G
3

H
3
6

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Practice Final Exam
Page 1/10


d(A)=0

d(B)=?
B

2
1

2
E

d(E)=?

F
1




5

d(C)=? 6
C
4

d(D)=?
D
G_1

G_2

d(F)=?

e_1

d(G)=?

Problem 1: 10 points.
Consider the function Mystery dened below.
Mystery(n)
if n > 1 then begin
print(xxx);
Mystery(n/2);
end
If we call Mystery(n), where n is an integer power of 3 and n > 1, how many xs (as an exact
function of n) does call Mystery(n) print? Justify your answer/show your work (solve recurrences
using the substitution method, do not use O() notation.)
Answer:5IFTNBMMFTUOUIBUJTBQPXFSPGJTO$MFBSMZ .ZTUFSZ 
QSJOUTYhTBOEDBMMT
.ZTUFSZ 
.ZTUFSZ 
*OUVSO .ZTUFSZ 
EPFTOPUHPJOUPUIFNBJOMPPQ IFODFJUEPFTOPUQSJOUBOZ
YhTBOEJUEPFTOPUDBVTFBOZGVSUIFSSFDVSTJWFDBMMT5IVT.ZTUFSZ 

8IFOOLXJUIL .ZTUFSZ O
QSJOUTYhTBOEDBMMT.ZTUFSZ O

8FUIVTIBWFUPTPMWF5 O
5 O
  XIFSFOJTBQPTJUJWFQPXFSPG XJUI5 

8FTPMWFUIJTSFDVSSFODFCZTVCTUJUVUJPO XIFSFUIFHFOFSBMGPSNJT5 Y
5 Y
 

e_2

d(H)=?

T_1

T_2

e_k

CZFMFNFOUBSZDBMDVMBUJPOT
CZTVCTUJUVUJOHYO ?
UPUIFHFOFSBMGPSN

CZFMFNFOUBSZDBMDVMBUJPOT

CZHVFTTJOHUIFHFOFSBMUFSN

LOPXJOHUIBU5 
 XBOULTVDIUIBUO ?L

UIVT

1
A

CZTVCTUJUVUJOHYOUPUIFHFOFSBMGPSN

)DOVH&RXQWHUH[DPSOH

10

20

1
A

10

F
B

20

Problem 2: 10 points *HW2 Problem 4.


Let X(1, . . . , n) and Y (1, . . . , n) be two arrays, each containing n numbers already in sorted order.
Describe an O(log n)-comparison algorithm to nd the median of all 2n elements in arrays x and
Y . Justify your answer in correctness and running time.
Answer:4FFTPMVUJPOUP)81SPCMFN

10
E

UIVT   XIJDIDPSSFDUMZQSFEJDUTUIBU5 




Last Name: ............................. First Name: .............................. Email: ..............................
CS 3510 A, Spring 2015, Practice Final Exam
Page 2/10

2
Last Name: ............................. First Name: .............................. Email: ..............................
CS 3510 A, Spring 2015, Practice Final Exam
Page 3/10

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Practice Final Exam
Page 6/10

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Practice Final Exam
Page 9/10

Problem 3: 10 points *HW4 Problem 3.


Let a(1), . . . , a(n) be an unsorted input array of n distinct positive integers, where n is odd. A
wigly arrangement of a is a permutation of the input such that

Problem 6: 10 points.


Let G(V,E) be an undirected connected graph with distinct postive costs on its edges. Let T be
the collection of all spanning trees of G. Let Tmin be the unique minimum cost spanning tree of
G. Give a polynomial time algorithm that nds a second minimum cost spanning tree of G, ie a
spanningtreewhosecostisminimumamongalltreesinT \Tmin . Youmaygiveasimpledescription
ofthealgorithm(nopseudocode.) Youshouldincludeashortargumentofcorrectnessandrunning
time.
Answer:5IFSFJTBUMFBTUPOFFEHFPG5NJOUIBUEPFTOPUCFMPOHUPUIFTFDPOENJOJNVNTQBOOJOHUSFF8F
NBZUIFSFGPSFSVOBQPMZUJNFNJODPTUTQBOOJOHUSFFBMHPSJUINUPFBDIPGUIFHSBQIT(F 7 &=\F^
GPSBMM
F5NJO5IFSFBSF ]7]
TVDI(FhTBOEFBDIPOFXJMMQSPEVDFBNJODPTUTQBOOJOHUSFF5F NJO8FPVUQVU
UIF5F NJOPGUIFNJOJNVNDPTU

Problem 9: 10 points.


MAX3SAT is the following problem. On input a boolean formula in 3CNF, over n variables and
containingmclauses,outputatruthassignmentthatsatiseskclauses,andsuchthatthereisno
truthassignmentthatsatisesmorethankclauses.Showthat3SATPMAX3SAT.

a((1)) > a((2)) < a((3)) > a((4)) < a((5)) . . . a((n 2)) > a((n 1)) < a((n)).
For example, on input 100, 20, 2, 5, 200, 50, 40, 201, 300
a wigly arrangement is 100, 20, 200, 2, 50, 5, 201, 40, 300
since 100 > 20 < 200 > 2 < 50 > 5 < 201 > 40 < 300.
Give an O(n) comparison algorithm that outputs a wigly arrangement of an unsorted input array
a(1), . . . , a(n) of n distimct integers, where n is odd. You may give a simple description of the
algorithm (no pseudocode.) You should include a short argument of correctness and running time.
Answer:4FFTPMVUJPOUP)81SPCMFN

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Practice Final Exam
Page 7/10

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Practice Final Exam
Page 4/10

Problem 7: 10 points.
Let G(V, E) be a line with weights on its vertices. The MaxIS is the problem of nding an
independent set of G whose sum of the weights of the vertices is maximized over all independent
sets of G. Give an example to show that the following heaviest rst greedy algorithm does not
always nd an independent set of maximum total weight.
Start with S equal to the empty set.
While some node remains in G
Pick a node vi of maximum weight
Add vi to S
Delete vi and its neighbors from G
End While
Return S
Answer:

Problem 4: 10 points *Quiz 2 Problem 3.


Let G(V, E) be a directed graph. Give an O(|V | + |E|) algorithm that decides if there is a vertex
v V that is reachable from every other vertex u V , ie there is a path from u to v, for all u V .
Hint: First consider the case where G(V, E) is acyclic.
Answer:4FFTPMVUJPOUP2VJ[1SPCMFN
Last Name: ............................. First Name: .............................. Email: ..............................
CS 3510 A, Spring 2015, Practice Final Exam
Page 5/10
Problem 5: 10 points.
Let G(V,E) be an undirected connected graph, with positive costs ce on its edges. Let G (V,E)
be the same graph as G, but the cost of each edge e whose original cost in G was ce is replaced in
G by c2e . For each of the following two statements, decide if it is true or false. If it is true, give a
short explanation. If it is false, give a counterexample.
(a) If T is a minimum cost spanning tree of G, then T is a minimum cost spanning tree of G .
(b)WheresandtaredistinctverticesofV,ifPisaminimumcoststpathinG,thenPisa
minimumcoststpathinG.
Answer:
 
B
5SVF*GBSFUIFDPTUTPGUIFFEHFTPG(JOOPOEFDSFBTJOHPSEFS UIFO
BSFUIFDPTUTPGUIFFEHFTPG(hJOOPOEFDSFBTJOHPSEFS5IVT UIF.45

BMHPSJUINXIJDIDPOTJEFSTFEHFTJOOPOEFDSFBTJOHPSEFSPGDPTUBEETUIFNUPUIF.45JGOPDZDMFJT
DSFBUFE XJMMDPOTJEFSFEHFTJOUIFFYBDUTBNFPSEFSGPS(BOE(hBOEPVUQVUUIFTBNFUSFFGPS(BOE(h
C
'BMTF$PVOUFSFYBNQMF

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Practice Final Exam
Page 8/10
Problem 8: 10 points *HW7 Problem 5.
Let G(V,E) be a directed graph. Recall that a Hamilton Path in G is a path of length (|V|1)
that vistis every vertex exactly once. Give a polynomial time algorithm that decides if a directed
acyclic graph has a Hamilton Path. Justify correctness and running time of your answer.
Answer:4FFTPMVUJPOUP)81SPCMFN

Answer:8FOFFEUPBSHVFUIBU JGUIFSFJTBQPMZOPNJTBMUJNFBMHPSJUINGPSTPMWJOH."94"5 UIFO


UIFSFJTBQPMZOPNJBMUJNFBMHPSJUINGPSEFDJEJOH4"5
-FUGCFBCPPMFBOGPSNVMB$/' PWFSOWBSJBCMFTBOEDPOUBJOJOHNDMBVTFT
8FHJWFGBTJOQVUUPBQPMZOPNJBMUJNFBMHPSJUINGPSTPMWJOH."94"5BOEHFUBUSVUIBTTJHONFOUBT
PVUQVU
*GTBUJTGJFTBMMNDMBVTFTPGG UIFOGIBTBTBUJTGZJOHBTTJHONFOUBOEJUJTB:&4JOTUBODF
*GTBUJTGJFTTUSJDUMZMFTTUIBONDMBVTFTG JFBUMFBTUPOFDMBVTFJTOPUTBUJTGJFECZU
UIFOGIBTBTBUJTGZJOH
BTTJHONFOUBOEJUJTB:&4JOTUBODF

Last Name: ............................. First Name: .............................. Email: ..............................


CS 3510 A, Spring 2015, Practice Final Exam
Page 10/10
Problem 10: 10 points *In CLRS.
Let G(V,E) be an undirectedgraph. Let OPT be the size of the smallest vertex cover of G. Give
a polynomial time algorithm that nds a vertex cover of G that contains at most 2OPT vertices.
Justifyyour answer.
Answer:8FGJOEBNBYJNBMNBUDIJOHBOEBEEUIFFOEQPJOUTPGBMMFEHFTUP$
"113097&35&9$07&3
$ JOJUJBMMZUIFWFSUFYDPWFSDPOUBJOTOPWFSUJDFT

. JOJUJBMMZUIFNBUDIJOHDPOUBJOTOPFEHFT

XIJMF&
MFUF\V W^&CFBOBSCJUSBSZFEHF
..\F^ BEEUIFFEHFFUPUIFNBUDIJOH

$$\V W^ BEECPUIFOEQPJOUTPGFUPUIFWFSUFYDPWFS

GPSBMMFh\V Y^TFU&&=\Fh^ SFNPWFBMMFEHFTJODJEFOUUPVGSPN&

GPSBMMFh\W Y^TFU&&=\Fh^ SFNPWFBMMFEHFTJODJEFOUUPWGSPN&

$MBJN5IFBCPWFBMHPSJUINPCWJPVTMZSVOTJOQPMZOPNJBMUJNF
$MBJN$JTBWFSUFYDPWFS5IJTJTFBTZUPBSHVFCZDPOUSBEJDUJPO*OQBSUJDVMBS JGJOUIFFOEPGUIF
BMHPSJUIN UIFSFFYJTUTBOFEHFF\V W^ &TVDIUIBUOFJUIFSVOPSWCFMPOHUP$ UIFOXIZXBTUIJTFEHF
OPUDPOTJEFSFEJOUIFXIJMFMPPQ

$MBJN*G015JTUIFTJ[FPGUIFTNBMMFTUWFSUFYPG( UIFO]$]015
5PTFFUIJT GJSTUOPUFUIBUGPSFWFSZFEHFJOF\V W^. BUMFBTUPOFPGVPSWNVTUCFMPOHUPUIF
TNBMMFTUWFSUFYDPWFS5IFOSFBMJ[FUIBU.DPOTJTUTPGFEHFTUIBUEPOPUTIBSFBOZPGUIFJSFOEQPJOUT
5IVT 015].]0OUIFPUIFSIBOE ]$]].]5IVT].]015

Das könnte Ihnen auch gefallen