Problem:
Score : 600 points

Problem Statement

For a non-negative integer K, we define a fractal of level K as follows:

A fractal of level 0 is a grid with just one white square.

When K > 0, a fractal of level K is a 3^K \times 3^K grid. If we divide this grid into nine 3^{K-1} \times 3^{K-1} subgrids:

The central subgrid consists of only black squares.

Each of the other eight subgrids is a fractal of level K-1.

For example, a fractal of level 2 is as follows:

In a fractal of level 30, let (r, c) denote the square at the r-th row from the top and the c-th column from the left.

You are given Q quadruples of integers (a_i, b_i, c_i, d_i).
For each quadruple, find the distance from (a_i, b_i) to (c_i, d_i).

Here the distance from (a, b) to (c, d) is the minimum integer n that satisfies the following condition:

There exists a sequence of white squares (x_0, y_0), \ldots, (x_n, y_n) satisfying the following conditions:

(x_0, y_0) = (a, b)

(x_n, y_n) = (c, d)

For every i (0 \leq i \leq n-1), (x_i, y_i) and (x_{i+1}, y_{i+1}) share a side.

Constraints

1 \leq Q \leq 10000

1 \leq a_i, b_i, c_i, d_i \leq 3^{30}

(a_i, b_i) \neq (c_i, d_i)

(a_i, b_i) and (c_i, d_i) are white squares.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

Q
a_1 \ b_1 \ c_1 \ d_1
:
a_Q \ b_Q \ c_Q \ d_Q

Output

Print Q lines.
The i-th line should contain the distance from (a_i, b_i) to (c_i, d_i).

Sample Input 1

2
4 2 7 4
9 9 1 9

Sample Output 1

5
8

Solution in Pascal (FPC 2.6.2) (judge verdict: Wrong Answer)

var
	Q,i,j:Longint;
	T:Array[0..30]of int64;
	a,b,c,d,ans,plus,tmp:int64;
begin
	T[0]:=1;
	for i:=1 to 30 do T[i]:=T[i-1]*3;
	read(Q);
	for i:=1 to Q do begin
		read(a,b,c,d);
		dec(a);
		dec(b);
		dec(c);
		dec(d);
		ans:=abs(a-c)+abs(b-d);
		plus:=0;
		for j:=30 downto 1 do begin
			if(a div T[j-1]=c div T[j-1])and(a div T[j-1]mod 3=1)then begin
				b:=b div T[j-1];
				d:=d div T[j-1];
				if b>d then begin
					tmp:=b;
					b:=d;
					d:=tmp;
				end;
				while b mod 3<>1 do inc(b);
				while(d>=0)and(d mod 3<>1)do dec(d);
				if b<=d then begin
					a:=a mod T[j];
					c:=c mod T[j];
					if a>c then begin
						tmp:=a;
						a:=c;
						c:=tmp;
					end;
					if a+c+1<3*T[j-1]then plus:=a+1-T[j-1]else plus:=2*T[j-1]-c;
					break;
				end;
			end;
			if(b div T[j-1]=d div T[j-1])and(b div T[j-1]mod 3=1)then begin
				a:=a div T[j-1];
				c:=c div T[j-1];
				if a>c then begin
					tmp:=a;
					a:=c;
					c:=tmp;
				end;
				while a mod 3<>1 do inc(a);
				while(c>=0)and(c mod 3<>1)do dec(c);
				if a<=c then begin
					b:=b mod T[j];
					d:=d mod T[j];
					if b>d then begin
						tmp:=b;
						b:=d;
						d:=tmp;
					end;
					if b+d+1<3*T[j-1]then plus:=b+1-T[j-1]else plus:=2*T[j-1]-d;
					break;
				end;
			end;
		end;
		writeln(ans+plus*2);
	end;
end.