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 sys, re
from collections import deque, defaultdict, Counter
from math import sqrt, hypot, factorial, pi, sin, cos, radians, log10
if sys.version_info.minor >= 5: from math import gcd
else: from fractions import gcd 
from heapq import heappop, heappush, heapify, heappushpop
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul, xor
from copy import copy, deepcopy
from functools import reduce, partial
from fractions import Fraction
from string import ascii_lowercase, ascii_uppercase, digits
from datetime import date

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def round(x): return int((x*2+1) // 2)
def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD
def lcm(x, y): return (x * y) // gcd(x, y)
def lcm_list(nums): return reduce(lcm, nums, 1)
def gcd_list(nums): return reduce(gcd, nums, nums[0])
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

A,B,Q=MAP()

S=[-INF]*(A+2)
for i in range(A):
    S[i+1]=INT()
T=[-INF]*(B+2)
for i in range(B):
    T[i+1]=INT()
S[-1]=T[-1]=INF


L1=[INF]*(A+2)

R1=[INF]*(A+2)
for i in range(1, A+1):
    idx=bisect_right(T, S[i])-1
    if T[idx]!=0:
        L1[i]=S[i]-T[idx]
    idx=bisect_left(T, S[i])
    if T[idx]!=INF:
        R1[i]=T[idx]-S[i]


L2=[INF]*(B+2)

R2=[INF]*(B+2)
for i in range(1, B+1):
    idx=bisect_right(S, T[i])-1
    if S[idx]!=0:
        L2[i]=T[i]-S[idx]
    idx=bisect_left(S, T[i])
    if S[idx]!=INF:
        R2[i]=S[idx]-T[i]

for i in range(Q):
    dist1=dist2=dist3=dist4=INF
    x=INT()
    
    idx=bisect_right(S, x)-1
    
    dist1=x-S[idx]
    
    dist1+=min(L1[idx], R1[idx])
    idx=bisect_left(S, x)
    dist2=S[idx]-x
    dist2+=min(L1[idx], R1[idx])
    idx=bisect_right(T, x)-1
    dist3=x-T[idx]
    dist3+=min(L2[idx], R2[idx])
    idx=bisect_left(T, x)
    dist4=T[idx]-x
    dist4+=min(L2[idx], R2[idx])
    print(min(dist1, dist2, dist3, dist4))

Solution (Python):


import sys, re
from collections import deque, defaultdict, Counter
from math import sqrt, hypot, factorial, pi, sin, cos, radians, log10
if sys.version_info.minor >= 5: from math import gcd
else: from fractions import gcd 
from heapq import heappop, heappush, heapify, heappushpop
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul, xor
from copy import copy, deepcopy
from functools import reduce, partial
from fractions import Fraction
from string import ascii_lowercase, ascii_uppercase, digits
from datetime import date

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def round(x): return int((x*2+1) // 2)
def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD
def lcm(x, y): return (x * y) // gcd(x, y)
def lcm_list(nums): return reduce(lcm, nums, 1)
def gcd_list(nums): return reduce(gcd, nums, nums[0])
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

A,B,Q=MAP()

S=[0]*(A+2)
for i in range(A):
    S[i+1]=INT()
T=[0]*(B+2)
for i in range(B):
    T[i+1]=INT()
S[-1]=T[-1]=INF


L1=[INF]*(A+2)

R1=[INF]*(A+2)
for i in range(1, A+1):
    idx=bisect_right(T, S[i])-1
    if T[idx]!=0:
        L1[i]=S[i]-T[idx]
    idx=bisect_left(T, S[i])
    if T[idx]!=INF:
        R1[i]=T[idx]-S[i]


L2=[INF]*(B+2)

R2=[INF]*(B+2)
for i in range(1, B+1):
    idx=bisect_right(S, T[i])-1
    if S[idx]!=0:
        L2[i]=T[i]-S[idx]
    idx=bisect_left(S, T[i])
    if S[idx]!=INF:
        R2[i]=S[idx]-T[i]

for i in range(Q):
    dist1=dist2=dist3=dist4=INF
    x=INT()
    
    idx=bisect_right(S, x)-1
    if S[idx]!=0:
        
        dist1=x-S[idx]
        
        dist1+=min(L1[idx], R1[idx])
    idx=bisect_left(S, x)
    if S[idx]!=INF:
        dist2=S[idx]-x
        dist2+=min(L1[idx], R1[idx])
    idx=bisect_right(T, x)-1
    if T[idx]!=0:
        dist3=x-T[idx]
        dist3+=min(L2[idx], R2[idx])
    idx=bisect_left(T, x)
    if T[idx]!=INF:
        dist4=T[idx]-x
        dist4+=min(L2[idx], R2[idx])
    print(min(dist1, dist2, dist3, dist4))

Solution (Python):
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))

A,B,Q=rl()
s=[0]*(A+2)
t=[0]*(B+2)
X=[0]*Q
for i in range(1,A+1):
    s[i]=ri()
s[0],s[A+1]=-float('inf'),float('inf')
s.sort()
for i in range(1,B+1):
    t[i]=ri()
t[0],t[B+1]=-float('inf'),float('inf')
t.sort()
for i in range(Q):
    X[i]=ri()

import bisect
for x in X:
    s_i = bisect.bisect_left(s,x)
    t_i = bisect.bisect_left(t,x)
    s_l = x-s[s_i-1]
    s_r = s[s_i]-x
    t_l = x-t[t_i-1]
    t_r = t[t_i]-x
    ans = min(
        [max(s_l,t_l), s_l+t_r+min(s_l,t_r), s_r+t_l+min(s_r,t_l), max(s_r,t_r)]
    )
    print(ans)

Solution (Python):
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))

A,B,Q=rl()
s=[0]*(A+2)
t=[0]*(B+2)
X=[0]*Q
for i in range(1,A+1):
    s[i]=ri()
s[0],s[A+1]=-float('inf'),float('inf')
s.sort()
for i in range(1,B+1):
    t[i]=ri()
t[0],t[B+1]=-float('inf'),float('inf')
t.sort()
for i in range(Q):
    X[i]=ri()

import bisect
for x in X:
    s_i = bisect.bisect_left(s,x)
    t_i = bisect.bisect_left(t,x)
    s_l = x-s[s_i-1]
    s_r = s[s_i]-x
    t_l = x-t[t_i-1]
    t_r = t[t_i]-x
    ans = min(
        [max(s_l,t_l), s_l+t_r+min(s_l,t_r), s_r+t_l+min(s_r,t_l), max(s_r,t_r)]
    )
    print(ans)

Solution (Python):


import sys, re
from collections import deque, defaultdict, Counter
from math import sqrt, hypot, factorial, pi, sin, cos, radians, log10
if sys.version_info.minor >= 5: from math import gcd
else: from fractions import gcd 
from heapq import heappop, heappush, heapify, heappushpop
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul, xor
from copy import copy, deepcopy
from functools import reduce, partial
from fractions import Fraction
from string import ascii_lowercase, ascii_uppercase, digits
from datetime import date

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def round(x): return int((x*2+1) // 2)
def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD
def lcm(x, y): return (x * y) // gcd(x, y)
def lcm_list(nums): return reduce(lcm, nums, 1)
def gcd_list(nums): return reduce(gcd, nums, nums[0])
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

A,B,Q=MAP()

S=[0]*(A+2)
for i in range(A):
    S[i+1]=INT()
T=[0]*(B+2)
for i in range(B):
    T[i+1]=INT()
S[-1]=T[-1]=INF


L1=[INF]*(A+2)

R1=[INF]*(A+2)
for i in range(1, A+1):
    idx=bisect_right(T, S[i])-1
    if idx!=0:
        L1[i]=S[i]-T[idx]
    idx=bisect_left(T, S[i])
    if idx!=INF:
        R1[i]=T[idx]-S[i]

L2=[INF]*(B+2)

R2=[INF]*(B+2)
for i in range(1, B+1):
    idx=bisect_right(S, T[i])-1
    if idx!=0:
        L2[i]=T[i]-S[idx]
    idx=bisect_left(S, T[i])
    if idx!=INF:
        R2[i]=S[idx]-T[i]

for i in range(Q):
    dist1=dist2=dist3=dist4=INF
    x=INT()
    idx=bisect_right(S, x)-1
    if idx!=0:
        dist1=x-S[idx]
        dist1+=min(L1[idx], R1[idx])
    idx=bisect_left(S, x)
    if idx!=INF:
        dist2=S[idx]-x
        dist2+=min(L1[idx], R1[idx])
    idx=bisect_right(T, x)-1
    if idx!=0:
        dist3=x-T[idx]
        dist3+=min(L2[idx], R2[idx])
    idx=bisect_left(T, x)
    if idx!=INF:
        dist4=T[idx]-x
        dist4+=min(L2[idx], R2[idx])
    print(min(dist1, dist2, dist3, dist4))

Solution (Python):
import bisect
import sys
A, B, Q = map(int, input().split())
INF = 10 ** 13
s = [-INF] + [int(input()) for i in range(A)] + [INF]
t = [-INF] + [int(input()) for i in range(B)] + [INF]
xs = [int(sys.stdin.readline()) for i in range(Q)]
for x in xs:
    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 bisect
import sys
A, B, Q = map(int, input().split())
INF = 10 ** 13
s = [-INF] + [int(input()) for i in range(A)] + [INF]
t = [-INF] + [int(input()) for i in range(B)] + [INF]
xs = [int(sys.stdin.readline()) for i in range(Q)]
for x in xs:
    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 bisect

def nearlr(l, x):
    n = bisect.bisect(l, x)
    return n-1, n

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:
    s_1, s_2 = nearlr(s, _x)
    t_1, t_2 = nearlr(t, _x)
    s_cand = []
    t_cand = []
    if s_1 < 0:
        s_cand = [s[s_2] - _x]
    elif s_2 >= len(s):
        s_cand = [s[s_1] - _x]
    else:
        s_cand = [s[s_1] - _x, s[s_2] - _x]
    if t_1 < 0:
        t_cand = [t[t_2] - _x]
    elif t_2 >= len(t):
        t_cand = [t[t_1] - _x]
    else:
        t_cand = [t[t_1] - _x, t[t_2] - _x]
    ans = float('inf')
    for _s in s_cand:
        for _t in t_cand:
            if _t * _s < 0:
                ans = min(ans, abs(_s) * 2 + abs(_t), abs(_s) + abs(_t) * 2)
            else:
                ans = min(ans, max(abs(_s), abs(_t)))
    print(ans)

Solution (Python):
import bisect

def nearlr(l, x):
    n = bisect.bisect(l, x)
    return n-1, n

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

for _x in x:
    s_1, s_2 = nearlr(s, _x)
    t_1, t_2 = nearlr(t, _x)
    s_cand = []
    t_cand = []
    if s_1 < 0:
        s_cand = [s[s_2] - _x]
    elif s_2 >= len(s):
        s_cand = [s[s_1] - _x]
    else:
        s_cand = [s[s_1] - _x, s[s_2] - _x]
    if t_1 < 0:
        t_cand = [t[t_2] - _x]
    elif t_2 >= len(t):
        t_cand = [t[t_1] - _x]
    else:
        t_cand = [t[t_1] - _x, t[t_2] - _x]
    ans = float('inf')
    for _s in s_cand:
        for _t in t_cand:
            if _t * _s < 0:
                ans = min(ans, abs(_s) * 2 + abs(_t), abs(_s) + abs(_t) * 2)
            else:
                ans = min(ans, max(abs(_s), abs(_t)))
    print(ans)

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)]
x=[int(input()) for i in range(q)]
s.insert(0, -(10**11))
s.append(10**11)
t.insert(0, -(10**11))
t.append(10**11)

for xi in x:
  sb = bisect.bisect(s, xi)
  tb = bisect.bisect(t, xi)
  
  print(min((abs(s[sb]-xi)+abs(t[tb]-s[sb])), 
              (abs(s[sb]-xi)+abs(t[tb-1]-s[sb])),
              (abs(s[sb-1]-xi)+abs(t[tb]-s[sb-1])),
              (abs(s[sb-1]-xi)+abs(t[tb-1]-s[sb-1])),
              (abs(t[tb]-xi)+abs(s[sb]-t[tb])),
              (abs(t[tb]-xi)+abs(s[sb-1]-t[tb])),
              (abs(t[tb-1]-xi)+abs(s[sb]-t[tb-1])),
              (abs(t[tb-1]-xi)+abs(s[sb-1]-t[tb-1]))))

Solution (Python):
import bisect
a,b,q = (int(i) for i in input().split())
s = [int(input()) for s in range(a)]
t = [int(input()) for p in range(b)]
inf = 10**15
s = [-inf]+s+[inf]
t = [-inf]+t+[inf]
def distan(x,s,t):
  return(min(abs(x-s)+abs(s-t),abs(x-t)+abs(t-s)))

for i in range(q):
  x = int(input())
  sl = bisect.bisect_left(s,x)
  sr = bisect.bisect_right(s,x)
  if sl == sr:sl -= 1
  tl = bisect.bisect_left(t,x)
  tr = bisect.bisect_right(t,x)
  if tl == tr:tl -= 1
    
  sl = s[sl]
  sr = s[sr]
  tl = t[tl]
  tr = t[tr]
  ans = inf
  
  print(min(distan(x,sl,tl),distan(x,sr,tl),distan(x,sl,tr),distan(x,sr,tr)))

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())
    s_h = bisect.bisect(S,x)
    s_l = s_h - 1
    t_h = bisect.bisect(T,x)
    t_l = t_h - 1

    ans = inf
    for s in [S[s_l],S[s_h]]:
        for t in [T[t_l],T[t_h]]:
            d1 = abs(s-x)+abs(t-s)
            d2 = abs(t-x)+abs(s-t)
            ans = min(ans,d1,d2)
    
    print(ans)

Solution (Python):
def main():
    a, b, q = map(int, input().rstrip("\n").split(" "))

    jinja_list = []

    for i in range(a):
        jinja_list.append(int(input().rstrip("\n")))

    temple_list = []
    for i in range(b):
        temple_list.append(int(input().rstrip("\n")))

    from bisect import bisect

    for i in range(q):
        pos = int(input().rstrip("\n"))

        jinja_index = bisect(jinja_list, pos)
        jinja_left = jinja_list[jinja_index - 1:jinja_index]
        jinja_right = jinja_list[jinja_index:jinja_index + 1]

        temple_index = bisect(temple_list, pos)
        temple_left = temple_list[temple_index - 1:temple_index]
        temple_right = temple_list[temple_index:temple_index + 1]

        distances = []
        
        if jinja_left and temple_left:
            distances.append(pos - min(jinja_left[0], temple_left[0]))
            
        if jinja_right and temple_right:
            distances.append(max(jinja_right[0], temple_right[0]) - pos)
            
        if jinja_left and temple_right:
            left_right = abs(pos - jinja_left[0]) + abs(temple_right[0] - jinja_left[0])
            right_left = abs(pos - temple_right[0]) + abs(jinja_left[0] - temple_right[0])
            distances.append(left_right)
            distances.append(right_left)
            
        if jinja_right and temple_left:
            left_right = abs(pos - temple_left[0]) + abs(jinja_right[0] - temple_left[0])
            right_left = abs(pos - jinja_right[0]) + abs(temple_left[0] - jinja_right[0])
            distances.append(left_right)
            distances.append(right_left)
            
        
        print(min(distances))
        
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)

Solution (Python):


def io_generator():
	return input()



def t_search(a_list, pos):
	oo=10**20
	if pos< a_list[0]:
		pm=oo
		pp=a_list[0]-pos
		return pm,pp
	elif pos>a_list[-1]:
		pm=pos-a_list[-1]
		pp=oo
		return pm,pp
	ok=0
	ng=len(a_list)-1
	while abs(ok-ng)>1:
		mid=(ok+ng)//2
		if a_list[mid]<=pos:
			ok=mid
		else:
			ng=mid
	
	if a_list[ok]==pos:
		return 0,0
	pm=a_list[ok]
	pp=a_list[ok+1]
	return pos-pm, pp-pos

def main(io):
	a,b,q= map(int, io().split())
	syu=list(range(a))
	ten=list(range(b))
	for i in range(a):
		syu[i]=int(io())
	for i in range(b):
		ten[i]=int(io())
		
	ret=list(range(q))
	for i in range(q):
		init_pos=int(io())
		md_syu,pd_syu = t_search(syu,init_pos)
		md_ten,pd_ten= t_search(ten,init_pos)
		r=min(
			max(md_syu,md_ten),
			md_syu*2+pd_ten,
			pd_syu*2+md_ten,
			md_ten*2+pd_syu,
			pd_ten*2+md_syu,
			max(pd_syu,pd_ten)
			)
		ret[i]=str(r)
		
	for r in ret:
		print(r)



if __name__ == "__main__":
	io= lambda : io_generator()
	main(io)

Solution (Python):
from bisect import bisect_left

INF = 10**12


def main():
    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())
        l1 = bisect_left(S, x)
        l2 = bisect_left(T, x)
        tmp = INF
        for s in (S[l1-1], S[l1]):
            for t in (T[l2-1], T[l2]):
                tmp = min(tmp, abs(s-t) + abs(x-s))
                tmp = min(tmp, abs(s-t) + abs(x-t))
        print(tmp)


if __name__ == "__main__":
    main()

Solution (Python):
A, B, Q = list(map(int,input().split()))
s = [float("-inf")]
t = [float("-inf")]
x = []
for i in range(A):
  s.append(int(input()))
for i in range(B):
  t.append(int(input()))
for i in range(Q):
  x.append(int(input()))
s.append(float("inf"))
t.append(float("inf"))
xs = list(x)
xs.sort()
sl = {}
sr = {}
tl = {}
tr = {}
i = 0
for j in range(1, A+2):
  while i<Q and xs[i]<s[j]:
    sl[xs[i]] = s[j-1]
    sr[xs[i]] = s[j]
    i += 1
i = 0
for j in range(1, B+2):
  while i<Q and xs[i]<t[j]:
    tl[xs[i]] = t[j-1]
    tr[xs[i]] = t[j]
    i += 1
for xi in x:
  sli = sl[xi]
  sri = sr[xi]
  tli = tl[xi]
  tri = tr[xi]
  p = [
    xi - min(sli,tli),
    max(sri,tri) - xi,
    min(sri-xi,xi-tli)*2+max(sri-xi,xi-tli),
    min(tri-xi,xi-sli)*2+max(tri-xi,xi-sli),
  ]
  print(min(p))

Solution (Python):
import bisect



DBG = False

def find_lt(a, x):
    i = bisect.bisect_left(a, x)
    if i:
        return i-1, a[i-1]
    else:
        return 0, a[0]

def readlist(n):
    return list(map(int, (input() for _ in range(n))))

def main():
    A, B, Q = map(int, input().split(' '))
    S = readlist(A)
    T = readlist(B)
    X = readlist(Q)
    if DBG: print(S)
    if DBG: print(T)
    def get_right(lst, left, x):
        if lst[left] > x:
            
            return left, lst[left]
        right = left + 1
        if right < len(lst):
            return right, lst[right]
        else:
            
            return left, lst[left]
    def print_status(sl_i, sl_v, sr_i, sr_v, tl_i, tl_v, tr_i, tr_v):
        def tostr(i, v):
            return str(i) + " (" + str(v) + ")"
        print("S: " + tostr(sl_i, sl_v), tostr(sr_i, sr_v),
                " T: " + tostr(tl_i, tl_v), tostr(tr_i, tr_v))
    def solve(x):
        if DBG: print("Q:", x)
        sl_i, sl_v = find_lt(S, x)
        sr_i, sr_v = get_right(S, sl_i, x)
        tl_i, tl_v = find_lt(T, x)
        tr_i, tr_v = get_right(T, tl_i, x)
        if DBG: print_status(sl_i, sl_v, sr_i, sr_v, tl_i, tl_v, tr_i, tr_v)
        def distance(p0, p1):
            
            d = abs(p0 - x)
            
            d = d + abs(p1 - p0)
            if DBG: print(p0, p1, "->", d)
            return d
        
        
        dists = []
        dists.append(distance(sl_v, tl_v))
        dists.append(distance(tl_v, sl_v))
        dists.append(distance(sl_v, tr_v))
        dists.append(distance(tl_v, sr_v))
        dists.append(distance(sr_v, tl_v))
        dists.append(distance(tr_v, sl_v))
        dists.append(distance(sr_v, tr_v))
        dists.append(distance(tr_v, sr_v))
        if DBG: print(dists)
        return min(dists)
    for x in X:
        print(solve(x))

main()

Solution (Python):
a,b,q=(input().split())
a,b,q=int(a),int(b),int(q)
s=[int(input()) for i in range(a)]
t=[int(input()) for i in range(b)]
x=[int(input()) for i in range(q)]
dist=['' for i in range(8)]
dist1=['' for i in range(2)]
dist2=['' for i in range(4)]
sp1=['' for i in range(2)]
tp1=['' for i in range(4)]

import bisect
for k in range(q):

    p1=bisect.bisect_left(s,x[k])

    if p1==0:
        dist1[0]=s[0]-x[k]
        dist1[1]=s[0]-x[k]
        sp1[0]=s[0]
        sp1[1]=s[0]        
    elif p1==a:
        dist1[0]=x[k]-s[a-1]
        dist1[1]=x[k]-s[a-1]
        sp1[0]=s[a-1]
        sp1[1]=s[a-1]
    else:
        dist1[0]=x[k]-s[p1-1]
        dist1[1]=s[p1]-x[k]
        sp1[0]=s[p1-1]
        sp1[1]=s[p1]
 
    p11=bisect.bisect_left(t,sp1[0])

    if p11==0:
        dist2[0]=t[0]-sp1[0]
        dist2[1]=t[0]-sp1[0]
    elif p11==b:
        dist2[0]=sp1[0]-t[b-1]
        dist2[1]=sp1[0]-t[b-1]
    else:
        dist2[0]=sp1[0]-t[p11-1]
        dist2[1]=t[p11]-sp1[0]
        
    p11=bisect.bisect_left(t,sp1[1])

    if p11==0:
        dist2[2]=t[0]-sp1[1]
        dist2[3]=t[0]-sp1[1]
    elif p11==b:
        dist2[2]=sp1[1]-t[b-1]
        dist2[3]=sp1[1]-t[b-1]
    else:
        dist2[2]=sp1[1]-t[p11-1]
        dist2[3]=t[p11]-sp1[1]
        
    dist[0]=dist1[0]+dist2[0]
    dist[1]=dist1[0]+dist2[1]
    dist[2]=dist1[1]+dist2[2]
    dist[3]=dist1[1]+dist2[3]
                

    p1=bisect.bisect_left(t,x[k])

    if p1==0:
        sp1[0]=t[0]
        sp1[1]=t[0]
        dist1[0]=t[0]-x[k]
        dist1[1]=t[0]-x[k]
    elif p1==b:
        sp1[0]=t[b-1]
        sp1[1]=t[b-1]
        dist1[0]=x[k]-t[b-1]
        dist1[1]=x[k]-t[b-1]
    else:
        sp1[0]=t[p1-1]
        sp1[1]=t[p1]
        dist1[0]=x[k]-t[p1-1]
        dist1[1]=t[p1]-x[k]
        
    p11=bisect.bisect_left(s,sp1[0])

    if p11==0:
        dist2[0]=s[0]-sp1[0]
        dist2[1]=s[0]-sp1[0]
    elif p11==a:
        dist2[0]=sp1[0]-s[a-1]
        dist2[1]=sp1[0]-s[a-1]
    else:
        dist2[0]=sp1[0]-s[p11-1]
        dist2[1]=s[p11]-sp1[0]
    
    p11=bisect.bisect_left(s,sp1[1])

    if p11==0:
        dist2[2]=s[0]-sp1[1]
        dist2[3]=s[0]-sp1[1]       
    elif p11==a:
        dist2[2]=sp1[1]-s[a-1]
        dist2[3]=sp1[1]-s[a-1]
    else:
        dist2[2]=sp1[1]-s[p11-1]
        dist2[3]=s[p11]-sp1[1]

    dist[4]=dist1[0]+dist2[0]
    dist[5]=dist1[0]+dist2[1]
    dist[6]=dist1[1]+dist2[2]
    dist[7]=dist1[1]+dist2[3]
    
    ans=min(dist[0],dist[1],dist[2],dist[3],dist[4],dist[5],dist[6],dist[7])

    print(ans)

Solution (Python):

import bisect

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










for i in range(q):
    x = int(input())
    k = bisect.bisect_left(s, x)
    sb = s[k]
    sa = s[k-1]
    j = bisect.bisect_left(t, x)
    tb = t[j]
    ta = t[j-1]

    y = []
    for h in [sa, sb]:
        for g in [ta, tb]:
            y.append(abs(x-h) + abs(h-g))
    for h in [ta, tb]:
        for g in [sa, sb]:
            y.append(abs(x-h) + abs(h-g))

    print(min(y))

Solution (Python):
from bisect import bisect_left
I = lambda x: [-1<<50] + [int(input()) for i in range(x)] + [1<<50]

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

for _ in range(Q):
    x = int(input())
    BLS = bisect_left(S,x)  
    BLT = bisect_left(T,x) 

    LS = x - S[BLS-1]
    RS = S[BLS] - x
    LT = x - T[BLT-1]
    RT = T[BLT] - x
    
    print(min(max(LS,LT),max(RS,RT),LS*2+RT,LT*2+RS,RT*2+LS,RS*2+LT))

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

for _ in range(q):
    z = int(input())
    x, y = bs.bisect_right(s, z), bs.bisect_right(t, z)
    s1, s2, t1, t2 = s[x-1], s[x], t[y-1], t[y]
    print(min(max(z - s1, z - t1), max(s2 - z, t2 - z),
    min(2 * t2 - z - s1, 2 * s2 - z - t1), min(z + t2 - 2 * s1, z + s2 - 2 * t1)))

Solution (Python):
from bisect import bisect_left
I = lambda x: [-1<<50] + [int(input()) for i in range(x)] + [1<<50]

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

for _ in range(Q):
    x = int(input())
    BLS = bisect_left(S,x)  
    BLT = bisect_left(T,x) 

    LS = S[BLS-1] 
    RS = S[BLS] 
    LT = T[BLT-1] 
    RT = T[BLT]  
    
    print(min(  
        x-min(LS,LT),
        max(RS,RT)-x,
        (x-LS)*2+(RT-x),
        (x-LT)*2+(RS-x),
        (RT-x)*2+(x-LS),
        (RS-x)*2+(x-LT)
        ))

Solution (Python):
from bisect import bisect_left
I = lambda x: [-1<<50] + [int(input()) for i in range(x)] + [1<<50]

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

for _ in range(Q):
    x = int(input())
    LS_ = bisect_left(S,x)
    LT_ = bisect_left(T,x)



    LS = S[LS_-1]
    RS = S[LS_]
    LT = T[LT_-1]
    RT = T[LT_]

    print(min(
        x-min(LS,LT),
        max(RS,RT)-x,
        (x-LS)*2+(RT-x),
        (x-LT)*2+(RS-x),
        (RT-x)*2+(x-LS),
        (RS-x)*2+(x-LT)
        ))

Solution (Python):
import bisect
import itertools
 
a, b, q = map(int, input().split())
ss, tt = [], []
for _ in range(a):
  ss.append(int(input()))
for _ in range(b):
  tt.append(int(input()))
  
for _ in range(q):
  x = int(input())
  md = pow(10, 15)
  xs, xt = bisect.bisect_left(ss, x), bisect.bisect_left(tt, x)
  ls, rs, lt, rt = ss[max(0, xs-1)], ss[min(a-1, xs)], tt[max(0, xt-1)], tt[min(b-1, xt)]
  for s, t in itertools.product([ls, rs], [lt, rt]):
    if s > t:
      if t > x:
        md = s - x if s - x < md else md
      elif s > x:
        if md > 2 * (s-x) + x-t:
          md = 2 * (s-x) + x-t
        if md > 2 * (x-t) + s-x:
          md = 2 * (x-t) + s-x
      else:
        md = x - t if x - t < md else md
    else:  
      if s > x:
        md = t - x if t - x < md else md
      elif t > x:
        if md > 2 * (x-s) + t-x:
          md = 2 * (x-s) + t-x
        if md > 2 * (t-x) + x-s:
          md = 2 * (t-x) + x-s
      else:
        md = x - s if x - s < md else md
  print(md)

Solution (Python):
import numpy as np
import bisect
INF = 10**11
def solve(a, b, q, s, t, x):
    for xi in x:
        si = bisect.bisect_left(s, xi)
        ti = bisect.bisect_left(t, xi)
        sl = s[si-1]
        tl = t[ti-1]
        sr = s[si]
        tr = t[ti]
        ans = min([
            max(sr-xi, tr-xi),
            max(xi-sl, xi-tl),
            (sr-xi+sr-tl),
            (xi-tl+sr-tl),
            (tr-xi+tr-sl),
            (xi-sl+tr-sl)
        ])
        print(ans)

a, b, q = map(int, input().split())
s = np.asarray([int(input()) for i in range(a)] + [-INF, INF], dtype=int)
t = np.asarray([int(input()) for i in range(b)] + [-INF, INF], dtype=int)
x = np.asarray([int(input()) for i in range(q)], dtype=int)
s.sort()
t.sort()
solve(a,b,q,s,t,x)

Solution (Python):
INF = int(1e18)

def compute():
    from sys import stdin
    A, B, Q = list(map(int, stdin.readline().split()))
    s = sorted(int(stdin.readline().split()[0]) for _ in range(A))
    t = sorted(int(stdin.readline().split()[0]) for _ in range(B))

    from bisect import bisect_left
    for _ in range(Q):
        x = int(stdin.readline().split()[0])

        i1 = bisect_left(s, x)
        i1 = i1 if i1 < A else i1-1
        i2 = i1-1 if (i1>0) and s[i1]!=x else i1

        res = INF
        for y in set((s[i1], s[i2])):
            j1 = bisect_left(t, y)
            j1 = j1 if (j1 < B) else j1-1
            j2 = j1-1 if (j1 > 0) and t[j1]!=y else j1
            for z in set((t[j1],t[j2])):
                
                res = min(res, abs(x-y) + abs(y-z))
                res = min(res, abs(x-z) + abs(z-y))

        print(res)


if __name__ == "__main__":
    compute()