Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm for Human Towering

In Cracking the Coding Interview, Fourth Edition, there is such a problem:

A circus is designing a tower routine consisting of people standing atop one anoth- er’s shoulders For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her Given the heights and weights of each person in the circus, write a method to compute the largest possible number of people in such a tower.

EXAMPLE: Input (ht, wt): (65, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68, 110)

Output: The longest tower is length 6 and includes from top to bottom: (56, 90) (60,95) (65,100) (68,110) (70,150) (75,190)


Here is its solution in the book

Step 1 Sort all items by height first, and then by weight This means that if all the heights are unique, then the items will be sorted by their height If heights are the same, items will be sorted by their weight

Step 2 Find the longest sequence which contains increasing heights and increasing weights To do this, we:

a) Start at the beginning of the sequence Currently, max_sequence is empty

b) If, for the next item, the height and the weight is not greater than those of the previous item, we mark this item as “unfit”

c) If the sequence found has more items than “max sequence”, it becomes “max sequence”

d) After that the search is repeated from the “unfit item”, until we reach the end of the original sequence


I have some questions about its solutions.

Q1

I believe this solution is wrong.

For example

(3,2) (5,9) (6,7) (7,8)

Obviously, (6,7) is an unfit item, but how about (7,8)? According to the solution, it is NOT unfit as its h and w are bother bigger than (6,7), however, it cannot be considered into the sequence, because (7,8) does not fit (5,9).

Am I right?

If I am right, what is the fix?

Q2

I believe even if there is a fix for the above solution, the style of the solution will lead to at least O(n^2), because it need to iterate again and again, according to step 2-d.

So is it possible to have a O(nlogn) solution?

like image 355
Jackson Tale Avatar asked Jul 22 '13 22:07

Jackson Tale


1 Answers

You can solve the problem with dynamic programming.

Sort the troupe by height. For simplicity, assume all the heights h_i and weights w_j are distinct. Thus h_i is an increasing sequence.

We compute a sequence T_i, where T_i is a tower with person i at the top of maximal size. T_1 is simply {1}. We can deduce subsequent T_k from the earlier T_j — find the largest tower T_j that can take k's weight (w_j < w_k) and stand k on it.

The largest possible tower from the troupe is then the largest of the T_i.

This algorithm takes O(n**2) time, where n is the cardinality of the troupe.

like image 164
Colonel Panic Avatar answered Sep 23 '22 11:09

Colonel Panic