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: Time Limit Exceeded

Solution code:
import bisect

A, B, Q = map(int, input().split())
S = [int(input()) for _ in range(A)]
# print(S)
T = [int(input()) for _ in range(B)]
# print(T)
X = [int(input()) for _ in range(Q)]

score_left_T_right_S = float('inf')
score_left_T_left_S = float('inf')
score_right_T_left_S = float('inf')
score_right_T_right_S = float('inf')
for x in X:
    if bisect.bisect_left(S, x) < A and S[bisect.bisect_left(S, x)] == x:
        left_S = x
        right_S = x
    else:
        if bisect.bisect_right(S, x) - 1 >= 0:
            left_S = S[bisect.bisect_right(S, x) - 1]
        elif bisect.bisect_right(S, x) - 1 < 0:
            left_S = None
        if bisect.bisect_right(S, x) < A:
            right_S = S[bisect.bisect_right(S, x)]
        elif bisect.bisect_right(S, x) >= A:
            right_S = None

    if bisect.bisect_right(T, x) < B and T[bisect.bisect_right(T, x)] == x:
        left_T = x
        right_T = x
    else:
        if bisect.bisect_right(T, x) - 1 >= 0:
            left_T = T[bisect.bisect_right(T, x) - 1]
        elif bisect.bisect_right(T, x) - 1 < 0:
            left_T = None
        if bisect.bisect_right(T, x) < B:
            right_T = T[bisect.bisect_right(T, x)]
        elif bisect.bisect_right(T, x) >= B:
            right_T = None

    if left_T and right_S:
        score_left_T_right_S = min(abs(left_T - x) + abs(left_T - right_S), abs(right_S - x) + abs(left_T - right_S))

    if left_T and left_S:
        score_left_T_left_S = min(abs(left_T - x) + abs(left_T - left_S), abs(left_S - x) + abs(left_T - left_S))

    if right_T and left_S:
        score_right_T_left_S = min(abs(right_T - x) + abs(right_T - left_S),
                                   abs(left_S - x) + abs(right_T - left_S))

    if right_T and right_S:
        score_right_T_right_S = min(abs(right_T - x) + abs(right_T - right_S),
                                  abs(right_S - x) + abs(right_T - right_S))

    print(min(score_left_T_right_S, score_left_T_left_S, score_right_T_left_S, score_right_T_right_S))

    score_left_T_right_S = float('inf')
    score_left_T_left_S = float('inf')
    score_right_T_left_S = float('inf')
    score_right_T_right_S = float('inf')

Submission status: Time Limit Exceeded

Solution code:
import bisect

A, B, Q = map(int, input().split())
S = [int(input()) for _ in range(A)]
# print(S)
T = [int(input()) for _ in range(B)]
# print(T)
X = [int(input()) for _ in range(Q)]

score_left_T_right_S = 10**100
score_left_T_left_S = 10**100
score_right_T_left_S = 10**100
score_right_T_right_S = 10**100
for x in X:
    if bisect.bisect_left(S, x) < A and S[bisect.bisect_left(S, x)] == x:
        left_S = x
        right_S = x
    else:
        if bisect.bisect_right(S, x) - 1 >= 0:
            left_S = S[bisect.bisect_right(S, x) - 1]
        elif bisect.bisect_right(S, x) - 1 < 0:
            left_S = None
        if bisect.bisect_right(S, x) < A:
            right_S = S[bisect.bisect_right(S, x)]
        elif bisect.bisect_right(S, x) >= A:
            right_S = None

    if bisect.bisect_right(T, x) < B and T[bisect.bisect_right(T, x)] == x:
        left_T = x
        right_T = x
    else:
        if bisect.bisect_right(T, x) - 1 >= 0:
            left_T = T[bisect.bisect_right(T, x) - 1]
        elif bisect.bisect_right(T, x) - 1 < 0:
            left_T = None
        if bisect.bisect_right(T, x) < B:
            right_T = T[bisect.bisect_right(T, x)]
        elif bisect.bisect_right(T, x) >= B:
            right_T = None

    if left_T and right_S:
        score_left_T_right_S = min(abs(left_T - x) + abs(left_T - right_S), abs(right_S - x) + abs(left_T - right_S))

    if left_T and left_S:
        score_left_T_left_S = min(abs(left_T - x) + abs(left_T - left_S), abs(left_S - x) + abs(left_T - left_S))

    if right_T and left_S:
        score_right_T_left_S = min(abs(right_T - x) + abs(right_T - left_S),
                                   abs(left_S - x) + abs(right_T - left_S))

    if right_T and right_S:
        score_right_T_right_S = min(abs(right_T - x) + abs(right_T - right_S),
                                  abs(right_S - x) + abs(right_T - right_S))

    print(min(score_left_T_right_S, score_left_T_left_S, score_right_T_left_S, score_right_T_right_S))

    score_left_T_right_S = 10 ** 100
    score_left_T_left_S = 10 ** 100
    score_right_T_left_S = 10 ** 100
    score_right_T_right_S = 10 ** 100

Submission status: Time Limit Exceeded

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

def doit(st, x):
    lo, hi = 0, len(st) - 1
    while hi - lo > 1:
        mid = (lo + hi) // 2
        if st[mid] < x:
            lo = mid
        else:
            hi = mid
    mid = (lo + hi) // 2
    return st[mid], st[mid + 1]

for _ in range(q):
    x = int(input())
    s1, s2 = doit(s, x)
    t1, t2 = doit(t, x)
    print(min(abs(s1 - x) + min(abs(t1 - s1), abs(t2 - s1)),
              abs(s2 - x) + min(abs(t1 - s2), abs(t2 - s2)),
              abs(t1 - x) + min(abs(s1 - t1), abs(s2 - t1)),
              abs(t2 - x) + min(abs(s1 - t2), abs(s2 - t2))))

Submission status: Time Limit Exceeded

Solution code:
a, b, q = map(int, input().split())
s = [int(input()) for _ in range(a)]
t = [int(input()) for _ in range(b)]

s = sorted(s)
t = sorted(t)
st = []
(i, j) = (0, 0)
while i < len(s) or j < len(t):
    if j == len(t) or (i < len(s) and s[i] < t[j]):
        st.append((s[i], min(abs(s[i] - t[max(j - 1, 0)]),
                             abs(s[i] - t[min(j, len(t) - 1)]))))
        i += 1
    else:
        st.append((t[j], min(abs(t[j] - s[max(i - 1, 0)]),
                             abs(t[j] - s[min(i, len(s) - 1)]))))
        j += 1

def doit(x):
    lo, hi = 0, len(st) - 1
    while hi - lo > 1:
        mid = (lo + hi) // 2
        if st[mid][0] < x:
            lo = mid
        else:
            hi = mid
    mid = (lo + hi) // 2
    return min(abs(st[mid][0] - x) + st[mid][1], abs(st[mid + 1][0] - x) + st[mid + 1][1])

for _ in range(q):
    print(doit(int(input())))

Submission status: Time Limit Exceeded

Solution code:
def binarySearch(a, val):
    left, right = -1, len(a)
    while left + 1 < right:
        mid = (left + right) >> 1
        if a[mid] < val:
            left = mid
        else:
            right = mid
    return a[right] if right < len(a) else 1 << 35

def binarySearch2(a, val):
    left, right = -1, len(a)
    while left + 1 < right:
        mid = (left + right) >> 1
        if a[mid] <= val:
            left = mid
        else:
            right = mid
    return a[left] if left >= 0 else -(1 << 35)

nShrines, nTemples, nQueries = map(int, input().split())
shrines = [int(input()) for _ in range(nShrines)]
temples = [int(input()) for _ in range(nTemples)]
starts = [int(input()) for _ in range(nQueries)]
for start in starts:
    shrineToRight = binarySearch(shrines, start)
    templeToRight = binarySearch(temples, start)
    shrineToLeft = binarySearch2(shrines, start)
    templeToLeft = binarySearch2(temples, start)
    ret = min(
        max(shrineToRight, templeToRight) - start,
        start - min(shrineToLeft, templeToLeft),
        templeToRight - start + templeToRight - shrineToLeft,
        shrineToRight - start + shrineToRight - templeToLeft,
        start - shrineToLeft + templeToRight - shrineToLeft,
        start - templeToLeft + shrineToRight - templeToLeft
    )
    print(ret)

Submission status: Time Limit Exceeded

Solution code:
A,B,Q = map(int,input().split())
jinjya = [0]*(A+1)+[float('inf')]#範囲を絞るために両サイドに0と無限を挿入
tera =[0]*(B+1)+[float('inf')]
for i in range(A):
  jinjya[i+1] =int(input())
for i in range(B):
  tera[i+1] =int(input())

for i in range(Q):
  x=int(input())
#出発地点の前後の神社と寺の場所を知りたい。つまり出発点より前にある対象のインデックス
  L=0
  R=A+2
  while R-L>1:
    P=(L+R)//2
    if x<jinjya[P]:
      R=P
    else:
      L=P
  jinjya_L=L
  
  L=0
  R=B+2
  while R-L>1:
    P=(L+R)//2
    if x<tera[P]:
      R=P
    else:
      L=P
  tera_L=L

#xの左側の神社と寺のインデックスがわかったのでそれらに対して距離を測って最小を探す。
#両サイドのダミーに注意する。
  a=jinjya[jinjya_L]
  b=jinjya[jinjya_L+1]
  c=tera[tera_L]
  d=tera[tera_L+1]
  if jinjya_L==0:
    a=b
  if tera_L==0:
    c=d
  answer=min(abs(x-a)+abs(a-c),abs(x-c)+abs(c-a),abs(x-b)+abs(b-c),abs(x-c)+abs(c-b),abs(x-a)+abs(a-d),abs(x-d)+abs(d-a),abs(x-b)+abs(b-d),abs(x-d)+abs(d-b))
  print(answer)

Submission status: Time Limit Exceeded

Solution code:
import sys


sys.setrecursionlimit(10000)


def my_search(l, low, high, t):
    n = (low+high)//2
    if t > l[n]:
        low = n
    else:
        high = n
    if high == low + 1:
        return low
    else:
        return my_search(l, low, high, t)

a,b,q = [int(_) for _ in input().split()]
s_l = [-float('inf')]
t_l = [-float('inf')]
x_l = []
for i in range(a):
    s_l.append(int(input()))
s_l.append(float('inf'))
for i in range(b):
    t_l.append(int(input()))
t_l.append(float('inf'))
for i in range(q):
    x_l.append(int(input()))
for i in range(q):
    x = x_l[i]
    s1_id = my_search(s_l, 0, len(s_l)-1, x)
    s2_id = s1_id + 1
    s1 = s_l[s1_id]
    s2 = s_l[s2_id]
    t1_id = my_search(t_l, 0, len(t_l)-1, x)
    t2_id = t1_id + 1
    t1 = t_l[t1_id]
    t2 = t_l[t2_id]
    res = float('inf')
    for s in [s1,s2]:
        for t in [t1,t2]:
            d1, d2 = abs(s-x) + abs(t-s), abs(t-x) + abs(s-t)
            res = min(res, d1, d2)
    print(res)

Submission status: Time Limit Exceeded

Solution code:
a,b,q = list(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.sort()
t.sort()

#print(s)
#print(t)
import bisect
for xi in x:
    i = bisect.bisect_left(s,xi)
    s_right = 10**11
    if i < len(s):
        s_right = s[i] - xi
    s_left = 10**11
    if i != 0:
        s_left = xi - s[i-1]
    j = bisect.bisect_left(t,xi)
    t_right = 10**11
    if j < len(t):
        t_right = t[j] - xi
    t_left = 10**11
    if j != 0:
        t_left = xi - t[j-1]
    #print(i,j,xi)
    #print(s_left,s_right,t_left,t_right)
    ans = min(max(s_right,t_right), max(s_left,t_left), min(s_left,t_right)*2+max(s_left,t_right), min(s_right,t_left)*2+max(s_right,t_left))
    print(ans)

Submission status: Time Limit Exceeded

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

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

#print(s)
#print(t)
import bisect
for xi in x:
    i = bisect.bisect_left(s,xi)
    s_right = 10**11
    if i < len(s):
        s_right = s[i] - xi
    s_left = 10**11
    if i != 0:
        s_left = xi - s[i-1]
    j = bisect.bisect_left(t,xi)
    t_right = 10**11
    if j < len(t):
        t_right = t[j] - xi
    t_left = 10**11
    if j != 0:
        t_left = xi - t[j-1]
    #print(i,j,xi)
    #print(s_left,s_right,t_left,t_right)
    ans = min(max(s_right,t_right), max(s_left,t_left), min(s_left,t_right)*2+max(s_left,t_right), min(s_right,t_left)*2+max(s_right,t_left))
    print(ans)

Submission status: Time Limit Exceeded

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

sl = [-float("inf")]
for _ in range(a):
    sl.append(int(input()))
sl.append(float("inf"))
tl = [-float("inf")]
for _ in range(b):
    tl.append(int(input()))
tl.append(float("inf"))
    
import bisect


for _ in range(q):
    x = int(input())
    index1 = bisect.bisect(sl, x) 
    index2 = bisect.bisect(tl, x)
    rs = abs(sl[index1] - x) 
    ls = abs(sl[index1-1] - x)
    rt = abs(tl[index2] - x)
    lt = abs(tl[index2-1] - x)
    ansl = []
    ansl.append(max(rs,rt))
    ansl.append(max(ls,lt))
    ansl.append(2*min(rs,lt)+max(rs,lt))
    ansl.append(2*min(ls,rt)+max(ls,rt))
    print(min(ansl))

Submission status: Time Limit Exceeded

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

def dis(x,p,q):
    return min(abs(x-s[p])+abs(s[p]-t[q]),abs(x-t[q])+abs(s[p]-t[q]))

def kai(x):
    res = INF
    s1 = bisect.bisect_right(s,x)
    ls = [s1,s1 - 1]
    t1 = bisect.bisect_right(t,x)
    lt = [t1,t1 - 1]
    for ss in ls:
        for st in lt:
            res = min(res,dis(x,ss,st))
    return res

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

Submission status: Time Limit Exceeded

Solution code:
import bisect
import sys
input = sys.stdin.readline
a,b,q=map(int, input().split())
s=[int(input()) for i in range(a)]
t=[int(input()) for i in range(b)]
x=[int(input()) for i in range(q)]
s=[-float('inf')]+s+[float('inf')]
t=[-float('inf')]+t+[float('inf')]

for i in range(q):
    index1=bisect.bisect_right(s, x[i]) 
    index2=bisect.bisect_right(t, x[i])  
    v1=abs(x[i]-s[index1-1])
    v2=abs(x[i]-s[index1])
    w1=abs(x[i]-t[index2-1])
    w2=abs(x[i]-t[index2])

    
    ans=min(2*v1+w2,2*v2+w1,2*w1+v2,2*w2+v1,v1+abs(w1-v1),w1+abs(w1-v1),v2+abs(w2-v2),w2+abs(w2-v2))
    print(ans)

Submission status: Time Limit Exceeded

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

for i in range(q):
    index1=bisect.bisect_right(s, x[i]) 
    index2=bisect.bisect_right(t, x[i])  
    v1=abs(x[i]-s[index1-1])
    v2=abs(x[i]-s[index1])
    w1=abs(x[i]-t[index2-1])
    w2=abs(x[i]-t[index2])

    
    ans=min(2*v1+w2,2*v2+w1,2*w1+v2,2*w2+v1,v1+abs(w1-v1),w1+abs(w1-v1),v2+abs(w2-v2),w2+abs(w2-v2))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
r = []
S, T, Q = map(int, input().strip().split())
for i in range(S):
    r.append([int(input().strip()), 's'])
for i in range(T):
    r.append([int(input().strip()), 't'])
#print(r)
for i in range(Q):
    choices = []
    X = int(input().strip())
    r.append([X, 'x'])
    r.sort()
    #print(r)
    r = [[0, '*']] + [[0, '*']] + r + [[10 ** 11, '*']] + [[10 ** 11, '*']]
    #print(r)
    r[0][1] = '*'
    r[1][1] = '*'
    r[-1][1] = '*'
    r[-2][1] = '*'
    #print(r)
    start = 0
    for j in r:
        #print(j[1], r.index(j))
        if j[1] == 'x':
            start = r.index(j)
            break
    #print(start)
    #print(r[start])
    first = r[start + 1]
    #print(first)
    for k in r[start + 2:]:
        if k[1] != first[1] and k[1] != '*' and first[1] != '*':
            second = k
            choices.append([first, second])
            break
    for n in r[start - 1:0:-1]:
        if n[1] != first[1] and n[1] != '*' and first[1] != '*':
            second = n
            choices.append([first, second])
            break
    first = r[start - 1]
    #print(first)
    for k in r[start - 2:0:-1]:
        #print(k, first)
        if k[1] != first[1] and k[1] != '*' and first[1] != '*':
            second = k
            choices.append([first, second])
            break
    for m in r[start + 1:]:
        if m[1] != first[1] and m[1] != '*' and first[1] != '*':
            second = m
            choices.append([first, second])
            break

    #print(choices)
    distance = 0
    minimum = 10 ** 12
    for i in choices:
        trip1 = abs(i[0][0] - X)
        trip2 = abs(i[1][0] - i[0][0])
        total = trip1 + trip2
        if total < minimum:
            minimum = total
    print(minimum)

    #print()
    del r[start]
    del r[-1]
    del r[-1]
    del r[0]
    del r[0]
    #print(r)
    #print()
    #print()
    #print()

Submission status: Time Limit Exceeded

Solution code:
def main():
    a,b,q = map(int,input().split())
    A = []
    B = []
    
    for _ in range(a):
        A.append(int(input()))
    
    for _ in range(b):
        B.append(int(input()))
    
    def search(A,x):
        left =0
        right = len(A)-1
        
        if x<A[0]:
            return (float('inf'),abs(x - A[left]))
        if x >A[-1]:
            return (abs(x - A[right]),float('inf'))
        
        while left != right-1:
            center = (left+right)//2
            
            if A[center] > x:
                right = center
            else:
                left = center
        
        return (abs(x - A[left]),abs(x - A[right]))
    
    
    def dist(A,x,lr):
        if lr == float('inf'):
            return float('inf')
        return abs(x - A[lr])
    
    for _ in range(q):
        x = int(input())
        sl,sr = search(A,x)
        tl,tr = search(B,x)
        print(min(min(sl,sr)+min(tl,tr)+min(min(sl,sr),min(tl,tr)),max(sl,tl),max(sr,tr)))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    a,b,q = map(int,input().split())
    A = []
    B = []
    
    for _ in range(a):
        A.append(int(input()))
    
    for _ in range(b):
        B.append(int(input()))
    
    def search(A,x):
        left =0
        right = len(A)-1
        
        if x<A[0]:
            return (float('inf'),abs(x - A[left]))
        if x >A[-1]:
            return (abs(x - A[right]),float('inf'))
        
        while left != right-1:
            center = (left+right)//2
            
            if A[center] > x:
                right = center
            else:
                left = center
        
        return (abs(x - A[left]),abs(x - A[right]))
    
    
    def dist(A,x,lr):
        if lr == float('inf'):
            return float('inf')
        return abs(x - A[lr])
    
    for _ in range(q):
        x = int(input())
        sl,sr = search(A,x)
        tl,tr = search(B,x)
        p1 = min(sl,sr)+min(tl,tr)+min(min(sl,sr),min(tl,tr))
        p2 = max(sl,tl)
        p3 = max(sr,tr)
        print(min(p1,p2,p3))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    a,b,q = map(int,input().split())
    A = []
    B = []
    
    for _ in range(a):
        A.append(int(input()))
    
    for _ in range(b):
        B.append(int(input()))
    
    def search(A,x):
        left =0
        right = len(A)-1
        
        if x<A[0]:
            return (float('inf'),0)
        if x >A[-1]:
            return (right,float('inf'))
        
        while left != right-1:
            center = (left+right)//2
            
            if A[center] > x:
                right = center
            else:
                left = center
        
        return (left,right)
    
    
    def dist(A,x,lr):
        if lr == float('inf'):
            return float('inf')
        return abs(x - A[lr])
    
    for _ in range(q):
        x = int(input())
        sl,sr = search(A,x)
        tl,tr = search(B,x)
        sl = dist(A,x,sl)
        sr = dist(A,x,sr)
        tl = dist(B,x,tl)
        tr = dist(B,x,tr)
        p1 = min(sl,sr)+min(tl,tr)+min(min(sl,sr),min(tl,tr))
        p2 = max(sl,tl)
        p3 = max(sr,tr)
        print(min(p1,p2,p3))

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
a,b,q = map(int,input().split())
A = []
B = []

for _ in range(a):
    A.append(int(input()))

for _ in range(b):
    B.append(int(input()))

def search(A,x):
    left =0
    right = len(A)-1
    
    if x<A[0]:
        return (float('inf'),0)
    if x >A[-1]:
        return (right,float('inf'))
    
    while left != right-1:
        center = (left+right)//2
        
        if A[center] > x:
            right = center
        else:
            left = center
    
    return (left,right)


def dist(A,x,lr):
    if lr == float('inf'):
        return float('inf')
    return abs(x - A[lr])

for _ in range(q):
    x = int(input())
    sl,sr = search(A,x)
    tl,tr = search(B,x)
    sl = dist(A,x,sl)
    sr = dist(A,x,sr)
    tl = dist(B,x,tl)
    tr = dist(B,x,tr)
    p1 = min(sl,sr)+min(tl,tr)+min(min(sl,sr),min(tl,tr))
    p2 = max(sl,tl)
    p3 = max(sr,tr)
    print(min(p1,p2,p3))

Submission status: Time Limit Exceeded

Solution code:
import bisect as bi

def dL(x,li):
    ind=bi.bisect_left(li,x)
    if ind==0:
        return 10**11
    else:
        return x-li[ind-1]

def dR(x,li):
    ind=bi.bisect_left(li,x)
    if ind==len(li):
        return 10**11
    else:
        return li[ind]-x

def ans(x,s,t):
    dLs=dL(x,s);dRs=dR(x,s)
    dLt=dL(x,t);dRt=dR(x,t)
    # 西の神社から訪ねる(d1)
    d1=dLs
    if dLs<dLt:
        d1+=min(toLt[x-dLs],toRt[x-dLs])
    d2=dRs
    if dRs<dRt:
        d2+=min(toLt[x+dRs],toRt[x+dRs])
    d3=dLt
    if dLt<dLs:
        d3+=min(toLs[x-dLt],toRs[x-dLt])
    d4=dR(x,t)
    if dRt<dRs:
        d4+=min(toLs[x+dRt],toRs[x+dRt])
    
    return min(d1,d2,d3,d4)

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

# 各神社の座標につき，東西の最寄りの寺までの距離を計算しておく
toLt={};toRt={}
for i in range(A):
    toLt[s[i]]=dL(s[i],t)
    toRt[s[i]]=dR(s[i],t)
# 同上
toLs={};toRs={}
for i in range(B):
    toLs[t[i]]=dL(t[i],s)
    toRs[t[i]]=dR(t[i],s)

for i in range(Q):
    print(ans(int(input()),s,t))

Submission status: Time Limit Exceeded

Solution code:
import bisect as bi

def L(x,l):
    return x-l[bi.bisect_left(l,x)-1]

def R(x,l):
    return l[bi.bisect_left(l,x)]-x

def ans(x):
    global s;global t
    
    # 西の神社から訪ねる(d1)
    d1=dLs=L(x,s);dLt=L(x,t)
    if dLt>dLs:
        d1+=min(L(x-dLs,t),R(x-dLs,t))
    
    d2=dRs=R(x,s);dRt=R(x,t)
    if dRt>dRs:
        d2+=min(L(x+dRs,t),R(x+dRs,t))
    
    d3=dLt
    if dLs>dLt:
        d3+=min(L(x-dLt,s),R(x-dLt,s))
    
    d4=dRt
    if dRs>dRt:
        d4+=min(L(x+dRt,s),R(x+dRt,s))
    
    return min(d1,d2,d3,d4)

A,B,Q=map(int,input().split())
s=[-10**10]
for i in range(A):
    s.append(int(input()))
s.append(2*10**10)

t=[-10**10]
for i in range(B):
    t.append(int(input()))
t.append(2*10**10)

for i in range(Q):
    print(ans(int(input())))

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect
inf=float("inf")
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 range(q):
    west=inf
    east=inf
    c=inf
    d=inf
    j=bisect(s,x[i])
    k=bisect(t,x[i])
    if j!=a and k!=0:
        c=s[j]-t[k-1]+min(s[j]-x[i],x[i]-t[k-1])
    if k!=b and j!=0:
        d=t[k]-s[j-1]+min(x[i]-s[j-1],t[k]-x[i])
    if j!=0 and k!=0:
        west=max(x[i]-s[j-1],x[i]-t[k-1])
    if j!=a and k!=b:
        east=max(s[j]-x[i],t[k]-x[i])
    print(min(west,east,c,d))

Submission status: Time Limit Exceeded

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)]
X = [int(input()) for i in range(Q)]


def bs(x, L, ub, lb):
    if x < L[0]:
        return -1
    if x > L[-1]:
        return len(L)-1
    c = (ub+lb)//2
    if ub-lb <= 1:
        return c
    if L[c] >= x:
        return bs(x, L, c, lb)
    else:
        return bs(x, L, ub, c)
    
for i in range(Q):
    s_l = bs(X[i], S, A-1, 0)
    t_l = bs(X[i], T, B-1, 0)
    
    if s_l < 0:
        sl = 10**11
        su = S[0]-X[i]
    elif s_l == A-1:
        sl = X[i]-S[s_l]
        su = 10**11
    else:
        sl = X[i]-S[s_l]
        su = S[s_l+1]-X[i]
        
    if t_l < 0:
        tl = 10**11
        tu = T[0]-X[i]
    elif t_l == B-1:
        tl = X[i]-T[t_l]
        tu = 10**11
    else:
        tl = X[i]-T[t_l]
        tu = T[t_l+1]-X[i]
    ans = min(max(su, tu), max(sl, tl), su*2+tl, tl*2+su, sl*2+tu, tu*2+sl)
    print(ans)

Submission status: Time Limit Exceeded

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)]
X = [int(input()) for i in range(Q)]

def bs_up(x, L, ub, lb):
    if x > L[-1]:
        return 10**11+1
    if x < L[0]:
        return L[0]
    if ub-lb <= 1:
        return L[(ub+lb)//2+1]
    c = (ub+lb)//2
    if L[c] > x:
        return bs_up(x, L, c, lb)
    else:
        return bs_up(x, L, ub, c)
    
def bs_low(x, L, ub, lb):
    if x < L[0]:
        return -10**11-1
    if x > L[-1]:
        return L[-1]
    if ub-lb <= 1:
        return L[(ub+lb)//2]
    c = (ub+lb)//2
    if L[c] >= x:
        return bs_low(x, L, c, lb)
    else:
        return bs_low(x, L, ub, c)
    
for i in range(Q):
    s_u = bs_up(X[i], S, A-1, 0)-X[i]
    t_u = bs_up(X[i], T, B-1, 0)-X[i]
    s_l = bs_low(X[i], S, A-1, 0)-X[i]
    t_l = bs_low(X[i], T, B-1, 0)-X[i]
    print(min(max(s_u, t_u), max(-s_l, -t_l), s_u*2-t_l, s_u-2*t_l, t_u*2-s_l, t_u-2*s_l))

Submission status: Time Limit Exceeded

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)]
X = [int(input()) for x in range(Q)]

L = []
for i in range(A):
    L.append([S[i], "s"])
for i in range(B):
    L.append([T[i], "t"])
for i in range(Q):
    L.append([X[i], "x", i])
    
L.sort()
ans = []
for i in range(len(L)):
    if L[i][1] == "x":
        c = i+1
        jud = []
        temp_s = []
        temp_t = []
        cnt = 0
        while c < len(L) and len(jud) < 2:
            if L[c][1] == "s" and "s" not in jud:
                jud.append("s")
                temp_s.append(L[c][0]-L[i][0])
            if L[c][1] == "t" and "t" not in jud:
                jud.append("t")
                temp_t.append(L[c][0]-L[i][0])
            c += 1
        if len(temp_s) == 0:
            temp_s.append(10**11+1)
        if len(temp_t) == 0:
            temp_t.append(10**11+1)
        c = i-1
        jud = []
        while c >= 0 and len(jud) < 2:
            if L[c][1] == "s" and "s" not in jud:
                jud.append("s")
                temp_s.append(L[c][0]-L[i][0])
            if L[c][1] == "t" and "t" not in jud:
                jud.append("t")
                temp_t.append(L[c][0]-L[i][0])
            c -= 1
        if len(temp_s) == 1:
            temp_s.append(-10**11-1)
        if len(temp_t) == 1:
            temp_t.append(-10**11-1)
        temp = []
        temp.append(max(temp_s[0], temp_t[0]))
        temp.append(max(-temp_s[1], -temp_t[1]))
        temp.append(min(2*temp_s[0]-temp_t[1], temp_s[0]-2*temp_t[1]))
        temp.append(min(2*temp_t[0]-temp_s[1], temp_t[0]-2*temp_s[1]))
        ans.append([L[i][2], min(temp)])
        
        
ans.sort()
for i in range(Q):
    print(ans[i][1])

Submission status: Time Limit Exceeded

Solution code:
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())
S = [-10**10*2-1] + S + [10**10*2+1]
for i in range(b):
  T[i] = int(input())
T = [-10**10*2-1] + T + [10**10*2+1]
for i in range(q):
  X[i] = int(input())
#print(S)  
#print(T)  
from bisect import bisect_left
from bisect import bisect_right
for i in range(q):
  s_left = bisect_right(S, X[i]) - 1
  s_right = bisect_right(S, X[i])
  t_left = bisect_right(T, X[i]) - 1
  t_right = bisect_right(T, X[i])
  #print(X[i], S[s_left], S[s_right], T[t_right], T[t_left])
  l_rr = max(S[s_right] - X[i], T[t_right] - X[i])
  l_ll = max(X[i] - S[s_left], X[i] - T[t_left])
  l_rslt = (S[s_right] - X[i]) + (S[s_right] - T[t_left])
  l_rtls = (T[t_right] - X[i]) + (T[t_right] - S[s_left])
  l_lsrt = (X[i] - S[s_left]) + (T[t_right] - S[s_left])
  l_ltrs = (X[i] - T[t_left]) + (S[s_right] - T[t_left])
  print(min(l_rr, l_ll, l_rslt, l_rtls, l_lsrt, l_ltrs))

Submission status: Time Limit Exceeded

Solution code:
import bisect

def main():
    A, B, Q = map(int, input().split())
    s = list(int(input()) for _ in range(A))
    t = list(int(input()) for _ in range(B))

    sort_s = sorted(s)
    sort_t = sorted(t)
    for _ in range(Q):
        x = int(input())
        s_near = bisect.bisect_left(sort_s, x)
        t_near = bisect.bisect_left(sort_t, x)

        s_candidate = []
        t_candidate = []

        if s_near == 0:
            s_candidate.append(sort_s[s_near])
        elif s_near == A:
            s_candidate.append(sort_s[s_near-1])
        else:
            s_candidate.append(sort_s[s_near])
            s_candidate.append(sort_s[s_near-1])
        
        if t_near == 0:
            t_candidate.append(sort_t[t_near])
        elif t_near == B:
            t_candidate.append(sort_t[t_near-1])
        else:
            t_candidate.append(sort_t[t_near])
            t_candidate.append(sort_t[t_near-1])

        ans = float('inf')
        # sを先に訪れるパターンを考える
        for i in s_candidate:
            for j in t_candidate:
                tmp = abs(x - i) + abs(i - j)
                ans = min(ans, tmp)

        # tをさきに訪れるパターンを考える
        for k in t_candidate:
            for l in s_candidate:
                tmp = abs(x - k) + abs(k - l)
                ans = min(ans, tmp)

        print(ans)
        
main()