Problem:
 Score : 400 points    Problem Statement Along a road running in an east-west direction, there are A shrines and B temples.
The i -th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i -th temple from the west is located at a distance of t_i meters from the west end of the road.  Answer the following Q queries:   Query i ( 1 \leq i \leq Q ): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)       Constraints  1 \leq A, B \leq 10^5  1 \leq Q \leq 10^5  1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}  1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}  1 \leq x_i \leq 10^{10}  s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.  All values in input are integers.         Input Input is given from Standard Input in the following format:  A  B  Q  s_1  :  s_A  t_1  :  t_B  x_1  :  x_Q       Output Print Q lines. The i -th line should contain the answer to the i -th query.        Sample Input 1 2 3 4
100
600
400
900
1000
150
2000
899
799      Sample Output 1 350
1400
301
399  There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.   Query 1 : If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.  Query 2 : If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.  Query 3 : If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.  Query 4 : If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.        Sample Input 2 1 1 3
1
10000000000
2
9999999999
5000000000      Sample Output 2 10000000000
10000000000
14999999998  The road is quite long, and we may need to travel a distance that does not fit into a 32 -bit integer.

Solution (Python):
import bisect
a, b, q = map(int, input().split())
INF = 10**18
shrines = [-INF]+[int(input())for _ in range(a)]
temples = [-INF]+[int(input())for _ in range(b)]

for _ in range(q):
    x = int(input())

    ans = INF
    
    Ri = bisect.bisect_left(shrines, x)
    Li = Ri-1
    if Ri != a+1:
        R = shrines[Ri]
        Rj = bisect.bisect_left(temples, R)
        Lj = Rj-1
        d = INF
        if Rj != b+1:
            d = min(d, temples[Rj]-x)
        if Lj != 0:
            d = min(d, R-temples[Lj]+R-x)
        if d < ans:
            ans = d
    if Li != 0:
        L = shrines[Li]
        Rj = bisect.bisect_left(temples, L)
        Lj = Rj-1
        d = INF
        if Rj != b+1:
            d = min(d, temples[Rj]-L+x-L)
        if Lj != 0:
            d = min(d, x-temples[Lj])
        if d < ans:
            ans = d

    
    Ri = bisect.bisect_left(temples, x)
    Li = Ri-1
    if Ri != b+1:
        R = temples[Ri]
        Rj = bisect.bisect_left(shrines, R)
        Lj = Rj-1
        d = INF
        if Rj != a+1:
            d = min(d, shrines[Rj]-x)
        if Lj != 0:
            d = min(d, R-shrines[Lj]+R-x)
        if d < ans:
            ans = d
    if Li != 0:
        L = temples[Li]
        Rj = bisect.bisect_left(shrines, L)
        Lj = Rj-1
        d = INF
        if Rj != a+1:
            d = min(d, shrines[Rj]-L+x-L)
        if Lj != 0:
            d = min(d, x-shrines[Lj])
        if d < ans:
            ans = d

    print(ans)

Solution (Python):
from bisect import bisect_left
from itertools import product
from sys import maxsize

a, b, q = map(int, input().split())
s = [-maxsize] + [int(input()) for _ in range(a)] + [maxsize]
t = [-maxsize] + [int(input()) for _ in range(b)] + [maxsize]

for _ in range(q):
    x = int(input())
    i = bisect_left(s, x)
    j = bisect_left(t, x)
    res = maxsize
    for ss, tt in product((s[i-1], s[i]), (t[j-1], t[j])):
        res = min(res, abs(ss-x)+abs(tt-ss), abs(tt-x)+abs(ss-tt))
    print(res)

Solution (Python):
import sys
from bisect import bisect_left

input = sys.stdin.readline


def solve(Q, S, T, X):
    ans = [0] * Q
    INF = 10 ** 11
    for q, x in enumerate(X):
        min_dist = INF
        i_s = bisect_left(S, x)
        i_t = bisect_left(T, x)
        for s in (S[i_s - 1], S[i_s]):
            for t in (T[i_t - 1], T[i_t]):
                dist_s2t = abs(x - s) + abs(s - t)
                dist_t2s = abs(x - t) + abs(t - s)
                min_dist = min(min_dist, dist_s2t, dist_t2s)
        ans[q] = min_dist
    return ans


def main():
    A, B, Q = map(int, input().split())
    S = [0] * (A + 2)
    T = [0] * (B + 2)
    X = [0] * Q
    for i in range(1, A + 1):
        S[i] = int(input())
    for i in range(1, B + 1):
        T[i] = int(input())
    for i in range(Q):
        X[i] = int(input())

    S[0] = T[0] = -10 ** 11
    S[-1] = T[-1] = 10 ** 11

    ans = solve(Q, S, T, X)
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Solution (Python):


import bisect
A, B, Q = map(int, input().split())
INF = 10 ** 18
s = [-INF] + [int(input()) for i in range(A)] + [INF]
t = [-INF] + [int(input()) for i in range(B)] + [INF]
for q in range(Q):
    x = int(input())
    b, d = bisect.bisect_left(s, x), bisect.bisect_left(t, x)
    res = INF
    for S in [s[b - 1], s[b]]:
        for T in [t[d - 1], t[d]]:
            d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
            res = min(res, d1, d2)
    print(res)

Solution (Python):

import bisect
A, B, Q = map(int, input().split())
INF = 10 ** 18
s = [-INF] + [int(input()) for i in range(A)] + [INF]
t = [-INF] + [int(input()) for i in range(B)] + [INF]
for q in range(Q):
    x = int(input())
    b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
    res = INF
    for S in [s[b - 1], s[b]]:
        for T in [t[d - 1], t[d]]:
            d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
            res = min(res, d1, d2)
    print(res)

Solution (Python):
import sys

import numba as nb
import numpy as np

input = sys.stdin.readline


@nb.njit("i8(i8[:],i8)", cache=True)
def binary_search(a, key):
    """Meguru type binary search"""
    ng = -1
    ok = len(a)

    def is_ok(a, key, idx):
        if key <= a[idx]:
            return True
        else:
            return False

    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if is_ok(a, key, mid):
            ok = mid
        else:
            ng = mid

    return ok


@nb.njit("i8[:](i8,i8[:],i8[:],i8[:])", cache=True)
def solve(Q, S, T, X):
    ans = np.zeros(shape=Q, dtype=np.int64)
    INF = 10 ** 11
    for q, x in enumerate(X):
        min_dist = INF
        i_s = binary_search(S, x)
        i_t = binary_search(T, x)
        for s in (S[i_s - 1], S[i_s]):
            for t in (T[i_t - 1], T[i_t]):
                dist_s2t = abs(x - s) + abs(s - t)
                dist_t2s = abs(x - t) + abs(t - s)
                min_dist = min(min_dist, dist_s2t, dist_t2s)
        ans[q] = min_dist
    return ans


def main():
    A, B, Q = map(int, input().split())
    S = np.zeros(shape=(A + 2), dtype=np.int64)
    T = np.zeros(shape=(B + 2), dtype=np.int64)
    X = np.zeros(shape=Q, dtype=np.int64)
    for i in range(1, A + 1):
        S[i] = int(input())
    for i in range(1, B + 1):
        T[i] = int(input())
    for i in range(Q):
        X[i] = int(input())

    S[0] = T[0] = -10 ** 11
    S[-1] = T[-1] = 10 ** 11

    ans = solve(Q, S, T, X)
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Solution (Python):
import sys

import numba as nb
import numpy as np

input = sys.stdin.readline


@nb.njit("i8(i8[:],i8)", cache=True)
def binary_search(a, key):
    """Meguru type binary search"""
    ng = -1
    ok = len(a)

    def is_ok(a, key, idx):
        if key <= a[idx]:
            return True
        else:
            return False

    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if is_ok(a, key, mid):
            ok = mid
        else:
            ng = mid

    return ok


@nb.njit("i8[:](i8,i8[:],i8[:],i8[:])", cache=True)
def solve(Q, S, T, X):
    ans = np.zeros(shape=Q, dtype=np.int64)
    INF = 10 ** 11
    for q, x in enumerate(X):
        min_dist = INF
        
        i = binary_search(S, x)
        if 0 < i:
            l_s = S[i - 1]
            dist_s = abs(x - l_s)
            j = binary_search(T, l_s)
            l_t, r_t = T[j - 1], T[j]
            dist_t = min(abs(l_s - l_t), abs(r_t - l_s)) if 0 < j else abs(r_t - l_s)
            min_dist = min(min_dist, dist_s + dist_t)
        r_s = S[i]
        dist_s = abs(r_s - x)
        j = binary_search(T, r_s)
        l_t, r_t = T[j - 1], T[j]
        dist_t = min(abs(r_s - l_t), abs(r_t - r_s)) if 0 < j else abs(r_t - r_s)
        min_dist = min(min_dist, dist_s + dist_t)

        
        i = binary_search(T, x)
        if 0 < i:
            l_t = T[i - 1]
            dist_t = abs(l_t - x)
            j = binary_search(S, l_t)
            l_s, r_s = S[j - 1], S[j]
            dist_s = min(abs(l_t - l_s), abs(r_s - l_t)) if 0 < j else abs(r_s - l_t)
            min_dist = min(min_dist, dist_s + dist_t)
        r_t = T[i]
        dist_t = abs(r_t - x)
        j = binary_search(S, r_t)
        l_s, r_s = S[j - 1], S[j]
        dist_s = min(abs(r_t - l_s), abs(r_s - r_t)) if 0 < j else abs(r_s - r_t)
        min_dist = min(min_dist, dist_s + dist_t)

        ans[q] = min_dist
    return ans


def main():
    A, B, Q = map(int, input().split())
    S = np.zeros(shape=A, dtype=np.int64)
    T = np.zeros(shape=B, dtype=np.int64)
    X = np.zeros(shape=Q, dtype=np.int64)
    for i in range(A):
        S[i] = int(input())
    for i in range(B):
        T[i] = int(input())
    for i in range(Q):
        X[i] = int(input())

    ans = solve(Q, S, T, X)
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Solution (Python):
import sys

import numba as nb
import numpy as np

input = sys.stdin.readline


@nb.njit("i8(i8[:],i8)", cache=True)
def binary_search(a, key):
    """Meguru type binary search"""
    ng = -1
    ok = len(a)

    def is_ok(a, key, idx):
        if key <= a[idx]:
            return True
        else:
            return False

    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if is_ok(a, key, mid):
            ok = mid
        else:
            ng = mid

    return ok


@nb.njit("i8[:](i8,i8[:],i8[:],i8[:])", cache=True)
def solve(Q, S, T, X):
    ans = np.zeros(shape=Q, dtype=np.int64)
    for q, x in enumerate(X):
        min_dist = 10 ** 11
        
        i = binary_search(S, x)
        if 0 < i:
            l_s = S[i - 1]
            dist_s = abs(x - l_s)
            j = binary_search(T, l_s)
            l_t, r_t = T[j - 1], T[j]
            dist_t = min(abs(l_s - l_t), abs(r_t - l_s)) if 0 < j else abs(r_t - l_s)
            min_dist = min(min_dist, dist_s + dist_t)
        r_s = S[i]
        dist_s = abs(r_s - x)
        j = binary_search(T, r_s)
        l_t, r_t = T[j - 1], T[j]
        dist_t = min(abs(r_s - l_t), abs(r_t - r_s)) if 0 < j else abs(r_t - r_s)
        min_dist = min(min_dist, dist_s + dist_t)

        
        i = binary_search(T, x)
        if 0 < i:
            l_t = T[i - 1]
            dist_t = abs(l_t - x)
            j = binary_search(S, l_t)
            l_s, r_s = S[j - 1], S[j]
            dist_s = min(abs(l_t - l_s), abs(r_s - l_t)) if 0 < j else abs(r_s - l_t)
            min_dist = min(min_dist, dist_s + dist_t)
        r_t = T[i]
        dist_t = abs(r_t - x)
        j = binary_search(S, r_t)
        l_s, r_s = S[j - 1], S[j]
        dist_s = min(abs(r_t - l_s), abs(r_s - r_t)) if 0 < j else abs(r_s - r_t)
        min_dist = min(min_dist, dist_s + dist_t)

        ans[q] = min_dist
    return ans


def main():
    A, B, Q = map(int, input().split())
    S = np.zeros(shape=A, dtype=np.int64)
    T = np.zeros(shape=B, dtype=np.int64)
    X = np.zeros(shape=Q, dtype=np.int64)
    for i in range(A):
        S[i] = int(input())
    for i in range(B):
        T[i] = int(input())
    for i in range(Q):
        X[i] = int(input())

    ans = solve(Q, S, T, X)
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Solution (Python):
import numpy as np
import sys
input = sys.stdin.buffer.readline

a, b, q = map(int,input().split())
ab = [[-1, -10**11], [-1, 10**11]]
aa = [-10**11, 10**11]
bb = [-10**11, 10**11]
for i in range(a):
    x = int(input())
    ab.append([0, x])
    aa.append(x)
    
for i in range(b):
    x = int(input())
    ab.append([1, x])
    bb.append(x)
ab = sorted(ab, key=lambda x:(x[1], x[0]))
aa.sort()
bb.sort()

ab_arr = np.array(ab)
ab_arr = ab_arr.T[1]

a_arr = np.array(aa)
b_arr = np.array(bb)

for cq in range(q):
    ans = 10**12
    s = int(input())
    ci = np.searchsorted(ab_arr, s)
    for cj in [ci, ci-1]:
        d = abs(ab_arr[cj] - s)
        flg = ab[cj][0]
        if flg:
            na = np.searchsorted(a_arr, ab_arr[cj])
            d2 = min(abs(a_arr[na] - ab_arr[cj]), abs(a_arr[na-1] - ab_arr[cj]))
            d += d2
        else:
            nb = np.searchsorted(b_arr, ab_arr[cj])
            d2 = min(abs(b_arr[nb] - ab_arr[cj]), abs(b_arr[nb-1] - ab_arr[cj]))
            d += d2
        ans = min(ans, d)
    print(ans)

Solution (Python):
import bisect
INF = 10**13
A, B, Q = map(int, input().split())
S = [int(input()) for a in range(A)]
T = [int(input()) for b in range(B)]
for q in range(Q):
    x = int(input())
    si = bisect.bisect_left(S, x)
    ti = bisect.bisect_left(T, x)
    Sq = [S[max(si-1, 0)], S[min(si, A-1)]]
    Tq = [T[max(ti-1, 0)], T[min(ti, B-1)]]
    ans = float('inf')
    for i in range(2):
        for j in range(2):
            s = Sq[i]
            t = Tq[j]
            if (s < x and t < x) or (x < s and x < t):
                xs, tx = abs(x-s), abs(x-t)
                ans = min(ans, max(xs, tx))
            else:
                xs, tx = abs(s-x), abs(t-x)
                ans = min(ans, min(xs, tx)*2 + max(xs, tx))

    print(ans)

Solution (Python):
from bisect import bisect_left
a,b,q = map(int,input().split())
INF = 10**15
s = [-INF] + sorted([int(input()) for _  in range(a)]) + [INF]
t = [-INF] + sorted([int(input()) for _  in range(b)]) + [INF]

for i in range(q):
    pro = int(input())
    s_index = bisect_left(s, pro)
    t_index = bisect_left(t, pro)
    s1,s2 = s[s_index-1] , s[s_index]
    t1,t2 = t[t_index-1] , t[t_index]
    
    minimum = []
    kouho1 = abs(pro-s1)+ abs(s1-t1)
    minimum.append(kouho1)
    kouho2 = abs(pro-s1)+ abs(s1-t2)
    minimum.append(kouho2)
    kouho3 = abs(pro-t1)+ abs(t1-s1)
    minimum.append(kouho3)
    kouho4 = abs(pro-t2)+ abs(t2-s1)
    minimum.append(kouho4)
    kouho5 = abs(pro-s2)+ abs(s2-t1)
    minimum.append(kouho5)
    kouho6 = abs(pro-s2)+ abs(s2-t2)
    minimum.append(kouho6)
    kouho7 = abs(pro-t1)+ abs(s2-t1)
    minimum.append(kouho7)
    kouho8 = abs(pro-t2)+ abs(s2-t2)
    minimum.append(kouho8)
    print(min(minimum))

Solution (Python):
import bisect

a,b,q = map(int,input().split())
shrine = [-10**12, 10**12]
for _ in range(a):
    s = int(input())
    shrine.append(s)
shrine.sort()

temple = [-10**12, 10**12]
for _ in range(b):
    t = int(input())
    temple.append(t)
temple.sort()

for _ in range(q):
    x = int(input())
    sx = bisect.bisect_right(shrine,x)
    tx = bisect.bisect_right(temple,x)
    ans = 10**12
    
    for i in [shrine[sx-1], shrine[sx]]:
        for j in [temple[tx-1], temple[tx]]:
            
            case_1 = abs(i-x)+abs(i-j)
            
            case_2 = abs(j-x)+abs(i-j)
            ans = min(ans,case_1,case_2)
            
    print(ans)

Solution (Python):
import bisect

a,b,q = map(int,input().split())
shrine = [-10**12, 10**12]
for _ in range(a):
    s = int(input())
    shrine.append(s)
shrine.sort()

temple = [-10**12, 10**12]
for _ in range(b):
    t = int(input())
    temple.append(t)
temple.sort()

for _ in range(q):
    x = int(input())
    sx = bisect.bisect_right(shrine,x)
    tx = bisect.bisect_right(temple,x)
    ans = 10**12
    for i in [shrine[sx-1], shrine[sx]]:
        for j in [temple[tx-1], temple[tx]]:
            case_1 = abs(i-x)+abs(i-j)
            case_2 = abs(j-x)+abs(i-j)
            ans = min(ans,case_1,case_2)
            
    print(ans)

Solution (Python):
import bisect
A, B, Q = map(int, input().split())
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
X = [int(input()) for _ in range(Q)]

def D(a,b,c):
    return abs(a-b) + abs(b-c)

def getAns(x):
    ret = 10**18
    U = [S, T]
    for k in range(len(U)):
        u = U[k]
        v = U[(k-1)%2]
        idx = bisect.bisect_left(u, x)
        for i in [idx-1, idx]:
            if not 0<=i<len(u):
                continue
            idxx = bisect.bisect_left(v, u[i])
            for j in [idxx-1, idxx]:
                if 0<=j<len(v):
                    ret = min(ret, D(x, u[i], v[j]))
    return ret

for x in X:
    print(getAns(x))

Solution (Python):
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue



sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7


ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))






def main():
    a, b, q = ns()
    s = [ni() for _ in range(a)]
    t = [ni() for _ in range(b)]

    def disLR(a, idx):
        small = a[max(0, idx - 1)]
        large = a[min(len(a) - 1, idx)]
        return [small, large]

    for _ in range(q):
        ans = INF

        x = ni()

        idxs = bisect.bisect_left(s, x)
        a1 = disLR(s, idxs)

        idxt = bisect.bisect_left(t, x)
        a2 = disLR(t, idxt)

        for ta1 in a1:
            for ta2 in a2:
                tmp1 = abs(x - ta1) + abs(ta2 - ta1)
                tmp2 = abs(x - ta2) + abs(ta1 - ta2)
                ans = min(ans, tmp1, tmp2)

        print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue



sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7


ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))




def disLR(a, idx):
    small = a[max(0, idx - 1)]
    large = a[min(len(a) - 1, idx)]
    return [small, large]


def main():
    a, b, q = ns()
    s = [ni() for _ in range(a)]
    t = [ni() for _ in range(b)]

    for _ in range(q):
        ans = INF

        x = ni()

        idxs = bisect.bisect_left(s, x)
        a1 = disLR(s, idxs)

        idxt = bisect.bisect_left(t, x)
        a2 = disLR(t, idxt)

        for ta1 in a1:
            for ta2 in a2:
                tmp1 = abs(x - ta1) + abs(ta2 - ta1)
                tmp2 = abs(x - ta2) + abs(ta1 - ta2)
                ans = min(ans, tmp1, tmp2)

        print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue



sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7


ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))




def disLR(a, idx):
    small = a[max(0, idx - 1)]
    large = a[min(len(a) - 1, idx)]
    return [small, large]


def main():
    a, b, q = ns()
    s = [ni() for _ in range(a)]
    t = [ni() for _ in range(b)]

    for _ in range(q):
        ans = INF

        x = ni()

        idxs = bisect.bisect_left(s, x)
        a1 = disLR(s, idxs)

        idxt = bisect.bisect_left(t, x)
        a2 = disLR(t, idxt)

        for ta1 in a1:
            for ta2 in a2:
                tmp1 = abs(x - ta1) + abs(ta2 - ta1)
                tmp2 = abs(x - ta2) + abs(ta1 - ta2)
                ans = min(ans, tmp1, tmp2)

        print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue



sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7


ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))




def disLR(a, idx):
    small = a[max(0, idx - 1)]
    large = a[min(len(a) - 1, idx)]
    return small, large


def main():
    a, b, q = ns()
    s = [ni() for _ in range(a)]
    t = [ni() for _ in range(b)]

    for _ in range(q):
        ans = INF

        x = ni()
        tmpans = [0] * 4

        idxs = bisect.bisect_left(s, x)
        sml, lrg = disLR(s, idxs)
        tmpans[0] += abs(x - sml)
        tmpans[1] += abs(x - lrg)
        idxsml = bisect.bisect_left(t, sml)
        tmpans[0] += min([abs(sml - i) for i in disLR(t, idxsml)])
        idxlrg = bisect.bisect_left(t, lrg)
        tmpans[1] += min([abs(lrg - i) for i in disLR(t, idxlrg)])

        idxt = bisect.bisect_left(t, x)
        sml, lrg = disLR(t, idxt)
        tmpans[2] += abs(x - sml)
        tmpans[3] += abs(x - lrg)
        idxsml = bisect.bisect_left(s, sml)
        tmpans[2] += min([abs(sml - i) for i in disLR(s, idxsml)])
        idxlrg = bisect.bisect_left(s, lrg)
        tmpans[3] += min([abs(lrg - i) for i in disLR(s, idxlrg)])
        ans = min(ans, min(tmpans))
        print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue



sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7


ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))




def disLR(a, idx):
    small = a[max(0, idx - 1)]
    large = a[min(len(a) - 1, idx)]
    return small, large


def main():
    a, b, q = ns()
    s = [ni() for _ in range(a)]
    t = [ni() for _ in range(b)]

    for _ in range(q):
        ans = INF

        x = ni()
        tmpans = [0] * 4

        idxs = bisect.bisect_left(s, x)
        sml, lrg = disLR(s, idxs)
        tmpans[0] += abs(x - sml)
        tmpans[1] += abs(x - lrg)
        idxsml = bisect.bisect_left(t, sml)
        tmpans[0] += min([abs(sml - i) for i in disLR(t, idxsml)])
        idxlrg = bisect.bisect_left(t, lrg)
        tmpans[1] += min([abs(lrg - i) for i in disLR(t, idxlrg)])

        idxt = bisect.bisect_left(t, x)
        sml, lrg = disLR(t, idxt)
        tmpans[2] += abs(x - sml)
        tmpans[3] += abs(x - lrg)
        idxsml = bisect.bisect_left(s, sml)
        tmpans[2] += min([abs(sml - i) for i in disLR(s, idxsml)])
        idxlrg = bisect.bisect_left(s, lrg)
        tmpans[3] += min([abs(lrg - i) for i in disLR(s, idxlrg)])
        ans = min(ans, min(tmpans))
        print(ans)


if __name__ == '__main__':
    main()

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 

from decimal import *



A, B, Q = MAP()
s = [-INF] + [INT() for _ in range(A)] + [INF]
t = [-INF] + [INT() for _ in range(B)] + [INF]

for _ in range(Q):
	x = INT()
	idx_s = bisect(s, x)
	idx_t = bisect(t, x)

	ans = INF
	for S, T in product([idx_s, idx_s-1], [idx_t, idx_t-1]):
		if min(s[S], t[T]) <= x <= max(s[S], t[T]):
			tmp = abs(s[S]-t[T]) + min(abs(x-s[S]), abs(x-t[T]))
		else:
			tmp = max(abs(x-s[S]), abs(x-t[T]))
		ans = min(ans, tmp)

	for S in [idx_s, idx_s-1]:
		for T in [idx_t, idx_t-1]:
			tmp = min(abs(x-s[S])+abs(s[S]-t[T]), abs(x-t[T])+abs(s[S]-t[T]))
			ans = min(ans, tmp)

	print(ans)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 

from decimal import *



A, B, Q = MAP()
s = [-INF] + [INT() for _ in range(A)] + [INF]
t = [-INF] + [INT() for _ in range(B)] + [INF]

for _ in range(Q):
	x = INT()
	idx_s = bisect(s, x)
	idx_t = bisect(t, x)

	ans = INF
	for S, T in product([idx_s, idx_s-1], [idx_t, idx_t-1]):
		if min(s[S], t[T]) <= x <= max(s[S], t[T]):
			tmp = abs(s[S]-t[T]) + min(abs(x-s[S]), abs(x-t[T]))
		else:
			tmp = max(abs(x-s[S]), abs(x-t[T]))
		ans = min(ans, tmp)

	print(ans)

Solution (Python):
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 

from decimal import *



A, B, Q = MAP()
s = [INT() for _ in range(A)]
t = [INT() for _ in range(B)]

for _ in range(Q):
	x = INT()
	idx_s = bisect(s, x)
	idx_t = bisect(t, x)

	S = []
	T = []
	if 0 < idx_s:
		S.append(s[idx_s-1])
	if idx_s < A:
		S.append(s[idx_s])

	if 0 < idx_t:
		T.append(t[idx_t-1])
	if idx_t < B:
		T.append(t[idx_t])

	ans = INF
	for shrine, temple in product(S, T):
		if min(shrine, temple) <= x <= max(shrine, temple):
			tmp = abs(shrine-temple) + min(abs(x-shrine), abs(x-temple))
		else:
			tmp = max(abs(x-shrine), abs(x-temple))
		ans = min(ans, tmp)

	print(ans)

Solution (Python):
from bisect import *
a, b, q = map(int,input().split())
s = [int(input()) for _ in range(a)]
t = [int(input()) for _ in range(b)]
inf = 10 ** 18
s = [-inf] + s + [inf]
t = [-inf] + t + [inf]

for i in range(q):
    x = int(input())
    s_ind = bisect_left(s, x)
    t_ind = bisect_left(t, x)
    
    res = inf
    for cand_s in [s[s_ind - 1], s[s_ind]]:
        for cand_t in [t[t_ind - 1], t[t_ind]]:
            st = abs(cand_s - cand_t)
            dx = min(abs(cand_s - x), abs(cand_t - x))
            
            res = min(res, st + dx)
    
    print(res)

Solution (Python):
from bisect import *
a, b, q = map(int,input().split())
s = [int(input()) for _ in range(a)]
t = [int(input()) for _ in range(b)]
inf = 10 ** 18
s = [-inf] + s + [inf]
t = [-inf] + t + [inf]

for i in range(q):
    x = int(input())
    s_ind = bisect_left(s, x)
    t_ind = bisect_left(t, x)
    
    res = inf
    for cand_s in [s[s_ind - 1], s[s_ind]]:
        for cand_t in [t[t_ind - 1], t[t_ind]]:
            st = abs(cand_s - cand_t)
            dx = min(abs(cand_s - x), abs(cand_t - x))
            
            res = min(res, st + dx)
    
    print(res)

Solution (Python):
import bisect
A, B, Q = map(int, input().split())
INF=10**18
s =[-INF] + [int(input()) for i in range(A)] + [INF]
t =[-INF] + [int(input()) for i in range(B)] + [INF]
for q in range(Q):
  x = int(input())
  b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x) 
  res = INF
  for S in [s[b - 1], s[b]]:
    for T in [t[d - 1], t[d]]:
      d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T) 
      res = min(res, d1, d2)
  print(res)

Solution (Python):
def main():
    from bisect import bisect_left
    import sys
    input = sys.stdin.buffer.readline
    def near(A, x):
        return [A[(i:=bisect_left(A, x)) - 1], A[i]]
    a, b, q = map(int, input().split())
    INF = 10 ** 15
    S = [-INF] + [int(input()) for _ in range(a)] + [INF]
    T = [-INF] + [int(input()) for _ in range(b)] + [INF]
    for _ in range(q):
        x = int(input())
        print(min([min(abs(s - x) + abs(t - s), abs(t - x) + abs(s - t)) for s in near(S, x) for t in near(T, x)]))

if __name__ == '__main__':
    main()