Hilbert's Maze
Time limit5sMemory limit256 MB
Given a maze built by k rounds of the Hilbert curve transformation, find the shortest path length between two cells for each of up to 300000 queries.
- Level
Hard8 of 10
- Topics
- Divide and conquer, Recursion, Implementation
- Solved
- No attempts yet
Problem
You are playing a computer game "Hilbert's Maze". The goal of the game is to find a way out of various mazes. The last level has the trickiest maze, and you cannot find your way out of it. Tired of the maze's complexity, you decide to use your programming skills instead.
The maze is a rectangular field divided into identical square cells, with walls along some cell borders. While standing in a cell, you can move to an adjacent cell (two cells are adjacent if they share a border segment) when no wall blocks the way.
The maze is built with the following recursive rule. Start from the basic maze (Figure 1), and apply the transformation shown in Figure 2 times to get the resulting maze . The coordinate system is shown in Figure 2, with the cell in the lower left corner at . For example, is shown in Figure 3.
You can leave the maze. The square with corners and is the boundary, and there are no walls outside it. You can walk along the border or move as far from the maze as you like. Find the shortest path from the start cell to the target cell. Start and target cells are chosen at random for each attempt, so you want a program that finds shortest paths for many instances.
Input
The first line contains an integer (), the number of test cases. Each of the next lines contains five space-separated integers , , , , (, ). Here is the number of transformations used to build the maze, is the start cell, and is the target cell. The two cells may coincide.
Output
Print lines. The -th line contains the minimum number of moves from the start cell to the target cell in the -th test case. It is guaranteed that a path between the two cells exists.
Hint
The figure below illustrates the second and third samples.



