Under construction

Still being built. Things may change

Hilbert's Maze

Time limit5sMemory limit256 MB

Summary
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 T0T_0 (Figure 1), and apply the transformation shown in Figure 2 kk times to get the resulting maze TkT_k. The coordinate system is shown in Figure 2, with the cell in the lower left corner at (1,1)(1, 1). For example, T2T_2 is shown in Figure 3.

Figure 1Figure 2Figure 3

You can leave the maze. The square with corners (1,1)(1, 1) and (2k+1−1,2k+1−1)(2^{k+1}-1, 2^{k+1}-1) 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 TT (1≤T≤3⋅1051 \leq T \leq 3 \cdot 10^5), the number of test cases. Each of the next TT lines contains five space-separated integers kk, xsx_s, ysy_s, xtx_t, yty_t (0≤k≤300 \leq k \leq 30, 1≤xs,ys,xt,yt≤2k+1−11 \leq x_s, y_s, x_t, y_t \leq 2^{k+1}-1). Here kk is the number of transformations used to build the maze, (xs,ys)(x_s, y_s) is the start cell, and (xt,yt)(x_t, y_t) is the target cell. The two cells may coincide.

Output

Print TT lines. The ii-th line contains the minimum number of moves from the start cell to the target cell in the ii-th test case. It is guaranteed that a path between the two cells exists.

Hint

The figure below illustrates the second and third samples.

Examples1

  1. Example 1

    Input
    3
    0 1 1 1 1
    1 1 3 3 3
    1 1 1 3 3
    
    Expected output
    0
    4
    8