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):
def main():
    from bisect import bisect_left
    import sys
    input = sys.stdin.buffer.readline
    def dist(x, s, t):
        if s < x and t < x:
            return x - min(s, t)
        elif s > x and t > x:
            return max(s, t) - x
        else:
            if (ds := abs(x - s)) <= (dt := abs(x - t)):
                return 2 * ds + dt
            else:
                return ds + 2 * dt
    def near(A, x):
        if (i := bisect_left(A, x)) == 0:
            return [A[0], ]
        elif 0 < i < len(A):
            return [A[i - 1], A[i]]
        else:
            return [A[-1], ]
    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())
        ans = 100000000000
        for s in near(S, x):
            for t in near(T, x):
                ans = min(ans, dist(x, s, t))
        print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
from bisect import bisect_left

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()
s=[float('INF')*(-1)]+s+[float('INF')]
t=[float('INF')*(-1)]+t+[float('INF')]
for i in range(q):
    x = int(input())
    sp=bisect_left(s,x)-1
    tp=bisect_left(t,x)-1
    s1=s[sp]
    t1=t[tp]
    s2=s[sp+1]
    t2=t[tp+1]
    print(min(max(x-s1,x-t1),max(s2-x,t2-x),x-s1+t2-s1,x-t1+s2-t1,s2-x+s2-t1,t2-x+t2-s1))

Solution (Python):

import bisect

INF = 10 ** 18


def solve(s,t,x):
  ans = [0]*len(x)
  for i in range(len(x)):
    b = bisect.bisect_right(s,x[i])
    d = bisect.bisect_right(t,x[i])
    res = INF
    for S in [s[b-1],s[b]]:
      for T in [t[d-1],t[d]]:
        res = min(res,abs(S-x[i]) + abs(T-S),abs(T-x[i])+abs(T-S))
    ans[i] = res
  return ans



def main():
  A,B,Q = map(int,input().split())
  s = [-10**18] + [int(input()) for _ in range(A)] + [10**18]
  t = [-10**18] + [int(input()) for _ in range(B)] + [10**18]
  x = [int(input()) for _ in range(Q)]
  ans = solve(s,t,x)
  for i in range(Q):
    print(ans[i])
  return

if __name__ == '__main__':
  main()

Solution (Python):
import bisect
INF=10**100

A,B,Q,*stx,=open(0).read().split()
A,B,Q=map(int,[A,B,Q])
slist=[-INF]+[int(stx[i]) for i in range(A)]+[INF]
tlist=[-INF]+[int(stx[i]) for i in range(A,A+B)]+[INF]
xlist=[int(stx[i]) for i in range(A+B,A+B+Q)]
oslist=[0]*2
otlist=[0]*2
sr_index=0
tr_index=0
for i in xlist:
    ans=INF
    sr_index=bisect.bisect_left(slist,i)
    oslist=[slist[sr_index-1],slist[sr_index]]
    tr_index=bisect.bisect_left(tlist,i)
    otlist=[tlist[tr_index-1],tlist[tr_index]]
    for j in oslist:
        for k in otlist:
            ans=min(ans,abs(j-i)+abs(k-j),abs(k-i)+abs(j-k))
    print(ans)

Solution (Python):
A, B, Q = map(int, input().split())
S = [-10**18]+sorted([int(input()) for _ in range(A)])+[10**18]
T = [-10**18]+sorted([int(input()) for _ in range(B)])+[10**18]
import bisect
for _ in range(Q):
  x = int(input())
  i = bisect.bisect_left(S, x)
  j = bisect.bisect_left(T, x)
  p, q, r, s = S[i-1], S[i], T[j-1], T[j]
  res = 10**18
  for a in (p, q):
    for b in (r, s):
      res = min(res, abs(x-a)+abs(a-b), abs(x-b)+abs(a-b))
  print(res)

Solution (Python):
from bisect 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):
  x=int(input())
  s_inx=bisect(s,x)
  t_inx=bisect(t,x)

  s_l=s[s_inx-1]
  s_r=s[s_inx]

  t_l=t[t_inx-1]
  t_r=t[t_inx]

  ans=10**18
  for i in [s_l,s_r]:
    for j in [t_l,t_r]:
      d1=abs(i-x)+abs(j-i)
      d2=abs(j-x)+abs(i-j)
      ans=min(ans,d1,d2)

  print(ans)

Solution (Python):
from bisect import bisect

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

for i in range(q):
  x=int(input())
  s_inx=bisect(s,x)
  t_inx=bisect(t,x)

  s_l=s[s_inx-1]
  s_r=s[s_inx]

  t_l=t[t_inx-1]
  t_r=t[t_inx]

  ans=10**18
  for i in [s_l,s_r]:
    for j in [t_l,t_r]:
      d1=abs(i-x)+abs(j-i)
      d2=abs(j-x)+abs(i-j)
      ans=min(ans,d1,d2)

  print(ans)

Solution (Python):
from bisect import bisect

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

for i in range(q):
  x=int(input())
  s_inx=bisect(s,x)
  t_inx=bisect(t,x)

  s_l=s[s_inx-1]
  s_r=s[s_inx]

  t_l=t[t_inx-1]
  t_r=t[t_inx]

  ans=10**18
  for i in [s_l,s_r]:
    for j in [t_l,t_r]:
      ans=min(ans,abs(i-x)+abs(j-i))

  for i in [t_l,t_r]:
    for j in [s_l,s_r]:
      ans=min(ans,abs(i-x)+abs(j-i))

  print(ans)

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from bisect import bisect

a,b,q=nii()
s=[-10**18]+[int(input()) for i in range(a)]+[10**18]
t=[-10**18]+[int(input()) for i in range(b)]+[10**18]

for i in range(q):
  x=int(input())
  s_inx=bisect(s,x)
  t_inx=bisect(t,x)

  s_l=s[s_inx-1]
  s_r=s[s_inx]

  t_l=t[t_inx-1]
  t_r=t[t_inx]

  ans=10**18
  for i in [s_l,s_r]:
    for j in [t_l,t_r]:
      ans=min(ans,abs(i-x)+abs(j-i))

  for i in [t_l,t_r]:
    for j in [s_l,s_r]:
      ans=min(ans,abs(i-x)+abs(j-i))

  print(ans)

Solution (Python):
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from bisect import bisect

a,b,q=nii()
s=[-10**18]+[int(input()) for i in range(a)]+[10**18]
t=[-10**18]+[int(input()) for i in range(b)]+[10**18]

for i in range(q):
  x=int(input())
  s_inx=bisect(s,x)
  t_inx=bisect(t,x)

  s_l=s[s_inx-1]
  s_r=s[s_inx]

  t_l=t[t_inx-1]
  t_r=t[t_inx]

  ans=10**18
  for i in [s_l,s_r]:
    for j in [t_l,t_r]:
      ans=min(ans,abs(i-x)+abs(j-i))

  for i in [t_l,t_r]:
    for j in [s_l,s_r]:
      ans=min(ans,abs(i-x)+abs(j-i))

  print(ans)

Solution (Python):
def abc119_d():
    import sys
    read = sys.stdin.buffer.read
    inp = iter(map(int, read().split()))

    a = next(inp)
    b = next(inp)
    q = next(inp)
    S = [next(inp) for _ in range(a)]
    T = [next(inp) for _ in range(b)]

    from bisect import bisect_left
    inf = 10**12

    for _ in range(q):
        x = next(inp)
        si = bisect_left(S, x)
        ti = bisect_left(T, x)

        sl, sr = inf, inf
        tl, tr = inf, inf
        if 0 < si: sl = x - S[si-1]
        if si < a: sr = S[si] - x
        if 0 < ti: tl = x - T[ti-1]
        if ti < b: tr = T[ti] - x

        ans = inf
        ans = min(ans, max(sl, tl))
        ans = min(ans, max(sr, tr))
        ans = min(ans, 2 * min(sl, tr) + max(sl, tr))
        ans = min(ans, 2 * min(sr, tl) + max(sr, tl))
        print(ans)

if __name__ == '__main__':
    abc119_d()

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:
    
    sx = bisect.bisect(S, x)
    
    try:
        se = S[sx]
    except:
        
        se = S[-1]
    
    try:
        sw = S[sx-1]
    except:
        
        sw = S[0]

    tx = bisect.bisect(T, x)
    
    try:
        te = T[tx]
    except:
        
        te = T[-1]
    
    try:
        tw = T[tx-1]
    except:
        
        tw = T[0]

    
    
    
    
    
    
    
    
    
    routes = []
    for s in [se, sw]:
        for t in [te, tw]:
            routes.append(abs(s - x)+abs(t - s))
            routes.append(abs(t - x)+abs(s - t))

    
    print(min(routes))

Solution (Python):
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

A, B, Q = mapint()
Ss = [-10**20]+[int(input()) for _ in range(A)]+[10**20]
Ts = [-10**20]+[int(input()) for _ in range(B)]+[10**20]
Ss.sort()
Ts.sort()
from bisect import bisect_left

for _ in range(Q):
    x = int(input())
    xs = bisect_left(Ss, x)
    xt = bisect_left(Ts, x)

    rr = max(Ss[xs]-x, Ts[xt]-x)
    ll = max(x-Ss[xs-1], x-Ts[xt-1])
    lr = min(abs(x-Ss[xs-1])*2+abs(x-Ts[xt]), abs(x-Ts[xt-1])*2+abs(x-Ss[xs]))
    rl = min(abs(x-Ss[xs-1])+abs(x-Ts[xt])*2, abs(x-Ts[xt-1])+abs(x-Ss[xs])*2)
    print(min(rr, ll, rl, lr))

Solution (Python):
from bisect import bisect_right
INFTY = 10**11
A,B,Q = map(int,input().split())
S = [int(input()) for _ in range(A)]
S.insert(0,-INFTY)
S.append(INFTY)
T = [int(input()) for _ in range(B)]
T.insert(0,-INFTY)
T.append(INFTY)
for _ in range(Q):
    x = int(input())
    indS = bisect_right(S,x)
    indT = bisect_right(T,x)
    d1 = x-S[indS-1]+abs(S[indS-1]-T[indT-1])
    d2 = x-S[indS-1]+abs(S[indS-1]-T[indT])
    d3 = S[indS]-x+abs(S[indS]-T[indT-1])
    d4 = S[indS]-x+abs(S[indS]-T[indT])
    d5 = x-T[indT-1]+abs(T[indT-1]-S[indS-1])
    d6 = x-T[indT-1]+abs(T[indT-1]-S[indS])
    d7 = T[indT]-x+abs(T[indT]-S[indS-1])
    d8 = T[indT]-x+abs(T[indT]-S[indS])
    print(min(d1,d2,d3,d4,d5,d6,d7,d8))

Solution (Python):
def main():
    from bisect import bisect_left
    A, B, Q = map(int, input().split())
    INF = 2 * 10 ** 10
    S = [-INF] + [int(input()) for _ in range(A)] + [INF]
    T = [-INF] + [int(input()) for _ in range(B)] + [INF]
    S_rev = [-s for s in S][::-1]
    T_rev = [-t for t in T][::-1]

    for q in range(Q):
        x = int(input())
        ans = 5 * 10 ** 10

        
        cost1_s = S[bisect_left(S, x)] - x
        cost1_t = T[bisect_left(T, x)] - x
        ans = min(ans, max(cost1_s, cost1_t))

        
        cost2_s = S_rev[bisect_left(S_rev, -x)] + x
        cost2_t = T_rev[bisect_left(T_rev, -x)] + x
        ans = min(ans, max(cost2_s, cost2_t))

        
        cost3_s = S[bisect_left(S, x)] - x
        cost3_t = T_rev[bisect_left(T_rev, -x)] + x
        ans = min(ans, 2 * min(cost3_s, cost3_t) + max(cost3_s, cost3_t))

        
        cost3_s = S_rev[bisect_left(S_rev, -x)] + x
        cost3_t = T[bisect_left(T, x)] - x
        ans = min(ans, 2 * min(cost3_s, cost3_t) + max(cost3_s, cost3_t))

        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)]
s.sort()
t = [int(input()) for i in range(b)]
t.sort()

"""
sとtのどちらを先にするか
左右どちらに走るか
の都合4パターンの最小値を選べばよい
"""

def minl(x):
    
    idx = bisect.bisect_left(s, x)
    ret = 3*10**10
    if idx == 0:
        first = s[0] - x
        now = s[0]
        idx = bisect.bisect_left(t, now)
        if idx == 0:
            second = t[0] - now
        elif idx == b:
            second = now - t[b-1]
        else:
            second = min(now - t[idx-1], t[idx]-now)
        ret = min(ret, first+second)
    elif idx == a:
        first = x - s[a-1]
        now = s[a-1]
        idx = bisect.bisect_left(t, now)
        if idx == 0:
            second = t[0] - now
        elif idx == b:
            second = now - t[b-1]
        else:
            second = min(now - t[idx-1], t[idx]-now)
        ret = min(ret, first+second)
    else:
        for first_g in [s[idx-1], s[idx]]:
            first = abs(first_g - x)
            now = first_g
            idx = bisect.bisect_left(t, now)
            if idx == 0:
                second = t[0] - now
            elif idx == b:
                second = now - t[b-1]
            else:
                second = min(now - t[idx-1], t[idx]-now)
            ret = min(ret, first+second)
    
    
    idx = bisect.bisect_left(t, x)
    if idx == 0:
        first = t[0] - x
        now = t[0]
        idx = bisect.bisect_left(s, now)
        if idx == 0:
            second = s[0] - now
        elif idx == a:
            second = now - s[a-1]
        else:
            second = min(now - s[idx-1], s[idx]-now)
        ret = min(ret, first+second)
    elif idx == b:
        first = x - t[b-1]
        now = t[b-1]
        idx = bisect.bisect_left(s, now)
        if idx == 0:
            second = s[0] - now
        elif idx == a:
            second = now - s[a-1]
        else:
            second = min(now - s[idx-1], s[idx]-now)
        ret = min(ret, first+second)
    else:
        for first_g in [t[idx-1], t[idx]]:
            first = abs(first_g - x)
            now = first_g
            idx = bisect.bisect_left(s, now)
            if idx == 0:
                second = s[0] - now
            elif idx == a:
                second = now - s[a-1]
            else:
                second = min(now - s[idx-1], s[idx]-now)
            ret = min(ret, first+second)
    return ret

for i in range(q):
    x = int(input())
    print(minl(x))

Solution (Python):
from bisect import bisect_left

import sys
input = sys.stdin.readline  
A,B,Q = (int(i) for i in input().split())
st ={"s":[],"t":[]}
x =[0] *Q

for i in range(A):
    aa = int(input())
    st["s"].append(aa)
st["s"].append(10**11)

for i in range(B):
    bb = int(input())
    st["t"].append(bb)
st["t"].append(10**11)


for i in range(Q):
    x[i] = int(input())


dist =[]
for xi in x:
    
    xs =bisect_left(st["s"],xi)
    s_l =st["s"][xs-1] 
    s_r =st["s"][xs  ] 
    xs_l =abs(xi -s_l)  
    xs_r =abs(xi -s_r)    

    xs_l_t =bisect_left(st["t"],s_l ) 
    t_l =st["t"][xs_l_t -1] 
    t_r =st["t"][xs_l_t   ] 
    xs_l_t_l =abs(s_l -t_l) 
    xs_l_t_r =abs(s_l -t_r) 
    
    xs_r_t =bisect_left(st["t"],s_r ) 
    t_l =st["t"][xs_r_t -1] 
    t_r =st["t"][xs_r_t   ] 
    xs_r_t_l =abs(s_r -t_l) 
    xs_r_t_r =abs(s_r -t_r)
    ds =min(xs_l +xs_l_t_l ,xs_l +xs_l_t_r ,xs_r +xs_r_t_l ,xs_r +xs_r_t_r)

     
    xs =bisect_left(st["t"],xi)
    s_l =st["t"][xs-1] 
    s_r =st["t"][xs  ] 
    xs_l =abs(xi -s_l)  
    xs_r =abs(xi -s_r)    

    xs_l_t =bisect_left(st["s"],s_l ) 
    t_l =st["s"][xs_l_t -1] 
    t_r =st["s"][xs_l_t   ] 
    xs_l_t_l =abs(s_l -t_l) 
    xs_l_t_r =abs(s_l -t_r) 
    
    xs_r_t =bisect_left(st["s"],s_r ) 
    t_l =st["s"][xs_r_t -1] 
    t_r =st["s"][xs_r_t   ] 
    xs_r_t_l =abs(s_r -t_l) 
    xs_r_t_r =abs(s_r -t_r)
    dt =min(xs_l +xs_l_t_l ,xs_l +xs_l_t_r ,xs_r +xs_r_t_l ,xs_r +xs_r_t_r)
    print(min(ds,dt))

Solution (Python):
import sys
import itertools

import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines



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 bound(Z, z):
    l = 0
    r = len(Z) - 1
    while r - l > 1:
        m = (l + r) // 2
        if Z[m] >= z:
            r = m
        else:
            l = m
    return r

for x in X:
    s = [0] * 2
    s[0] = bound(S, x)
    s[1] = s[0] - 1

    t = [0] * 2
    t[0] = bound(T, x)
    t[1] = t[0] - 1

    ans = INF
    
    for i in range(2):
        for j in range(2):
            val = 0
            if x >= S[s[i]] and x >= T[t[j]]:
                val = max(abs(x - S[s[i]]), abs(x - T[t[j]]))
            elif x <= S[s[i]] and x <= T[t[j]]:
                val = max(abs(x - S[s[i]]), abs(x - T[t[j]]))
            else:
                val = min(abs(x - S[s[i]]) * 2 + abs(x - T[t[j]]), abs(x - S[s[i]]) + abs(x - T[t[j]]) * 2)
            ans = min(ans, val)
    
    
    
    
    print(ans)

Solution (Python):
import bisect
a, b, q = 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 = [-float('inf')] + ss + [float('inf')]
ts = [-float('inf')] + ts + [float('inf')]
for x in xs:
    s_r = bisect.bisect_left(ss, x)
    t_r = bisect.bisect_left(ts, x)
    s_l = s_r - 1
    t_l = t_r - 1
    res = float('inf')
    if ss[s_l] > ts[t_l]:
        res = min(res, x - ts[t_l], (x - ss[s_l])*2 + (ts[t_r] - x))
    elif ss[s_l] < ts[t_l]:
        res = min(res, x - ss[s_l], (x - ts[t_l])*2 + (ss[s_r] - x))
    else:
        res = min(res, (x - ss[s_l])*2 + (ss[s_r] - x), x - ss[s_l]*2 + (ts[t_r] - x))
    if ss[s_r] > ts[t_r]:
        res = min(res, ss[s_r] - x, (ts[t_r] - x)*2 + (x - ss[s_l]))
    elif ss[s_r] < ts[t_r]:
        res = min(res, ts[t_r] - x, (ss[s_r] - x)*2 + (x - ts[t_l]))
    else:
        res = min(res, (ss[s_r] - x)*2 + (x - ss[s_l]), (ss[s_r] - x)*2 + (x - ts[t_l]))
    print(res)

Solution (Python):
import sys
from bisect import bisect_left

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    a, b, q = map(int, input().split())
    S = [-f_inf] + list(int(input()) for _ in range(a)) + [f_inf]
    T = [-f_inf] + list(int(input()) for _ in range(b)) + [f_inf]

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

        idx_s = bisect_left(S, x)
        idx_t = bisect_left(T, x)
        for s in [S[idx_s - 1], S[idx_s]]:
            for t in [T[idx_t - 1], T[idx_t]]:
                d1 = abs(s - x) + abs(s - t)
                d2 = abs(t - x) + abs(t - s)
                res = min(res, d1, d2)
        print(res)


if __name__ == '__main__':
    resolve()

Solution (Python):

from bisect import bisect_right

def main():
    A, B, Q = map(int, input().split())
    s = [int(input()) for _ in range(A)]
    t = [int(input()) for _ in range(B)]
    
    s = [-10**12] + s + [10**12]
    t = [-10**12] + t + [10**12]

    for _ in range(Q):
        x = int(input())
        i = bisect_right(s,x)
        j = bisect_right(t,x)
        
        ans = []

        ans.append(max(abs(s[i-1] - x), abs(t[j-1] - x)))
        ans.append(max(abs(s[i] - x), abs(t[j] - x)))
        ans.append(abs(s[i-1] - x) + abs(t[j] - x) + min(abs(s[i-1]-x), abs(t[j]-x)))
        ans.append(abs(s[i] - x) + abs(t[j-1] - x) + min(abs(s[i]-x), abs(t[j-1]-x)))

        print(min(ans))

if __name__ == "__main__":
    main()

Solution (Python):





def leq_search(xs, x, s, t):
    
    if t-s <= 3:
        res = 0
        for i in range(s, t):
            if xs[i] <= x:
                res = i
        return res

    i = (s+t)//2
    if xs[i] <= x:
        return leq_search(xs, x, i, t)
    else:
        return leq_search(xs, x, s, i)


def geq_search(xs, x, s, t):
    
    if t-s <= 3:
        res = 0
        for i in range(t-1, s-1, -1):
            if xs[i] >= x:
                res = i
        return res

    i = (s+t)//2
    if xs[i] >= x:
        return geq_search(xs, x, s, i+1)
    else:
        return geq_search(xs, x, i+1, t)


def nearest_search(xs, x, s, t):
    
    if t-s <= 3:
        res = s
        for i in range(s, t):
            if abs(x-xs[i]) < abs(x-xs[res]):
                res = i
        return res

    i = (s+t)//2
    if xs[i] <= x:
        return nearest_search(xs, x, i, t)
    else:
        return nearest_search(xs, x, s, i+1)


def main():
    A, B, Q = map(int, input().split())
    s = [None] * A
    t = [None] * B
    xs = [None] * Q
    for i in range(A):
        s[i] = int(input())
    for i in range(B):
        t[i] = int(input())
    for i in range(Q):
        xs[i] = int(input())

    S, T = 0, 1
    st = [[s[i], S, i] for i in range(A)]
    st.extend([[t[i], T, i] for i in range(B)])
    
    st = sorted(st, key=lambda x: x[0])
    st_retrieval = [x[0] for x in st]

    
    s_near_t = [None] * A
    for i in range(A):
        s_near_t[i] = t[nearest_search(t, s[i], 0, B)]

    
    t_near_s = [None] * B
    for i in range(B):
        t_near_s[i] = s[nearest_search(s, t[i], 0, A)]

    for x in xs:
        
        near_i = leq_search(st_retrieval, x, 0, A+B)
        val, mark, i = st[near_i]
        
        
        
        cand1 = abs(val-x)
        if mark == S:
            near_t = s_near_t[i]
            cand1 += abs(near_t-val)
        else:
            near_s = t_near_s[i]
            cand1 += abs(near_s-val)

        
        near_i = geq_search(st_retrieval, x, 0, A+B)
        val, mark, i = st[near_i]
        
        
        
        cand2 = abs(val-x)
        if mark == S:
            near_t = s_near_t[i]
            cand2 += abs(near_t-val)
        else:
            near_s = t_near_s[i]
            cand2 += abs(near_s-val)
        
        print(min(cand1, cand2))


main()

Solution (Python):
from bisect import bisect_left

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

for i in x:
    
    idx_s, idx_t = bisect_left(s, i), bisect_left(t, i)
    ans = dummy
    for j in [s[idx_s-1], s[idx_s]]:
        for k in [t[idx_t-1], t[idx_t]]:
            res1, res2 = abs(j - i) + abs(k - j), abs(k - i) + abs(j - k)
            ans = min(ans, res1, res2)
    print(ans)

Solution (Python):
from bisect import bisect_left
A, B, Q = map(int, input().split())
s = [int(input()) for _ in range(A)]
t = [int(input()) for _ in range(B)]

s.sort()
t.sort()

for k in range(Q):
    x = int(input())
    ans = []
    ms = bisect_left(s, x)
    for i in [-1, 0]:
        if 0 <= ms + i <= A - 1:
            mt = bisect_left(t, s[ms + i])
            for j in [-1, 0]:
                if 0 <= mt + j <= B - 1:
                    ans.append(abs(s[ms + i] - x) + abs(t[mt + j] - s[ms + i]))
    mt = bisect_left(t, x)
    for i in [-1, 0]:
        if 0 <= mt + i <= B - 1:
            ms = bisect_left(s, t[mt + i])
            for j in [-1, 0]:
                if 0 <= ms + j <= A - 1:
                    ans.append(abs(t[mt + i] - x) + abs(s[ms + j] - t[mt + i]))
    print(min(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 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

def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  

A,B,Q = LI()
inf = 10**12
s = [-inf]+[I() for _ in range(A)]+[inf]
t = [-inf]+[I() for _ in range(B)]+[inf]
x = [I() for _ in range(Q)]

from bisect import bisect



for i in range(Q):
    y = x[i]
    a = bisect(s,y)
    b = bisect(t,y)
    s1,s2,t1,t2 = s[a-1],s[a],t[b-1],t[b]
    z1 = abs(y-s1)+abs(s1-t1)
    z2 = abs(y-s1)+abs(s1-t2)
    z3 = abs(y-s2)+abs(s2-t1)
    z4 = abs(y-s2)+abs(s2-t2)
    z5 = abs(y-t1)+abs(t1-s1)
    z6 = abs(y-t1)+abs(t1-s2)
    z7 = abs(y-t2)+abs(t2-s1)
    z8 = abs(y-t2)+abs(t2-s2)
    print(min(z1,z2,z3,z4,z5,z6,z7,z8))

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 = sorted(S)
T = sorted(T)

for j in range(Q):
    x = int(input())
    a = S[bisect.bisect_left(S, x)-1]
    b = T[bisect.bisect_left(T, x)-1]
    if x <=S[-1]:
        a_ = S[bisect.bisect_right(S,x)]
    else:
        a_ = S[bisect.bisect_right(S,x)-1]
    if x <= T[-1]:
        b_ = T[bisect.bisect_right(T,x)]
    else:
        b_ = T[bisect.bisect_right(T,x)-1]
    y = min([abs(a-x)+abs(b-a),abs(a-x)+abs(b_-a),abs(a_-x)+abs(b-a_),abs(a_-x)+abs(b_-a_),
            abs(b-x)+abs(a-b),abs(b-x)+abs(a_-b), abs(b_-x)+abs(a-b_), abs(b_-x)+abs(b_-a_)])
    print(y)

Solution (Python):
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from bisect import bisect

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

for i in range(q):
  x = int(input())
  ss = bisect(s,x)
  if ss == 0:
    sR = s[0]
    sL = s[0]
  elif ss == len(s):
    sR = s[-1]
    sL = s[-1]
  else:
    sR = s[ss]
    sL = s[ss-1]
    
  sRt = bisect(t,sR)
  sLt = bisect(t,sL)
  if sRt == 0:
    sRtL = t[0]
  else:
    sRtL = t[sRt-1]
  if sLt == len(t):
    sLtR = t[-1]
  else:
    sLtR = t[sLt]
  if sRt == len(t):
    sRtR = t[-1]
  else:
    sRtR = t[sRt]
  if sLt == 0:
    sLtL = t[0]
  else:
    sLtL = t[sLt-1]
  chk = min(abs(x-sL)+abs(sL-sLtL),abs(x-sL)+abs(sL-sLtR),abs(x-sR)+abs(sR-sRtR),abs(x-sR)+abs(sR-sRtL))
  ss = bisect(t,x)
  if ss == 0:
    sR = t[0]
    sL = t[0]
  elif ss == len(t):
    sR = t[-1]
    sL = t[-1]
  else:
    sR = t[ss]
    sL = t[ss-1]
  sRt = bisect(s,sR)
  sLt = bisect(s,sL)
  if sRt == 0:
    sRtL = s[0]
  else:
    sRtL = s[sRt-1]
  if sLt == len(s):
    sLtR = s[-1]
  else:
    sLtR = s[sLt]
  if sRt == len(s):
    sRtR = s[-1]
  else:
    sRtR = s[sRt]
  if sLt == 0:
    sLtL = s[0]
  else:
    sLtL = s[sLt-1]  
  chk = min(chk,abs(x-sL)+abs(sL-sLtL),abs(x-sL)+abs(sL-sLtR),abs(x-sR)+abs(sR-sRtR),abs(x-sR)+abs(sR-sRtL))
  print(chk)

Solution (Python):
from bisect import bisect_left
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()))
INF = 10**12
for _ in range(q):
    x = int(input())
    s_l = t_l = -INF
    s_r = t_r = INF
    tmp = bisect_left(s, x)
    if tmp>0:
        s_l = s[tmp-1]
    if tmp<a:
        s_r = s[tmp]
    tmp = bisect_left(t, x)
    if tmp>0:
        t_l = t[tmp-1]
    if tmp<b:
        t_r = t[tmp]
    ans = min(
        x-min(s_l, t_l),
        max(s_r, t_r)-x,
        s_r-t_l+min(s_r-x, x-t_l),
        t_r-s_l+min(t_r-x, x-s_l)
    )
    print(ans)

Solution (Python):
from bisect import *
A,B,Q=map(int,input().split())
INF=10**15
S=[-INF*10,-INF]
for i in range(A):
  S.append(int(input()))
S.append(INF)
S.append(INF*10)
T=[-INF*10,-INF]
for i in range(B):
  T.append(int(input()))
T.append(INF)
T.append(INF*10)
D,E,F,G,V,W,X,Y,Z,P=0,0,0,0,0,0,0,0,0,0
for i in range(Q):
  X=int(input())
  V=bisect_left(S,X)
  Y,Z=S[V-1],S[V]
  D,E=abs(X-Y),abs(X-Z)
  V,W=bisect_left(T,Y),bisect_left(T,Z)
  F,G=min(abs(Y-T[V-1]),abs(Y-T[V])),min(abs(Z-T[W-1]),abs(Z-T[W]))
  P=min(D+F,E+G)
  V=bisect_left(T,X)
  Y,Z=T[V-1],T[V]
  D,E=abs(X-Y),abs(X-Z)
  V,W=bisect_left(S,Y),bisect_left(S,Z)
  F,G=min(abs(Y-S[V-1]),abs(Y-S[V])),min(abs(Z-S[W-1]),abs(Z-S[W]))
  print(min(P,D+F,E+G))

Solution (Python):
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
def gcd(*numbers): reduce(math.gcd, numbers)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7
count = 0
ans = 0

A, B, Q = I()
inf = float("inf")
s = [-inf]+sorted([k() for _ in range(A)])+[inf]
t = [-inf]+sorted([k() for _ in range(B)])+[inf]
aa = []

for i in range(Q):
    q = k()
    S = bisect.bisect(s,q)
    T = bisect.bisect(t,q)
    ans = inf
    for j in [s[S-1],s[S]]:
        for z in [t[T-1],t[T]]:
            x = abs(j-q)+abs(j-z)
            y = abs(z-q)+abs(j-z)
            ans = min(ans,x,y)
    aa.append(ans)

for i in aa:
    print(i)

Solution (Python):
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)]
from bisect import bisect_left
for xi in x:
  ans=float('inf')
  si=bisect_left(s,xi)
  ti=bisect_left(t,xi)
  
  if xi<=s[-1] and xi<=t[-1]:
    ans=min(ans,max(s[si]-xi,t[ti]-xi))
  
  if xi>=s[0] and xi>=t[0]:
    ss=0 if si<a and xi-s[si]==0 else xi-s[si-1]
    tt=0 if ti<b and xi-t[ti]==0 else xi-t[ti-1]
    ans=min(ans,max(ss,tt))
    
  
  
  if s[0]<=xi and xi<=t[-1]:
    w=xi-s[si-1]
    e=t[ti]-xi
    tmp=2*min(w,e)+max(w,e)
    ans=min(ans,tmp)
  
  if t[0]<=xi and xi<=s[-1]:
    w=xi-t[ti-1]
    e=s[si]-xi
    tmp=2*min(w,e)+max(w,e)
    ans=min(ans,tmp)
  print(ans)

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

for i in range(Q):
    ans = 10 ** 19
    x = int(input())
    stmp1 = bisect.bisect_left(s, x)
    for j in range(2):
        if stmp1 == 0 and j == 1:
            continue
        if stmp1 == A and j == 0:
            continue
        ttmp1 = bisect.bisect_left(t, s[stmp1 - j])
        ktmp = 10 ** 11
        if ttmp1 != 0:
            ktmp = min(ktmp, abs(s[stmp1 - j] - t[ttmp1 - 1]))
        if ttmp1 != B:
            ktmp = min(ktmp, abs(s[stmp1 - j] - t[ttmp1]))
        total = abs(x - s[stmp1 - j]) + ktmp
        ans = min(ans, total)

    ttmp1 = bisect.bisect_left(t, x)
    for j in range(2):
        if ttmp1 == 0 and j == 1:
            continue
        if ttmp1 == B and j == 0:
            continue
        stmp1 = bisect.bisect_left(s, t[ttmp1 - j])
        ktmp = 10 ** 11
        if stmp1 != 0:
            ktmp = min(ktmp, abs(t[ttmp1 - j] - s[stmp1 - 1]))
        if stmp1 != A:
            ktmp = min(ktmp, abs(t[ttmp1 - j] - s[stmp1]))
        total = abs(x - t[ttmp1 - j]) + ktmp
        ans = min(ans, total)
    print(ans)