Labyrinth Adventures (Codeforces 1681E)
Tags: Others, matrices

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 $$$(1, 1)$$$). 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 $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$.

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 $$$(x_1, y_1)$$$ to cell $$$(x_2, y_2)$$$.

Note: Here is the map of the labyrinth from the second example. The doors are marked red.  

Sample Inputs:
2
1 1 1 1
10
1 1 1 1
1 1 1 2
1 1 2 1
1 1 2 2
1 2 1 2
1 2 2 1
1 2 2 2
2 1 2 1
2 1 2 2
2 2 2 2

4
1 1 1 1
2 1 2 2
3 2 1 3
5
2 4 4 3
4 4 3 3
1 2 3 3
2 2 4 4
1 4 2 3

Sample Outputs:
0
1
1
2
0
2
1
0
1
0

3
4
3
6
2

Solution (Python):
(standard_input, packages, output_together) = (1, 1, 0)
(dfs, hashing, read_from_file) = (0, 0, 0)
de = 1
if 1:
    if standard_input:
        import io, os, sys
        input = lambda : sys.stdin.readline().strip()
        import math
        inf = math.inf

        def I():
            return input()

        def II():
            return int(input())

        def MII():
            return map(int, input().split())

        def LI():
            return list(input().split())

        def LII():
            return list(map(int, input().split()))

        def LFI():
            return list(map(float, input().split()))

        def GMI():
            return map(lambda x: int(x) - 1, input().split())

        def LGMI():
            return list(map(lambda x: int(x) - 1, input().split()))
    if packages:
        from io import BytesIO, IOBase
        import random
        import os
        import bisect
        import typing
        from collections import Counter, defaultdict, deque
        from copy import deepcopy
        from functools import cmp_to_key, lru_cache, reduce
        from heapq import merge, heapify, heappop, heappush, heappushpop, nlargest, nsmallest
        from itertools import accumulate, combinations, permutations, count, product
        from operator import add, iand, ior, itemgetter, mul, xor
        from string import ascii_lowercase, ascii_uppercase, ascii_letters
        from typing import *
        BUFSIZE = 4096
    if output_together:

        class FastIO(IOBase):
            newlines = 0

            def __init__(self, file):
                self._fd = file.fileno()
                self.buffer = BytesIO()
                self.writable = 'x' in file.mode or 'r' not in file.mode
                self.write = self.buffer.write if self.writable else None

            def read(self):
                while True:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    if not b:
                        break
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines = 0
                return self.buffer.read()

            def readline(self):
                while self.newlines == 0:
                    b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
                    self.newlines = b.count(b'\n') + (not b)
                    ptr = self.buffer.tell()
                    (self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
                self.newlines -= 1
                return self.buffer.readline()

            def flush(self):
                if self.writable:
                    os.write(self._fd, self.buffer.getvalue())
                    (self.buffer.truncate(0), self.buffer.seek(0))

        class IOWrapper(IOBase):

            def __init__(self, file):
                self.buffer = FastIO(file)
                self.flush = self.buffer.flush
                self.writable = self.buffer.writable
                self.write = lambda s: self.buffer.write(s.encode('ascii'))
                self.read = lambda : self.buffer.read().decode('ascii')
                self.readline = lambda : self.buffer.readline().decode('ascii')
        sys.stdout = IOWrapper(sys.stdout)
    if dfs:
        from types import GeneratorType

        def bootstrap(f, stack=[]):

            def wrappedfunc(*args, **kwargs):
                if stack:
                    return f(*args, **kwargs)
                else:
                    to = f(*args, **kwargs)
                    while True:
                        if type(to) is GeneratorType:
                            stack.append(to)
                            to = next(to)
                        else:
                            stack.pop()
                            if not stack:
                                break
                            to = stack[-1].send(to)
                    return to
            return wrappedfunc
    if hashing:
        RANDOM = random.getrandbits(20)

        class Wrapper(int):

            def __init__(self, x):
                int.__init__(x)

            def __hash__(self):
                return super(Wrapper, self).__hash__() ^ RANDOM
    if read_from_file:
        file = open('input.txt', 'r').readline().strip()[1:-1]
        fin = open(file, 'r')
        input = lambda : fin.readline().strip()
        output_file = open('output.txt', 'w')

        def fprint(*args, **kwargs):
            print(*args, **kwargs, file=output_file)
    if de:

        def debug(*args, **kwargs):
            print('\x1b[92m', end='')
            print(*args, **kwargs)
            print('\x1b[0m', end='')
outs = []
n = II()
pos1 = []
pos2 = []
for _ in range(n - 1):
    (x1, y1, x2, y2) = GMI()
    pos1.append(y1)
    pos2.append(x2)
dist = [[n * n] * (4 * (n - 2)) for _ in range(n.bit_length())]
for i in range(n - 2):
    dist[0][4 * i] = abs(pos1[i] - pos1[i + 1]) + 1
    dist[0][4 * i + 1] = min(i * 2 - pos1[i] - pos2[i] + abs(pos2[i] - pos2[i + 1]), (i + 1) * 2 - pos1[i] - pos2[i + 1]) + 1
    dist[0][4 * i + 2] = min(i * 2 - pos1[i] - pos2[i] + abs(pos1[i] - pos1[i + 1]), (i + 1) * 2 - pos1[i + 1] - pos2[i]) + 1
    dist[0][4 * i + 3] = abs(pos2[i] - pos2[i + 1]) + 1
for j in range(n.bit_length() - 1):
    for i in range(n - 2 - (1 << j)):
        tmp = i + (1 << j)
        dist[j + 1][4 * i] = min(dist[j][4 * i] + dist[j][4 * tmp], dist[j][4 * i + 1] + dist[j][4 * tmp + 2])
        dist[j + 1][4 * i + 1] = min(dist[j][4 * i] + dist[j][4 * tmp + 1], dist[j][4 * i + 1] + dist[j][4 * tmp + 3])
        dist[j + 1][4 * i + 2] = min(dist[j][4 * i + 2] + dist[j][4 * tmp], dist[j][4 * i + 3] + dist[j][4 * tmp + 2])
        dist[j + 1][4 * i + 3] = min(dist[j][4 * i + 3] + dist[j][4 * tmp + 3], dist[j][4 * i + 2] + dist[j][4 * tmp + 1])
q = II()
for _ in range(q):
    (x1, y1, x2, y2) = GMI()
    if max(x1, y1) == max(x2, y2):
        outs.append(abs(x1 - x2) + abs(y1 - y2))
    else:
        if max(x1, y1) > max(x2, y2):
            (x1, x2) = (x2, x1)
            (y1, y2) = (y2, y1)
        (p1, p2) = (max(x1, y1), max(x2, y2))
        d11 = abs(y1 - pos1[p1]) if x1 == p1 else 2 * p1 - pos1[p1] - x1
        d12 = abs(x1 - pos2[p1]) if y1 == p1 else 2 * p1 - pos2[p1] - y1
        d21 = abs(y2 - pos1[p2 - 1]) if x2 == p2 else 2 * p2 - pos1[p2 - 1] - x2
        d22 = abs(x2 - pos2[p2 - 1]) if y2 == p2 else 2 * p2 - pos2[p2 - 1] - y2
        d21 += 1
        d22 += 1
        (f0, f1, f2, f3) = (0, n * n, n * n, 0)
        p = p1
        d = p2 - p1 - 1
        while d:
            x = d & -d
            i = x.bit_length() - 1
            (f0, f1, f2, f3) = (min(f0 + dist[i][4 * p], f1 + dist[i][4 * p + 2]), min(f0 + dist[i][4 * p + 1], f1 + dist[i][4 * p + 3]), min(f2 + dist[i][4 * p], f3 + dist[i][4 * p + 2]), min(f2 + dist[i][4 * p + 1], f3 + dist[i][4 * p + 3]))
            d -= x
            p += x
        outs.append(min(d11 + f0 + d21, d11 + f1 + d22, d12 + f2 + d21, d12 + f3 + d22))
print('\n'.join(map(str, outs)))

Solution (Python):
import sys
input = sys.stdin.readline
from typing import List, Tuple
INF = 10 ** 18
N = int(input())
inpos: List[Tuple[Tuple[int, int], Tuple[int, int]]] = [((0, 0), (0, 0))] * N
outpos = list(inpos)
for i in range(1, N):
    (yt, xt, yr, xr) = map(int, input().split())
    assert yt == xr == i, i
    outpos[i - 1] = ((xt - 1, yt - 1), (xr - 1, yr - 1))
    inpos[i] = ((xt - 1, yt), (xr, yr - 1))

def dist(x1, y1, x2, y2) -> int:
    return abs(x1 - x2) + abs(y1 - y2)
M = int(input())
O = [INF] * M
qs = []
for i in range(M):
    (y1, x1, y2, x2) = map(lambda s: int(s) - 1, input().split())
    if max(x1, y1) > max(x2, y2):
        (x1, y1, x2, y2) = (x2, y2, x1, y1)
    if max(x1, y1) == max(x2, y2):
        O[i] = dist(x1, y1, x2, y2)
    else:
        qs.append((x1, y1, x2, y2, i))
D = [[0, 0] for _ in range(N)]

def solve(lo: int, hi: int, qs: List[Tuple]):
    m = (lo + hi) // 2
    (left, here, right) = ([], [], [])
    for t in qs:
        (x1, y1, x2, y2, qi) = t
        if max(x2, y2) < m:
            left.append(t)
        elif max(x1, y1) >= m:
            right.append(t)
        else:
            here.append(t)
    if left:
        solve(lo, m, left)
    if right:
        solve(m, hi, right)
    if here:
        assert m > 0
        for mdoor in range(2):
            (tdoor, rdoor) = inpos[m]
            D[m] = [0, dist(*tdoor, *rdoor)]
            if mdoor:
                D[m].reverse()
            for i in range(m, hi - 1):
                (in_tdoor, in_rdoor) = inpos[i]
                (out_tdoor, out_rdoor) = outpos[i]
                D[i + 1][0] = min(D[i][0] + dist(*in_tdoor, *out_tdoor) + 1, D[i][1] + dist(*in_rdoor, *out_tdoor) + 1)
                D[i + 1][1] = min(D[i][0] + dist(*in_tdoor, *out_rdoor) + 1, D[i][1] + dist(*in_rdoor, *out_rdoor) + 1)
            for i in range(m - 1, lo - 1, -1):
                (in_tdoor, in_rdoor) = outpos[i]
                (out_tdoor, out_rdoor) = inpos[i]
                D[i][0] = min(D[i + 1][0] + dist(*in_tdoor, *out_tdoor) + 1, D[i + 1][1] + dist(*in_rdoor, *out_tdoor) + 1)
                D[i][1] = min(D[i + 1][0] + dist(*in_tdoor, *out_rdoor) + 1, D[i + 1][1] + dist(*in_rdoor, *out_rdoor) + 1)
            for (x1, y1, x2, y2, qi) in here:
                (l1, l2) = (max(x1, y1), max(x2, y2))
                assert l1 < m and l2 >= m
                (in_tdoor, in_rdoor) = inpos[l2]
                (d_in_tdoor, d_in_rdoor) = D[l2]
                (out_tdoor, out_rdoor) = outpos[l1]
                (d_out_tdoor, d_out_rdoor) = D[l1 + 1]
                d_out_tdoor += 1
                d_out_rdoor += 1
                dr = min(dist(x2, y2, *in_tdoor) + d_in_tdoor, dist(x2, y2, *in_rdoor) + d_in_rdoor)
                dl = min(dist(x1, y1, *out_tdoor) + d_out_tdoor, dist(x1, y1, *out_rdoor) + d_out_rdoor)
                O[qi] = min(O[qi], dl + dr)
solve(0, N, qs)
print('\n'.join(map(str, O)))

Solution (Python):
import sys
input = sys.stdin.readline
from typing import List, Tuple
INF = 10 ** 18
N = int(input())
inpos: List[Tuple[Tuple[int, int], Tuple[int, int]]] = [((0, 0), (0, 0))] * N
outpos = list(inpos)
for i in range(1, N):
    (yt, xt, yr, xr) = map(int, input().split())
    assert yt == xr == i, i
    outpos[i - 1] = ((xt - 1, yt - 1), (xr - 1, yr - 1))
    inpos[i] = ((xt - 1, yt), (xr, yr - 1))

def dist(x1, y1, x2, y2) -> int:
    return abs(x1 - x2) + abs(y1 - y2)
M = int(input())
O = [INF] * M
qs = []
for i in range(M):
    (y1, x1, y2, x2) = map(lambda s: int(s) - 1, input().split())
    if max(x1, y1) > max(x2, y2):
        (x1, y1, x2, y2) = (x2, y2, x1, y1)
    if max(x1, y1) == max(x2, y2):
        O[i] = dist(x1, y1, x2, y2)
    else:
        qs.append((x1, y1, x2, y2, i))
D = [[0, 0] for _ in range(N)]

def solve(lo: int, hi: int, qs: List[Tuple]):
    m = (lo + hi) // 2
    (left, here, right) = ([], [], [])
    for t in qs:
        (x1, y1, x2, y2, qi) = t
        if max(x2, y2) < m:
            left.append(t)
        elif max(x1, y1) >= m:
            right.append(t)
        else:
            here.append(t)
    if here:
        assert m > 0
        for mdoor in range(2):
            (tdoor, rdoor) = inpos[m]
            D[m] = [0, dist(*tdoor, *rdoor)]
            if mdoor:
                D[m].reverse()
            for i in range(m, hi - 1):
                (in_tdoor, in_rdoor) = inpos[i]
                (out_tdoor, out_rdoor) = outpos[i]
                D[i + 1][0] = min(D[i][0] + dist(*in_tdoor, *out_tdoor) + 1, D[i][1] + dist(*in_rdoor, *out_tdoor) + 1)
                D[i + 1][1] = min(D[i][0] + dist(*in_tdoor, *out_rdoor) + 1, D[i][1] + dist(*in_rdoor, *out_rdoor) + 1)
            for i in range(m - 1, lo - 1, -1):
                (in_tdoor, in_rdoor) = outpos[i]
                (out_tdoor, out_rdoor) = inpos[i]
                D[i][0] = min(D[i + 1][0] + dist(*in_tdoor, *out_tdoor) + 1, D[i + 1][1] + dist(*in_rdoor, *out_tdoor) + 1)
                D[i][1] = min(D[i + 1][0] + dist(*in_tdoor, *out_rdoor) + 1, D[i + 1][1] + dist(*in_rdoor, *out_rdoor) + 1)
            for (x1, y1, x2, y2, qi) in here:
                (l1, l2) = (max(x1, y1), max(x2, y2))
                assert l1 < m and l2 >= m
                (in_tdoor, in_rdoor) = inpos[l2]
                (d_in_tdoor, d_in_rdoor) = D[l2]
                (out_tdoor, out_rdoor) = outpos[l1]
                (d_out_tdoor, d_out_rdoor) = D[l1 + 1]
                d_out_tdoor += 1
                d_out_rdoor += 1
                dr = min(dist(x2, y2, *in_tdoor) + d_in_tdoor, dist(x2, y2, *in_rdoor) + d_in_rdoor)
                dl = min(dist(x1, y1, *out_tdoor) + d_out_tdoor, dist(x1, y1, *out_rdoor) + d_out_rdoor)
                O[qi] = min(O[qi], dl + dr)
    if left:
        solve(lo, m, left)
    if right:
        solve(m, hi, right)
solve(0, N, qs)
print('\n'.join(map(str, O)))