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

Solution (Python):
import bisect

A, B, Q = map(int, input().split())
K = []
T = []
for i in range(A):
    K.append(int(input()))
for j in range(B):
    T.append(int(input()))
K.sort()
T.sort()
l_1 = len(K)
l_2 = len(T)

Ans = []
for i in range(Q):
    c = int(input())
    p = bisect.bisect_right(K, c)
    if p >= l_1:
        p -= 1
    dis_1 = abs(c - K[p-1])
    dis_2 = abs(c - K[p])
    q_1 = bisect.bisect_right(T, K[p-1])
    q_2 = bisect.bisect_right(T, K[p])
    if q_1 >= l_2:
        q_1 -= 1
    if q_2 >= l_2:
        q_2 -= 1
    result_1 = min([dis_1 + abs(K[p-1] - T[q_1-1]), dis_1 + abs(K[p-1] - T[q_1]), dis_2 + abs(K[p] - T[q_2-1]), dis_2 + abs(K[p] - T[q_2])])

    p = bisect.bisect_right(T, c)
    if p >= l_2:
        p -= 1
    dis_1 = abs(c - T[p-1])
    dis_2 = abs(c - T[p])
    q_1 = bisect.bisect_right(K, T[p-1])
    q_2 = bisect.bisect_right(K, T[p])
    if q_1 >= l_1:
        q_1 -= 1
    if q_2 >= l_1:
        q_2 -= 1
    result_2 = min([dis_1 + abs(T[p-1] - K[q_1-1]), dis_1 + abs(T[p-1] - K[q_1]), dis_2 + abs(T[p] - K[q_2-1]), dis_2 + abs(T[p] - K[q_2])])
    Ans.append(min(result_1, result_2))

for i in Ans:
    print(i)

Solution (Python):
import sys, os, math, bisect, itertools, collections, heapq, queue

from decimal import Decimal
from collections import defaultdict, deque



sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)


MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    A, B, Q = il()
    S = [-MAX, MAX]
    for _ in range(A):
        S.append(ii())
    S.sort()
    T = [-MAX, MAX]
    for _ in range(B):
        T.append(ii())
    T.sort()

    for _ in range(Q):
        q = ii()
        Srange = bisect.bisect_left(S, q)
        Trange = bisect.bisect_left(T, q)
        print(min(abs(q - S[Srange - 1]) + abs(S[Srange - 1] - T[Trange]),
                  abs(q - S[Srange - 1]) + abs(S[Srange - 1] - T[Trange - 1]),
                  abs(q - S[Srange]) + abs(S[Srange] - T[Trange - 1]),
                  abs(q - S[Srange]) + abs(S[Srange] - T[Trange]),
                  abs(q - T[Trange - 1]) + abs(T[Trange - 1] - S[Srange]),
                  abs(q - T[Trange - 1]) + abs(T[Trange - 1] - S[Srange - 1]),
                  abs(q - T[Trange]) + abs(T[Trange] - S[Srange - 1]),
                  abs(q - T[Trange]) + abs(T[Trange] - S[Srange])))


if __name__ == '__main__':
    main()

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7






A, B, Q = getNM()

S = getArray(A)

T = getArray(B)
query = getArray(Q)

S.insert(0, -float('inf'))
T.insert(0, -float('inf'))
S.append(float('inf'))
T.append(float('inf'))

def close(data, point):
    west = data[bisect_left(data, point) - 1]
    east = data[bisect_left(data, point)]

    return west, east

for i in range(Q):
    now = query[i]
    shrine_west, shrine_east = close(S, now)
    temple_west, temple_east = close(T, now)

    ww = now - min(shrine_west, temple_west)
    we_1 = (now - shrine_west) * 2 + (temple_east - now)
    we_2 = (now - temple_west) * 2 + (shrine_east - now)
    ee = max(shrine_east, temple_east) - now
    ew_1 = (shrine_east - now) * 2 + (now - temple_west)
    ew_2 = (temple_east - now) * 2 + (now - shrine_west)

    print(min(ww, we_1, we_2, ee, ew_1, ew_2))

Solution (Python):
from bisect import bisect_left,bisect
a,b,q = map(int,input().split())
jin = [-10**16]
for i in range(a):
    jin.append(int(input()))
jin.append(10**16)
tera = [-10**20]
for i in range(b):
    tera.append(int(input()))
tera.append(10**20)
for i in range(q):
    x = int(input())
    j = bisect(jin,x)
    t = bisect(tera,x)
    j1 = jin[j]
    j2 = jin[j-1]
    t1 = tera[t]
    t2 = tera[t-1]
    ans = min(abs(x-j1)+abs(j1-t1),abs(x-j1)+abs(j1-t2),abs(x-j2)+abs(j2-t1),abs(x-j2)+abs(j2-t2))
    ans = min(ans,abs(x-t1)+abs(t1-j1),abs(x-t1)+abs(t1-j2),abs(x-t2)+abs(t2-j1),abs(x-t2)+abs(t2-j2))
    print(ans)

Solution (Python):
import bisect

left_sentinel = -2 * (10 ** 10)
right_sentinel = 3 * (10 ** 10)

A, B, Q = map(int, input().split())
ss = [left_sentinel] + [int(input()) for _ in range(A)] + [right_sentinel]
ts = [left_sentinel] + [int(input()) for _ in range(B)] + [right_sentinel]

for _ in range(Q):
    x = int(input())
    s_index = bisect.bisect_left(ss, x)
    right_s = ss[s_index]
    left_s = ss[s_index - 1]
    t_index = bisect.bisect_left(ts, x)
    right_t = ts[t_index]
    left_t = ts[t_index - 1]
    ans = min(
        max(right_s, right_t) - x,
        right_s - left_t + min(right_s - x, x - left_t),
        right_t - left_s + min(right_t - x, x - left_s),
        x - min(left_s, left_t)
    )
    print(ans)

Solution (Python):






import sys
input = sys.stdin.readline

import math

import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache





MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"






def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]


def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()


def DD(arg): return defaultdict(arg)


def inv(n): return pow(n, MOD-2, MOD)


kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret


def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr


def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors


def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum


def gcd(a, b):
    while b: a, b = b, a % b
    return a


def lcm(a, b):
    return a * b // gcd (a, b)


def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count


def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]


def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count





A,B,Q =  IL()
S = ILs(A)
T = ILs(B)
ST = S+T
ST.sort()
dic = DD(str)
for s in S:
  dic[s] = "s"
for t in T:
  dic[t] = "t"


for _ in range(Q):
  q = I()
  p = bisect.bisect(ST,q)
  l = max(0,p-1)
  r = min(p,A+B-1)
  if dic[ST[l]]=="s":
    p = bisect.bisect(T,ST[l])
    ll = max(0,p-1)
    rr = min(p,B-1)
    dl = min(abs(T[ll]-ST[l]),abs(T[rr]-ST[l]))
  else:
    p = bisect.bisect(S,ST[l])
    ll = max(0,p-1)
    rr = min(p,A-1)
    dl = min(abs(S[ll]-ST[l]),abs(S[rr]-ST[l]))
  if dic[ST[r]]=="s":
    p = bisect.bisect(T,ST[r])
    ll = max(0,p-1)
    rr = min(p,B-1)
    dr = min(abs(T[ll]-ST[r]),abs(T[rr]-ST[r]))
  else:
    p = bisect.bisect(S,ST[r])
    ll = max(0,p-1)
    rr = min(p,A-1)
    dr = min(abs(S[ll]-ST[r]),abs(S[rr]-ST[r]))
  print(min(abs(ST[l]-q)+dl,abs(ST[r]-q)+dr))

Solution (Python):



from bisect import bisect_left,bisect_right
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())
    
    sl=float("-inf")
    sr=float("inf")
    tl=float("-inf")
    tr=float("inf")
    a=bisect_left(s,x)
    if a>0:
        sl = s[a-1]
    if a<=A-1:
        sr = s[a]
    b=bisect_left(t,x)
    if b>0:
        tl = t[b-1]
    if b<=B-1:
        tr = t[b]
    
    
    
    pat_LL = x - min(sl,tl)
    pat_LR = sr-tl + min(sr-x,x-tl)
    pat_RL = tr-sl + min(tr-x,x-sl)
    pat_RR = max(sr,tr)-x
    
    print(min(pat_LL,pat_LR,pat_RL,pat_RR))

Solution (Python):
import bisect
import sys
sys.setrecursionlimit(10**9)

def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()
def deb(text): print("-------\n{}\n-------".format(text))

INF = 10**20
def main():
    A,B,Q=mi()
    X,Y= [], []
    for i in range(A):
        X.append(ii())
    for i in range(B):
        Y.append(ii())
    
    def search_min_dist(Z,z):
        insert_i = bisect.bisect_left(Z,z)
        res = []
        m = INF
        for di in [-2,-1,0,1,2]:
            i = insert_i + di
           
            if 0<= i < len(Z):
                res.append(Z[i])

        return res


    for q in range(Q):
        x=ii()
        minX = search_min_dist(X,x)
        minY = search_min_dist(Y,x)

        ans = INF
        for mx in minX:
            for my in minY:
                min_dist_x,min_dist_y = mx,my
                if not min_dist_x < min_dist_y:
                    min_dist_x,min_dist_y = min_dist_y,min_dist_x

                _ans = 0
                if min_dist_x <= x <= min_dist_y:
                    _ans = min(min_dist_y-x,x-min_dist_x) + min_dist_y - min_dist_x
                elif x <= min_dist_x <= min_dist_y:
                    _ans = min_dist_y - x
                else:
                    _ans = -min_dist_x + x
                
    
                ans = min(ans,_ans)
        print(ans)

        

if __name__ == "__main__":
    main()

Solution (Python):
import bisect
A,B,Q =list(map(int,input().split()))
s = []
t = []
for i in range(A):
    s.append(int(input()))
for i in range(B):
    t.append(int(input()))
for i in range(Q):
    x=(int(input()))    
    s_index_af = bisect.bisect(s,x)
    if s_index_af == A:
        s_index_af -= 1
        s_index_bf = s_index_af
    else:
        s_index_bf = s_index_af -1

    t_index_af = bisect.bisect(t,x)
    if t_index_af == B:
        t_index_af -= 1
        t_index_bf = t_index_af
    else:
        t_index_bf = t_index_af -1
   
    jl = [s[s_index_bf]-x,s[s_index_af]-x]
    tl = [t[t_index_bf]-x,t[t_index_af]-x]

    jt = []
    jt.append(abs(jl[0])+abs(tl[0]-jl[0]))
    jt.append(abs(jl[0])+abs(tl[1]-jl[0]))
    jt.append(abs(jl[1])+abs(tl[0]-jl[1]))
    jt.append(abs(jl[1])+abs(tl[1]-jl[1]))

    jt.append(abs(tl[0])+abs(jl[0]-tl[0]))
    jt.append(abs(tl[0])+abs(jl[1]-tl[0]))
    jt.append(abs(tl[1])+abs(jl[0]-tl[1]))
    jt.append(abs(tl[1])+abs(jl[1]-tl[1]))

            
    print(min(jt))

Solution (Python):




INF = 10**12

from bisect import bisect_right
 
A,B,Q = map(int,input().split())
s = [int(input()) for i in range(A)]
t = [int(input()) for i in range(B)]
ans =[]
for i in range(0,Q,1):
    tmpans = INF

    q = int(input())
    sr = bisect_right(s,q)
    sl = sr-1
    sr = min(sr,A-1)
    sl = max(0,sl)
    for j in (sr,sl):
        tr = bisect_right(t,s[j])
        tl = tr-1
        tr = min(tr,B-1)
        tl = max(0,tl)
        ansR=abs(s[j]-q)+abs(s[j]-t[tr])
        ansL=abs(s[j]-q)+abs(s[j]-t[tl])
        tmpans = min(tmpans,ansR,ansL)

    
    tr = bisect_right(t,q)
    tl = tr-1
    tr = min(tr,B-1)
    tl = max(0,tl)
    for j in (tr,tl):
        sr = bisect_right(s,t[j])
        sl = sr-1
        sr = min(sr,A-1)
        sl = max(0,sl)
        ansR=abs(t[j]-q)+abs(t[j]-s[sr])
        ansL=abs(t[j]-q)+abs(t[j]-s[sl])
        tmpans = min(tmpans,ansR,ansL)
    
    ans.append(tmpans)

for i in range(0,Q,1):
    print(ans[i])

Solution (Python):
import bisect
 
A, B, Q = map(int, input().split())
INF = float('inf')
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())
    b = bisect.bisect_right(s, x)
    d = bisect.bisect_right(t, x)
    ans = INF
    for S in [s[b-1], s[b]]:
        for T in [t[d-1], t[d]]:
            ans1 = abs(S-x) + abs(S-T)
            ans2 = abs(T-x) + abs(T-S)
            ans = min(ans, ans1, ans2)
    print(ans)

Solution (Python):


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

a,b,q=MI()
lis1=[I() for i in range(a)]
lis2=[I() for i in range(b)]
lis1.append(inf)
lis2.append(inf)
lis1=[-inf]+lis1
lis2=[-inf]+lis2


for i in range(q):
    u=I()
    x=bisect_left(lis1,u)
    y=bisect_left(lis2,u)
    
    Lll=u-min(lis1[x-1],lis2[y-1])
    Lrr=max(lis1[x],lis2[y])-u
    Llr1=2*(u-lis1[x-1])+(lis2[y]-u)
    Llr2=2*(lis2[y]-u)+u-lis1[x-1]
    Lrl1=2*(u-lis2[y-1])+lis1[x]-u
    Lrl2=2*(lis1[x]-u)+u-lis2[y-1]
    
    print(min(Lll,Lrr,Lrl1,Lrl2,Llr1,Llr2))

Solution (Python):


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

a,b,q=MI()
lis1=[-inf]
lis2=[-inf]
for i in range(a):
    lis1.append(I())
for i in range(b):
    lis2.append(I())
lis1.append(inf)
lis2.append(inf)


for i in range(q):
    u=I()
    x=bisect_left(lis1,u)
    y=bisect_left(lis2,u)
    
    Lll=u-min(lis1[x-1],lis2[y-1])
    Lrr=max(lis1[x],lis2[y])-u
    Llr1=2*(u-lis1[x-1])+(lis2[y]-u)
    Llr2=2*(lis2[y]-u)+u-lis1[x-1]
    Lrl1=2*(u-lis2[y-1])+lis1[x]-u
    Lrl2=2*(lis1[x]-u)+u-lis2[y-1]
    
    print(min(Lll,Lrr,Lrl1,Lrl2,Llr1,Llr2))

Solution (Python):


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

a,b,q=MI()
lis1=[-inf]
lis2=[-inf]
for i in range(a):
    lis1.append(I())
for i in range(b):
    lis2.append(I())
lis1.append(inf)
lis2.append(inf)


for i in range(q):
    u=I()
    x=bisect_left(lis1,u)
    y=bisect_left(lis2,u)
    
    Lll=u-min(lis1[x-1],lis2[y-1])
    Lrr=max(lis1[x],lis2[y])-u
    Llr1=2*(u-lis1[x-1])+(lis2[y]-u)
    Llr2=2*(lis2[y]-u)+u-lis1[x-1]
    Lrl1=2*(u-lis2[y-1])+lis1[x]-u
    Lrl2=2*(lis1[x]-u)+u-lis2[y-1]
    
    print(min(Lll,Lrr,Lrl1,Lrl2,Llr1,Llr2))

Solution (Python):
import bisect

A, B, Q = map(int, input().split())
INF = float('inf')
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())
    b = bisect.bisect_right(s, x)
    d = bisect.bisect_right(t, x)
    ans = INF
    for S in [s[b-1], s[b]]:
        for T in [t[d-1], t[d]]:
            ans1 = abs(S-x) + abs(S-T)
            ans2 = abs(T-x) + abs(T-S)
            ans = min(ans, ans1, ans2)
    print(ans)

Solution (Python):
import bisect
import itertools
import sys

def main(args):
    
    A, B, Q = map(int,input().split())
    S = [0]*A
    T = [0]*B
    for i in range(A):
        S[i] = int(input())
    for i in range(B):
        T[i] = int(input())
    
    S = [-10**18] + S + [10**18]
    T = [-10**18] + T +[10**18]
    
    def solve(j, t, start):
        jinja_l = S[j-1]
        jinja_r = S[j]
        tera_l = T[t-1]
        tera_r = T[t]
        jinja = [jinja_l, jinja_r]
        tera = [tera_l ,tera_r]
        
        ans = float('inf')
        for u,v in list(itertools.product(jinja, tera)):
            ans = min(ans, abs(start-u)+abs(v-u))
            ans = min(ans, abs(v-start)+abs(v-u))
        
        return ans
    
    for i in range(Q):
        x = int(input())
        ans = solve(bisect.bisect_left(S, x), bisect.bisect_left(T ,x), x)
        print(ans)
        
if __name__ == '__main__':
    main(sys.argv[1:])

Solution (Python):
import bisect
INF=10**11
A,B,q=map(int,input().split())
a=[-INF]+[int(input()) for _ in range(A)]+[INF]
b=[-INF]+[int(input()) for _ in range(B)]+[INF]
for _ in range(q):
  x=int(input())
  i=bisect.bisect_left(a,x)
  j=bisect.bisect_left(b,x)
  ans=min(max(a[i],b[j])-x,x-min(a[i-1],b[j-1]),a[i]-b[j-1]+min(a[i]-x,x-b[j-1]),b[j]-a[i-1]+min(b[j]-x,x-a[i-1]))
  print(ans)

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

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



for q in range(Q):
    x = int(input())
    b, 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(T-S)
            res = min(res, d1, d2)
    print(res)

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

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')

INF = 10**12


def main():

    A, B, Q = in_nn()
    tmp = list(map(int, read().split()))
    s = [-INF] + tmp[:A] + [INF]
    t = [-INF] + tmp[A:A + B] + [INF]
    x = tmp[A + B:]

    a = [0] * Q
    d = lambda a, b: abs(a - b)

    for i in range(Q):

        n = x[i]

        si = bisect.bisect_right(s, n)
        a1 = s[si - 1]
        a2 = s[si]

        ti = bisect.bisect_right(t, n)
        b1 = t[ti - 1]
        b2 = t[ti]

        ans = d(n, a1) + min(d(a1, b1), d(a1, b2))
        ans = min(ans, d(n, a2) + min(d(a2, b1), d(a2, b2)))
        ans = min(ans, d(n, b1) + min(d(b1, a1), d(b1, a2)))
        ans = min(ans, d(n, b2) + min(d(b2, a1), d(b2, a2)))
        a[i] = ans

    print('\n'.join(map(str, a)))


if __name__ == '__main__':
    main()

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

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')

INF = 10**12
d = lambda a, b: abs(a - b)


def main():

    A, B, Q = in_nn()
    tmp = list(map(int, read().split()))
    s = tmp[:A]
    t = tmp[A:A + B]
    x = tmp[A + B:]

    a = [0] * Q

    for i in range(Q):

        n = x[i]

        if n <= s[0]:
            a1 = -INF
            a2 = s[0]
        elif n >= s[-1]:
            a1 = s[-1]
            a2 = INF
        else:
            si = bisect.bisect_right(s, n)
            a1 = s[si - 1]
            a2 = s[si]

        if n <= t[0]:
            b1 = -INF
            b2 = t[0]
        elif n >= t[-1]:
            b1 = t[-1]
            b2 = INF
        else:
            ti = bisect.bisect_right(t, n)
            b1 = t[ti - 1]
            b2 = t[ti]

        
        ans = d(n, a1) + min(d(a1, b1), d(a1, b2))
        ans = min(ans, d(n, a2) + min(d(a2, b1), d(a2, b2)))
        ans = min(ans, d(n, b1) + min(d(b1, a1), d(b1, a2)))
        ans = min(ans, d(n, b2) + min(d(b2, a1), d(b2, a2)))
        a[i] = ans

    print('\n'.join(map(str, 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]
q = [int(input()) for i in range(Q)]
for x in q:
    b,d = bisect.bisect_left(s,x),bisect.bisect_left(t,x)
    res  = INF
    for S in [s[b-1],s[b]]:
        for T in [t[d-1],t[d]]:
            d1,d2 = abs(S-x)+abs(T-S),abs(T-x)+abs(S-T)
            res = min(res,d1,d2)
    print(res)

Solution (Python):
import bisect
A,B,Q=map(int,input().split())
INF=10**18
S=[-INF]+[int(input()) for i in range(A)]+[INF]
T=[-INF]+[int(input()) for i in range(B)]+[INF]
for q in range(Q):
    x=int(input())
    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 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)]

st=[0]*A
ts=[0]*B

for i in range(A):
  tmp=bisect.bisect_left(t, s[i])
  if tmp==0:
    st[i]=t[0]-s[i]
  elif tmp==B:
    st[i]=s[i]-t[-1]
  else:
    st[i]=min(s[i]-t[tmp-1], t[tmp]-s[i])
    
for i in range(B):
  tmp=bisect.bisect_left(s, t[i])
  if tmp==0:
    ts[i]=s[0]-t[i]
  elif tmp==A:
    ts[i]=t[i]-s[-1]
  else:
    ts[i]=min(t[i]-s[tmp-1], s[tmp]-t[i])

for i in range(Q):
  cand=set()
  tmp=bisect.bisect_left(s, x[i])
  if tmp>0:
    cand.add(x[i]-s[tmp-1]+st[tmp-1])
  if tmp<A:
    cand.add(s[tmp]-x[i]+st[tmp])
    
  tmp=bisect.bisect_left(t, x[i])
  if tmp>0:
    cand.add(x[i]-t[tmp-1]+ts[tmp-1])
  if tmp<B:
    cand.add(t[tmp]-x[i]+ts[tmp])
    
  print(min(cand))

Solution (Python):
a,b,q = map(int,input().split())
tl=[]
qlist=[]
for i in range(a):tl.append((int(input()),0,i))
for i in range(b):tl.append((int(input()),1,i))
for i in range(q):
    q1=int(input())
    tl.append((q1,2,i))
    qlist.append(q1)
tl.sort()
prea=[-1]*q
preb=[-1]*q
ta=tb=-1
for i,c in enumerate(tl):
    if   c[1]==0:ta=c[0]
    elif c[1]==1:tb=c[0]
    elif c[1]==2:prea[c[2]],preb[c[2]]=ta,tb
posta=[-1]*q
postb=[-1]*q
ra=rb=-1
for i,c in enumerate(tl[::-1]):
    if   c[1]==0:ra=c[0]
    elif c[1]==1:rb=c[0]
    elif c[1]==2:posta[c[2]],postb[c[2]]=ra,rb

def cal(pra,poa,prb,pob,q):
    gmin = 999999999999
    if pra!=-1 and prb!=-1:
        if pra<prb:gmin=min(gmin,q-pra)
        else:      gmin=min(gmin,q-prb)
    if pra!=-1 and pob!=-1:gmin=min(gmin,pob-pra+min(q-pra,pob-q))
    if prb!=-1 and poa!=-1:gmin=min(gmin,poa-prb+min(poa-q,q-prb))
    if poa!=-1 and pob!=-1:
        if poa<pob:gmin=min(gmin,pob-q)
        else:      gmin=min(gmin,poa-q)
    return gmin
for a1,a2,b1,b2,q in zip(prea,posta,preb,postb,qlist):print(cal(a1,a2,b1,b2,q))

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 bisect
A,B,Q=map(int,input().split())
s=[-10**15]
t=[-10**15]
ans=[]
for _ in range(A):
    s.append(int(input()))
for _ in range(B):
    t.append(int(input()))
s.append(10**15)
t.append(10**15)
def search(a,b,q):
    dis=10**15
    S=[s[a-1],s[a]]
    T=[t[b-1],t[b]]
    for i in range(2):
        for j in range(2):
            A=min(abs(S[i]-q),abs(T[j]-q))+abs(S[i]-T[j])
            dis=min(dis,A)
    return dis
for _ in range(Q):
    q=int(input())
    r=bisect.bisect_left(s,q)
    l=bisect.bisect_left(t,q)
    ans.append(search(r,l,q))
for i in ans:
    print(i)