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())
s = [-10**11]+[int(input()) for _ in range(a)]+[10**11]
t = [-10**11]+[int(input()) for _ in range(b)]+[10**11]
for i in range(q):
  ans = 10**11
  x = int(input())
  l = bisect.bisect(s,x)
  m = bisect.bisect(t,x)
  arr = [[s[l-1],s[l]],[t[m-1],t[m]]]
  for i in range(4):
    S = 0
    now = x
    for j in range(2):
      t0 = now-arr[j][i >> j & 1]
      S += t0*((-1)**(t0<0))
      now -= t0
    if ans > S:
      ans = S
  for i in range(4):
    S = 0
    now = x
    for j in range(2):
      t0 = now-arr[1-j][i >> j & 1]
      S += t0*((-1)**(t0<0))
      now -= t0
    if ans > S:
      ans = S
  print(ans)

Solution (Python):


import bisect

def nearest(x, lst):
    p = bisect.bisect_left(lst, x)
    
    if p == 0:
        return lst[p], None
    if p == len(lst):
        return lst[p - 1], None
    if lst[p] == x:
        return lst[p], None
    return lst[p - 1], lst[p]
 

def submit():
    a, b, q = map(int, input().split())

    slist = [int(input()) for _ in range(a)]
    tlist = [int(input()) for _ in range(b)]
    qlist = [int(input()) for _ in range(q)]

    near_s = {s: nearest(s, tlist) for s in slist}
    near_t = {t: nearest(t, slist) for t in tlist}

    anss = []
    for q in qlist:
        ans = float('inf')
        
        n = nearest(q, slist)
        for e in n:
            if not e: 
                continue
            for ee in near_s[e]:
                if not ee:
                    continue
                if ans > abs(q - e) + abs(ee - e):
                    ans = abs(q - e) + abs(ee - e)                            
        
        n = nearest(q, tlist)
        for e in n:
            if not e:
                continue
            for ee in near_t[e]:
                if not ee:
                    continue
                if ans > abs(q - e) + abs(ee - e):
                    ans = abs(q - e) + abs(ee - e)
        anss.append(ans)

    for ans in anss:
        print(ans)


submit()

Solution (Python):
from bisect import bisect_left
def main():
    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 _ in range(q):
        x = int(input())
        sind = bisect_left(s, x)
        tind = bisect_left(t, x)
        
        res = INF
        for S in [s[sind-1], s[sind]]:
            for T in [t[tind-1], t[tind]]:
                d1 = abs(x-S) + abs(S-T)
                d2 = abs(x-T) + abs(T-S)
                res = min([res, d1, d2])
        print(res)
main()

Solution (Python):
from bisect import bisect_left

a, b, q = map(int, input().split())
S = []
T = []
X = []


def calc(x, a, b):
    return abs(a - b) + min(abs(x - a), abs(x - b))


for _ in range(a):
    S.append(int(input()))
for _ in range(b):
    T.append(int(input()))
for _ in range(q):
    x = int(input())

    basho1 = bisect_left(S, x)
    basho11 = min(basho1, a - 1)
    basho12 = basho11 - 1

    basho2 = bisect_left(T, x)
    basho21 = min(basho2, b - 1)
    basho22 = basho21 - 1
    ans = calc(x, S[basho11], T[basho21])
    ans = min(ans, calc(x, S[basho11], T[basho22]))
    ans = min(ans, calc(x, S[basho12], T[basho21]))
    ans = min(ans, calc(x, S[basho12], T[basho22]))
    print(ans)

Solution (Python):
A, B, Q = map(int, input().split())
s = []
for _ in range(A):
    s.append(int(input()))
t = []
for _ in range(B):
    t.append(int(input()))
x = []
for _ in range(Q):
    x.append(int(input()))

def binsearch(threshold, lst):
    left, right = -1, len(lst)

    while right - left > 1:
        mid = (left + right) // 2
        if lst[mid] > threshold:
            right = mid
        else:
            left = mid
    return (left, right)

for q in x:
    ans = 10 ** 11
    for i in range(2):
        for j in range(2):
            a = binsearch(q, s)[i]
            b = binsearch(q, t)[j]
            
            if 0 <= a <= A - 1 and 0 <= b <= B - 1:
                    
                    ans = min(ans, abs(s[a] -t[b]) + min(abs(s[a]-q), abs(t[b]-q)))
    print(ans)

Solution (Python):
import sys
input = lambda: sys.stdin.readline().rstrip()
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 i in range(Q):
    x = int(input())
    right_s = bisect.bisect_right(s, x)
    right_t = bisect.bisect_right(t, x)

    ans = INF
    
    for S in [s[right_s-1], s[right_s]]:
        for T in [t[right_t-1], t[right_t]]:
            ans = min(ans, abs(x-S) + abs(T-S), abs(x-T) + abs(S-T))

    print(ans)

Solution (Python):
import bisect
M = 10**12
a, b, q = [int(x) for x in input().split()]
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
for i in range(q):
  x = int(input())
  lst = []
  i_s = bisect.bisect_left(s, x)
  i_t = bisect.bisect_left(t, x)
  if i_s == 0:
    sl, sr = -M, s[i_s]
  elif i_s == a:
    sl, sr = s[i_s-1], M
  else:
    sl, sr = s[i_s-1], s[i_s]
  if i_t == 0:
    tl, tr = -M, t[i_t]
  elif i_t == b:
    tl, tr = t[i_t-1], M
  else:
    tl, tr = t[i_t-1], t[i_t]
  d = M
  for ss in [sl, sr]:
    for tt in [tl, tr]:
      d1 = abs(ss - x) + abs(ss - tt)
      d2 = abs(tt - x) + abs(ss - tt)
      d = min(d, d1, d2)
  print(d)

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

a,b,q=map(int,input().split())
A=[]
for i in range(a):
    A.append(int(input()))
B=[]
for i in range(b):
    B.append(int(input()))
Q={}
for i in range(q):
    Q[int(input())]=i
X=sorted(Q)

C=[]
now=0
for i in range(a):
    while now<b and A[i]>=B[now]:
        now+=1
    if now==0:
        C.append(abs(A[i]-B[0]))
    elif now==b:
        C.append(abs(A[i]-B[b-1]))
    else:
        C.append(min(abs(A[i]-B[now-1]),abs(A[i]-B[now])))
D=[]
now=0
for i in range(b):
    while now<a and B[i]>=A[now]:
        now+=1
    if now==0:
        D.append(abs(B[i]-A[0]))
    elif now==a:
        D.append(abs(B[i]-A[a-1]))
    else:
        D.append(min(abs(B[i]-A[now-1]),abs(B[i]-A[now])))

Y=[]
now=0
for i in range(q):
    while now<b and X[i]>=B[now]:
        now+=1
    if now==0:
        Y.append(abs(X[i]-B[0])+D[0])
    elif now==b:
        Y.append(abs(X[i]-B[b-1])+D[b-1])
    else:
        Y.append(min(abs(X[i]-B[now-1])+D[now-1],
                     abs(X[i]-B[now])+D[now]))
Z=[]
now=0
for i in range(q):
    while now<a and X[i]>=A[now]:
        now+=1
    if now==0:
        Z.append(abs(X[i]-A[0])+C[0])
    elif now==a:
        Z.append(abs(X[i]-A[a-1])+C[a-1])
    else:
        Z.append(min(abs(X[i]-A[now-1])+C[now-1],
                     abs(X[i]-A[now])+C[now]))
        
Ans=[0]*q
for i in range(q):
    x=Q[X[i]] 
    Ans[x]=min(Y[i],Z[i])
for ans in Ans:
    print(ans)

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

S = [0]*A
for i in range(A):
  S[i] = int(input())

T = [0]*B
for i in range(B):
  T[i] = int(input())

import bisect
ans = []
for i in range(Q):
  mini = 10**11
  x = int(input())
  indS = bisect.bisect(S,x)
  indT = bisect.bisect(T,x)
  if indS != A: 
    if indT != B:
        mini = min(max(S[indS],T[indT])-x,mini) 
        
    if indT != 0:
        mini = min(S[indS]-T[indT-1]+min(S[indS]-x,x-T[indT-1]),mini) 
        
  if indS != 0: 
    if indT != B:
        mini = min(T[indT]-S[indS-1]+min(x-S[indS-1],T[indT]-x),mini)  
        
    if indT != 0:
        mini = min(x-min(S[indS-1],T[indT-1]),mini) 
        
  ans.append(mini)




print(*ans, sep='\n')

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

S = [0]*A
for i in range(A):
  S[i] = int(input())

T = [0]*B
for i in range(B):
  T[i] = int(input())

import bisect
ans = []
for i in range(Q):
  mini = 10**11
  x = int(input())
  indS = bisect.bisect(S,x)
  indT = bisect.bisect(T,x)
  if indS != A: 
    if indT != B:
        mini = min(max(S[indS],T[indT])-x,mini) 
        
    if indT != 0:
        mini = min(S[indS]-T[indT-1]+min(S[indS]-x,x-T[indT-1]),mini) 
        
  if indS != 0: 
    if indT != B:
        mini = min(T[indT]-S[indS-1]+min(x-S[indS-1],T[indT]-x),mini)  
        
    if indT != 0:
        mini = min(x-min(S[indS-1],T[indT-1]),mini) 
        
  ans.append(mini)




print(*ans, sep='\n')

Solution (Python):
import bisect
a,b,q=map(int,input().split())
A=[-1*(10**12)]
B=[-1*(10**12)]
for i in range(a):
    A.append(int(input()))
for i in range(b):
    B.append(int(input()))

A.append(10**12)
B.append(10**12)

for i in range(q):
    x=int(input())
    ia=bisect.bisect_right(A,x)

    ms=A[ia-1]
    ps=A[ia]
    
    ib=bisect.bisect_right(B,x)
    
    mt=B[ib-1]
    pt=B[ib]
        
    ans=min(x-min(ms,mt),max(ps,pt)-x,(ps-mt)+min(ps-x,x-mt),(pt-ms)+min(pt-x,x-ms))
    print(ans)

Solution (Python):
from bisect import bisect_right
A, B, Q = map(int, input().split())
INF = float('inf')
S = [-INF] + [int(input()) for _ in range(A)] + [INF]
T = [-INF] + [int(input()) for _ in range(B)] + [INF]
X = [int(input()) for _ in range(Q)]
for x in X:
    b, d =  bisect_right(S, x), bisect_right(T, x)
    ans = INF
    for s in [S[b - 1], S[b]]:
        for t in [T[d - 1], T[d]]:
            d1, d2 = abs(s - x) + abs(s - t), abs(t - x) + abs(s - t)
            ans = min(ans, d1, d2)
    print(ans)

Solution (Python):
import bisect
import itertools

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

INF = float('inf')
S = [-INF] + [int(input()) for _ in range(A)] + [INF]
T = [-INF] + [int(input()) for _ in range(B)] + [INF]
X = [int(input()) for _ in range(Q)]

def solve(x):
  i = bisect.bisect_left(S, x)
  j = bisect.bisect_left(T, x)
  result = INF
  
  for s,t in itertools.product(S[i-1:i+1], T[j-1:j+1]):
    d = min(abs(s-x),abs(t-x)) + abs(t-s) 
    result = min(result,d)
  return result

for x in X:
  ans = solve(x)
  print(ans)

Solution (Python):


import bisect

def main():
    a, b, q = map(int, input().split())
    huge = 10 ** 18
    s = [-huge] + [int(input()) for i in range(a)] + [huge]
    t = [-huge] + [int(input()) for i in range(b)] + [huge]
    for i in range(q):
        x = int(input())
        b = bisect.bisect_right(s, x)
        d = bisect.bisect_right(t, x)
        res = huge
        for sh in s[b - 1:b + 1]:
            for te in t[d - 1:d + 1]:
                d1 = abs(sh - x) + abs(sh - te)
                d2 = abs(te - x) + abs(sh - te)
                res = min(res, d1, d2)
        print(res)


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)]
for i in range(q):
    x = int(input())
    index1 = bisect.bisect(s,x)
    index2 = bisect.bisect(t,x)
    cands = []
    if index1 != 0:
        sl = x-s[index1-1]
    if index1 != a:
        sr = s[index1]-x
    if index2 != 0:
        tl = x-t[index2-1]
    if index2 != b:
        tr = t[index2]-x
    if index1 != 0:
        if index2 != 0:
            cands.append(max(sl,tl))
        if index2 != b:
            cands.append(sl*2+tr)
            cands.append(tr*2+sl)
    if index1 != a:
        if index2 != 0:
            cands.append(sr*2+tl)
            cands.append(sr+tl*2)
        if index2 != b:
            cands.append(max(sr,tr))
    print(min(cands))

Solution (Python):
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    
    from itertools import combinations, permutations, accumulate, groupby
    
    from bisect import bisect_left,bisect_right
    import heapq
    from math import floor, ceil
    

    
    

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

    for _ in range(q):
        pos = int(input())
        l_s = bisect_left(s, pos)
        l_t = bisect_left(t, pos)

        left_shrine = s[l_s-1]
        right_shrine = s[l_s]
        left_temple = t[l_t-1]
        right_temple = t[l_t]

        d1 = pos - min(left_shrine, left_temple)
        d2 = max(right_shrine, right_temple) - pos
        d3 = 2 * (pos - left_shrine) + (right_temple - pos)
        d4 = 2 * (right_temple - pos) + (pos - left_shrine)
        d5 = 2 * (pos - left_temple) + (right_shrine - pos)
        d6 = 2 * (right_shrine - pos) + (pos - left_temple)

        ans = min([
            d1, d2, d3, d4, d5, d6
        ])
        print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
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)]
s.sort()
t.sort()
for _ in range(q):
  x=int(input())
  idx1=bisect.bisect_left(s,x)
  idx2=bisect.bisect_left(t,x)
  d=[]
  if idx1<a and idx2<b:
    d.append(max(s[idx1]-x,t[idx2]-x))
  if 1<=idx1 and 1<=idx2:
    d.append(max(x-s[idx1-1],x-t[idx2-1]))
  if 1<=idx1 and idx2<b:
    d.append((t[idx2]-x)*2+x-s[idx1-1])
    d.append((x-s[idx1-1])*2+t[idx2]-x)
  if idx1<a and 1<=idx2:
    d.append((s[idx1]-x)*2+x-t[idx2-1])
    d.append((x-t[idx2-1])*2+s[idx1]-x)
  print(min(d))

Solution (Python):
import sys
from bisect import *
from heapq import *
from collections import *
from itertools import *
from functools import *
from math import *
from fractions import *

sys.setrecursionlimit(100000000)
input = lambda: sys.stdin.readline().rstrip()

def main():
    A, B, Q = map(int, input().split())
    s, t = [], []
    for _ in range(A):
        s.append(int(input()))
    for _ in range(B):
        t.append(int(input()))
    for _ in range(Q):
        x = int(input())
        i = bisect_left(s, x)
        j = bisect_left(t, x)
        
        
        s_candidates = [s[k] for k in [i - 1, i] if 0 <= k < A]
        t_candidates = [t[k] for k in [j - 1, j] if 0 <= k < B]
        ans = float('inf')
        for s_candidate in s_candidates:
            for t_candidate in t_candidates:
                right = max(x, s_candidate, t_candidate) - x
                left = x - min(x, s_candidate, t_candidate)
                ans = min(ans, min(right, left) * 2 + max(right, left))
        print(ans)






main()

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

for _ in range(q):
    ans = inf
    x = int(input())
    index_s = bisect_left(shrine, x)
    index_t = bisect_left(temple, x)

    for s in [shrine[index_s-1], shrine[index_s]]:
        for t in [temple[index_t-1], temple[index_t]]:
            ans = min(
                ans,
                abs(x-s) + abs(s-t),
                abs(x-t) + abs(s-t)
            )

    print(ans)

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

for _ in range(q):
    ans = inf
    x = int(input())
    index_s = bisect_left(shrine, x)
    index_t = bisect_right(temple, x)
    
    for s in [shrine[index_s-1], shrine[index_s]]:
        for t in [temple[index_t-1], temple[index_t]]:
            ans = min(
                ans,
                abs(x-s) + abs(s-t),
                abs(x-t) + abs(s-t)
            )

    print(ans)

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

for _ in range(q):
    ans = inf
    x = int(input())
    index_s = bisect_left(shrine, x)
    index_t = bisect_right(temple, x)
    for i in range(index_s-1, index_s+1):
        s = shrine[i]
        i_t = index_t
        t0, t1 = temple[i_t-1], temple[i_t]
        ans = min(
            ans,
            abs(x - s) + abs(s - t0),
            abs(x - s) + abs(s - t1),
        )

    for i in range(index_t-1, index_t+1):
        t = temple[i]
        i_s = index_s
        s0 = shrine[i_s - 1]
        s1 = shrine[i_s]
        ans = min(
            ans,
            abs(x - t) + abs(t - s0),
            abs(x - t) + abs(t - s1),
        )

    print(ans)

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

for i in range(q):
    x=int(input())
    p=bisect.bisect_left(s,x)
    q=bisect.bisect_left(t,x)

    sl,sr,tl,tr=s[p-1],s[p],t[q-1],t[q]

    sltl=x-min(sl,tl)
    srtr=max(sr,tr)-x
    sltr=min(x-sl*2+tr,-x-sl+tr*2)
    srtl=min(x-tl*2+sr,-x-tl+sr*2)
    print(min(sltl,srtr,sltr,srtl))

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

a=[-float("inf")]
b=[-float("inf")]
for i in range(A):
    a.append(int(input()))
for i in range(B):
    b.append(int(input()))   
a+=[float("inf")]
b+=[float("inf")]

for i in range(Q):
    q = int(input())
    x = bisect.bisect_left(a, q)
    y = bisect.bisect_left(b, q)
    ans = float("inf")
    for j in [a[x-1], a[x]]:
        for k in [b[y-1], b[y]]:
            ans1 = abs(j-q)+abs(j-k)
            ans2 = abs(k-q)+abs(j-k)
            ans = min(ans, ans1, ans2)
    print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
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 _ in range(q):
    x = int(input())
    i = bisect.bisect_right(s,x)
    j = bisect.bisect_right(t,x)
    d = INF
    for si in [s[i-1],s[i]]:
        for ti in [t[j-1],t[j]]:
            d1 = abs(x-si)+abs(ti-si)
            d2 = abs(x-ti)+abs(ti-si)
            d = min(d,d1,d2)
    print(d)

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

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

import bisect

for i in x:
    s_idx = bisect.bisect_right(s, i)
    ans = 10 ** 18
    if s_idx == 0:
        s_ = [s[0]]
    elif s_idx >= a:
        s_ = [s[-1]]
    else:
        s_ = [s[s_idx], s[s_idx - 1]]
    for j in s_:
        tmp = abs(i - j)
        t_idx = bisect.bisect_right(t, j)
        if t_idx == 0:
            tmp += abs(j - t[0])
        elif t_idx >= b:
            tmp += abs(j - t[-1])
        else:
            tmp += min(abs(j - t[t_idx]), abs(j - t[t_idx - 1]))
        ans = min(tmp, ans)
    
    t_idx = bisect.bisect_right(t, i)
    if t_idx == 0:
        t_ = [t[0]]
    elif t_idx >= b:
        t_ = [t[-1]]
    else:
        t_ = [t[t_idx], t[t_idx - 1]]
    for j in t_:
        tmp = abs(i - j)
        s_idx = bisect.bisect_right(s, j)
        if s_idx == 0:
            tmp += abs(j - s[0])
        elif s_idx >= a:
            tmp += abs(j - s[-1])
        else:
            tmp += min(abs(j - s[s_idx]), abs(j - s[s_idx - 1]))
        ans = min(tmp, ans)
    print(ans)

Solution (Python):


import os
from sys import stdin, stdout

if(os.getenv('__LOCAL__')):
    __dirname = os.path.dirname(__file__)
    __basename = os.path.splitext(os.path.basename(__file__))[0]
    __inputname = './input/' + __basename + '.txt'
    __outputname = './output/' + __basename + '.txt'
    __input_path = os.path.join(__dirname, __inputname)
    __output_path = os.path.join(__dirname, __outputname)
    stdin = open(__input_path)
    

def main():
    A, B, Q = map(int, stdin.readline().rstrip().split(' '))
    s = list()
    t = list()
    s.append(-1e12)
    t.append(-1e12)
    s += [int(stdin.readline()) for _ in range(A)]
    t += [int(stdin.readline()) for _ in range(B)]
    X = [int(stdin.readline()) for _ in range(Q)]
    ansvec = list()
    s.append(1e12)
    t.append(1e12)
    
    
    
    for x in X:
        ls = 0
        rs = A+2
        lt = 0
        rt = B+2
        while(rs-ls>1):
            mids=(ls+rs)//2
            if(s[mids]<=x):
                ls = mids
            else:
                rs = mids

        while(rt-lt>1):
            midt=(lt+rt)//2
            if(t[midt]<=x):
                lt = midt
            else:
                rt = midt

        if(t[lt]<=s[ls] and s[rs]<=t[rt]):
            ans = min(abs(t[lt]-x),abs(t[rt]-x))
        elif(s[ls]<=t[lt] and t[rt]<=s[rs]):
            ans = min(abs(s[ls]-x),abs(s[rs]-x))
        elif(s[ls]<=t[lt] and s[rs]<=t[rt]):
            ans = min(abs(s[ls]-x),abs(t[rt]-x), 2*abs(s[rs]-x)+abs(t[lt]-x), 2*abs(t[lt]-x)+abs(s[rs]-x))
        elif(t[lt]<=s[ls] and t[rt]<=s[rs]):
            ans = min(abs(t[lt]-x),abs(s[rs]-x), 2*abs(s[ls]-x)+abs(t[rt]-x), 2*abs(t[rt]-x)+abs(s[ls]-x))
        ansvec.append(ans)

    for a in ansvec:
        stdout.write("{}\n".format(a))

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())
  i =bisect.bisect_right(S,x)
  j =bisect.bisect_right(T,x)
  d=INF
  for s in [S[i-1],S[i]]:
    for t in [T[j-1],T[j]]:
      d1 = abs(s-x) + abs(s-t)
      d2 = abs(t-x) + abs(s-t)
      d = min(d,d1,d2)
      
  print(d)

Solution (Python):
import sys
import bisect

input = sys.stdin.readline


def main():
    A, B, Q = [int(x) for x in input().split()]
    S = [int(input()) for _ in range(A)]
    T = [int(input()) for _ in range(B)]
    for _ in range(Q):
        x = int(input())
        si = bisect.bisect_left(S, x)
        ti = bisect.bisect_left(T, x)
        sl = -float("inf")
        if si != 0:
            sl = S[si - 1]
        sr = float("inf")
        if si != A:
            sr = S[si]
        tl = -float("inf")
        if ti != 0:
            tl = T[ti - 1]
        tr = float("inf")
        if ti != B:
            tr = T[ti]

        tmp1 = max(x - sl, x - tl)
        tmp2 = max(sr, tr) - x
        tmp3 = 2 * (x - sl) + tr - x
        tmp4 = 2 * (x - tl) + sr - x
        tmp5 = x - sl + 2 * (tr - x)
        tmp6 = x - tl + 2 * (sr - x)

        print(min(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6))


if __name__ == '__main__':
    main()

Solution (Python):

import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect, bisect_right, bisect_left

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

A, B, Q = MAP()
S = [INT() for i in range(A)]
T = [INT() for i in range(B)]
X = [INT() for i in range(Q)]
S.insert(0, -INF)
S.append(INF)
T.insert(0, -INF)
T.append(INF)

for x in X:
    s = bisect(S, x)
    t = bisect(T, x)
    
    
    
    res = INF
    for a in [S[s-1], S[s]]:
        for b in [T[t-1], T[t]]:
            res = min(res, min(abs(a - x) + abs(b - a), abs(x - b) + abs(b - a)))
    print(res)

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

INF = 10**18

A, B, Q = map(int, input().split())
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())
    si = bisect_left(S,x)
    ti = bisect_left(T,x)
    res = INF
    res = min(res, max(S[si] - x, T[ti] - x))
    res = min(res, max(x - S[si - 1], x - T[ti - 1]))
    res = min(res, x + T[ti] - 2 * S[si - 1])
    res = min(res, -x + 2 * T[ti] - S[si - 1])
    res = min(res, x + S[si] - 2 * T[ti - 1])
    res = min(res, -x + 2 * S[si] - T[ti - 1])
    print(res)

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

for _ in range(Q):
  x = int(input())
  s_ = bisect.bisect_right(S, x)
  t_ = bisect.bisect_right(T, x)
  s_min = x-S[max(s_-1, 0)]
  s_max = S[min(s_, A-1)]-x
  t_min = x-T[max(t_-1, 0)]
  t_max = T[min(t_, B-1)]-x
  
  if s_min < 0:
    s_min =  3 * 10 ** 10 + 7
  if s_max < 0:
    s_max = 3 * 10 ** 10 + 7
  if t_min < 0:
    t_min = 3 * 10 ** 10 + 7
  if t_max < 0:
    t_max = 3 * 10 ** 10 + 7
  print(min([
    max(s_min, t_min), 
    max(s_max, t_max), 
    s_min + t_max + min(s_min, t_max),
    s_max + t_min + min(s_max, t_min)
  ]))

Solution (Python):


A,B,Q = list(map(int, input().rstrip().split()))
s_list = [-10**11] + [int(input().strip()) for _ in range(A)] + [10**11]
t_list = [-10**11] + [int(input().strip()) for _ in range(B)] + [10**11]
x_list = [int(input().strip()) for _ in range(Q)]






x_dic={}

x_sort = sorted(x_list)

i_x=0
for i in range(len(s_list) - 1):
    
    while s_list[i] <= x_sort[i_x] <= s_list[i+1]:
        x_dic[x_sort[i_x]] = [i,(i+1)]
        i_x += 1
        
        if i_x > len(x_sort)-1: break
    if i_x > len(x_sort)-1: break
    

i_x=0
for i in range(len(t_list) - 1):
    
    while t_list[i] <= x_sort[i_x] <= t_list[i+1]:
        x_dic[x_sort[i_x]].extend( [i,(i+1)] )
        i_x += 1
        
        if i_x > len(x_sort)-1: break
    if i_x > len(x_sort)-1: break


for x in x_list:
    dist_min=10**11
    
    for s in x_dic[x][0:2]:
        for t in x_dic[x][2:4]:
            diff1 = abs(s_list[s] - x) + abs(t_list[t] - s_list[s])
            diff2 = abs(t_list[t] - x) + abs(s_list[s] - t_list[t])
            dist_min = min(dist_min, diff1, diff2)
    
    print(dist_min)

Solution (Python):
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline

from bisect import bisect_left
from bisect import bisect_right

a, b, q = map(int, input().split())

s = [0]* a
t = [0]* b
X = [0]* q
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())

INF = float('inf')

for x in X:
    index_ls = bisect_left(s,x)
    index_lt = bisect_left(t,x)
    index_rs = bisect_right(s,x)
    index_rt = bisect_right(t,x)
    ans = INF
    right_s = INF
    left_s = -INF
    right_t = INF
    left_t = -INF

    if index_ls < a: right_s = s[index_ls]
    if index_lt < b: right_t = t[index_lt]
    if index_rs > 0: left_s = s[index_rs-1]
    if index_rt > 0: left_t = t[index_rt-1]

    ans1 = max(right_s-x,right_t-x)
    ans2 = max(x-left_s,x-left_t)
    ans3 = right_s-x + right_s-left_t
    ans4 = right_t-x + right_t-left_s
    ans5 = x-left_t + right_s-left_t
    ans6 = x-left_s + right_t-left_s

    print(min(ans1,ans2,ans3,ans4,ans5,ans6))

Solution (Python):
import bisect
import itertools
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)]
INF = float("inf")
for x_ in x:
  ind_s = bisect.bisect_left(s,x_)
  ind_t = bisect.bisect_left(t,x_)
  s_l = s[ind_s-1] if ind_s > 0 else -INF
  s_r = s[ind_s] if ind_s < a else INF
  t_l = t[ind_t-1] if ind_t > 0 else -INF
  t_r = t[ind_t] if ind_t < b else INF
  ans = INF
  for s_ in [s_l,s_r]:
    for t_ in [t_l,t_r]:
      if abs(s_-x_)>abs(t_-x_):
        sub1,sub2 = t_,s_
      else:
        sub1,sub2 = s_,t_
      ans = min(ans,abs(sub1-x_)+abs(sub1-sub2))
  print(ans)

Solution (Python):
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)]

from bisect import bisect

for i in range(q):
    y=bisect(s,x[i])
    z=bisect(t,x[i])
    k=([0] if y==0 else [a-1] if y==a else [y-1,y])
    l=([0] if z==0 else [b-1] if z==b else [z-1,z])
    mi=100000000000000
    for n in k:
        for m in l:
            if abs(s[n]-x[i])>abs(t[m]-x[i]):
                sub1,sub2=t[m],s[n]
            else:
                sub1,sub2=s[n],t[m]
            mi=min(mi,abs(sub1-x[i])+abs(sub2-sub1))
    print(mi)

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

bLeft = bisect.bisect_left

for x in X:
    si = bLeft(S, x)
    sleft = float('inf')
    sright = float('inf')
    if si != 0:
        sleft = x-S[si-1]
    if si != A:
        sright = S[si]-x

    ti = bLeft(T, x)
    tleft = float('inf')
    tright = float('inf')
    if ti != 0:
        tleft = x-T[ti-1]
    if ti != B:
        tright = T[ti]-x

    ans1 = max(sleft, tleft)
    ans2 = max(sright, tright)
    ans3 = min(min(sleft, sright), min(tleft, tright)) + min(sleft, sright) + min(tleft, tright)
    print(min(ans1, ans2, ans3))