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 = list(map(int, input().split()))
shine = []
temple = []
inf = 10**11
x = []
for i in range(a):
    shine.append(int(input()))
shine.append(inf)
for i in range(b):
    temple.append(int(input()))
temple.append(inf)
s2t = [0 for i in range(a+1)]
t2s = [0 for i in range(b+1)]
for i in range(a+1):
    index = bisect.bisect_left(temple, shine[i])
    if index >= 1:
        s2t[i] = min(abs(shine[i] - temple[index]), abs(shine[i] - temple[index - 1]))
    else:
        s2t[i] = abs(shine[i] - temple[index])
for i in range(b+1):
    index = bisect.bisect_left(shine, temple[i])
    if index >= 1:
        t2s[i] = min(abs(temple[i] - shine[index]), abs(temple[i] - shine[index - 1]))
    else:
        t2s[i] = abs(temple[i] - shine[index])
ans = [] 
for i in range(q):
    x = int(input())
    shine_index = bisect.bisect_left(shine, x)
    temple_index = bisect.bisect_left(temple, x)
    #shine_index -> 一番近い神社に行く
    if shine_index >= 1:
        B = abs(shine[shine_index-1] - x) + s2t[shine_index-1]
    else:
        B = inf
    A = abs(shine[shine_index] - x) + s2t[shine_index]
    C = abs(temple[temple_index] - x) + t2s[temple_index]
    if temple_index >= 1:
        D = abs(temple[temple_index-1] - x) + t2s[temple_index-1]
    else:
        D = inf
    print(min([A,B,C,D]))

Submission status: Accepted

Solution code:
from bisect import bisect_left

def main():
    A, B, Q = map(int, input().split())
    S = [-10**12] + [int(input()) for _ in range(A)] + [10**12]
    T = [-10**12] + [int(input()) for _ in range(B)] + [10**12]
    for _ in range(Q):
        x = int(input())
        s = bisect_left(S, x)
        t = bisect_left(T, x)
        sl, sr = x - S[s - 1], S[s] - x
        tl, tr = x - T[t - 1], T[t] - x
        if sl < tl:
            m = min(tl, 2 * sl + tr)
        else:
            m = min(sl, 2 * tl + sr)
        if sr < tr:
            m = min(m, tr, 2 * sr + tl)
        else:
            m = min(m, sr, 2 * tr + sl)
        print(m)

main()

Submission status: Accepted

Solution code:
import bisect
def main():
    A, B, Q = map(int, input().split())
    s = []
    for _ in range(A):
        s.append(int(input()))
    t = []
    for _ in range(B):
        t.append(int(input()))
    for _ in range(Q):
        x = int(input())
        i = bisect.bisect_left(s, x)
        j = bisect.bisect_left(t, x)
        if i == 0:
            i_d = [s[i] - x]
        elif i == A:
            i_d = [s[i-1] - x]
        else:
            i_d = [s[i-1] - x, s[i] - x]
        if j == 0:
            j_d = [t[j] - x]
        elif j == B:
            j_d = [t[j-1] - x]
        else:
            j_d = [t[j-1] - x, t[j] - x]
        m = 10**12
        for y in i_d:
            for z in j_d:
                if y * z < 0:
                    m = min(m, abs(y)*2 + abs(z), abs(y) + abs(z)*2)
                else:
                    m = min(m, max(abs(y), abs(z)))
        print(m)
main()

Submission status: Accepted

Solution code:
from bisect import *
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)]
value1=2*(10**10)
for x in X:
    value=value1
    s1=bisect_left(S,x)
    for s in [s1-1,s1]:
        if -1< s < A:
            t1=bisect_left(T,S[s])
            for t in [t1-1,t1]:
                a=0
                if -1< t < B:
                    if x>S[s]:
                        a+=x-S[s]
                    else:
                        a+=S[s]-x
                    if S[s]>T[t]:
                        a+=S[s]-T[t]
                    else:
                        a+=T[t]-S[s]
                    if value>a:
                        value=a
    t1=bisect_left(T,x)
    for t in [t1-1,t1]:
        if -1< t < B:
            s1=bisect_left(S,T[t])
            for s in [s1-1,s1]:
                a=0
                if -1< s < A:
                    if x>T[t]:
                        a+=x-T[t]
                    else:
                        a+=T[t]-x
                    if S[s]>T[t]:
                        a+=S[s]-T[t]
                    else:
                        a+=T[t]-S[s]
                    if value>a:
                        value=a

    print(value)

Submission status: Accepted

Solution code:
from sys import stdout
printn = lambda x: stdout.write(str(x))
inn = lambda : int(input())
inl   = lambda: list(map(int, input().split()))
inm   = lambda:      map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 999999999999
R = 10**9 + 7
import bisect

def ddprint(x):
  if DBG:
    print(x)

a,b,q = inm()
s = []
t = []
for i in range(a):
    s.append(inn())
for i in range(b):
    t.append(inn())
for qq in range(q):
    x = inn()
    mn = BIG

    i = bisect.bisect_left(s,x)
    j = bisect.bisect_left(t,x)
    #ddprint("i {} j {}".format(i,j))
    if i>0 and j>0:
        mn = min(mn, x-min(s[i-1],t[j-1]))
    if i>0 and j<b:
        mn = min(mn, min(x-s[i-1],t[j]-x)+t[j]-s[i-1])
    if i<a and j>0:
        mn = min(mn, min(x-t[j-1],s[i]-x)+s[i]-t[j-1])
    if i<a and j<b:
        mn = min(mn, max(s[i],t[j])-x)
    print(mn)

Submission status: Accepted

Solution code:
import bisect
sizeA, sizeB, Q = map(int, input().split())
A = []
B = []
for h in range(sizeA):
    A.append(int(input()))
for hh in range(sizeB):
    B.append(int(input()))
for i in range(Q):
    now = int(input())
    a_place = bisect.bisect_left(A, now)
    b_place = bisect.bisect_left(B, now)
    if a_place != 0:
        a_left = A[a_place - 1]
    else:
        a_left = -10**11
    if a_place != sizeA:
        a_right = A[a_place]
    else:
        a_right = 10 ** 20
    if b_place != 0:
        b_left = B[b_place - 1]
    else:
        b_left = -10 ** 10
    if b_place != sizeB:
        b_right = B[b_place]
    else:
        b_right = 10 ** 20
    kouho1 = max(a_right, b_right) - now
    kouho2 = abs(now - min(a_left, b_left))
    kouho3 = abs(a_left - b_right)+min(b_right-now,now-a_left)
    kouho4 = abs(b_left - a_right)+min(a_right-now, now-b_left)
    print(min(kouho1, kouho2, kouho3, kouho4))
#print(A,B)

Submission status: Accepted

Solution code:
from bisect import bisect_left
A, B, Q = map(int, input().split())
S = sorted([int(input()) for i in range(A)])
T = sorted([int(input()) for i in range(B)])
X = [int(input()) for i in range(Q)]


for x in X:
  s_index = bisect_left(S, x)
  s_left = S[s_index - 1] if s_index > 0 else None
  s_right = S[s_index] if s_index < A else None
  t_index = bisect_left(T, x)
  t_left = T[t_index - 1] if t_index > 0 else None
  t_right = T[t_index] if t_index < B else None

  ans = float("inf")

  sl = [s_left, s_right]
  tl = [t_left, t_right]

  for s in sl:
    if not s: continue
    for t in tl:
      if not t: continue
      ans = min(ans, abs(x-s) + abs(t-s))

  for t in tl:
    if not t: continue
    for s in sl:
      if not s: continue
      ans = min(ans, abs(x-t) + abs(t-s)) 

  print(ans)

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 i in range(a)]
  t=[int(input()) for i in range(b)]
  x=[int(input()) for i in range(q)]
  inf=10**11
  minf=-10**11
  s=[minf]+s+[inf]
  t=[minf]+t+[inf]
  for i in range(q):
    ns=bisect_left(s,x[i])
    nt=bisect_left(t,x[i])
    ans=float('inf')
    for j in [s[ns],s[ns-1]]:
      for k in [t[nt],t[nt-1]]:
        ans=min(ans,min(abs(x[i]-j),abs(x[i]-k))+abs(max(j,k)-min(j,k)))
    print(ans)
if __name__=='__main__':
  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 i in range(a)]
  t=[int(input()) for i in range(b)]
  x=[int(input()) for i in range(q)]
  inf=10**11
  minf=-10**11
  s=[minf]+s+[inf]
  t=[minf]+t+[inf]
  for i in range(q):
    ns=bisect_left(s,x[i])
    nt=bisect_left(t,x[i])
    ans=float('inf')
    for j in [s[ns],s[ns-1]]:
      for k in [t[nt],t[nt-1]]:
        ans=min(ans,min(abs(x[i]-j),abs(x[i]-k))+abs(max(j,k)-min(j,k)))
    print(ans)
if __name__=='__main__':
  main()

Submission status: Accepted

Solution code:
from bisect import bisect_left
def main():
  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)]
  inf=10**11
  minf=-10**11
  s=[minf]+s+[inf]
  t=[minf]+t+[inf]
  for i in range(q):
    ns=bisect_left(s,x[i])
    nt=bisect_left(t,x[i])
    ans=float('inf')
    for j in [s[ns],s[ns-1]]:
      for k in [t[nt],t[nt-1]]:
        ans=min(ans,min(abs(x[i]-j),abs(x[i]-k))+abs(max(j,k)-min(j,k)))
    print(ans)
if __name__=='__main__':
  main()

Submission status: Accepted

Solution code:
import bisect

A, B, Q = map(int, input().split())
s = [-float('inf')] + [int(input()) for _ in range(A)] + [float('inf')]
t = [-float('inf')] + [int(input()) for _ in range(B)] + [float('inf')]
X = [int(input()) for _ in range(Q)]

for x in X:
    sp = bisect.bisect_left(s, x)
    tp = bisect.bisect_left(t, x) 
    res = float('inf')
    for S in [s[sp-1], s[sp]]:
        for T in [t[tp-1], t[tp]]:
            d1, d2 = abs(S-x) + abs(T-S), abs(T-x)+abs(S-T)
            res = min(res, d1, d2)
    print(res)

Submission status: Accepted

Solution code:
from bisect import bisect

def main():
    a,b,q,*stx = map(int,open(0).read().split())
    s = [-1e10] + stx[:a] + [2*1e10]
    t = [-1e10] + stx[a:a+b] + [2*1e10]
    x = stx[a+b:a+b+q]
    for i in x:
        pos_s = bisect(s,i)
        pos_t = bisect(t,i)
        sl = s[pos_s-1]; sr = s[pos_s]
        tl = t[pos_t-1]; tr = t[pos_t]
        ans = min( i-min(sl,tl), max(sr,tr)-i, (sr-i) + (sr-tl), (tr-i) + (tr-sl), (i-sl) + (tr-sl), (i-tl) + (sr-tl) )
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_left
a,b,q,*stx = map(int,open(0).read().split())
s = [-1e10] + stx[:a] + [2*1e10]
t = [-1e10] + stx[a:-q] + [2*1e10]
x = stx[-q:]
for i in x:
    pos_s = bisect_left(s,i)
    pos_t = bisect_left(t,i)
    sl = s[pos_s-1]; sr = s[pos_s]
    tl = t[pos_t-1]; tr = t[pos_t]
    ans = min( i-min(sl,tl), max(sr,tr)-i, (sr*2-i-tl), (tr*2-i-sl), (i+tr-sl*2), (i+sr-tl*2) )
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect
a,b,q,*stx = map(int,open(0).read().split())
s = [-1e10] + stx[:a] + [2*1e10]
t = [-1e10] + stx[a:a+b] + [2*1e10]
x = stx[a+b:a+b+q]
for i in x:
    pos_s = bisect(s,i)
    pos_t = bisect(t,i)
    sl = s[pos_s-1]; sr = s[pos_s]
    tl = t[pos_t-1]; tr = t[pos_t]
    ans = min( i-min(sl,tl), max(sr,tr)-i, (sr-i) + (sr-tl), (tr-i) + (tr-sl), (i-sl) + (tr-sl), (i-tl) + (sr-tl) )
    print(ans)

Submission status: Accepted

Solution code:
import bisect

a,b,q = map(int, input().split())
S = [-float('inf')]+[int(input()) for _ in range(a)]+[float('inf')]
T = [-float('inf')]+[int(input()) for _ in range(b)]+[float('inf')]
X = [int(input()) for _ in range(q)]


for q_i in range(q):
  x_pos_s = bisect.bisect_left(S, X[q_i])
  x_pos_t = bisect.bisect_left(T, X[q_i])
  
  s_1 = S[x_pos_s-1]
  t_1 = T[x_pos_t-1]
  s_2 = S[x_pos_s]
  t_2 = T[x_pos_t]
  
  ans = min(abs(X[q_i]-min(s_1,t_1)),
            abs(X[q_i]-max(s_2,t_2)),
            abs(s_2-t_1)+min(abs(X[q_i]-s_2),abs(X[q_i]-t_1)),
            abs(t_2-s_1)+min(abs(X[q_i]-t_2),abs(X[q_i]-s_1)))
  
  print(ans)

Submission status: Accepted

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input()) # n=1
def inpm(): return map(int,input().split()) # x=1,y=2
def inpl(): return list(map(int, input().split())) # a=[1,2,3,4,5,...,n]
def inpls(): return list(input().split())  # a=['1','2','3',...,'n']
def inplm(n): return list(int(input()) for _ in range(n)) # x=[] 複数行
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)] # [[2,2,2,2],[1,1,1,1],[3,3,3,3]] 
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)]) # [[1,1,1,1],[2,2,2,2],[3,3,3,3]] 
def graph():
    n=inp()
    g=[[] for _ in range(n)]
    for i in range(n):
        a = inp()
        a -= 1
        g[i].append(a)
        g[a].append(i)
    return n,g

def f(li, x):
    n = len(li)
    ok = -1
    ng = n
    while abs(ok-ng) > 1:
        mid = (ok+ng)//2
        if li[mid] < x:
            ok = mid
        else:
            ng = mid
    return ok

def main():
    a,b,q = inpm()
    s = inplm(a)
    t = inplm(b)
    x = inplm(q)
    s = tuple(s)
    t = tuple(t)
    x = tuple(x)
    for i in range(q):
        start = x[i]
        n = len(s)
        ok = -1
        ng = n
        while abs(ok-ng) > 1:
            mid = (ok+ng)//2
            if s[mid] < start:
                ok = mid
            else:
                ng = mid
        index_s = ok
        n = len(t)
        ok = -1
        ng = n
        while abs(ok-ng) > 1:
            mid = (ok+ng)//2
            if t[mid] < start:
                ok = mid
            else:
                ng = mid
        index_t = ok
        a1 = 10**11
        b1 = 10**11
        c1 = 10**11
        d1 = 10**11
        if index_t+1 < b and index_s+1 < a:
            d1 = abs(max(s[index_s+1],t[index_t+1]) - start)
        if index_s >= 0 and index_t+1 < b:
            a1 = min(abs(start - s[index_s]) + abs(s[index_s] - t[index_t+1]), abs(start - t[index_t+1]) + abs(s[index_s] - t[index_t+1]) )  
        if index_t >= 0 and index_s+1 < a:
            b1 = min(abs(start - t[index_t]) + abs(s[index_s+1] - t[index_t]),abs(start - s[index_s+1]) + abs(s[index_s+1] - t[index_t]))
        if index_s >= 0 and index_t >= 0:
            c1 = abs(start - min(s[index_s],t[index_t]))
        print(min(a1,b1,c1,d1))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
inpurt = sys.stdin.readline
a, b, q = map(int, input().split())
INF = 10 ** 11
s = [-INF] + [int(input()) for _ in range(a)] + [INF]
t = [-INF] + [int(input()) for _ in range(b)] + [INF]

for _ in range(q):
    xi = int(input())
    index_s = bisect_left(s, xi)
    s1 = xi - s[index_s - 1]
    s2 = s[index_s] - xi
    index_t = bisect_left(t, xi)
    t1 = xi - t[index_t - 1]
    t2 = t[index_t] -xi
    print(min(max(s1, t1), max(s2, t2), min(s1, t2) * 2 + max(s1, t2), min(s2, t1) * 2 + max(s2, t1)))

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

from bisect import bisect_left

for i in range(q):
    y=bisect_left(s,x[i])
    z=bisect_left(t,x[i])
    k=([0] if y==0 else [a-1] if y==a else [y-1,y])
    l=([0] if z==0 else [b-1] if z==b else [z-1,z])
    mi=100000000000000
    for n in k:
        for m in l:
            if abs(s[n]-x[i])>abs(t[m]-x[i]):
                sub1,sub2=t[m],s[n]
            else:
                sub1,sub2=s[n],t[m]
            mi=min(mi,abs(sub1-x[i])+abs(sub2-sub1))
    print(mi)

Submission status: Accepted

Solution code:
#距離が同じときに注意，次を踏まえた方向に移動しないとダメ
#最寄りの神社/寺まで移動したときに寺/神社をすでに通過したか判定

import bisect
import sys
input = sys.stdin.readline

A,B,Q=map(int,input().split())
s=[0]*A
t=[0]*B

for i in range(A):
    s[i]=int(input())

for i in range(B):
    t[i]=int(input())
    
#神社/寺から最寄りの寺/神社のインデックスを記憶
ns=[0]*A
nt=[0]*B

def bi_se(L,x):
    k=bisect.bisect_left(L,x)
    if k==len(L):
        return k-1
    d1=abs(x-L[k])
    d2=abs(x-L[k-1])
    kk=k
    if d2<d1:
        kk=k-1
    return kk
    

for i in range(A):
    ns[i]=bi_se(t,s[i])
    
for i in range(B):
    nt[i]=bi_se(s,t[i])
    
for i in range(Q):
    x=int(input())
    ai=bi_se(s,x)
    la=abs(x-s[ai])#最寄りの神社まで移動
    k_start=bisect.bisect_left(t,x)
    k_next=bisect.bisect_left(t,s[ai])
    if k_start==k_next:
        la+=abs(s[ai]-t[ns[ai]])
    
    bi=bi_se(t,x)
    lb=abs(x-t[bi])
    k_start=bisect.bisect_left(s,x)
    k_next=bisect.bisect_left(s,t[bi])
    if k_start==k_next:
        lb+=abs(t[bi]-s[nt[bi]])
    print(min(la,lb))

Submission status: Accepted

Solution code:
import bisect

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

S = [-float('inf')]+[int(input()) for _ in range(a)]+[float('inf')]
T = [-float('inf')]+[int(input()) for _ in range(b)]+[float('inf')]
X = [int(input()) for _ in range(q)]

for x_i in X:
  pos_s = bisect.bisect_right(S, x_i)
  pos_t = bisect.bisect_right(T, x_i)
  
  s1 = S[pos_s-1]
  s2 = S[pos_s]
  t1 = T[pos_t-1]
  t2 = T[pos_t]
  
  ans1 = x_i - min(s1, t1)
  ans2 = max(s2, t2) - x_i
  ans3 = s2 - t1 + min(s2-x_i, x_i-t1)
  ans4 = t2 - s1 + min(t2-x_i, x_i-s1)
  print(min(ans1, ans2, ans3, ans4))

Submission status: Accepted

Solution code:
from bisect import bisect

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

for i in x:
    ans = INF
    idx_s = bisect(s, i)
    idx_t = bisect(t, i)
    for S in [s[idx_s - 1], s[idx_s]]:
        for T in [t[idx_t - 1], t[idx_t]]:
            d1 = abs(i - S) + abs(S - T)
            d2 = abs(i - T) + abs(S - T)
            ans = min(ans, d1, d2)
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left


INF = 10 ** 12
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]
Q = [int(input()) for _ in range(Q)]


for q in Q:
    ps = bisect_left(S, q)
    s1, s2 = S[ps - 1], S[ps]

    pt = bisect_left(T, q)
    t1, t2 = T[pt - 1], T[pt]

    ans = INF
    for s in (s1, s2):
        for t in (t1, t2):
            path1 = abs(q - s) + abs(s - t)
            path2 = abs(q - t) + abs(s - t)
            ans = min(ans, path1, path2)
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left

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


for q in Q:
    ps = bisect_left(S, q)
    if ps == len(S):
        s1, s2 = S[ps - 1], S[ps - 1]
    elif ps == 0:
        s1, s2 = S[ps], S[ps]
    else:
        s1, s2 = S[ps - 1], S[ps]

    pt = bisect_left(T, q)
    if pt == len(T):
        t1, t2 = T[pt - 1], T[pt - 1]
    elif pt == 0:
        t1, t2 = T[pt], T[pt]
    else:
        t1, t2 = T[pt - 1], T[pt]

    ans = 10 ** 11
    for s in (s1, s2):
        for t in (t1, t2):
            path1 = abs(q - s) + abs(s - t)
            path2 = abs(q - t) + abs(s - t)
            ans = min(ans, path1, path2)
    print(ans)

Submission status: Accepted

Solution code:
import bisect

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

ans = []
for i in range(Q):
    x = int(input())
    s = bisect.bisect_left(S, x)
    s = min([s,len(S)-1])
    kyori_s = S[s]
    st1 = min([bisect.bisect_left(T, kyori_s), len(T)-1])
    st2 = max([st1-1,0])
    kyori1 = abs(kyori_s-x) + min([abs(T[st1]-kyori_s),abs(T[st2]-kyori_s)])

    s = max([s-1,0])
    kyori_s = S[s]
    st1 = min([bisect.bisect_left(T, kyori_s), len(T)-1])
    st2 = max([st1-1,0])
    kyori2 = abs(kyori_s-x) + min([abs(T[st1]-kyori_s),abs(T[st2]-kyori_s)])

    t = bisect.bisect_left(T, x)
    t = min([t,len(T)-1])
    kyori_t = T[t]
    ts1 = min([bisect.bisect_left(S, kyori_t), len(S)-1])
    ts2 = max([ts1-1,0])
    kyori3 = abs(kyori_t-x) + min([abs(S[ts1]-kyori_t),abs(S[ts2]-kyori_t)])

    t = max([t-1,0])
    kyori_t = T[t]
    ts1 = min([bisect.bisect_left(S, kyori_t), len(S)-1])
    ts2 = max([ts1-1,0])
    kyori4 = abs(kyori_t-x) + min([abs(S[ts1]-kyori_t),abs(S[ts2]-kyori_t)])

    ans.append(min([kyori1,kyori2,kyori3,kyori4]))

for i in ans:
    print(i)

Submission status: Accepted

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

inf = float('INF')
for _ in range(q):
    x = int(input())
    # print('x', x)
    ss = bisect(s, x)
    tt = bisect(t, x)
    ans = inf
    for i in range(max(ss-1,0),min(ss+1,a)):
        for j in range(max(tt-1,0),min(tt+1,b)):
            ii,jj = abs(s[i] - x) + abs(s[i] - t[j]), abs(t[j] - x) + abs(s[i] - t[j])
            tmp = min(ii,jj)
            if ans > tmp:
                ans = tmp
    print(ans)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left as bi_l, bisect_right as bi_r

inf = float('inf')

a, b, q = map(int, sys.stdin.readline().split())
*I, = map(int, sys.stdin.read().split())
s = I[:a]
t = I[a:a+b]
X = I[a+b:]

def main():
    for x in X:
        ls = bi_r(s, x) - 1
        rs = bi_l(s, x)
        lt = bi_r(t, x) - 1
        rt = bi_l(t, x)
        dls = s[ls] - x if ls >= 0 else -inf
        drs = s[rs] - x if rs <= a - 1 else inf
        dlt = t[lt] - x if lt >= 0 else -inf
        drt = t[rt] - x if rt <= b - 1 else inf
        
        res = inf
        for ds in [dls, drs]:
            for dt in [dlt, drt]:
                if ds * dt > 0:
                    d = max(abs(ds), abs(dt))
                else:
                    ds = abs(ds)
                    dt = abs(dt)
                    d = min(ds, dt) * 2 + max(ds, dt)
                res = min(res, d)
        yield res

if __name__ == '__main__':
    ans = main()
    print(*ans, sep='\n')

Submission status: Accepted

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

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

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 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 main():
    A, B, Q = LI()
    s = []
    t = []
    x = []
    for _ in range(A):
        s.append(I())
    for _ in range(B):
        t.append(I())
    for _ in range(Q):
        x.append(I())

    # ダミー境界を加える
    s = [-inf] + s + [inf]
    t = [-inf] + t + [inf]

    for pos in x:
        l_s = bisect.bisect_left(s, pos)
        l_t = bisect.bisect_left(t, pos)

        left_shrine = s[l_s-1]
        right_shrine = s[l_s]
        left_temple = t[l_t-1]
        right_temple = t[l_t]

        d1 = pos - min(left_shrine, left_temple)
        d2 = max(right_shrine, right_temple) - pos
        d3 = 2 * (pos - left_shrine) + (right_temple - pos)
        d4 = 2 * (right_temple - pos) + (pos - left_shrine)
        d5 = 2 * (pos - left_temple) + (right_shrine - pos)
        d6 = 2 * (right_shrine - pos) + (pos - left_temple)

        ans = min([
            d1, d2, d3, d4, d5, d6
        ])
        print(ans)

    '''
    ダミー境界を加えない場合
    for pos in x:
        l_s = bisect.bisect_left(s, pos)
        l_t = bisect.bisect_left(t, pos)

        if l_s == 0:
            left_shrine = None
        else:
            left_shrine = s[l_s-1]
        if l_s == A:
            right_shrine = None
        else:
            right_shrine = s[l_s]

        if l_t == 0:
            left_temple = None
        else:
            left_temple = t[l_t-1]
        if l_t == B:
            right_temple = None
        else:
            right_temple = t[l_t]

        d1, d2, d3, d4, d5, d6 = inf, inf, inf, inf, inf, inf
        if left_shrine and left_temple:
            d1 = pos - min(left_shrine, left_temple)
        if right_shrine and right_temple:
            d2 = max(right_shrine, right_temple) - pos
        if left_shrine and right_temple:
            d3 = 2 * (pos - left_shrine) + (right_temple - pos)
            d4 = 2 * (right_temple - pos) + (pos - left_shrine)
        if left_temple and right_shrine:
            d5 = 2 * (pos - left_temple) + (right_shrine - pos)
            d6 = 2 * (right_shrine - pos) + (pos - left_temple)

        ans = min([
            d1, d2, d3, d4, d5, d6
        ])
        print(ans)
        '''
main()

Submission status: Accepted

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

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

DR = [1, -1, 0, 0]
DC = [0, 0, 1, -1]

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 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 main():
    A, B, Q = LI()
    s = []
    t = []
    x = []
    for _ in range(A):
        s.append(I())
    for _ in range(B):
        t.append(I())
    for _ in range(Q):
        x.append(I())
    for pos in x:
        l_s = bisect.bisect_left(s, pos)
        l_t = bisect.bisect_left(t, pos)

        if l_s == 0:
            left_shrine = None
        else:
            left_shrine = s[l_s-1]
        if l_s == A:
            right_shrine = None
        else:
            right_shrine = s[l_s]

        if l_t == 0:
            left_temple = None
        else:
            left_temple = t[l_t-1]
        if l_t == B:
            right_temple = None
        else:
            right_temple = t[l_t]

        d1, d2, d3, d4, d5, d6 = inf, inf, inf, inf, inf, inf
        if left_shrine and left_temple:
            d1 = pos - min(left_shrine, left_temple)
        if right_shrine and right_temple:
            d2 = max(right_shrine, right_temple) - pos
        if left_shrine and right_temple:
            d3 = 2 * (pos - left_shrine) + (right_temple - pos)
            d4 = 2 * (right_temple - pos) + (pos - left_shrine)
        if left_temple and right_shrine:
            d5 = 2 * (pos - left_temple) + (right_shrine - pos)
            d6 = 2 * (right_shrine - pos) + (pos - left_temple)

        ans = min([
            d1, d2, d3, d4, d5, d6
        ])
        print(ans)
main()

Submission status: Accepted

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

INF=1e50

s=sorted([int(input())for i in range(A)])
t = sorted([int(input())for i in range(B)])
X=[int(input())for i in range(Q)]

rs = list(map(lambda x: -x, s[::-1]))
rt = list(map(lambda x: -x, t[::-1]))

s+=[INF]
t+=[INF]
rs+=[INF]
rt+=[INF]

import bisect

for x in X:
    se = s[bisect.bisect_left(s, x)] - x
    sw = rs[bisect.bisect_left(rs, -x)] + x
    te = t[bisect.bisect_left(t, x)] - x
    tw = rt[bisect.bisect_left(rt, -x)] + x
    kouho = []
    kouho.append(max(se,te))
    kouho.append(max(sw,tw))
    kouho.append(sw*2+te)
    kouho.append(se*2+tw)
    kouho.append(tw*2+se)
    kouho.append(te*2+sw)

    print(min(kouho))
    # print(bisect.bisect_left(s, x))
    # print(s[bisect.bisect_left(s, x)])

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 q in range(Q):
    x = int(input())
    # upper_boundを使う
    b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
    res = INF
    for S in [s[b-1], s[b]]:  # xを挟んで左側と右側
        for T in [t[d-1], t[d]]:  # xを挟んで右側と左側
            d1, d2 = abs(S-x) + abs(T-S), abs(T-x) + abs(S-T)  # 神社行って寺行くのと, 寺行って神社行く, の2通り
            res = min(res, d1, d2)
    print(res)

Submission status: Accepted

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

def main():
    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 = float('inf')
    s = [-INF] + s + [INF]
    t = [-INF] + t + [INF]
    
    
    for i in range(Q):
        S,T = bisect.bisect_right(s,x[i]),bisect.bisect_right(t,x[i])
        ans = INF
        for j in [s[S],s[S-1]]:
            for k in [t[T],t[T-1]]:
                l,_l = abs(j-x[i])+abs(k-j),abs(k-x[i])+abs(j-k)
                ans = min(ans,l,_l)
        print(ans)
    
if __name__ == "__main__":
    main()