## GUPTA MECHANICAL

IN THIS WEBSITE I CAN TELL ALL ABOUT TECH. TIPS AND TRICKS APP REVIEWS AND UNBOXINGS ALSO TECH. NEWS .............

## Labyrinth Adventures Codeforces Solution | Codeforces Problem Solution 2022

time limit per test
6 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

You found a map of a weirdly shaped labyrinth. The map is a grid, consisting of $n$ rows and $n$ columns. The rows of the grid are numbered from $1$ to $n$ from bottom to top. The columns of the grid are numbered from $1$ to $n$ from left to right.

The labyrinth has $n$ layers. The first layer is the bottom left corner (cell $\left(1,1\right)$). The second layer consists of all cells that are in the grid and adjacent to the first layer by a side or a corner.

The third layer consists of all cells that are in the grid and adjacent to the second layer by a side or a corner. And so on.

The labyrinth with $5$ layers, for example, is shaped as follows:

The layers are separated from one another with walls. However, there are doors in these walls.

Each layer (except for layer $n$) has exactly two doors to the next layer. One door is placed on the top wall of the layer and another door is placed on the right wall of the layer. For each layer from $1$ to $n-1$ you are given positions of these two doors. The doors can be passed in both directions: either from layer $i$ to layer $i+1$ or from layer $i+1$ to layer $i$.

If you are standing in some cell, you can move to an adjacent by a side cell if a wall doesn't block your move (e.g. you can't move to a cell in another layer if there is no door between the cells).

Now you have $m$ queries of sort: what's the minimum number of moves one has to make to go from cell $\left({x}_{1},{y}_{1}\right)$ to cell $\left({x}_{2},{y}_{2}\right)$.

Input

The first line contains a single integer $n$ ($2\le n\le {10}^{5}$) — the number of layers in the labyrinth.

The $i$-th of the next $n-1$ lines contains four integers ${d}_{1,x},{d}_{1,y},{d}_{2,x}$ and ${d}_{2,y}$ ($1\le {d}_{1,x},{d}_{1,y},{d}_{2,x},{d}_{2,y}\le n$) — the coordinates of the doors. Both cells are on the $i$-th layer. The first cell is adjacent to the top wall of the $i$-th layer by a side — that side is where the door is. The second cell is adjacent to the right wall of the $i$-th layer by a side — that side is where the door is.

The next line contains a single integer $m$ ($1\le m\le 2\cdot {10}^{5}$) — the number of queries.

The $j$-th of the next $m$ lines contains four integers ${x}_{1},{y}_{1},{x}_{2}$ and ${y}_{2}$ ($1\le {x}_{1},{y}_{1},{x}_{2},{y}_{2}\le n$) — the coordinates of the cells in the $j$-th query.

Output

For each query, print a single integer — the minimum number of moves one has to make to go from cell $\left({x}_{1},{y}_{1}\right)$ to cell $\left({x}_{2},{y}_{2}\right)$.