Building a tower of cubes

You can make a stable tower of cubes without putting a larger one on a smaller one, and you cannot put heavier in a lighter cube.

Write a program that gives you the highest tower of N cubes.

The first line of the input txt contains the number of cubes. (1 <= n <= 100) The next N lines indicate the length and weight of the cube.

Example:

Input.txt       Output.txt (from bottom to top)
5               3
10 3            20 5
20 5            10 3
15 6            10 2
15 1
10 2

Memory Limit: 16 MB Duration: 0.2 s

Can you help me?

+4
source share
3 answers

Algorithm

In the algorithm, I came up with work using a list of ordered pairs. The steam is first ordered by one element, then the second.

We keep lists of pairs, where each new pair:

  • added to the end of the highest list if it can fit after the last item
  • , , ,
  • , .

  • , .
  • n -th ( ), .
  • n, k, n, , n, - 2. - i, k, 2 i. k .

.


foreach ordered pair
    maximumIndex <- 0
    maximumList <- null
    foreach list
        highest, length <- FindLongestPath(list, pair)
        if highest > maximumHeight
            maximumHeight<- highest 
            maximumIndex <- lenght
            maximumList <- list
    if maximumIndex = 0
        lists.add(new list{pair});
    else if maximumIndex < maximumList.Length
        lists.add(new list{maximumList[0..maximumIndex - 1] + pair});
    else
        list.add{pair};

FindLongestPath , , . (for , ), O (N ^ 2) .

, O (N log N), , N <= 100 .


, # pastebin: http://pastebin.com/3vLn343j

"Input.txt", , , ( Visual Studio , " " - , ").

+1

. , :

// `Input` is a list of `Cube` who have a `Size` and `Weight` property

int largestStack(input_cubes_left, currentCube)
{
   max = 0 // at worst, there are no cubes that fit on top of currentCube
   foreach (cube in input_cubes_left)
   {
      // skip all cubes which don't fit
      if (cube.Size <= current.Size and cube.Weight <= current.Weight)
      {

        // measure the stack with currentCube, this cube, and whatever is left
        size = 1 + largestStack(input_cubes_without_cube, cube)

        // but of course we only count the ones 
        // which are bigger than our best result
        if size>max 
          max = size
      }
   }
   return max;
}

, , (N !). , :

  • , ?
  • Linq ?
+1

, ( /), , :

  • node
  • (A → B), B A

, DAG (http://en.wikipedia.org/wiki/Directed_acyclic_graph)

DAG. .

Let's go back to the assumption, even consider equal cubes, we can make small changes to cover equal cubes. (each node has an attribute - equalCount, the number of equal cubes and the definition of a long path to the sum of equalCount along the path to replace the original definition: the number of node along the path)

+1
source

All Articles