New Hanoi Tower

Given three rods with up to 10 labeled disks, find the minimum number of moves to sort them so each rod holds only its matching disk type.

Medium7BFSImplementationSimulationBrute forceInterviewNo attempts yetTime limit5sMemory limit512 MB

Problem

The rules of the new Hanoi tower game are as follows.

  • There are three rods: rod A, rod B, and rod C.
  • When the game starts, each rod holds zero or more disks.
  • All disks have the same size, and each disk is of type A, B, or C. A disk of type A is called disk A, and the other two types are named the same way.
  • One move takes the topmost disk of one rod and places it on top of another rod.
  • The goal is to leave only disk A on rod A, only disk B on rod B, and only disk C on rod C.

Given the starting contents of the three rods, write a program that finds the minimum number of moves needed to reach the goal.

Input

The first line contains the number of disks on rod A and the contents of rod A. The second line contains the number of disks on rod B and the contents of rod B. The third line contains the number of disks on rod C and the contents of rod C.

The contents of a rod are written from the bottom disk upward as a string made only of the characters A, B, and C. A rod with no disks is given as the number 0 with no string after it. The total number of disks on the three rods is at least 1 and at most 10.

Output

Print the minimum number of moves needed to reach the goal on one line.

Hint

A state where rod A holds one disk B, rod B holds one disk C, and rod C holds one disk A takes five moves.

  • Move disk A to rod A
  • Move disk C to rod C
  • Move disk A to rod C
  • Move disk B to rod B
  • Move disk A to rod A

A state where rod A holds disk C, disk B, and disk A from the bottom up while the other two rods are empty also takes five moves.

  • Move disk A to rod C
  • Move disk B to rod B
  • Move disk A to rod B
  • Move disk C to rod C
  • Move disk A to rod A