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.



Sample input:
2 3 4
100
600
400
900
1000
150
2000
899
799


Sample output:
350
1400
301
399

Submission status: Accepted

Solution code:
import bisect
a, b, q = map(int, input().split())
s = [0] * a
t = [0] * b
x = [0] * q

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

s.append(- 10 ** 20)
s.append(10 ** 20)
t.append(- 10 ** 20)
t.append(10 ** 20)

s.sort()
t.sort()

for i in range(q):
    ans = 10 ** 20

    s_idx = bisect.bisect_left(s, x[i])
    sl = s_idx - 1
    sr = s_idx

    t_idx = bisect.bisect_left(t, x[i])
    tl = t_idx - 1
    tr = t_idx

    ans = min(ans, max(abs(s[sl] - x[i]), abs(t[tl] - x[i])))
    ans = min(ans, max(abs(s[sr] - x[i]), abs(t[tr] - x[i])))
    ans = min(ans, min(abs(s[sl] - x[i]) * 2 + abs(x[i] - t[tr]),
                       abs(s[sl] - x[i]) + abs(x[i] - t[tr]) * 2))
    ans = min(ans, min(abs(t[tl] - x[i]) * 2 + abs(x[i] - s[sr]),
                       abs(t[tl] - x[i]) + abs(x[i] - s[sr]) * 2))
    print(ans)

Submission status: Accepted

Solution code:
a,b,q=map(int,input().split())
S=[int(input()) for i in range(a)]
T=[int(input()) for i in range(b)]
Q=[int(input()) for i in range(q)]

QLIST=[[10**15,10**15,10**15,10**15] for i in range(q)]

QI=[[Q[i],i] for i in range(q)]
QI.sort()

i=0
j=0

while j<q and i<a:
    if S[i]>QI[j][0]:
        if i>0:
            QLIST[QI[j][1]][0]=QI[j][0]-S[i-1]
        QLIST[QI[j][1]][1]=S[i]-QI[j][0]

        j+=1
    else:
        i+=1

    if i==a:
        for h in range(j,q):
            QLIST[QI[h][1]][0]=QI[h][0]-S[i-1]

i=0
j=0

while j<q and i<b:
    if T[i]>QI[j][0]:
        if i>0:
            QLIST[QI[j][1]][2]=QI[j][0]-T[i-1]
        QLIST[QI[j][1]][3]=T[i]-QI[j][0]

        j+=1
    else:
        i+=1

    if i==b:
        for h in range(j,q):
            QLIST[QI[h][1]][2]=QI[h][0]-T[i-1]
        
        
for L1,R1,L2,R2 in QLIST:
    A=max(L1,L2)
    B=max(R1,R2)
    C=min(L1,R1)*2+min(L2,R2)
    D=min(L1,R1)+min(L2,R2)*2

    print(min(A,B,C,D))

Submission status: Accepted

Solution code:
import bisect
a, b, q = map(int, input().split())
s = [int(input()) for _ in range(a)]
t = [int(input()) for _ in range(b)]
for i in range(q):
    x = int(input())
    idx_s = bisect.bisect_left(s, x)
    idx_t = bisect.bisect_left(t, x)

    indices_s = []
    indices_t = []

    if idx_s == 0:
        indices_s.append(0)
    elif idx_s == a:
        indices_s.append(a-1)
    else:
        indices_s.append(idx_s)
        indices_s.append(idx_s-1)

    if idx_t == 0:
        indices_t.append(0)
    elif idx_t == b:
        indices_t.append(b-1)
    else:
        indices_t.append(idx_t)
        indices_t.append(idx_t-1)

    ans = []
    for i in indices_s:
        for j in indices_t:
            l, r = min(s[i], t[j]), max(s[i], t[j])
            if x < l:
                ans.append(r-x)
            elif l <= x and x < r:
                ans.append(min(r-l+(x-l), r-l+(r-x)))
            else:
                ans.append(x-l)
    print(min(ans))

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def li(): return map(int, stdin.readline().split())
def li_(): return map(lambda x: int(x)-1, stdin.readline().split())
def lf(): return map(float, stdin.readline().split())
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(stdin.readline())
def nf(): return float(stdin.readline())

from bisect import bisect_right

a,b,q = li()
s = [ni() for _ in range(a)]
t = [ni() for _ in range(b)]
query = [ni() for _ in range(q)]

for qi in query:
    shrine_right = float('inf')
    temple_right = float('inf')
    
    shrine_right_idx = bisect_right(s, qi)
    temple_right_idx = bisect_right(t, qi)
    
    if shrine_right_idx < a:
        shrine_right = s[shrine_right_idx]
        
    if temple_right_idx < b:
        temple_right = t[temple_right_idx]
    
    shrine_left = float('inf')
    temple_left = float('inf')
    
    if shrine_right_idx > 0:
        shrine_left = s[shrine_right_idx - 1]
        
    if temple_right_idx > 0:
        temple_left = t[temple_right_idx - 1] 
        
    cand = []
    
    # 前前
    cand.append(max(abs(qi - shrine_left), abs(qi - temple_left)))
    
    # 前後
    cand.append(abs(temple_right-shrine_left) + min(abs(qi - shrine_left), abs(qi - temple_right)))
    
    # 後前
    cand.append(abs(shrine_right-temple_left) + min(abs(qi - temple_left), abs(qi - shrine_right)))
    
    # 後後
    cand.append(max(abs(qi - shrine_right), abs(qi - temple_right)))
        
    print(min(cand))

Submission status: Accepted

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

MAX = 99999999999

s = sorted(s)
t = sorted(t)

#print(s)
#print(t)
#print(x)
for c in x:
    i = bisect.bisect_left(s, c)
    j = bisect.bisect_left(t, c)

    if i == 0:
        sl = MAX
    else:
        sl = c - s[i - 1]

    if i == a:
        sr = MAX
    else:
        sr = s[i] - c

    if j == 0:
        tl = MAX
    else:
        tl = c - t[j - 1]

    if j == b:
        tr = MAX
    else:
        tr = t[j] - c

    print(min(max(sr, tr), max(sl, tl), sr + tl + min(sr, tl), sl + tr + min(sl, tr)))

Submission status: Accepted

Solution code:
import bisect
import sys
input = sys.stdin.readline
a,b,q = map(int,input().split())
x = [int(input()) for i in range(a)]
y = [int(input()) for i in range(b)]
osoi = [int(input()) for i in range(q)]
x.sort()
y.sort()
xx = [0]*a
yy = [0]*b
n = 0
for i in range(a):
    while n < b-1 and abs(x[i]-y[n]) > abs(x[i]-y[n+1]):
        n+=1
    xx[i] = abs(x[i]-y[n])
n = 0
for i in range(b):
    while n < a-1 and abs(y[i]-x[n]) > abs(y[i]-x[n+1]):
        n+=1

    yy[i] = abs(y[i]-x[n])

for i in range(q):
    z = osoi[i]
    ans = 1<<61
    n = bisect.bisect_left(x, z)
    if n<a:
        tmp = abs(x[n]-z)+xx[n]
        ans = min(ans,tmp)
    if n>0:
        tmp = abs(x[n-1]-z)+xx[n-1]
        ans = min(ans,tmp)

    n = bisect.bisect_left(y, z)
    if n<b:
        tmp = abs(y[n]-z)+yy[n]
        ans = min(ans,tmp)
    if n>0:
        tmp = abs(y[n-1]-z)+yy[n-1]
        ans = min(ans,tmp)
    print(ans)

Submission status: Accepted

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

for i in range(Q):
	x = int(input())
	ids = bisect.bisect_left(S,x)
	idt = bisect.bisect_left(T,x)
	ans = 0
	sl = -10000000000000000
	sr = 10000000000000000
	tl = -10000000000000000
	tr = 10000000000000000
	if ids!=0:
		sl = S[ids-1]
	if ids!=A:
		sr = S[ids]
	if idt!=0:
		tl = T[idt-1]
	if idt!=B:
		tr = T[idt]
	ans = min(max(sr,tr)-x,x-min(sl,tl))
	ans = min(ans,2*abs(x-sl)+abs(x-tr),abs(x-sl)+2*abs(x-tr),2*abs(x-sr)+abs(x-tl),abs(x-sr)+2*abs(x-tl))
	print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left
A, B, Q = map(int, input().split())
S = [-float('inf')] + [int(input()) for i in range(A)] + [float('inf')]
T = [-float('inf')] + [int(input()) for i in range(B)] + [float('inf')]


for i in range(Q):
    x = int(input())
    Sx = bisect_left(S, x)
    Tx = bisect_left(T, x)
    S_w, S_e = S[Sx - 1], S[Sx]
    T_w, T_e = T[Tx - 1], T[Tx]

    S_wc, S_ec = abs(x - S_w), abs(x - S_e)
    T_wc, T_ec = abs(x - T_w), abs(x - T_e)

    west_only = max(S_wc, T_wc)
    east_only = max(S_ec, T_ec)
    west_east = 2 * min(S_wc, T_ec) + max(S_wc, T_ec)
    east_west = 2 * min(S_ec, T_wc) + max(S_ec, T_wc)

    print(min(west_only,
              east_only,
              west_east,
              east_west))

Submission status: Accepted

Solution code:
from bisect import bisect

A, B, Q = map(int, input().split())
s = [-10**15]
t = [-10**15]
for _ in range(A):
    s.append(int(input()))
s.append(10**15)
for _ in range(B):
    t.append(int(input()))
t.append(10**15)
x = list(map(int, (input() for _ in range(Q))))
for y in x:
    i = bisect(s, y)
    j = bisect(t, y)
    ans = min(
        max(abs(s[i] - y), abs(t[j] - y)),
        max(abs(s[i - 1] - y), abs(t[j - 1] - y)),
        2 * min(abs(s[i] - y), abs(t[j - 1] - y)) + max(abs(s[i] - y), abs(t[j - 1] - y)),
        2 * min(abs(s[i - 1] - y), abs(t[j] - y)) + max(abs(s[i - 1] - y), abs(t[j] - y))
    )
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left
a, b, q = map(int, input().split())
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
s.sort()
t.sort()
xs = [int(input()) for i in range(q)]

for x in xs:
    right_s = bisect_left(s, x)
    right_t = bisect_left(t, x)
    left_s = right_s-1
    left_t = right_t-1
    if right_s == 0:
        left_s = 0
    if right_t == 0:
        left_t = 0
    if right_s == a:
        right_s -= 1
    if right_t == b:
        right_t -= 1
    
    ss = [s[left_s], s[right_s]]
    tt = t[left_t], t[right_t]
    ans = float("inf")
    for i in ss:
        for j in tt:
            ans = min(ans, abs(i-j) + min(abs(i-x), abs(j-x)))
    print(ans)

Submission status: Accepted

Solution code:
import bisect

INF = 1000000000000
A, B, Q = [int(x) for x in input().split()]
s = [-INF] + [int(input()) for i in range(A)] + [INF]
t = [-INF] + [int(input()) for i in range(B)] + [INF]

def solve(x):
    sr = s[bisect.bisect_left(s, x)]
    sl = s[bisect.bisect_right(s, x) - 1]
    tr = t[bisect.bisect_left(t, x)]
    tl = t[bisect.bisect_right(t, x) - 1]
    
    a = max(abs(x - sl), abs(x - tl))
    b = max(abs(x - sr), abs(x - tr))
    c = min(abs(x - sl) + abs(sl - tr), abs(x - tl) + abs(tl - sr));
    d = min(abs(x - sr) + abs(sr - tl), abs(x - tr) + abs(tr - sl));
    return min(a, b, c, d)

for _ in range(Q):
    x = int(input())
    ans = solve(x)
    print(ans)

Submission status: Accepted

Solution code:
# coding:utf-8

import sys
import bisect
# from collections import Counter, defaultdict

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

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()


a, b, q = LI()
A = [-INF] + [II() for _ in range(a)] + [INF]
B = [-INF] + [II() for _ in range(b)] + [INF]

for _ in range(q):
    x = II()
    ans = INF
    x_a = bisect.bisect_left(A, x)
    for k in [-1, 0]:
        tmp = abs(x - A[x_a + k])
        x_b = bisect.bisect_left(B, A[x_a + k])
        tmp += min(abs(B[x_b] - A[x_a + k]), abs(B[x_b - 1] - A[x_a + k]))
        ans = min(ans, tmp)

    x_b = bisect.bisect_left(B, x)
    for k in [-1, 0]:
        tmp = abs(x - B[x_b + k])
        x_a = bisect.bisect_left(A, B[x_b + k])
        tmp += min(abs(A[x_a] - B[x_b + k]), abs(A[x_a - 1] - B[x_b + k]))
        ans = min(ans, tmp)

    print(ans)

Submission status: Accepted

Solution code:
import bisect
import sys

a, b, q = list(map(int, input().split()))
lines = sys.stdin.readlines()
sss = list(map(int, lines[:a]))
ttt = list(map(int, lines[a:a + b]))
xxx = list(map(int, lines[a + b:]))

nearest_temples = [0] * a
nearest_shrines = [0] * b
for i, s in enumerate(sss):
    ti = bisect.bisect(ttt, s)
    nt = 10 ** 11
    if ti > 0:
        nt = min(nt, abs(s - ttt[ti - 1]))
    if ti < b:
        nt = min(nt, abs(s - ttt[ti]))
    nearest_temples[i] = nt
for i, t in enumerate(ttt):
    si = bisect.bisect(sss, t)
    ns = 10 ** 11
    if si > 0:
        ns = min(ns, abs(t - sss[si - 1]))
    if si < a:
        ns = min(ns, abs(t - sss[si]))
    nearest_shrines[i] = ns

buf = []
for x in xxx:
    si = bisect.bisect(sss, x)
    ti = bisect.bisect(ttt, x)
    ans = 10 ** 11
    if si > 0:
        ans = min(ans, x - sss[si - 1] + nearest_temples[si - 1])
    if si < a:
        ans = min(ans, sss[si] - x + nearest_temples[si])
    if ti > 0:
        ans = min(ans, x - ttt[ti - 1] + nearest_shrines[ti - 1])
    if ti < b:
        ans = min(ans, ttt[ti] - x + nearest_shrines[ti])
    buf.append(ans)
print('\n'.join(map(str, buf)))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(10000)


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time 

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(A, B, X):
    for x in X:
        i = bisect.bisect_left(A, x)
        la = A[i-1] if i > 0 else sys.maxsize
        ra = A[i] if i < len(A) else sys.maxsize

        i = bisect.bisect_left(B, x)
        lb = B[i-1] if i > 0 else sys.maxsize
        rb = B[i] if i < len(B) else sys.maxsize

        # print(x, la, ra, lb, rb, abs(rb-x))
        e =  max(abs(x-la), abs(x-lb)) 
        f =  max(abs(ra-x), abs(rb-x))
        g = min(abs(la-x), abs(rb-x))*2 + max(abs(la-x), abs(rb-x))
        h = min(abs(ra-x), abs(lb-x))*2 + max(abs(ra-x), abs(lb-x))
        print(min(e, f, g, h))


def main():
    # N = read_int()
    AN, BN, Q = read_int_n()
    A = [read_int() for _ in range(AN)]
    B = [read_int() for _ in range(BN)]
    X = [read_int() for _ in range(Q)]
    slv(A, B, X)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect
A,B,Q=[int(i) for i in input().split(" ")]

shrine=[-10**11]
for i in range(A):
    shrine.append(int(input()))
shrine.append(10**11)
temple=[-10**11]
for j in range(B):
    temple.append(int(input()))
temple.append(10**11)

def nearest_place(x,spot):
    if spot=="shrine":
        ind=bisect.bisect_left(shrine,x)-1

        left=shrine[ind]
        try:
            right=shrine[ind+1]
        except IndexError:
            right=shrine[ind]
        return left,right
    else:
                ind=bisect.bisect_left(temple,x)-1
                left=temple[ind]
                try:
                    right=temple[ind+1]
                except IndexError:
                    right=temple[ind]
                return left,right
ans=[]
for q in range(Q):
    x=int(input())
    retval=[]
    ls,rs=nearest_place(x,"shrine")
    lslt,lsrt=nearest_place(ls,"temple")
    rslt,rsrt=nearest_place(rs,"temple")
    lt,rt=nearest_place(x,"temple")
    ltls,ltrs=nearest_place(lt,"shrine")
    rtls,rtrs=nearest_place(rt,"shrine")
    retval.append(abs(x-ls)+abs(ls-lt))
    retval.append(abs(x-ls)+abs(ls-rt))
    retval.append(abs(x-rs)+abs(rs-lt))
    retval.append(abs(x-rs)+abs(rs-rt))
    retval.append(abs(x-lt)+abs(lt-ls))
    retval.append(abs(x-lt)+abs(lt-rs))
    retval.append(abs(x-rt)+abs(rt-ls))
    retval.append(abs(x-rt)+abs(rt-rs))
    ans.append(min(retval))

for a in ans:
    print(a)

Submission status: Accepted

Solution code:
from bisect import bisect_left as bisect

a, b, q = [int(i) for i in 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)]

for x in X:
    s_i = bisect(S, x)
    t_i = bisect(T, x)
    min_s = min(abs(x - S[max(0, s_i - 1)]), abs(x - S[min(a - 1, s_i)]))
    min_t = min(abs(x - T[max(0, t_i - 1)]), abs(x - T[min(b - 1, t_i)]))
    ans = min_s + min_t + min(min_s, min_t)
    if s_i > 0 and t_i > 0:
        ans = min(ans, abs(x - min(S[s_i - 1], T[t_i - 1])))
    if s_i < a and t_i < b:
        ans = min(ans, abs(x - max(S[s_i], T[t_i])))
    
    print(ans)

Submission status: Accepted

Solution code:
from bisect import *
A,B,Q=map(int,input().split())
s=[-10**11]+[int(input()) for i in range(A)]+[10**11]
t=[-10**11]+[int(input()) for i in range(B)]+[10**11]
x=[int(input()) for i in range(Q)]
for i in range(Q):
    S=[0,0]
    T=[0,0]
    sidx=bisect_left(s,x[i])-1
    S[0]=s[sidx]
    S[1]=s[sidx+1]
    tidx=bisect_left(t,x[i])-1
    T[0]=t[tidx]
    T[1]=t[tidx+1]
    ans=10**12
    seq=[(0,1),(1,0),(1,1),(0,0)]
    for a,b in seq:
        tmp=abs(x[i]-S[a])+abs(S[a]-T[b])
        ans=min(ans,tmp)
        tmp=abs(x[i]-T[a])+abs(T[a]-S[b])
        ans=min(ans,tmp)
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left

INF = 30000000000

if __name__ == '__main__':
    a, b, q = map(int, input().split())
    ss = [- INF] + [int(input()) for _ in range(a)] + [INF]
    ts = [- INF] + [int(input()) for _ in range(b)] + [INF]
    xs = [int(input()) for _ in range(q)]

    for x in xs:
        sr = bisect_left(ss, x)
        tr = bisect_left(ts, x)
        sl = sr - 1
        tl = tr - 1
        can1 = ss[sr] - ts[tl] + min(ss[sr] - x, x - ts[tl])
        can2 = ts[tr] - ss[sl] + min(ts[tr] - x, x - ss[sl])
        can3 = max(ss[sr], ts[tr]) - x
        can4 = x - min(ss[sl], ts[tl])
        print(min(can1, can2, can3, can4))

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from bisect import bisect

A, B, Q = map(int, readline().split())
S = [int(readline()) for i in range(A)]
T = [int(readline()) for i in range(B)]
ans = []
INF = 10**18
for i in range(Q):
    x = int(readline())
    p = bisect(S, x-1)
    lp = x - S[p-1] if p >= 1 else INF
    rp = S[p] - x if p < A else INF
    q = bisect(T, x-1)
    lq = x - T[q-1] if q >= 1 else INF
    rq = T[q] - x if q < B else INF
    ans.append("%d\n" % (min(max(lp, lq), max(rp, rq), lp*2+rq, lp+rq*2, lq*2+rp, lq+rp*2)))
sys.stdout.writelines(ans)

Submission status: Accepted

Solution code:
#       )                         .MMdMMM;                    .M#(,dM]                        .:
#       )                        .M@d@d#Mb                    dMGMM(MN                        .:
#       )                        dM1MCdbMM_                  .M@MSN;dM-                       .:
#       )                       .M#(#?d#(Mb.. ...............JMIMIMLdM]                       .:
#       )                      ..M#?NHM# ?MMMMMMMMMH"""""""HMM@(Nad#(Mb                       .:
#       )                  .(MMMMH=..-(Jg[   `               daggmp  MNm,                     .:
#       )                ..MMY`     !qN;                       (J     ?MMN,                   .:
#       )               (MMD`       .MM@                      .MM{      .WMN,                 .:
#       )              dM@`         dMM%                      .MM}        (MMm                .:
#       )             .M#`          dMN!                      .MM}        ~(MMr               .:
#       )            .MM:           dM#                       .MM}        ..JM#               .:
#       )      ``    .M@            dMF                       .MM}        .~(M#   `  .        .:
#       )      ?MMMMMMMNgJ,         .7`                        T"!       .JJjMNgNNMMMB^       .:
#       )            dMr ?Mm,                                            7YYMM#!`             .:
#       )            dMb   ?`                  .,   ` ..                 ~.(MM%               .:
#       )         ..JgMMNNN)                  .Mn.(Mm-JM{               dHHMMNag.,            .:
#       )         ("!  ?MN,..,                (NM@"`~OMM}             ..~-(M@` _?"M[          .:
#       )               ,MMM#_                .M#    .M#`           .~.~JMMMNg-..             .:
#       )           ..gMB"?TMMNJ..              `     _`         .~~.(JdM#^  _"TMMNgJ-,       .:
#       )        .gMB=`      _7WMMNaJ...                 ....__-(JJgMMMM^          ?T"^       .:
#       )           ............  ?TWMMMMNNNNgggggggggggggNNMMMMMMBY7`...                     .:
#       )           WMMMMMMMMMMMMMNgJ,   (dMMMM#"TYYYYYYMMMMMMMNgMMMMMMMMMMMNNgJ-,            .:
#       )            -?TMNmuuuuUWMMMMMMNNMM@g@MMmJ--_(JMMg@g@@gMMMMMMWUXXXUWMMMMMMNe.         .:

import sys
import bisect
input = sys.stdin.readline

a,b,q = map(int,input().split())
s = []
t = []
for i in range(a):
    S = int(input())
    s.append(S)
for i in range(b):
    T = int(input())
    t.append(T)
s.sort()
t.sort()

def f(x):
    if 0<=x and a-1>= x:
        return True
    return False
def g(x):
    if 0<=x and b-1>= x:
        return True
    return False
for i in range(q):
    x = int(input())
    p = bisect.bisect_left(s,x)
    m = bisect.bisect_left(t,x)
    
    res = []
    if f(p) and g(m):
        res.append(max(t[m],s[p])-x)
    if f(p) and g(m-1):
        res.append(min(s[p]-x,x-t[m-1])+s[p]-t[m-1])
    if f(p-1) and g(m):
        res.append(t[m]-s[p-1]+min(t[m]-x,x-s[p-1]))
    if f(p-1) and g(m-1):
        res.append(x-min(t[m-1],s[p-1]))
    print(min(res))

Submission status: Runtime Error

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

s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]

import bisect

for i in range(q):
    qq = int(input())
    sp = bisect.bisect(s,qq)
    tp = bisect.bisect(t,qq)
    s1 = s[sp-1]
    if sp <a:
        s2 = s[sp]

    t1 = t[tp-1]
    if tp <b:
        t2 = t[tp]
    print(min(abs(qq-s1)+abs(s1-t1),abs(qq-s1)+abs(s1-t2),
              abs(qq-s2)+abs(s2-t1),abs(qq-s2)+abs(s2-t2),
              abs(qq-t1)+abs(t1-s1),abs(qq-t1)+abs(t1-s2),
              abs(qq-t2)+abs(t2-s1),abs(qq-t2)+abs(t2-s2)))

Submission status: Runtime Error

Solution code:
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)

Submission status: Runtime Error

Solution code:
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[i-1],T[i]]:
      d1 = abs(s-x)+abs(s-t)
      d2 = abs(t-x)+abs(s-t)
      d = min(d,d1,d2)
  print(d)

Submission status: Runtime Error

Solution code:
import bisect
a,b,q = map(int,input().split())
inf = 10**12
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())
  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[i-1],T[i]]:
      d1 = abs(s-x)+abs(s-t)
      d2 = abs(t-x)+abs(s-t)
      d = min(d,d1,d2)
  print(d)
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[i-1],T[i]]:
      d1 = abs(s-x)+abs(s-t)
      d2 = abs(t-x)+abs(s-t)
      d = min(d,d1,d2)
  print(d)

Submission status: Runtime Error

Solution code:
import bisect
a,b,q = map(int,input().split())
inf = 10**12
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())
  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[i-1],T[i]]:
      d1 = abs(s-x)+abs(s-t)
      d2 = abs(t-x)+abs(s-t)
      d = min(d,d1,d2)
  print(d)

Submission status: Runtime Error

Solution code:
import bisect
A,B,Q = map(int,input().split())
INF = float('inf')
S = [-INF]+[int(input()) for _ in range(A)]+[INF]
T = [-INF]+[int(input()) for _ in range(B)]+[INF]

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

Submission status: Runtime Error

Solution code:
import bisect
A,B,Q = map(int,input().split())
INF = float('inf')
S = [-INF]+[int(input()) for _ in range(A)]+[INF]
T = [-INF]+[int(input()) for _ in range(B)]+[INF]

ans = []
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[i-1],T[i]]:
            d1 = abs(x-s) + abs(s-t)
            d2 = abs(x-t) + abs(s-t)
            d = min(d,d1,d2)
    ans.append(d)
print(*ans,sep="\n")

Submission status: Runtime Error

Solution code:
import bisect
A,B,Q = map(int,input().split())
INF = float('inf')
S = [-INF]+[int(input()) for _ in range(A)]+[INF]
T = [-INF]+[int(input()) for _ in range(B)]+[INF]

ans = []
for q in range(Q):
    x = int(input())
    i = bisect.bisect_left(S,x)
    j = bisect.bisect_left(T,x)
    d = INF
    for s in [S[i-1],S[i]]:
        for t in [T[i-1],T[i]]:
            d1 = abs(x-s) + abs(s-t)
            d2 = abs(x-t) + abs(s-t)
            d = min(d,d1,d2)
    ans.append(d)
print(*ans,sep="\n")

Submission status: Runtime Error

Solution code:
from bisect import bisect_left

A,B,Q=map(int,input().split())
S=[int(input()) for i in range(A)]
T=[int(input()) for i in range(B)]
for i in range(Q):
    x=int(input())
    si=bisect_left(S,x)
    ti=bisect_left(T,x)
    if 0<si<A and 0<ti<B:
        sl,sr=abs(x-S[si-1]),abs(x-S[si])
        tl,tr=abs(x-T[ti-1]),abs(x-T[ti])
        print(min(max(sr,tr),max(sl,tl),sl+tr+min(sl,tr),sr+tl+min(sr,tl)))
    elif si==0 and ti==0:
        sr=abs(x-S[si])
        tr=abs(x-T[ti])
        print(sr,tr)
    elif si==A and ti==B:
        sl=abs(x-S[si-1]),abs(x-S[si])
        tl=abs(x-T[ti-1]),abs(x-T[ti])
        print(max(sl,tl))
    elif si==0 and ti==B:
        sr=abs(x-S[si])
        tl=abs(x-T[ti-1])
        print(sr+tl+min(sr,tl))
    elif si==A and ti==0:
        sl=abs(x-S[si-1])
        tr=abs(x-T[ti])
        print(sl+tr+min(sl,tr))
    elif si==0:
        sr=abs(x-S[si])
        tl,tr=abs(x-T[ti-1]),abs(x-T[ti])
        print(min(max(sr,tr),sr+tl+min(sr,tl)))
    elif si==A:
        sl=abs(x-S[si-1])
        tl,tr=abs(x-T[ti-1]),abs(x-T[ti])
        print(min(max(sl,tl),sl+tr+min(sl,tr)))
    elif ti==0:
        sl,sr=abs(x-S[si-1]),abs(x-S[si])
        tr=abs(x-T[ti])
        print(min(max(sr,tr),sl+tr+min(sl,tr)))
    elif ti==B:
        sl,sr=abs(x-S[si-1]),abs(x-S[si])
        tl=abs(x-T[ti-1])
        print(min(max(sl,tl),sr+tl+min(sr,tl)))

Submission status: Runtime Error

Solution code:
import bisect

a,b,q=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 _ in range(q):
  x = int(input())
  
  ans = [0,0,0,0]
  
  if x in s:
    sl = x
    sr = x
  else:
    i = bisect.bisect_left(s,x)
    sl = s[max(i-1,0)]
    sr = s[min(i,a-1)]
  if sl in t:
    tl = sl
    tr = sl
  else:
    j = bisect.bisect_left(t,sl)
    tl = t[max(j-1,0)]
    tr = t[min(j,b-1)]
  ans[0] = abs(sl-x) + min(abs(tl-sl), abs(tr-sl))
  if sr in t:
    tl = sr
    tr = sr
  else:
    j = bisect.bisect_left(t,sr)
    tl = t[j]
    tr = t[min(j+1,b-1)]
  ans[1] = abs(sr-x) + min(abs(tl-sr), abs(tr-sr))
  
  if x in t:
    tl = x
    tr = x
  else:
    i = bisect.bisect_left(t,x)
    tl = t[max(i-1,0)]
    tr = t[min(i,b-1)]
  if tl in s:
    sl = tl
    sr = tl
  else:
    j = bisect.bisect_left(s,tl)
    sl = s[max(j-1,0)]
    sr = s[min(j,a-1)]
  ans[2] = abs(tl-x) + min(abs(sl-tl), abs(sr-tl))
  if tr in s:
    sl = tr
    sr = tr
  else:
    j = bisect.bisect_left(s,tr)
    sl = s[max(j-1,0)]
    sr = s[min(j,a-1)]
  ans[3] = abs(tr-x) + min(abs(sl-tr), abs(sr-tr))
  print(min(ans))

Submission status: Runtime Error

Solution code:
import sys
input = sys.stdin.readline
INF = 10**11
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]
def binary_search(lis,x):
    ok = 0
    ng = len(lis)-1
    while ng-ok > 1:
        mid = (ok+ng)//2
        if lis[mid] < x:
            ok = mid
        else:
            ng = mid
    return ok
#print(s,t)
for _ in range(Q):
    x = int(input())
    ps = binary_search(s,x)
    pt = binary_search(t,x)
    ans = INF
    #print(ps,pt)
    for i in range(ps,ps+2):
        for j in range(pt,pt+2):
            ans = min(ans,abs(s[i]-X)+abs(s[i]-t[j]), abs(t[j]-X)+abs(t[j]-s[i]))
    print(ans)