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 sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]
import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))

A, B, Q = mi()

S = [ii() for _ in range(A)]
T = [ii() for _ in range(B)]

S_ = [S[0]] + S + [S[A-1]]
T_ = [T[0]] + T + [T[B-1]]

for _ in range(Q):
    f = ii()
    to_s = bisect.bisect_left(S, f)
    to_t = bisect.bisect_left(T, f)
    #ans_1 = ans_2 = 0
    #print(to_s, to_t)

    #ans_1 += abs(S_[to_s+1] - f)
    #ans_2 += abs(f - S_[to_s])
    #print(ans_1, ans_2)

    #ans_1 = min(ans_1 + abs(S_[to_s+1] - T_[to_t+1]), ans_1 + abs(S_[to_s+1] - T_[to_t]))
    #ans_2 = min(ans_2 + abs(S_[to_s] - T_[to_t+1]), ans_2 + abs(S_[to_s] - T_[to_t]))

    ans = min(abs(S_[to_s+1] - f) + abs(S_[to_s+1] - T_[to_t+1]), float('inf'))
    ans = min(abs(S_[to_s+1] - T_[to_t+1]) + abs(f- T_[to_t+1]), ans)
    ans = min(abs(S_[to_s+1] - f) + abs(S_[to_s+1] - T_[to_t]), ans)
    ans = min(abs(S_[to_s+1] - T_[to_t]) + abs(f- T_[to_t]), ans)
    ans = min(abs(S_[to_s] - f) + abs(S_[to_s] - T_[to_t+1]), ans)
    ans = min(abs(S_[to_s] - T_[to_t+1]) + abs(f- T_[to_t+1]), ans)
    ans = min(abs(S_[to_s] - f) + abs(S_[to_s] - T_[to_t]), ans)
    ans = min(abs(S_[to_s] - T_[to_t]) + abs(f- T_[to_t]), ans)
    print(ans)

Submission status: Accepted

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

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

    sl = [int(input()) for _ in range(a)]
    tl = [int(input()) for _ in range(b)]
    xl = [int(input()) for _ in range(q)]

    for x in xl:
        ans = 10**11

        curr_dist = 0
        ind_s = bisect.bisect_left(sl, x)
        ind_t = bisect.bisect_left(tl, x)
        
        for next_s in [ind_s, ind_s-1]:
            if 0 <= next_s < a:
                curr_dist = abs(x-sl[next_s])
                curr_pos = sl[next_s]
                ind_t2 = bisect.bisect_left(tl, curr_pos)
                if ind_t2 == 0:
                    curr_dist += abs(tl[0] - curr_pos)
                elif ind_t2 == b:
                    curr_dist += abs(tl[b-1] - curr_pos)
                else:
                    curr_dist += min( abs( tl[ind_t2-1] - curr_pos), abs(tl[ind_t2]-curr_pos))
                ans = min(curr_dist, ans)


        for next_t in [ind_t, ind_t-1]:
            if 0 <= next_t < b:
                curr_dist = abs(x-tl[next_t])
                curr_pos = tl[next_t]
                ind_s2 = bisect.bisect_left(sl, curr_pos)
                if ind_s2 == 0:
                    curr_dist += abs(sl[0] - curr_pos)
                elif ind_s2 == a:
                    curr_dist += abs(sl[a-1] - curr_pos)
                else:
                    curr_dist += min( abs( sl[ind_s2-1] - curr_pos), abs(sl[ind_s2]-curr_pos))
                ans = min(curr_dist, ans)

        print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import bisect

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

    sl = [int(input()) for _ in range(a)]
    tl = [int(input()) for _ in range(b)]
    xl = [int(input()) for _ in range(q)]

    for x in xl:
        ans = 10**11

        curr_dist = 0
        ind_s = bisect.bisect_left(sl, x)
        ind_t = bisect.bisect_left(tl, x)
        
        for next_s in [ind_s, ind_s-1]:
            if 0 <= next_s < a:
                curr_dist = abs(x-sl[next_s])
                curr_pos = sl[next_s]
                ind_t2 = bisect.bisect_left(tl, curr_pos)
                if ind_t2 == 0:
                    curr_dist += abs(tl[0] - curr_pos)
                elif ind_t2 == b:
                    curr_dist += abs(tl[b-1] - curr_pos)
                else:
                    curr_dist += min( abs( tl[ind_t2-1] - curr_pos), abs(tl[ind_t2]-curr_pos))
                ans = min(curr_dist, ans)


        for next_t in [ind_t, ind_t-1]:
            if 0 <= next_t < b:
                curr_dist = abs(x-tl[next_t])
                curr_pos = tl[next_t]
                ind_s2 = bisect.bisect_left(sl, curr_pos)
                if ind_s2 == 0:
                    curr_dist += abs(sl[0] - curr_pos)
                elif ind_s2 == a:
                    curr_dist += abs(sl[a-1] - curr_pos)
                else:
                    curr_dist += min( abs( sl[ind_s2-1] - curr_pos), abs(sl[ind_s2]-curr_pos))
                ans = min(curr_dist, ans)

        print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

sl = [int(input()) for _ in range(a)]
tl = [int(input()) for _ in range(b)]
xl = [int(input()) for _ in range(q)]

for x in xl:
    ans = 10**11

    curr_dist = 0
    ind_s = bisect.bisect_left(sl, x)
    ind_t = bisect.bisect_left(tl, x)
    
    for next_s in [ind_s, ind_s-1]:
        if 0 <= next_s < a:
            curr_dist = abs(x-sl[next_s])
            curr_pos = sl[next_s]
            ind_t2 = bisect.bisect_left(tl, curr_pos)
            if ind_t2 == 0:
                curr_dist += abs(tl[0] - curr_pos)
            elif ind_t2 == b:
                curr_dist += abs(tl[b-1] - curr_pos)
            else:
                curr_dist += min( abs( tl[ind_t2-1] - curr_pos), abs(tl[ind_t2]-curr_pos))
            ans = min(curr_dist, ans)


    for next_t in [ind_t, ind_t-1]:
        if 0 <= next_t < b:
            curr_dist = abs(x-tl[next_t])
            curr_pos = tl[next_t]
            ind_s2 = bisect.bisect_left(sl, curr_pos)
            if ind_s2 == 0:
                curr_dist += abs(sl[0] - curr_pos)
            elif ind_s2 == a:
                curr_dist += abs(sl[a-1] - curr_pos)
            else:
                curr_dist += min( abs( sl[ind_s2-1] - curr_pos), abs(sl[ind_s2]-curr_pos))
            ans = min(curr_dist, ans)

    print(ans)

Submission status: Accepted

Solution code:
import bisect
def resolve():
    A, B, Q = list(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)]
    #print("#####")
    for x in X:
        ans = float("inf")
        for Ary1, Ary2 in [[S, T], [T, S]]:
            ar1_nearests = get_nearest_pos(Ary1, x)
            for p in ar1_nearests:
                ar2_nearests = get_nearest_pos(Ary2, p)
                for p2 in ar2_nearests:
                    ans = min(ans, abs(x-p)+abs(p-p2))
        print(ans)

def get_nearest_pos(array, pos):
    res = []
    idx = bisect.bisect_left(array, pos)
    if idx == 0:
        res.append(array[idx])
    elif idx == len(array):
        res.append(array[idx-1])
    else:
        res.append(array[idx])
        res.append(array[idx-1])
    return res


if '__main__' == __name__:
    resolve()

Submission status: Accepted

Solution code:
#import sys
#import numpy as np
#import math
#import itertools
#from fractions import Fraction
#import itertools
from collections import deque
#import heapq
#from fractions  import gcd
#input=sys.stdin.readline
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 start in x:
    res=[]
    start_s=bisect.bisect_left(s,start)
    start_t=bisect.bisect_left(t,start)
    if start_s<a and start_t<b:
        res.append(max(s[start_s]-start,t[start_t]-start))
    if start_s-1>-1 and start_t-1>-1:
        res.append(max(start-s[start_s-1],start-t[start_t-1]))
    if start_s<a and start_t-1>-1:
        res.append(2*(s[start_s]-start)+start-t[start_t-1])
        res.append(2*(start-t[start_t-1])+s[start_s]-start)
    if start_t<b and start_s-1>-1:
        res.append(2*(t[start_t]-start)+start-s[start_s-1])
        res.append(2*(start-s[start_s-1])+t[start_t]-start)
    print(min(res))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import bisect

a, b, q = list(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)]

s.sort()
t.sort()

i = 0


for i in range(len(x)):

    r_shrine = bisect.bisect_right(s, x[i])
    r_temple = bisect.bisect_right(t, x[i])

    l_shrine = r_shrine-1
    l_temple = r_temple-1

    # print(l_shrine, r_shrine)
    # print(l_temple, r_temple)

    ans = []
    if l_shrine >= 0 and l_temple >= 0:
        ans.append(max(x[i]-s[l_shrine], x[i]-t[l_temple]))  # <<
    if r_shrine < a and r_temple < b:
        ans.append(max(s[r_shrine]-x[i], t[r_temple]-x[i]))  # >>
    if l_shrine >= 0 and r_temple < b:
        min_ = min(x[i]-s[l_shrine], t[r_temple]-x[i])
        ans.append(min_+(t[r_temple]-s[l_shrine]))  # <>
    if r_shrine < a and l_temple >= 0:
        min_ = min(x[i]-t[l_temple], s[r_shrine]-x[i])
        ans.append(min_+(s[r_shrine]-t[l_temple]))  # <>

    print(min(ans))

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

R = []
for x in X:
    SL, SR, TL, TR = 10**20, 10**20, 10**20, 10**20
    i = bisect.bisect_left(S, x)
    if i != 0:
        SL = x-S[i-1]
    if i != A:
        SR = S[i]-x

    j = bisect.bisect_left(T, x)
    if j != 0:
        TL = x-T[j-1]
    if j != B:
        TR = T[j]-x

    ans = min(max(SL, TL), min(2*SL+TR, SL+2*TR),
              min(2*TL+SR, TL+2*SR), max(SR, TR))
    R.append(ans)
print(*R, sep='\n')

Submission status: Accepted

Solution code:
from functools import lru_cache
from bisect import bisect
from sys import stdin
input = stdin.readline
A, B, Q = map(int, input().split())
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]

@lru_cache(maxsize=None)
def func(f, x):
    L = S if f else T
    i = bisect(L, x)
    if i == 0:
        return abs(x - L[0])
    elif i == len(L):
        return abs(x - L[-1])
    else:
        return min(abs(x - L[i]), abs(x - L[i - 1]))

for x in [int(input()) for _ in range(Q)]:
    ans = float("inf")
    i = bisect(S, x)
    if i != 0:
        ans = min(ans, func(0, S[i - 1]) + x - S[i - 1])
    if i != A:
        ans = min(ans, func(0, S[i]) + S[i] - x)
    i = bisect(T, x)
    if i != 0:
        ans = min(ans, func(1, T[i - 1]) + x - T[i - 1])
    if i != B:
        ans = min(ans, func(1, T[i]) + T[i] - x)
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left

A,B,Q=list(map(int,input().split()))
s=[-10**11]+[int(input()) for _ in range(A)]+[10**11]
t=[-10**11]+[int(input()) for _ in range(B)]+[10**11]
x=[int(input()) for _ in range(Q)]


for xi in x:
    p1=bisect_left(s,xi)
    p2=bisect_left(t,xi)
    l=10**11
    for ss in s[p1-1:p1+1]:
        for tt in t[p2-1:p2+1]:
            l=min(l,min(abs(ss-xi),abs(tt-xi))+abs(ss-tt))
    
    print(l)

Submission status: Accepted

Solution code:
a, b, q = map(int, input().split())
INF = 10 ** 15
s = [-INF] + [int(input()) for _ in range(a)] + [INF] # sorted
t = [-INF] + [int(input()) for _ in range(b)] + [INF] # sorted

from bisect import bisect_left, bisect_right

for _ in range(q):
    x = int(input())
    i = bisect_left(s, x)
    j = bisect_left(t, x)
    d = INF
    for sx in [s[i - 1], s[i]]:
        for tx in [t[j - 1], t[j]]:
            d1 = abs(sx - x) + abs(sx - tx)
            d2 = abs(tx - x) + abs(sx - tx)
            d = min(d, d1, d2)
    print(d)

Submission status: Accepted

Solution code:
a, b, q = map(int, input().split())
INF = 10 ** 15
s = [-INF] + [int(input()) for _ in range(a)] + [INF] # sorted
t = [-INF] + [int(input()) for _ in range(b)] + [INF] # sorted

from bisect import bisect_left, bisect_right

for _ in range(q):
    x = int(input())
    i = bisect_right(s, x)
    j = bisect_right(t, x)
    d = INF
    for sx in [s[i - 1], s[i]]:
        for tx in [t[j - 1], t[j]]:
            d1 = abs(sx - x) + abs(sx - tx)
            d2 = abs(tx - x) + abs(sx - tx)
            d = min(d, d1, d2)
    print(d)

Submission status: Accepted

Solution code:
import bisect

a, b, q = map(int, input().split())
ans = 0

shrine = []
temple = []

for i in range(a):
    s = int(input())
    shrine.append(s)

for i in range(b):
    t = int(input())
    temple.append(t)


for j in range(q):
    shrine_list = []
    temple_list = []
    query = int(input())
    shrine_index = bisect.bisect_left(shrine, query)
    temple_index = bisect.bisect_left(temple, query)
    if shrine_index == 0:
        shrine_list.append(shrine[shrine_index])
    elif shrine_index == len(shrine):
        shrine_list.append(shrine[shrine_index-1])
    else:
        shrine_list.append(shrine[shrine_index])
        shrine_list.append(shrine[shrine_index-1])
    if temple_index == 0:
        temple_list.append(temple[temple_index])
    elif temple_index == len(temple):
        temple_list.append(temple[temple_index-1])
    else:
        temple_list.append(temple[temple_index])
        temple_list.append(temple[temple_index-1])
    min_dist = 10**12
    for sh in shrine_list:
        for tm in temple_list:
            if sh < query < tm:
                dist = min(tm - sh + (query - sh), tm - sh + (tm - query))
            elif tm < query < sh:
                dist = min(sh - tm + (query - tm), sh - tm + (sh - query))
            elif min(query, sh, tm) == query:
                dist = max(sh, tm) - query
            elif max(query, sh, tm) == query:
                dist = query - min(sh, tm)
            if dist < min_dist:
                min_dist = dist
    print(min_dist)

Submission status: Accepted

Solution code:
def main():
    from bisect import bisect_left as bl
    a, b, q, *stx = map(int, open(0).read().split())
    s = [-float('Inf')] + stx[:a] + [float('Inf')]
    t = [-float('Inf')] + stx[a:a + b] + [float('Inf')]
    x = stx[a + b:]
    tmp = []
    for i in x:
        f, g = bl(s, i), bl(t, i)

        sr, sl = s[f - 1], s[f]
        tr, tl = t[g - 1], t[g]

        d = min([max(sl, tl) - i, i - min(sr, tr), 2 * (tl - sr) - max(i - sr, tl - i), 2 * (sl - tr) - max(sl - i, i - tr)])
        tmp.append(d)

    ans = '\n'.join(map(str, tmp))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    from bisect import bisect_left as bl
    a, b, q, *stx = map(int, open(0).read().split())
    s = [-float('Inf')] + stx[:a] + [float('Inf')]
    t = [-float('Inf')] + stx[a:a + b] + [float('Inf')]
    x = stx[a + b:]
    tmp = []
    for i in x:
        f, g = bl(s, i), bl(t, i)

        sl, sr = s[f - 1], s[f]
        tl, tr = t[g - 1], t[g]

        d = float('Inf')
        for j in [sl, sr]:
            for k in [tr, tl]:
                if j <= i and k <= i:
                    d = min(d, i - min(j, k))
                elif j <= i <= k or k <= i <= j:
                    d = min(d, min(abs(i - j), abs(i - k)) * 2 + max(abs(i - j), abs(i - k)))
                else:
                    d = min(d, max(j, k) - i)

        tmp.append(d)

    ans = '\n'.join(map(str, tmp))
    print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

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]

for k 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: Accepted

Solution code:
from sys import stdin
import bisect
def main():
    #入力
    readline=stdin.readline
    inf=10**18
    a,b,q=map(int,readline().split())
    s=[int(readline()) for _ in range(a)]
    s.insert(0,-inf)
    s.append(inf)
    t=[int(readline()) for _ in range(b)]
    t.insert(0,-inf)
    t.append(inf)
    x=[int(readline()) for _ in range(q)]

    for i in range(q):
        j=bisect.bisect_left(s,x[i])
        k=bisect.bisect_left(t,x[i])
        s_i=(s[j-1],s[j])
        t_i=(t[k-1],t[k])
        ans=float("inf")
        for u in s_i:
            for v in t_i:
                ans=min(ans,abs(u-x[i])+abs(v-u))

        for v in t_i:
            for u in s_i:
                ans=min(ans,abs(v-x[i])+abs(u-v))

        print(ans)

if __name__=="__main__":
    main()

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().rstrip()
from bisect import bisect
def main():
    a,b,q=map(int,input().split())
    S=[int(input())for _ in range(a)]
    T=[int(input())for _ in range(b)]

    def dfs(cur,flag1,flag2):
        if flag2==1:
            index_s=bisect(S,cur)
            #print(cur,index_s)
            if index_s>0 and index_s<a:
                if flag1==0:
                    return min(abs(S[index_s-1]-cur),abs(S[index_s]-cur))
                else:
                    return min(dfs(S[index_s-1],0,0)+abs(S[index_s-1]-cur),dfs(S[index_s],0,0)+abs(S[index_s]-cur))
            else:
                if index_s==a:
                    nx=S[-1]
                elif index_s==0:
                    nx=S[0]
                if flag1==1:
                    return dfs(nx,0,0)+abs(nx-cur)
                else:
                    return abs(nx-cur)
        else:
            index_t=bisect(T,cur)
            #print(cur,index_t)
            if index_t>0 and index_t<b:
                if flag1==0:
                    return min(abs(T[index_t-1]-cur),abs(T[index_t]-cur))
                else:
                    return min(dfs(T[index_t-1],0,1)+abs(T[index_t-1]-cur),dfs(T[index_t],0,1)+abs(T[index_t]-cur))
            else:
                if index_t==b:
                    nx=T[-1]
                elif index_t==0:
                    nx=T[0]
                if flag1==1:
                    return dfs(nx,0,1)+abs(nx-cur)
                else:
                    return abs(nx-cur)

    for i in range(q):
        x=int(input())
        print(min(dfs(x,1,1),dfs(x,1,0)))


if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_left

A, B, Q = map(int, input().split())
INF = 10**18
S = [int(input()) for _ in range(A)] + [INF, INF, -INF, -INF]
T = [int(input()) for _ in range(B)] + [INF, INF, -INF, -INF]

S.sort()
T.sort()

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

    s = bisect_left(S, x)
    ls = S[s - 1]
    rs = S[s]

    t = bisect_left(T, x)
    lt = T[t - 1]
    rt = T[t]

    ans = min(
        abs(ls - rt) + min(abs(x - ls), abs(x - rt)),
        abs(lt - rs) + min(abs(x - lt), abs(x - rs)),
        max(abs(x - ls), abs(x - lt)),
        max(abs(x - rs), abs(x - rt))
    )

    print(ans)

Submission status: Accepted

Solution code:
import bisect
import sys
def input():
    return sys.stdin.readline()[:-1]
def main():
    A, B, Q = map(int,input().split())
    s = [-10**20] + [int(input()) for k in range(A)] + [10**20,10**20]
    t = [-10**20] + [int(input()) for k in range(B)] + [10**20,10**20]

    for _ in range(Q):
        x = int(input())
        S = bisect.bisect_left(s,x)
        T = bisect.bisect_left(t,x)
        print(min(
            max(s[S],t[T])-x,
            x-min(s[S-1],t[T-1]),
            s[S]-x + s[S]-t[T-1],
            t[T]-x + t[T]-s[S-1],
            x-s[S-1] + t[T]-s[S-1],
            x-t[T-1] + s[S]-t[T-1]))
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int,input().split())
s = [-10**20] + [int(input()) for k in range(A)] + [10**20,10**20]
t = [-10**20] + [int(input()) for k in range(B)] + [10**20,10**20]

for _ in range(Q):
    x = int(input())
    S = bisect.bisect_left(s,x)
    T = bisect.bisect_left(t,x)
    print(min(
        max(s[S],t[T])-x,
        x-min(s[S-1],t[T-1]),
        s[S]-x + s[S]-t[T-1],
        t[T]-x + t[T]-s[S-1],
        x-s[S-1] + t[T]-s[S-1],
        x-t[T-1] + s[S]-t[T-1]))

Submission status: Accepted

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

MY_INF = 10 ** 18

s = [int(input()) for _ in range(A)]
t = [int(input()) for _ in range(B)]
x = [int(input()) for _ in range(Q)]

s = [-MY_INF] + s + [MY_INF]
t = [-MY_INF] + t + [MY_INF]

import bisect

for i, xi in enumerate(x):
    ans = 10 ** 18
    #
    # s -> r
    idx_s = bisect.bisect_left(s, xi)
    #
    s_l = s[idx_s - 1]
    idx_tl = bisect.bisect_left(t, s_l)
    #
    t_ll = t[idx_tl - 1]
    ans_tmp = abs(s_l - xi) + abs(t_ll - s_l)
    ans = min(ans, ans_tmp)
    t_lr = t[idx_tl]
    ans_tmp = abs(s_l - xi) + abs(t_lr - s_l)
    ans = min(ans, ans_tmp)
    #
    s_r = s[idx_s]
    idx_tr = bisect.bisect_left(t, s_r)
    #
    t_rl = t[idx_tr - 1]
    ans_tmp = abs(s_r - xi) + abs(t_rl - s_r)
    ans = min(ans, ans_tmp)
    #
    t_rr = t[idx_tr]
    ans_tmp = abs(s_r - xi) + abs(t_rr - s_r)
    ans = min(ans, ans_tmp)
    #
    # t -> r
    idx_t = bisect.bisect_left(t, xi)
    #
    t_l = t[idx_t - 1]
    idx_sl = bisect.bisect_left(s, t_l)
    #
    s_ll = s[idx_sl - 1]
    ans_tmp = abs(t_l - xi) + abs(s_ll - t_l)
    ans = min(ans, ans_tmp)
    s_lr = s[idx_sl]
    ans_tmp = abs(t_l - xi) + abs(s_lr - t_l)
    ans = min(ans, ans_tmp)
    #
    t_r = t[idx_t]
    idx_sr = bisect.bisect_left(s, t_r)
    #
    s_rl = s[idx_sr - 1]
    ans_tmp = abs(t_r - xi) + abs(s_rl - t_r)
    ans = min(ans, ans_tmp)
    #
    s_rr = s[idx_sr]
    ans_tmp = abs(t_r - xi) + abs(s_rr - t_r)
    ans = min(ans, ans_tmp)
    #
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

a, b, q = [int(x) for x in input().split()]
s = [int(input()) for _ in range(a)]
t = [int(input()) for _ in range(b)]
ans = []

import bisect
ans = []
for _ in range(q):
    x = int(input())
    idx_s = bisect.bisect_left(s, x)
    idx_t = bisect.bisect_right(t, x)
    s_ = []
    t_ = []
    if idx_s < a:
        s_.append(s[idx_s])
    if idx_t < b:
        t_.append(t[idx_t])
    if idx_s - 1 >= 0:
        s_.append(s[idx_s - 1])
    if idx_t - 1 >= 0:
        t_.append(t[idx_t - 1])
    res = float("inf")
    for i in s_:
        for j in t_:
            if (i >= x and j >= x) or (i <= x and j <= x):
                res = min(res, max(abs(i - x), abs(j - x)))
            else:
                res = min(res, abs(i - x) + abs(i - j), abs(j - x) + abs(i - j))
    ans.append(res)
for i in ans:
    print(i)

Submission status: Accepted

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
import time,random

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]

def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(): return [list(map(int, l.split())) for l in sys.stdin.readlines()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def pe(s): return print(str(s), file=sys.stderr)
def JA(a, sep): return sep.join(map(str, a))
def JAA(a, s, t): return s.join(t.join(map(str, b)) for b in a)


def main():
    a,b,q = LI()
    sa = [-inf,-inf] + [I() for _ in range(a)] + [inf, inf]
    ta = [-inf,-inf] + [I() for _ in range(b)] + [inf, inf]
    xa = [I() for _ in range(q)]
    r = []
    for x in xa:
        si = bisect.bisect_left(sa, x)
        ti = bisect.bisect_left(ta, x)
        l = sa[si-1]
        k = x - l
        ti2 = bisect.bisect_left(ta, l)
        t = inf
        if ti2 > 0 and t > k + l - ta[ti2-1]:
            t = k + l - ta[ti2-1]
        if t > k + ta[ti2] - l:
            t = k + ta[ti2] - l
        l = sa[si]
        k = l - x
        ti2 = bisect.bisect_left(ta, l)
        if ti2 > 0 and t > k + l - ta[ti2-1]:
            t = k + l - ta[ti2-1]
        if t > k + ta[ti2] - l:
            t = k + ta[ti2] - l

        l = ta[ti-1]
        k = x - l
        si2 = bisect.bisect_left(sa, l)
        if si2 > 0 and t > k + l - sa[si2-1]:
            t = k + l - sa[si2-1]
        if t > k + sa[si2] - l:
            t = k + sa[si2] - l
        l = ta[ti]
        k = l - x
        si2 = bisect.bisect_left(sa, l)
        if si2 > 0 and t > k + l - sa[si2-1]:
            t = k + l - sa[si2-1]
        if t > k + sa[si2] - l:
            t = k + sa[si2] - l


        r.append(t)

    return JA(r, "\n")

print(main())

Submission status: Accepted

Solution code:
from bisect import bisect_left
import sys
def main():
    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)]
    X = [int(input()) for _ in range(Q)]
    INF = 10 ** 11
    S = [-INF] + S + [INF]
    T = [-INF] + T + [INF]
    for x in X:
        i = bisect_left(S, x)
        ls = x - S[i - 1]
        rs = S[i] - x
        j = bisect_left(T, x)
        lt = x - T[j - 1]
        rt = T[j] - x
        print(min(max(ls, lt), max(rs, rt), 2 * ls + rt, ls + 2 * rt, 2 * rs + lt, rs + 2 * lt))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect

def main():
    a, b, q = map(int, input().split())
    s = [0 for _ in range(a)]
    for i in range(a):
        s[i] = int(input())
    t = [0 for _ in range(b)]
    for i in range(b):
        t[i] = int(input())
    x = [0 for _ in range(q)]
    for i in range(q):
        x[i] = int(input())

    ans = [10**18 for _ in range(q)]
    for i in range(q):
        next1 = bisect.bisect(s, x[i])
        if next1 > 0:
            d1 = x[i] - s[next1-1]
            next2 = bisect.bisect(t, s[next1-1])
            if next2 > 0:
                d2 = d1 + (s[next1-1] - t[next2-1])
                if d2 < ans[i]:
                    ans[i] = d2
            if next2 < b:
                d2 = d1 + (t[next2] - s[next1-1])
                if d2 < ans[i]:
                    ans[i] = d2
        if next1 < a:
            d1 = s[next1] - x[i]
            next2 = bisect.bisect(t, s[next1])
            if next2 > 0:
                d2 = d1 + (s[next1] - t[next2-1])
                if d2 < ans[i]:
                    ans[i] = d2
            if next2 < b:
                d2 = d1 + (t[next2] - s[next1])
                if d2 < ans[i]:
                    ans[i] = d2

        next1 = bisect.bisect(t, x[i])
        if next1 > 0:
            d1 = x[i] - t[next1-1]
            next2 = bisect.bisect(s, t[next1-1])
            if next2 > 0:
                d2 = d1 + (t[next1-1] - s[next2-1])
                if d2 < ans[i]:
                    ans[i] = d2
            if next2 < a:
                d2 = d1 + (s[next2] - t[next1-1])
                if d2 < ans[i]:
                    ans[i] = d2
        if next1 < b:
            d1 = t[next1] - x[i]
            next2 = bisect.bisect(s, t[next1])
            if next2 > 0:
                d2 = d1 + (t[next1] - s[next2-1])
                if d2 < ans[i]:
                    ans[i] = d2
            if next2 < a:
                d2 = d1 + (s[next2] - t[next1])
                if d2 < ans[i]:
                    ans[i] = d2

    for i in range(q):
        print(ans[i])

if __name__ == '__main__':
    main()

Submission status: Accepted

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

S.sort()
T.sort()

S = [-10**18]+S+[10**18]
T = [-10**18]+T+[10**18]

import bisect

for i in range(q):
    x = int(input())
    j = bisect.bisect_left(S, x)
    k = bisect.bisect_left(T, x)
    ans = 10**18
    for dj, dk in (-1, -1), (-1, 0), (0, -1), (0, 0):
        nj = j+dj
        nk = k+dk
        temp = min(abs(S[nj]-x)+abs(T[nk]-S[nj]), abs(T[nk]-x)+abs(T[nk]-S[nj]))
        ans = min(ans, temp)
    print(ans)

Submission status: Accepted

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

A, B, Q = map(int, input().split())
s = [-10**18]+[int(input()) for _ in range(A)]+[10**18]
t = [-10**18]+[int(input()) for _ in range(B)]+[10**18]

for _ in range(Q):
    x = int(input())
    i = bisect_left(s, x)
    sl = s[i-1]
    sr = s[i]
    i = bisect_left(t, x)
    tl = t[i-1]
    tr = t[i]
    ans = 10**18
    
    for fi in [sl, sr]:
        for se in [tl, tr]:
            ans = min(ans, abs(fi-x)+abs(se-fi))
    
    for fi in [tl, tr]:
        for se in [sl, sr]:
            ans = min(ans, abs(fi-x)+abs(se-fi))
    
    print(ans)