Blog do projektu Open Source JavaHotel

niedziela, 18 marca 2018

Circus tower

Introduction
There is an exercise in "Cracking the coding interview", Circus Tower.

Circus Tower: 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
lnput(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)
The solution is based on finding the longest subsequence.
Alternative solution
But I developed a very similar solution in term of the directed graph and the solution is to find the longest possible path in the graph. Usually, we want to find the shortest path but this time it is different.  Athletes in the circus are graph nodes and if an athlete can stand atop the weightier athlete then there is an edge from the second to the first.
The C++ code as Eclipse CDC project is available here.
The class Athlete describes a single person and class AthleteGraph describes the connection. The graph is represented as a two-dimensional adjacency matrix. If there is a connection from i to j, then graph[i][j] is true.
The algorithm is recursive.
Assume that we are at the node i, and there are several adjacent nodes to i :  i1,i2 ... i(n). We calculated recursively the longest paths for i1, i2 .. i(n). The longest path starting from i is i itself concatenated with the longest among paths for i1,i2 ... i(n).
Complexity
The most complex is the graph creation because we have to compare a person with every other person to detect edges. So the complexity is O(n squared). Having the graph built, the complexity is O(m), where m is the number of edges, every edge is visited only once.


Brak komentarzy:

Prześlij komentarz