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):
from bisect import bisect

a, b, q = map(int, input().split())
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
x = [int(input()) for i in range(q)]

sentinel = lambda x: [-9e20] + x + [9e20]
s = sentinel(s)
t = sentinel(t)

for i in x:
    ss = bisect(s, i)
    tt = bisect(t, i)

    ll = max(s[ss], t[tt]) - i
    rr = i - min(s[ss-1], t[tt-1])
    rl = min((s[ss]- i) + s[ss] - t[tt-1], (t[tt]- i) + t[tt] - s[ss-1])
    lr = min((i - s[ss-1]) + t[tt] - s[ss-1], (i - t[tt-1]) + s[ss] - t[tt-1])

    print(min(ll, rr, rl, lr))

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

for q in range(q):
    x = int(input())
    m,n = bisect.bisect_right(shrine,x),bisect.bisect_right(temple,x)
    res = inf
    for s in [shrine[m-1],shrine[m]]:
        for t in [temple[n-1],temple[n]]:
            d1,d2 = abs(s-x)+abs(t-s),abs(t-x)+abs(s-t)
            res = min(res,d1,d2)
    print(res)

Solution (Python):
from bisect import bisect

a, b, q = map(int, input().split())
ss = [int(input()) for _ in range(a)]
tt = [int(input()) for _ in range(b)]
xx = [int(input()) for _ in range(q)]

def nearest2(ssortt, position) :
    l = len(ssortt)
    i = bisect(ssortt, position)
    if i == 0 : return (ssortt[0],)
    if i == l : return (ssortt[-1],)
    return (ssortt[i-1], ssortt[i])

for x in xx :
    ll = []
    for s in nearest2(ss, x) :
        for t in nearest2(tt, s) :
            ll.append(abs(s-x)+abs(t-s))
    for t in nearest2(tt, x) :
        for s in nearest2(ss, t) :
            ll.append(abs(t-x)+abs(s-t))
    print(min(ll))

Solution (Python):



import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline



a,b,q = [int(i) for i in readline().split()]
s = [-10**12]+[int(readline()) for i in range(a)]+[10**12]
t = [-10**12]+[int(readline()) for i in range(b)]+[10**12]

xx = [int(readline()) for i in range(q)]

from bisect import *
for x in xx:
    ans = 10**11
    i = bisect_left(s,x)
    j = bisect_left(t,x)
    d1 = max(s[i],t[j])-x
    d2 = x- min(s[i-1],t[j-1])

    d3 = (x-s[i-1]) + (t[j]-x) + min((x-s[i-1]), (t[j]-x))
    d4 = (x-t[j-1]) + (s[i]-x) + min((x-t[j-1]), (s[i]-x))


    ans = min(ans,d1,d2,d3,d4)
    print(ans)

Solution (Python):
import sys, bisect
input = sys.stdin.readline

a, b, q = map(int, input().split())
al = [-float("INF")] + [int(input()) for _ in range(a)] + [float("INF")]
bl = [-float("INF")] + [int(input()) for _ in range(b)] + [float("INF")]
for _ in range(q):
    res = float("INF")
    x = int(input())
    b, d = bisect.bisect_right(al, x), bisect.bisect_right(bl, x)
    ans = min(max(abs(al[b-1] - x), abs(bl[d-1] - x)),
              abs(al[b-1] - x) * 2 + abs(bl[d] - x),  
              abs(bl[d-1] - x) * 2 + abs(al[b] - x),  
              abs(al[b] - x) * 2 + abs(bl[d-1] - x),  
              abs(bl[d] - x) * 2 + abs(al[b-1] - x),  
              max(abs(al[b] - x), abs(bl[d] - x)),
              )
    print(ans)

Solution (Python):
import bisect
A,B,Q = map(int,input().split())
S = [-float('inf')]+list(int(input())for i in range(A))+[float('inf')]
T = [-float('inf')]+list(int(input())for i in range(B))+[float('inf')]
x = list(int(input())for i in range(Q))

for i in x:
    si = bisect.bisect_left(S,i)
    ti = bisect.bisect_left(T,i)
    ans = min(max(S[si],T[ti])-i,i-min(S[si-1],T[ti-1]),\
            2*S[si]-i-T[ti-1],2*T[ti]-i-S[si-1],\
             T[ti]+i-2*S[si-1],S[si]+i-2*T[ti-1])
    print(ans)

Solution (Python):
import bisect

A,B,Q = map(int,input().split())

s = [-1 * float("inf")]
t = [-1 * float("inf")]

for i in range(A):

    S = int(input())
    s.append(S)

for i in range(B):

    T = int(input())
    t.append(T)

s.append(float("inf"))
t.append(float("inf"))

for i in range(Q):

    x = int(input())

    si = bisect.bisect_left(s,x)
    ti = bisect.bisect_left(t,x)

    now = min( max(s[si],t[ti]) - x  ,  x - min(s[si-1],t[ti-1]) )
    now = min( now , 2 * min( s[si] - x , x - t[ti-1] ) + max(s[si] - x , x - t[ti-1]))
    now = min( now , 2 * min( t[ti] - x , x - s[si-1] ) + max(t[ti] - x , x - s[si-1]))

    print (now)

Solution (Python):
import sys
input=sys.stdin.readline
a,b,q=map(int,input().split())
s=[int(input()) for _ in range(a)]
t=[int(input()) for _ in range(b)]
import bisect
for _ in range(q):
    x=int(input())
    sb=bisect.bisect_left(s,x)
    tb=bisect.bisect_left(t,x)
    ss=[x-s[max(sb-1,0)],x-s[min(sb,a-1)]]
    tt=[x-t[max(tb-1,0)],x-t[min(tb,b-1)]]
    l=[]
    for i in ss:
        for j in tt:
            if i*j>=0:
                l.append(max(abs(i),abs(j)))
            else:
                l.append(max(abs(i),abs(j))+2*min(abs(i),abs(j)))
    print(min(l))

Solution (Python):
import sys
input=sys.stdin.readline
a,b,q=map(int,input().split())
s=[int(input()) for _ in range(a)]
t=[int(input()) for _ in range(b)]
import bisect
for _ in range(q):
    x=int(input())
    sb=bisect.bisect_left(s,x)
    tb=bisect.bisect_left(t,x)
    ss=[x-s[max(sb-1,0)],x-s[min(sb,a-1)]]
    tt=[x-t[max(tb-1,0)],x-t[min(tb,b-1)]]
    l=[]
    for i in ss:
        for j in tt:
            if i*j>=0:
                l.append(max(abs(i),abs(j)))
            else:
                l.append(max(abs(i),abs(j))+2*min(abs(i),abs(j)))
    print(min(l))

Solution (Python):
import sys
input=sys.stdin.readline
a,b,q=map(int,input().split())
s=[int(input()) for _ in range(a)]
t=[int(input()) for _ in range(b)]
import bisect
for _ in range(q):
    x=int(input())
    sb=bisect.bisect_left(s,x)
    tb=bisect.bisect_left(t,x)
    ss=[x-s[max(sb-1,0)],x-s[min(sb,a-1)]]
    tt=[x-t[max(tb-1,0)],x-t[min(tb,b-1)]]
    l=[]
    for i in ss:
        for j in tt:
            if i*j>=0:
                l.append(max(abs(i),abs(j)))
            else:
                l.append(max(abs(i),abs(j))+2*min(abs(i),abs(j)))
    print(min(l))

Solution (Python):
import sys
from bisect import bisect as br
A, B, Q = map(int, input().split())
inf = 10**11
S = [-inf] + [int(sys.stdin.readline()) for _ in range(A)] + [inf]
T = [-inf] + [int(sys.stdin.readline()) for _ in range(B)] + [inf]
X = [int(sys.stdin.readline()) for _ in range(Q)]

StoT = [0]*A
for i, s in enumerate(S[1:-1]):
    x = br(T, s)
    StoT[i] = (s, min(s - T[x-1], T[x] - s))

TtoS = [0]*B
for i, t in enumerate(T[1:-1]):
    x = br(S, t)
    TtoS[i] = (t, min(t - S[x-1], S[x] - t))

M = [(-inf, inf)] + TtoS + StoT + [(inf, inf)]
M.sort()
Mk , Mv = list(map(list, zip(*M)))
for x in X:
    idx = br(Mk, x)
    print(min(Mk[idx] - x + Mv[idx], x - Mk[idx-1] + Mv[idx-1]))

Solution (Python):
a,b,q=map(int,input().split())
s=[int(input()) for _ in range(a)]
t=[int(input()) for _ in range(b)]
import bisect
for _ in range(q):
    x=int(input())
    sb=bisect.bisect_left(s,x)
    tb=bisect.bisect_left(t,x)
    ss=[x-s[max(sb-1,0)],x-s[min(sb,a-1)]]
    tt=[x-t[max(tb-1,0)],x-t[min(tb,b-1)]]
    l=[]
    for i in ss:
        for j in tt:
            if i*j>=0:
                l.append(max(abs(i),abs(j)))
            else:
                l.append(max(abs(i),abs(j))+2*min(abs(i),abs(j)))
    print(min(l))

Solution (Python):
a,b,q=map(int,input().split())
s=[int(input()) for _ in range(a)]
t=[int(input()) for _ in range(b)]
import bisect
for _ in range(q):
    x=int(input())
    sb=bisect.bisect_left(s,x)
    tb=bisect.bisect_left(t,x)
    ss=[x-s[max(sb-1,0)],x-s[min(sb,a-1)]]
    tt=[x-t[max(tb-1,0)],x-t[min(tb,b-1)]]
    l=[]
    for i in ss:
        for j in tt:
            if i*j>=0:
                l.append(max(abs(i),abs(j)))
            else:
                l.append(max(abs(i),abs(j))+2*min(abs(i),abs(j)))
    print(min(l))

Solution (Python):
import bisect

A, B, Q = map(int, input().split())
s = [None] * A
t = [None] * B
for i in range(A):
  s[i] = int(input())
for i in range(B):
  t[i] = int(input())
  
for _ in range(Q):
  x = int(input())
  sr = bisect.bisect_left(s, x)
  if sr == A:
    sr -= 1
  sl = max([0, sr - 1])
  tr = bisect.bisect_left(t, x)
  if tr == B:
    tr -= 1
  tl = max([0, tr - 1])
  sr = s[sr]
  sl = s[sl]
  tr = t[tr]
  tl = t[tl]
  cand = [abs(tl - x) + abs(sl - tl), abs(tl - x) + abs(sr - tl),
         abs(tr - x) + abs(sl - tr), abs(tr - x) + abs(sr - tr),
         abs(sl - x) + abs(tl - sl), abs(sl - x) + abs(tr - sl),
         abs(sr - x) + abs(tl - sr), abs(sr - x) + abs(tr - sr),]
  print(min(cand))

Solution (Python):

INF = float("inf")
MOD = int(1e9 + 7)
def int1(n):
    return int(n) - 1
def parse(args, *params):
    return tuple(p(v) for p, v in zip(params, next(args).split()))


def bsr(a, v, lo=0, hi=None):
    if hi == None:
        hi = len(a) - 1
    if hi < lo:
        return lo
    mi = (lo + hi) // 2
    if v < a[mi]:
        return bsr(a, v, lo, mi - 1)
    else:
        return bsr(a, v, mi + 1, hi)


def main(args):
    A, B, Q = parse(args, int, int, int)
    S = list(int(next(args)) for _ in range(A))
    T = list(int(next(args)) for _ in range(B))
    X = tuple(int(next(args)) for _ in range(Q))

    s = [-INF] + S + [INF]
    t = [-INF] + T + [INF]
    for x in X:
        sr = bsr(s, x)
        sl = sr - 1
        tr = bsr(t, x)
        tl = tr - 1
        min_cost = INF
        for st in [s[sl], s[sr]]:
            for tt in [t[tl], t[tr]]:
                min_cost = min(min_cost, abs(st - x) + abs(tt - st))
                min_cost = min(min_cost, abs(tt - x) + abs(tt - st))
        print(min_cost)

import sys
if __name__ == '__main__':
    main(iter(sys.stdin.read().split("\n")))

Solution (Python):

INF = float("inf")
MOD = int(1e9 + 7)
def int1(n):
    return int(n) - 1
def parse(args, *params):
    return tuple(p(v) for p, v in zip(params, next(args).split()))

from bisect import bisect_right as bsr


def main(args):
    A, B, Q = parse(args, int, int, int)
    S = list(int(next(args)) for _ in range(A))
    T = list(int(next(args)) for _ in range(B))
    X = tuple(int(next(args)) for _ in range(Q))

    s = [-INF] + S + [INF]
    t = [-INF] + T + [INF]
    for x in X:
        sr = bsr(s, x)
        sl = sr - 1
        tr = bsr(t, x)
        tl = tr - 1
        min_cost = INF
        for st in [s[sl], s[sr]]:
            for tt in [t[tl], t[tr]]:
                min_cost = min(min_cost, abs(st - x) + abs(tt - st))
                min_cost = min(min_cost, abs(tt - x) + abs(tt - st))
        print(min_cost)

import sys
if __name__ == '__main__':
    main(iter(sys.stdin.read().split("\n")))

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):
from bisect import bisect_left as bl


A, B, Q = list(map(int, input().split()))
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]

for _ in range(Q):
    x = int(input())
    i = bl(S, x)
    j = bl(T, x)
    d = set()
    if i < A:
        a = S[i]
        if j < B:
            if T[j] <= a:
                d.add(a - x)
            else:
                d.add(T[j] - x)
                if j > 0:
                    k, l = a - x, x - T[j-1]
                    if k < l:
                        d.add(2 * k + l)
                    else:
                        d.add(2 * l + k)
        else:
            k, l = a - x, x - T[j-1]
            if k < l:
                d.add(2 * k + l)
            else:
                d.add(2 * l + k)
    if i > 0:
        a = S[i-1]
        if j > 0:
            if T[j-1] >= a:
                d.add(x - a)
            else:
                d.add(x - T[j-1])
                if j < B:
                    k, l = x - a, T[j] - x
                    if k < l:
                        d.add(2 * k + l)
                    else:
                        d.add(2 * l + k)
        else:
            k, l = x - a, T[j] - x
            if k < l:
                d.add(2 * k + l)
            else:
                d.add(2 * l + k)
    print(min(d))

Solution (Python):
import bisect
A, B, Q = map(int, input().split())

INF = 10**18

s = [-INF] + [int(input()) for _ in range(A)] + [INF]
t = [-INF] + [int(input()) for _ in range(B)] + [INF]

for q in range(Q):
  x = int(input())
  b = bisect.bisect_right(s, x)
  d = bisect.bisect_right(t, x)
  res = INF
  for S in [s[b-1], s[b]]:
    for T in [t[d-1], t[d]]:
      d1 = abs(S - x) + abs(T - S)
      d2 = abs(T - x) + abs(S - T)
      res = min(res, d1, d2)
      
  print(res)

Solution (Python):
import bisect
a,b,q = map(int,input().split())
s = list(int(input()) for _ in range(a))
t = list(int(input()) for _ in range(b))
x = list(int(input()) for _ in range(q))

s.insert(0,-10**18)
s.append(10**18)
t.insert(0,-10**18)
t.append(10**18)

for i in range(q):
    insert_xs = bisect.bisect_left(s,x[i])
    insert_xt = bisect.bisect_left(t,x[i])
    answer = 10**18
    for k1 in range(2):
        for k2 in range(2):
            distant = abs(s[insert_xs - k1]-x[i]) + abs(s[insert_xs - k1]-t[insert_xt - k2])
            if distant < answer:
                answer = distant
            distant = abs(t[insert_xt - k2]-x[i]) + abs(t[insert_xt - k2]-s[insert_xs - k1])
            if distant < answer:
                answer = distant
    print(answer)

Solution (Python):

import sys, bisect


def solve(A: int, B: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):
    s = [-1e18] + s + [1e18]
    t = [-1e18] + t + [1e18]
    for q in x:
        sRight = bisect.bisect_left(s, q)
        tRight = bisect.bisect_left(t, q)
        sLeft = sRight - 1
        tLeft = tRight - 1

        rr = max(s[sRight]-q, t[tRight]-q)
        ll = max(q-s[sLeft], q-t[tLeft])

        rl = min(
            2 * (s[sRight]-q) + (q-t[tLeft]),
            2 * (t[tRight]-q) + (q-s[sLeft]),
            2 * (q-s[sLeft]) + (t[tRight]-q),
            2 * (q-t[tLeft]) + (s[sRight]-q),
        )
        print(min(rr, ll, rl))
    return



def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = int(next(tokens))  
    B = int(next(tokens))  
    Q = int(next(tokens))  
    s = [ int(next(tokens)) for _ in range(A) ]  
    t = [ int(next(tokens)) for _ in range(B) ]  
    x = [ int(next(tokens)) for _ in range(Q) ]  
    solve(A, B, Q, s, t, x)

if __name__ == '__main__':
    main()

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)]

for x in X:
    p0, p1, p2, p3 = (10**12 for _ in range(4))
    si = bisect.bisect_left(S, x)
    ti = bisect.bisect_left(T, x)

    if si != 0 and ti != 0:
        p0 = max(x-S[si-1], x-T[ti-1])
    if si != 0 and ti != B:
        p1 = min(x-S[si-1], T[ti]-x)*2+max(x-S[si-1], T[ti]-x)
    if si != A and ti != 0:
        p2 = min(S[si]-x, x-T[ti-1])*2+max(S[si]-x, x-T[ti-1])
    if si != A and ti != B:
        p3 = max(S[si]-x, T[ti]-x)
    print(min(p0, p1, p2, p3))

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 i in range(Q):
  ans=inf
  x=int(input())
  b=bisect.bisect_left(s,x)
  d=bisect.bisect_left(t,x)
  for S in (s[b-1],s[b]):
    for T in (t[d-1],t[d]):
      ans=min(ans,abs(S-x)+abs(S-T),abs(T-x)+abs(S-T))
  print(ans)

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 i in range(Q):
  ans=inf
  x=int(input())
  b=bisect.bisect_left(s,x)
  d=bisect.bisect_left(t,x)
  for S in (s[b-1],s[b]):
    for T in (t[d-1],t[d]):
      ans=min(ans,abs(S-x)+abs(S-T),abs(T-x)+abs(S-T))
  print(ans)

Solution (Python):
import math
import bisect
A,B,Q = list(map(int,input().split(" ")))
Ss = [int(input())for _ in range(A)]
Ts = [int(input())for _ in range(B)]
Xs = [int(input())for _ in range(Q)]
Ss.sort()
Ts.sort()
ss = len(Ss)
ts = len(Ts)
for x in Xs:
    si = bisect.bisect_right(Ss,x)
    ti = bisect.bisect_right(Ts,x)

    cands = [[],[]]
    if si > 0:
        cands[0].append(Ss[si-1])
    if si < ss:
        cands[0].append(Ss[si])
    if ti > 0:
        cands[1].append(Ts[ti-1])
    if ti < ts:
        cands[1].append(Ts[ti])
 
    anss = []
    temp = 0
    for i in [0,1]:
        for t1 in cands[i]: 
            for t2 in cands[1-i]: 
                temp = abs(x-t1) +  abs(t2-t1)
                anss.append(temp)
    print(min(anss))

Solution (Python):
from bisect import bisect_left as bl
A, B, Q = map(int, input().split())
inf = 10 ** 11
Sh = [-1 * inf] + [int(input()) for _ in range(A)] + [inf]
Te = [-1 * inf] + [int(input()) for _ in range(B)] + [inf]
for _ in range(Q):
  x = int(input())
  b, d = bl(Sh, x), bl(Te, x)
  res = inf
  for S in [Sh[b - 1], Sh[b]]:
    for T in [Te[d - 1], Te[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

def resolve():
    A, B, Q = map(int, input().split())
    s = [int(input()) for _ in range(A)]
    t = [int(input()) for _ in range(B)]

    for _ in range(Q):
        i = int(input())
        s1 = -1 if bisect.bisect_left(s, i) == 0 else s[bisect.bisect_left(s, i)-1]
        s2 = -1 if bisect.bisect_right(s, i) >= A else s[bisect.bisect_right(s, i)]
        t1 = -1 if bisect.bisect_left(t, i) == 0 else t[bisect.bisect_left(t, i)-1]
        t2 = -1 if bisect.bisect_left(t, i) >= B else t[bisect.bisect_right(t, i)]
        tmp = []

        if s1 != -1 and t1 != -1:
            tmp.append(max(i-s1, i-t1))
        if s2 != -1 and t2 != -1:
            tmp.append(max(s2-i, t2-i))
        if s1 != -1 and t2 != -1:
            tmp.append(min(i-s1, t2-i) + t2-s1)
        if t1 != -1 and s2 != -1:
            tmp.append(min(i-t1, s2-i) + s2-t1)

        print(min(tmp))


if __name__ == "__main__":
    resolve()

Solution (Python):
from bisect import bisect_left, bisect_right

INF = int(1E18)
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)]
S.insert(0, -INF)
T.insert(0, -INF)
S.append(INF)
T.append(INF)

for x in X:
    i = bisect_left(S, x)
    j = bisect_left(T, x)
    s1, s2 = S[i-1], S[i]
    t1, t2 = T[j-1], T[j]
    s1 = abs(s1-x)
    s2 = abs(s2-x)
    t1 = abs(t1-x)
    t2 = abs(t2-x)
    l1 = max(s1, t1)
    l2 = min(s1, t1)
    r1 = max(s2, t2)
    r2 = min(s2, t2)
    E = [l1, r1]
    if (s1-t1)*(s2-t2) < 0:
        E.extend([2*l2+r2, 2*r2+l2])
    print(min(E))

Solution (Python):
def main():

    """ convenient functions
    
    
    
    
    
    """

    """convenient decorator
    
    
        
        
        
        
        
        
        
        
        
        
    """
    
    
    import sys
    sys.setrecursionlimit(10**7)
    from itertools import accumulate, combinations, permutations, product 
    
    from math import factorial, ceil, floor, sqrt
    def factorize(n):
        """return the factors of the Arg and count of each factor
        
        Args:
            n (long): number to be resolved into factors
        
        Returns:
            list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
        """
        fct = []  
        b, e = 2, 0  
        while b * b <= n:
            while n % b == 0:
                n = n // b
                e = e + 1
            if e > 0:
                fct.append((b, e))
            b, e = b + 1, 0
        if n > 1:
            fct.append((n, 1))
        return fct
    def combinations_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        
        if n < 0 or r < 0:
            raise Exception('combinations_count(n, r) not defined when n or r is negative')
        if n - r < r: r = n - r
        if r < 0: return 0
        if r == 0: return 1
        if r == 1: return n
        numerator = [n - r + k + 1 for k in range(r)]
        denominator = [k + 1 for k in range(r)]
        for p in range(2,r+1):
            pivot = denominator[p - 1]
            if pivot > 1:
                offset = (n - r) % p
                for k in range(p-1,r,p):
                    numerator[k - offset] /= pivot
                    denominator[k] /= pivot
        result = 1
        for k in range(r):
            if numerator[k] > 1:
                result *= int(numerator[k])
        return result
    def combinations_with_replacement_count(n, r):
        """Return the number of selecting r pieces of items from n kinds of items allowing individual elements to be repeated more than once.
        
        Args:
            n (long): number
            r (long): number
        
        Raises:
            Exception: not defined when n or r is negative
        
        Returns:
            long: number
        """
        if n < 0 or r < 0:
            raise Exception('combinations_with_replacement_count(n, r) not defined when n or r is negative')
        elif n == 0:
            return 1
        else:
            return combinations_count(n + r - 1, r)
    from bisect import bisect_left, bisect_right
    from collections import deque, Counter, defaultdict 
    from heapq import heapify, heappop, heappush, heappushpop, heapreplace,nlargest,nsmallest 
    from copy import deepcopy, copy 
    import operator
    from operator import itemgetter
    
    
    from functools import reduce, lru_cache
    def chmin(x, y):
        """change minimum
        if x > y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current minimum value
            y (long): potential minimum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x > y:
            x = y
            return (x, True)
        else:
            return (x, False)
    def chmax(x, y):
        """change maximum
        if x < y, x = y and return (x, True).
        convenient when solving problems of dp[i]
        
        Args:
            x (long): current maximum value
            y (long): potential maximum value
        
        Returns:
            (x, bool): (x, True) when updated, else (x, False)
        """
        if x < y:
            x = y
            return (x, True)
        else:
            return (x, False)

    from fractions import gcd 
    def gcds(numbers):
        return reduce(gcd, numbers)
    def lcm(x, y):
        return (x * y) // gcd(x, y)
    def lcms(numbers):
        return reduce(lcm, numbers, 1)

    
    
    INF = 10 ** 18
    MOD = 10 ** 9 + 7
    modpow = lambda a, n, p = MOD: pow(a, n, p) 
    def modinv(a, p = MOD):
        
        
        return modpow(a, p-2, p)
    def modinv_list(n, p = MOD):
        if n <= 1:
            return [0,1][:n+1]
        else:
            inv_t = [0,1]
            for i in range(2, n+1):
                inv_t += [inv_t[p % i] * (p - int(p / i)) % p]
            return inv_t
    def modfactorial_list(n, p = MOD):
        if n == 0:
            return [1]
        else:
            l = [0] * (n+1)
            tmp = 1
            for i in range(1, n+1):
                tmp = tmp * i % p
                l[i] = tmp
            return l
    def modcomb(n, k, fac_list = [], p = MOD):
        
        
        from math import factorial
        if n < 0 or k < 0 or n < k: return 0
        if n == 0 or k == 0: return 1
        if len(fac_list) <= n:
            a = factorial(n) % p
            b = factorial(k) % p
            c = factorial(n-k) % p
        else:
            a = fac_list[n]
            b = fac_list[k]
            c = fac_list[n-k]
        return (a * modpow(b, p-2, p) * modpow(c, p-2, p)) % p
    def modadd(a, b, p = MOD):
        return (a + b) % MOD
    def modsub(a, b, p = MOD):
        return (a - b) % p
    def modmul(a, b, p = MOD):
        return ((a % p) * (b % p)) % p
    def moddiv(a, b, p = MOD):
        return modmul(a, modpow(b, p-2, p))

    class UnionFindTree:
        """union find tree class
        TODO: fix this description...
        how to use (example):
        >>  uf = UnionFindTree(N) 
        >>  if uf.find_root(a) == uf.find_root(b):
        >>      do something
        >>  else:
        >>      do something
        >>      uf.unite(a, b)
        """
        def __init__(self, N):
            self.root = [-1] * (N+1)
            self.rank   = [0]  * (N+1)
            self.connected_num = [1] * (N+1)
    
        def find_root(self,x):
            root = self.root
            while root[x] != -1:
                x = root[x]
            return x
    
        def unite(self,x,y):
            root = self.root
            rank = self.rank
            connected_num = self.connected_num
            find_root = self.find_root
    
            rx = find_root(x)
            ry = find_root(y)
            if rx != ry:
                if rank[rx] < rank[ry]:
                    root[rx] = ry
                    rx,ry = ry,rx
                else:
                    if rank[rx] == rank[ry]:
                        rank[rx] += 1
                    root[ry] = rx       
                connected_num[rx] += connected_num[ry]

    """ initialize variables and set inputs
    
        
        
    
        
        
        
        
        
    
        
        
        
        
    
        
        
    """

    
    r = lambda: sys.stdin.readline().strip()
    r_int = lambda: int(r())
    R = lambda: list(map(int, r().split()))
    Rmap = lambda: map(int, r().split())
    Rfloat = lambda: list(map(float, r().split()))
    Rtuple = lambda: tuple(map(int, r().split()))

    """ how to treat input
    
    
    
    
    
    
    
    """

    if __name__ != '__main__':
        
        sys.stdin = open('sample.txt')
        
    
    

    A, B, Q = R()
    S = [-INF] + [int(r()) for _ in range(A)] + [INF] 
    T = [-INF] + [int(r()) for _ in range(B)] + [INF] 
    X = [int(r()) for _ in range(Q)]
    for x in X:
        s = bisect_left(S, x)
        t = bisect_left(T, x)
        
        
        
        
        
        
        
        sl = S[s-1]
        sr = S[s]
        
        
        
        
        
        
        
        tl = T[t-1]
        tr = T[t]
        print(min(min(abs(x-sl), abs(x-tr))+abs(sl-tr),
            min(abs(x-sr), abs(x-tl))+abs(sr-tl),
            max(abs(x-sl), abs(x-tl)),
            max(abs(x-sr), abs(x-tr)))
              )
        
    
    
    

    """memo: how to use defaultdict of list
    
    Dic = defaultdict(list)
    
    Dic[x].append(y)
    
    for k, v in Dic.items():
    """
    
    """memo: how to solve binary problems
    
    >>> a = 5
    >>> bin_str_a = format(a, '
    >>> print(bin_str_a)
    0b0101 
    """
    
    """memo: how to solve the problem
    creating simple test/answer
    greed
    simple dp
    graph
    """

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_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)