Problem:
 Score : 400 points    Problem Statement Along a road running in an east-west direction, there are A shrines and B temples.
The i -th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i -th temple from the west is located at a distance of t_i meters from the west end of the road.  Answer the following Q queries:   Query i ( 1 \leq i \leq Q ): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)       Constraints  1 \leq A, B \leq 10^5  1 \leq Q \leq 10^5  1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}  1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}  1 \leq x_i \leq 10^{10}  s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.  All values in input are integers.         Input Input is given from Standard Input in the following format:  A  B  Q  s_1  :  s_A  t_1  :  t_B  x_1  :  x_Q       Output Print Q lines. The i -th line should contain the answer to the i -th query.        Sample Input 1 2 3 4
100
600
400
900
1000
150
2000
899
799      Sample Output 1 350
1400
301
399  There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.   Query 1 : If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.  Query 2 : If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.  Query 3 : If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.  Query 4 : If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.        Sample Input 2 1 1 3
1
10000000000
2
9999999999
5000000000      Sample Output 2 10000000000
10000000000
14999999998  The road is quite long, and we may need to travel a distance that does not fit into a 32 -bit integer.

Solution (Python):

from collections import defaultdict
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return list(sys.stdin.readline())
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
mod = 1000000007






"""
n,a,b,c = LI()
l = IR(n)
f = [True for i in range(3)]
ans = 0
for i in range(n):
    for d in range(3):
        if abs(l[i]-[a,b,c][d]) <= 10 and f[d]:
            ans += abs(l[i]-[a,b,c][d])
            f[d] = False
            l[i] = -float("inf")
k = False
for i in f:
    if i:
        k = True
        break
if not k:
    print(ans)
    quit()
"""

a,b,q = LI()
s = IR(a)
t = IR(b)
for i in range(q):
    x = I()
    c = bisect.bisect_left(s,x)
    ans = float("inf")
    if c == a:
        k = abs(x-s[-1])
        y = s[-1]
        d = bisect.bisect_left(t,y)
        if d == b:
            k += abs(y-t[-1])
        else:
            if abs(y-t[d-1]) < abs(y-t[d]):
                k += abs(y-t[d-1])
            else:
                k += abs(y-t[d])
        ans = min(k,ans)
    else:
        k = abs(x-s[c-1])
        y = s[c-1]
        d = bisect.bisect_left(t,y)
        if d == b:
            k += abs(y-t[-1])
        else:
            if abs(y-t[d-1]) < abs(y-t[d]):
                k += abs(y-t[d-1])
            else:
                k += abs(y-t[d])
        ans = min(k,ans)
        k = abs(x-s[c])
        y = s[c]
        d = bisect.bisect_left(t,y)
        if d == b:
            k += abs(y-t[-1])
        else:
            if abs(y-t[d-1]) < abs(y-t[d]):
                k += abs(y-t[d-1])
            else:
                k += abs(y-t[d])
        ans = min(k,ans)
    c = bisect.bisect_left(t,x)
    if c == b:
        k = abs(x-t[-1])
        y = t[-1]
        d = bisect.bisect_left(s,y)
        if d == a:
            k += abs(y-s[-1])
        else:
            if abs(y-s[d-1]) < abs(y-s[d]):
                k += abs(y-s[d-1])
            else:
                k += abs(y-s[d])
        ans = min(k,ans)
    else:
        k = abs(x-t[c-1])
        y = t[c-1]
        d = bisect.bisect_left(s,y)
        if d == a:
            k += abs(y-s[-1])
        else:
            if abs(y-s[d-1]) < abs(y-s[d]):
                k += abs(y-s[d-1])
            else:
                k += abs(y-s[d])
        ans = min(k,ans)
        k = abs(x-t[c])
        y = t[c]
        d = bisect.bisect_left(s,y)
        if d == a:
            k += abs(y-s[-1])
        else:
            if abs(y-s[d-1]) < abs(y-s[d]):
                k += abs(y-s[d-1])
            else:
                k += abs(y-s[d])
        ans = min(k,ans)
    print(ans)

Solution (Python):
import sys
from collections import deque
import copy
import math
def get_read_func(fileobject):
    if fileobject == None :
        return raw_input
    else:
        return fileobject.readline

def bin_search(S, x):
    L = 0
    R = len(S) - 1

    while 1:
        M = (L + R)/2
        if (R - L) <= 1:
            if abs(S[R] - x) < abs(S[L] - x):
                return (R, L)
            elif abs(S[R] - x) > abs(S[L] - x):
                return (L, R)
            else:
                if L != R:
                    return (L, R)
                else:
                    return (L, R)
        if x == S[L]:
            return (L, R)
        if x == S[R]:
            return (R, R)
        if S[M] < x:
            L = M
        else:
            R = M



def main():
    if len(sys.argv) > 1:
        f = open(sys.argv[1])
    else:
        f = None
    read_func = get_read_func(f);
    input_raw = read_func().strip().split()
    [A, B, Q] = [int(input_raw[0]), int(input_raw[1]), int(input_raw[2])]

    jinja = []
    for i in range(A):
        input_raw = read_func().strip().split()
        jinja.append(long(input_raw[0]))
    tera = []
    for i in range(B):
        input_raw = read_func().strip().split()
        tera.append(long(input_raw[0]))

    for i in range(Q):
        input_raw = read_func().strip().split()
        x = long(input_raw[0])
        dist1 = [2**63-1 for i in range(2)]
        z = bin_search(jinja, x)
        for j in range(len(z)):
            if z[j] != -1:
                dist1[j] = abs(jinja[z[j]] - x)
                y = bin_search(tera, jinja[z[j]])
                dist1[j]  += abs(tera[y[0]] - jinja[z[j]])

        dist2 = [2**63-1 for i in range(2)]
        z = bin_search(tera, x)
        for j in range(len(z)):
            if z[j] != -1:
                dist2[j] = abs(tera[z[j]] - x)
                y = bin_search(jinja, tera[z[j]])
                dist2[j]  += abs(jinja[y[0]] - tera[z[j]])
        print min(min(dist1), min(dist2))



if __name__ == '__main__':
    main()

Solution (Python):
import bisect
a, b, q = map(int, input().split())
s = [int(input()) for _ in range(a)]
t = [int(input()) for _ in range(b)]
x = [int(input()) for _ in range(q)]
for i in x:
    si = bisect.bisect_left(s,i)
    ti = bisect.bisect_left(t,i)
    sl = 100000000000 if si == 0 else i - s[si-1]
    sr = 100000000000 if si == a else s[si] - i
    tl = 100000000000 if ti == 0 else i - t[ti-1]
    tr = 100000000000 if ti == b else t[ti] - i
    print(min(max(sl,tl), max(sr,tr), max(sl,tr) + min(sl, tr)*2, max(sr,tl) + min(sr,tl)*2))

Solution (Python):
A,B,Q=list(map(int,input().split()))
s=[0]*(A+2)
t=[0]*(B+2)
X=[0]*Q
s[0] = -float('inf')
s[A+1] = float('inf')
t[0] = -float('inf')
t[B+1] = float('inf')
for i in range(1,A+1):
    s[i] = int(input())
for i in range(1,B+1):
    t[i] = int(input())
for i in range(Q):
    X[i] = int(input())

import bisect

for x in X:
    s_i = bisect.bisect_left(s,x)
    t_i = bisect.bisect_left(t,x)
    s_l = abs(s[s_i-1]-x)
    s_r = s[s_i]-x
    t_l = abs(t[t_i-1]-x)
    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
from collections import defaultdict
from heapq import heappush, heappop
import math
import bisect
import random
def LI(): return list(map(int, input().split()))
def I(): return int(input())
def LS(): return input().split()
def S(): return list(input())
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
mod = 1000000007






"""
n,a,b,c = LI()
l = IR(n)
f = [True for i in range(3)]
ans = 0
for i in range(n):
    for d in range(3):
        if abs(l[i]-[a,b,c][d]) <= 10 and f[d]:
            ans += abs(l[i]-[a,b,c][d])
            f[d] = False
            l[i] = -float("inf")
k = False
for i in f:
    if i:
        k = True
        break
if not k:
    print(ans)
    quit()
"""

a,b,q = LI()
s = IR(a)
t = IR(b)
for i in range(q):
    x = int(sys.stdin.readline())
    c = bisect.bisect_left(s,x)
    ans = float("inf")
    if c == a:
        k = abs(x-s[-1])
        y = s[-1]
        d = bisect.bisect_left(t,y)
        if d == b:
            k += abs(y-t[-1])
        else:
            if abs(y-t[d-1]) < abs(y-t[d]):
                k += abs(y-t[d-1])
            else:
                k += abs(y-t[d])
        ans = min(k,ans)
    else:
        k = abs(x-s[c-1])
        y = s[c-1]
        d = bisect.bisect_left(t,y)
        if d == b:
            k += abs(y-t[-1])
        else:
            if abs(y-t[d-1]) < abs(y-t[d]):
                k += abs(y-t[d-1])
            else:
                k += abs(y-t[d])
        ans = min(k,ans)
        k = abs(x-s[c])
        y = s[c]
        d = bisect.bisect_left(t,y)
        if d == b:
            k += abs(y-t[-1])
        else:
            if abs(y-t[d-1]) < abs(y-t[d]):
                k += abs(y-t[d-1])
            else:
                k += abs(y-t[d])
        ans = min(k,ans)
    c = bisect.bisect_left(t,x)
    if c == b:
        k = abs(x-t[-1])
        y = t[-1]
        d = bisect.bisect_left(s,y)
        if d == a:
            k += abs(y-s[-1])
        else:
            if abs(y-s[d-1]) < abs(y-s[d]):
                k += abs(y-s[d-1])
            else:
                k += abs(y-s[d])
        ans = min(k,ans)
    else:
        k = abs(x-t[c-1])
        y = t[c-1]
        d = bisect.bisect_left(s,y)
        if d == a:
            k += abs(y-s[-1])
        else:
            if abs(y-s[d-1]) < abs(y-s[d]):
                k += abs(y-s[d-1])
            else:
                k += abs(y-s[d])
        ans = min(k,ans)
        k = abs(x-t[c])
        y = t[c]
        d = bisect.bisect_left(s,y)
        if d == a:
            k += abs(y-s[-1])
        else:
            if abs(y-s[d-1]) < abs(y-s[d]):
                k += abs(y-s[d-1])
            else:
                k += abs(y-s[d])
        ans = min(k,ans)
    print(ans)

Solution (Python):
from bisect import bisect_left, bisect_right
import sys
input = sys.stdin.readline
a, b, q = map(int, input().split())
s = [int(input()) for _ in range(a)]
t = [int(input()) for _ in range(b)]
q = [int(input()) for _ in range(q)]
for qi in q:
    qans = 10**18
    ai = bisect_left(s, qi)
    bi = bisect_left(t, qi)
    ac = []
    bc = []
    for i in range(2):
        if (0 <= ai + i < a):
            ac.append(ai + i);
        if (0 <= ai - i < a):
            ac.append(ai - i);
    for i in range(2):
        if (0 <= bi + i < b):
            bc.append(bi + i);
        if (0 <= bi - i < b):
            bc.append(bi - i);
    for i in ac:
        for j in bc:
            aa = s[i];
            bb = t[j];
            if (max(aa, bb) <= qi):
                qans = min(qans, qi - min(aa, bb))
            elif (qi <= min(aa, bb)):
                qans = min(qans, max(aa, bb) - qi)
            else:
                qans = min(qans, min(abs(aa - qi), abs(bb - qi)) * 2 + max(abs(aa - qi), abs(bb - qi)))
    print(qans)

Solution (Python):
import bisect

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

shrines = []
for i in range(A):
    shrines.append(int(input()))

temples = []
for i in range(B):
    temples.append(int(input()))

shortest_s_to_t = {}
for shrine in shrines:
    index = bisect.bisect_left(temples, shrine)
    if index == 0:
        distance = abs(shrine - temples[index])
        shortest_s_to_t[shrine] = distance
    elif index == B:
        distance = abs(shrine - temples[index - 1])
        shortest_s_to_t[shrine] = distance
    else:
        distance_left = abs(shrine - temples[index - 1])
        distance_right = abs(shrine - temples[index])
        shortest_s_to_t[shrine] = min(distance_left, distance_right)

shortest_t_to_s = {}
for temple in temples:
    index = bisect.bisect_left(shrines, temple)
    if index == 0:
        distance = abs(temple - shrines[index])
        shortest_t_to_s[temple] = distance
    elif index == A:
        distance = abs(temple - shrines[index - 1])
        shortest_t_to_s[temple] = distance
    else:
        distance_left = abs(temple - shrines[index - 1])
        distance_right = abs(temple - shrines[index])
        shortest_t_to_s[temple] = min(distance_left, distance_right)

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

    
    index = bisect.bisect_left(shrines, x)
    ans = 10**11
    if index > 0:
        left_shrine = shrines[index - 1]
        candidate = abs(x - left_shrine) + shortest_s_to_t[left_shrine]
        ans = min(ans, candidate)
    if index < A:
        right_shrine = shrines[index]
        candidate = abs(x - right_shrine) + shortest_s_to_t[right_shrine]
        ans = min(ans, candidate)

    
    index = bisect.bisect_left(temples, x)
    if index > 0:
        left_temple = temples[index - 1]
        candidate = abs(x - left_temple) + shortest_t_to_s[left_temple]
        ans = min(ans, candidate)
    if index < B:
        right_temple = temples[index]
        candidate = abs(x - right_temple) + shortest_t_to_s[right_temple]
        ans = min(ans, candidate)

    print(ans)

Solution (Python):
a, b, q = [int(i) for i in input().split(" ")]

s = [0] * a
t = [0] * b
x = [[0, 0]] * q






sd = 0
td = 0

for i in range(0, a):
    s[i] = int(input())
    
for i in range(0, b):
    t[i] = int(input())
    
for i in range(0, q):
    x[i] = [i, int(input())]

x = sorted(x, key = lambda k: k[1])
ans = [[0, 0]] * q

def sdd(i, x):
    if i < 0 or i >= a:
        return 10**12
    else:
        return abs(s[i] - x)
    
def tdd(i, x):
    if i < 0 or i >= b:
        return 10**12
    else:
        return abs(t[i] - x)
        
for j in range(0, q):
    bf = False
    for i in range(sd, a):
        if s[i] > x[j][1]:
            sd = i
            bf = True
            break
    if not bf:
        sd = a
        
    bf = False

    for i in range(td, b):
        if t[i] > x[j][1]:
            td = i
            bf = True
            break
    if not bf:
        td = b
    
    xj = x[j][1]
    a1 = min(max(sdd(sd - 1, xj), tdd(td - 1, xj)), max(sdd(sd, xj), tdd(td, xj)))
    a2 = min(2 * sdd(sd - 1, xj) + tdd(td, xj), 2 * tdd(td - 1, xj) + sdd(sd, xj), sdd(sd - 1, xj) + 2 * tdd(td, xj), tdd(td - 1, xj) + 2 * sdd(sd, xj))
    ans[j] = [x[j][0], min(a1, a2)]

ans = sorted(ans, key = lambda k: k[0])
for i in range(0, q):
    print(ans[i][1])

Solution (Python):
import bisect

A, B, Q = map(int, input().split())
s = [None] * A
t = [None] * B
x = [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):
    x[i] = int(input())

s.sort()
t.sort()

def calc(s, t, x):
    len_s = len(s)
    len_t = len(t)

    def f_nishi_pos(l, x):
        p1 = bisect.bisect_left(l, x)
        
        
        
        
        
        
        
        if p1 == len(l):
            return p1 - 1
        else:
            if l[p1] == x:
                return p1
            else:
                return p1 - 1

    def f_higashi_pos(l, x):
        
        p2 = bisect.bisect_right(l, x)
        
        
        
        
        
        
        if p2 == len(l):
            return p2 - 1
        else:
            return p2

    
    
    j_nishi_pos = f_nishi_pos(s, x)
    j_nishi = s[j_nishi_pos]
    
    j_higashi_pos = f_higashi_pos(s, x)
    j_higashi = s[j_higashi_pos]

    
    j_nishi_t_nishi_pos = f_nishi_pos(t, j_nishi)
    j_nishi_t_nishi = t[j_nishi_t_nishi_pos]
    
    j_nishi_t_higashi_pos = f_higashi_pos(t, j_nishi)
    j_nishi_t_higashi = t[j_nishi_t_higashi_pos]
    
    j_higashi_t_nishi = t[f_nishi_pos(t, j_higashi)]
    
    j_higashi_t_higashi = t[f_higashi_pos(t, j_higashi)]


    
    t_nishi = t[f_nishi_pos(t, x)]
    t_higashi = t[f_higashi_pos(t, x)]
    
    
    t_nishi_j_nishi = s[f_nishi_pos(s, t_nishi)]
    
    t_nishi_j_higashi = s[f_higashi_pos(s, t_nishi)]
    
    t_higashi_j_nishi = s[f_nishi_pos(s, t_higashi)]
    
    t_higashi_j_higashi = s[f_higashi_pos(s, t_higashi)]


    return min(
        abs(x - j_nishi) + abs(j_nishi - j_nishi_t_nishi),
        abs(x - j_nishi) + abs(j_nishi - j_nishi_t_higashi),
        abs(x - j_higashi) + abs(j_higashi - j_higashi_t_nishi),
        abs(x - j_higashi) + abs(j_higashi - j_higashi_t_higashi),
        abs(x - t_nishi) + abs(t_nishi - t_nishi_j_nishi),
        abs(x - t_nishi) + abs(t_nishi - t_nishi_j_higashi),
        abs(x - t_higashi) + abs(t_higashi - t_higashi_j_nishi),
        abs(x - t_higashi) + abs(t_higashi - t_higashi_j_higashi)
    )

for xx in x:
    print(calc(s, t, xx))

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

A, B, Q = map(int, input().split())
s = []
for i in range(A):
    s.append(int(input()))
t = []
for i in range(B):
    t.append(int(input()))
for i in range(Q):
    x = int(input())
    j = bisect.bisect(s, x)
    ans = 2 * 10 ** 10
    if j > 0:
        k = bisect.bisect(t, s[j - 1])
        if k > 0:
            ans = min(ans,abs(x-s[j-1])+abs(s[j-1]-t[k-1]))
        if k < B:
            ans = min(ans, abs(x-s[j-1])+abs(s[j-1]-t[k]))
    if j < A:
        k = bisect.bisect(t, s[j])
        if k > 0:
            ans = min(ans, abs(x-s[j])+abs(s[j]-t[k-1]))
        if k < B:
            ans = min(ans, abs(x-s[j])+abs(s[j]-t[k]))
    j = bisect.bisect(t, x)
    if j > 0:
        k = bisect.bisect(s, t[j - 1])
        if k > 0:
            ans = min(ans,abs(x-t[j-1])+abs(t[j-1]-s[k-1]))
        if k < A:
            ans = min(ans, abs(x-t[j-1])+abs(t[j-1]-s[k]))
    if j < B:
        k = bisect.bisect(s, t[j])
        if k > 0:
            ans = min(ans, abs(x-t[j])+abs(t[j]-s[k-1]))
        if k < A:
            ans = min(ans, abs(x-t[j])+abs(t[j]-s[k]))
    print(ans)

Solution (Python):

from itertools import product
from bisect import bisect, bisect_left
def inpl(): return list(map(int, input().split()))
A, B, Q = inpl()
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:
    ans = 1e12
    ls, lt = S[max(0, bisect(S, x)-1)], T[max(0, bisect(T, x)-1)]
    rs, rt = S[min(A-1, bisect_left(S, x))], T[min(B-1, bisect_left(T, x))]
    for s in [ls, rs]:
        for t in [lt, rt]:
            if s < t:
                a, b = s, t
            else:
                a, b = t, s

            if x < a:
                if ans > b-x:
                    ans = b-x
            elif b < x:
                if ans > x-a:
                    ans = x-a
            else:
                if ans > 2*(x-a) + (b-x):
                    ans = 2*(x-a) + (b-x)
                if ans > (x-a) + 2*(b-x):
                    ans = (x-a) + 2*(b-x)
    print(ans)

Solution (Python):
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
import bisect
A,B,Q = getList()
temple = []
shrine = []
for i in range(A):
    temple.append(getN())

for i in range(B):
    shrine.append(getN())

temple.sort()
shrine.sort()

near_sh = []
for t in temple:
    a = bisect.bisect_left(shrine, t)
    if a == 0:
        l = -1000000000000
    else:
        l = shrine[a-1]
    if a == B:
        r = 1000000000000
    else:
        r = shrine[a]
    near_sh.append((l,r))

def calc(x, a, direction):
    
    try:
        near_temp = temple[a-direction]
    except:
        return 100000000000
    cost_outshrine = abs(x-near_sh[a-direction][1-direction])
    cost_inshrine = abs(x-near_temp)
    if cost_inshrine < abs(near_temp - near_sh[a-direction][0+direction]):
        
        cost_inshrine = (abs(near_temp - near_sh[a-direction][0+direction])) + min(cost_inshrine, abs(x- near_sh[a - direction][0 + direction]))

    
    return min(cost_inshrine, cost_outshrine)




for i in range(Q):
    x = getN()
    a = bisect.bisect_left(temple,x)
    if a != 0:
        cost_l = calc(x,a,1)
    else:
        cost_l = 1000000000000
    if a != A:
        cost_r = calc(x,a,0)
    else:
        cost_r = 1000000000000

    print(min(cost_l, cost_r))

Solution (Python):
import sys
import bisect
a,b,q=map(int,input().split())
s=sorted([int(input()) for i in range(a)])
t=sorted([int(input()) for i in range(b)])
i=0
for line in sys.stdin:
    ans=999999999999
    x=int(line)
    w=bisect.bisect_left(s,x)
    for j in range(2):
        if not 0<=w-j<len(s):
            continue
        z=bisect.bisect_left(t,s[w-j])
        for k in range(2):
            if not 0<=z-k<len(t):
                continue
            tmp=abs(x-s[w-j])+abs(s[w-j]-t[z-k])
            if ans>tmp:
                ans=tmp
    w=bisect.bisect_left(t,x)
    for j in range(2):
        if not 0<=w-j<len(t):
            continue
        z=bisect.bisect_left(s,t[w-j])
        for k in range(2):
            if not 0<=z-k<len(s):
                continue
            tmp=abs(x-t[w-j])+abs(t[w-j]-s[z-k])
            if ans>tmp:
                ans=tmp
    print(ans)
    i+=1

Solution (Python):

from itertools import product
from bisect import bisect, bisect_left
def inpl(): return list(map(int, input().split()))
A, B, Q = inpl()
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:
    ans = 1e12
    ls, lt = S[max(0, bisect(S, x)-1)], T[max(0, bisect(T, x)-1)]
    rs, rt = S[min(A-1, bisect_left(S, x))], T[min(B-1, bisect_left(T, x))]
    for s in [ls, rs]:
        for t in [lt, rt]:
            if s < t:
                a, b = s, t
            else:
                a, b = t, s

            if x < a:
                if ans > b-x:
                    ans = b-x
            elif b < x:
                if ans > x-a:
                    ans = x-a
            else:
                if ans > 2*(x-a) + (b-x):
                    ans = 2*(x-a) + (b-x)
                if ans > (x-a) + 2*(b-x):
                    ans = (x-a) + 2*(b-x)
    print(ans)

Solution (Python):
from bisect import bisect_left, bisect_right
mx = 10**10

def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError

def find_lt(a, x):
    'Find rightmost value less than x'
    i = bisect_left(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_le(a, x):
    'Find rightmost value less than or equal to x'
    i = bisect_right(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bisect_right(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

def find_ge(a, x):
    'Find leftmost item greater than or equal to x'
    i = bisect_left(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

a, b, q = map(int, input().split())
aa = []
bb = []
for i in range(a):
  aa.append(int(input()))
for i in range(b):
  bb.append(int(input()))

aa.append(mx * 2)
bb.append(mx * 2)
aa.insert(0, -mx * 2)
bb.insert(0, -mx * 2)


for i in range(q):
  qi = int(input())
  

  a_low = find_lt(aa, qi)
  a_high = find_gt(aa, qi)

  b_low = find_lt(bb, qi)
  b_high = find_gt(bb, qi)

  len1 = qi - min([a_low, b_low])
  len2 = max([a_high, b_high]) - qi
  len3 = (a_high - qi) + (a_high - b_low)
  len4 = (b_high - qi) + (b_high - a_low)
  len5 = (qi - b_low) + (a_high - b_low)
  len6 = (qi - a_low) + (b_high - a_low)
  lens = [len1, len2, len3, len4, len5, len6]
  print(min(lens))

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

from sys import stdin, stdout
from bisect import bisect_left as bl, bisect_right as br

def f(x, s, t):
    a = abs(x - s) + abs(s - t)
    a = min(a, abs(x - t) + abs(t - s))
    return a

a, b, q = map(int, raw_input().strip().split())
inp = stdin.readlines()
out = []

s = [0 for i in xrange(a)]
t = [0 for i in xrange(b)]

ctr = 0
for i in xrange(a):
    s[i] = int(inp[i + ctr].strip())

ctr = a
for i in xrange(b):
    t[i] = int(inp[i + ctr].strip())

ctr += b
for i in xrange(q):
    x = int(inp[i + ctr].strip())
    idx_s = bl(s, x)

    s1 = -INF
    s2 = INF
    if idx_s:
        s1 = s[idx_s - 1]
    try: s2 = s[idx_s]
    except: pass

    idx_t = bl(t, x)
    t1 = -INF
    t2 = INF
    if idx_t:
        t1 = t[idx_t - 1]
    try: t2 = t[idx_t]
    except: pass
    
    ans = f(x, s1, t1)
    ans = min(ans, f(x, s1, t2))
    ans = min(ans, f(x, s2, t2))
    ans = min(ans, f(x, s2, t1))

    out.append(str(ans))

stdout.write("\n".join(out))

Solution (Python):

"""
This file is part of https://github.com/cheran-senthil/PyRival
Copyright 2019 Cheran Senthilkumar <hello@cheran.io>

"""
from __future__ import division, print_function

import itertools
import os
import sys
from atexit import register
from io import BytesIO


class dict(dict):
    """dict() -> new empty dictionary"""

    def items(self):
        """D.items() -> a set-like object providing a view on D's items"""
        return dict.iteritems(self)

    def keys(self):
        """D.keys() -> a set-like object providing a view on D's keys"""
        return dict.iterkeys(self)

    def values(self):
        """D.values() -> an object providing a view on D's values"""
        return dict.itervalues(self)


def gcd(x, y):
    """greatest common divisor of x and y"""
    while y:
        x, y = y, x % y
    return x


range = xrange

filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip

sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))

input = lambda: sys.stdin.readline().rstrip('\r\n')


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

    s = sorted(int(input()) for _ in range(a))
    t = sorted(int(input()) for _ in range(b))

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

        lo, hi = 0, a - 1
        while lo < hi:
            mi = lo + (hi - lo) // 2
            if s[mi] > x:
                hi = mi
            else:
                lo = mi + 1

        if lo == 0:
            p1, _p1 = s[0] - x, s[0] - x
        else:
            p1, _p1 = s[lo - 1] - x, s[lo] - x

        lo, hi = 0, b - 1
        while lo < hi:
            mi = lo + (hi - lo) // 2
            if t[mi] > x:
                hi = mi
            else:
                lo = mi + 1

        if lo == 0:
            p2, _p2 = t[0] - x, t[0] - x
        else:
            p2, _p2 = t[lo - 1] - x, t[lo] - x

        res = float('inf')

        if p1 <= 0 and p2 <= 0:
            res = min(res, abs(min(p1, p2)))

        if p1 <= 0 and _p2 <= 0:
            res = min(res, abs(min(p1, _p2)))

        if _p1 <= 0 and p2 <= 0:
            res = min(res, abs(min(_p1, p2)))

        if _p1 <= 0 and _p2 <= 0:
            res = min(res, abs(min(_p1, _p2)))

        if p1 >= 0 and p2 >= 0:
            res = min(res, max(p1, p2))

        if p1 >= 0 and _p2 >= 0:
            res = min(res, max(p1, _p2))

        if _p1 >= 0 and p2 >= 0:
            res = min(res, max(_p1, p2))

        if _p1 >= 0 and _p2 >= 0:
            res = min(res, max(_p1, _p2))

        res = min(res, 2 * abs(p1) + abs(p2))
        res = min(res, 2 * abs(p1) + abs(_p2))
        res = min(res, 2 * abs(_p1) + abs(p2))
        res = min(res, 2 * abs(_p1) + abs(_p2))

        res = min(res, 2 * abs(p2) + abs(p1))
        res = min(res, 2 * abs(p2) + abs(_p1))
        res = min(res, 2 * abs(_p2) + abs(p1))
        res = min(res, 2 * abs(_p2) + abs(_p1))

        print(res)


if __name__ == '__main__':
    main()

Solution (Python):
import bisect


def solve(A, B, Q, Ss, Ts, Xs):
    ans = []
    Ss.append(10 ** 21)
    Ss.insert(0, -10 ** 21)
    Ts.append(10 ** 21)
    Ts.insert(0, -10 ** 21)
    for x in Xs:
        s_right = bisect.bisect_right(Ss, x)
        s_left = max(s_right - 1, 0)
        t_right = bisect.bisect_right(Ts, x)
        t_left = max(t_right - 1, 0)

        s_right = Ss[s_right]
        s_left = Ss[s_left]
        t_right = Ts[t_right]
        t_left = Ts[t_left]

        d_s_right = abs(s_right - x)
        d_s_left = abs(s_left - x)
        d_t_right = abs(t_right - x)
        d_t_left = abs(t_left - x)

        tans = 10 ** 35
        if x <= s_right and x <= t_right:
            tans = min(tans, max(d_t_right, d_s_right))
        if s_right <= x and t_right <= x:
            tans = min(tans, max(d_t_right, d_s_right))
        if s_left <= x and t_left <= x:
            tans = min(tans, max(d_s_left, d_t_left))
        tans = min(tans, min(d_s_right, d_t_left) * 2 + max(d_s_right, d_t_left))
        tans = min(tans, min(d_t_right, d_s_left) * 2 + max(d_t_right, d_s_left))
        ans.append(str(tans))
    return "\n".join(ans)

if __name__ == "__main__":
    A, B, Q = tuple(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)]
    print(solve(A, B, Q, Ss, Ts, Xs))

Solution (Python):


import bisect

MAX_VAL = 2e+10


def make(src, dst):
  points = [v[0] for v in dst]

  for i in range(len(src)):
    p = src[i][0]
    j = bisect.bisect(points, p)

    if j == 0:
      v = dst[j][0] - p
    elif j == len(dst):
      v = p - dst[j - 1][0]
    else:
      v = min(dst[j][0] - p, p - dst[j - 1][0])

    src[i] = (p, v)


def main():
  a, b, s = map(int, input().split())
  shrines = [(int(input()),) for _ in range(a)]
  temples = [(int(input()),) for _ in range(b)]
  starts = [int(input()) for _ in range(s)]

  make(shrines, temples)
  make(temples, shrines)

  s_index = 0
  t_index = 0
  places = []

  while len(places) < len(shrines) + len(temples):
    if s_index == len(shrines):
      places.append(temples[t_index])
      t_index += 1
    elif t_index == len(temples):
      places.append(shrines[s_index])
      s_index += 1
    elif temples[t_index][0] < shrines[s_index][0]:
      places.append(temples[t_index])
      t_index += 1
    else:
      places.append(shrines[s_index])
      s_index += 1

  points = [p for p, _ in places]

  for start in starts:
    idx = bisect.bisect(points, start)
    value = None

    if idx == 0:
      value = points[idx] - start + places[idx][1]
    elif idx == len(points):
      value = start - points[idx - 1] + places[idx - 1][1]
    else:
      value = min(points[idx] - start + places[idx][1], start - points[idx - 1] + places[idx - 1][1])

    print(value, flush=True)


if __name__ == '__main__':
  main()