VIENTIAN - Tower of Vientiane

no tags 

The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks neatly stacked in order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:

  • Only one disk may be moved at a time.
  • Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.
  • No disk may be placed on top of a smaller disk.

It is known that the puzzle can be solved in 2n-1 steps for n disks.

Now consider the puzzle called The Tower of Vientiane. The rules are almost the same as for The Tower of Hanoi. But additionally there are limitations on the allowed moves. Let the initial rod be numbered 1, the target rod - 3, and the auxiliary rod - 2. The matrix of allowed moves is given. For example is can be allowed to move disks from rod 1 to rod 2 only, from rod 2 to rod 3 and from rod 3 to rod 1. You are to find out the minimal number of moves in which the puzzle can be solved given some limitations on the allowed moves.

Input

The first line of the input contains number t – the amount of tests. Then t test descriptions follow. The test starts with a 3×3 matrix, consisting of 1s and 0s. The 1 in i-th row and j-th column of the matrix means that the move from rod i to rod j is allowed, otherwise it is not allowed. The next line of each test contains the number n - the amount of disks for the corresponding testcase.

Constraints

1 <= t <= 10000
2 <= n <= 39

Output

For each test print the minimal number of moves in which the puzzle can be solved or "Epic Fail..." if it's impossible to solve the puzzle under such limitations.

Example

Input:
3
011
101
110
5
010
101
010
5
010
001
010
5

Output:
31
242
Epic Fail...

hide comments
Shreyans: 2013-11-12 18:36:16

According to my calculation, answer goes beyond long long(2^64) in matrix
001
100
010

For above case and n>31, answer goes beyond range, so do we need to print that or take just modulo to 10^9+7??

Last edit: 2013-11-12 18:37:08
:D: 2011-03-16 08:22:19

Also see RANJAN02, an easier version of this problem.


Added by:Spooky
Date:2009-11-02
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64 OBJC SQLITE
Resource:Advancement Autumn 2009, http://sevolymp.uuuq.com/