Problem:


Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

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

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.



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


Sample output:
350
1400
301
399

Submission status: Accepted

Solution code:
import bisect

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

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

X = [int(input()) for _ in range(Q)]

INF = float("inf")
"""
SやTについて、ある地点をスタート地点に選んだ時に取りうる行動は、SとTそれぞれについて現在値の東西のどちらに向かうかと、SとTどちらを先に行くか。
なのでそれら全通りについてためせばおK
"""
for x in X:
    sw = se = 0
    tw = te = 0
    idx_s = bisect.bisect_left(S, x)
    idx_t = bisect.bisect_left(T, x)

    if idx_s == len(S):
        se = INF
        sw = S[-1]
    elif idx_s == 0:
        sw = INF
        se = S[0]
    else:
        se = S[idx_s]
        sw = S[idx_s - 1]

    if idx_t == len(T):
        te = INF
        tw = T[-1]
    elif idx_t == 0:
        tw = INF
        te = T[0]
    else:
        te = T[idx_t]
        tw = T[idx_t - 1]
        
    a = abs(x-se) + abs(se-tw) if se != INF or tw != INF else 5* 10**10
    b = abs(x-tw) + abs(tw-se) if se != INF or tw != INF else 5* 10**10
    c = abs(x-sw) + abs(sw-te) if sw != INF or te != INF else 5* 10**10
    d = abs(x-te) + abs(te-sw) if sw != INF or te != INF else 5* 10**10
    print(min(
        a, 
        b, 
        c, 
        d,
        max(abs(x-sw), abs(x-tw)),
        max(abs(x-se), abs(x-te))))
    """
    print("--------")
    print(se,tw)
    print((
        abs(x-se) + abs(se-tw), 
        abs(x-tw) + abs(tw-se), 
        abs(x-sw) + abs(sw-te), 
        abs(x-te) + abs(te-sw),
        max(abs(x-sw), abs(x-tw)),
        max(abs(x-se), abs(x-te))))
    """

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines


def main():
    A, B, Q = map(int, readline().split())
    stx = list(map(int, read().split()))
    s = stx[:A]; t = stx[A:-Q]; x = stx[-Q:]
    s = [-10 ** 10] + s + [10 ** 11]
    t = [-10 ** 10] + t + [10 ** 11]

    for i in x:
        ax = bisect_left(s, i)
        bx = bisect_left(t, i)
        pp = max(s[ax], t[bx]) - i
        mm = i - min(s[ax - 1], t[bx - 1])
        pm = min(s[ax] * 2 - i - t[bx - 1], t[bx] * 2 - i - s[ax - 1])
        mp = min(i - s[ax - 1] * 2 + t[bx], i - t[bx - 1] * 2 + s[ax])
        print(min(pp, mm, pm, mp))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines

A, B, Q = map(int, readline().split())
stx = list(map(int, read().split()))
s = stx[:A]; t = stx[A:-Q]; x = stx[-Q:]
s = [-10 ** 10] + s + [10 ** 11]
t = [-10 ** 10] + t + [10 ** 11]

for i in x:
    ax = bisect_left(s, i)
    bx = bisect_left(t, i)
    pp = max(s[ax], t[bx]) - i
    mm = i - min(s[ax - 1], t[bx - 1])
    pm = min(s[ax] * 2 - i - t[bx - 1], t[bx] * 2 - i - s[ax - 1])
    mp = min(i - s[ax - 1] * 2 + t[bx], i - t[bx - 1] * 2 + s[ax])
    print(min(pp, mm, pm, mp))

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)]
S = [-10 ** 12] + S + [10 ** 12]
T = [-10 ** 12] + T + [10 ** 12]
for x in X:
    si = bisect.bisect_right(S, x)
    ti = bisect.bisect_right(T, x)
    Ls, Rs = x - S[si - 1], -x + S[si]
    Lt, Rt = x - T[ti - 1], -x + T[ti]
    ans = min(Ls * 2 + Rt, Ls + Rt * 2, Lt * 2 + Rs,
              Lt + Rs * 2, max(Ls, Lt), max(Rs, Rt))
    print(ans)

Submission status: Accepted

Solution code:
import bisect
a, b , q= map(int, input().split())
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 = [-INF] + s + [INF]
t = [-INF] + t + [INF]
for q in x:
    b, d = bisect.bisect(s, q), bisect.bisect(t, q)
    res = INF
    for S in [s[b-1], s[b]]:
        for T in [t[d-1], t[d]]:
            d1, d2 = abs(S-q) + abs(S-T), abs(T-q) + abs(S-T)
            res = min(res, d1, d2)
    print(res)

Submission status: Accepted

Solution code:
# D - Lazy Faith

import bisect

A, B, Q = map(int, input().split())
s,t,x = [],[],[]
for _ in range(A):
    s.append(int(input()))
for _ in range(B):
    t.append(int(input()))
for _ in range(Q):
    x.append(int(input()))
    
for start in x:
    ans_list = []
    
    tmp_idx = bisect.bisect_left(s,start)
    if start < s[0]:
        west_s = -1
    else:
        west_s = s[tmp_idx-1]
    if s[-1] < start:
        east_s = -1
    else:
        east_s = s[tmp_idx]
    
    tmp_idx = bisect.bisect_left(t,start)
    if start < t[0]:
        west_t = -1
    else:
        west_t = t[tmp_idx-1]
    if t[-1] < start:
        east_t = -1
    else:
        east_t = t[tmp_idx]
        
    if east_s != -1 and east_t != -1: # 東→東
        ans_list.append(abs(east_s - east_t) + (min(east_s, east_t) - start))
    if west_s != -1 and west_t != -1: # 西→西
        ans_list.append(abs(west_s - west_t) + (start - max(west_s, west_t)))
    if east_s != -1 and west_t != -1: # 東神社→西寺 or 西寺→東神社
        ans_list.append(east_s - start + (east_s - west_t))
        ans_list.append(start - west_t + (east_s - west_t))
    if west_s != -1 and east_t != -1: # 東寺→西神社 or 西神社→東寺
        ans_list.append(east_t - start + (east_t - west_s))
        ans_list.append(start - west_s + (east_t - west_s))

    print(min(ans_list))

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int,input().split())
INF = 10**11
S = [-INF] + [int(input()) for i in range(A)] + [INF]
T = [-INF] + [int(input()) for i in range(B)] + [INF]
#print(S,T)
for q in range(Q):
  x = int(input())
  i = bisect.bisect_right(S, x)
  j = bisect.bisect_right(T, x)
  d = INF
  for s in [S[i-1],S[i]]:
    for t in [T[j-1],T[j]]:
      d1 = abs(s-x)+abs(s-t)
      d2 = abs(t-x)+abs(s-t)
      d = min(d, d1, d2)
  print(d)

Submission status: Accepted

Solution code:
from bisect import bisect_left,bisect_right
a,b,q=map(int,input().split())
INF=float("inf")
s=[-INF]+[int(input())for i in range(a)]+[INF]
t=[-INF]+[int(input())for i in range(b)]+[INF]
for _ in range(q):
  x=int(input())
  b,c=bisect_right(s,x),bisect_right(t,x)
  a=INF
  for i in [s[b-1],s[b]]:
    for j in [t[c-1],t[c]]:
      a=min(a,abs(x-i)+abs(i-j),abs(x-j)+abs(j-i))
  print(a)

Submission status: Accepted

Solution code:
from bisect import bisect_right
INF = 10 ** 18
A, B, Q = [int(x) for x in input().split()]
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 x in X:
    ans = INF
    b = bisect_right(S, x)
    d = bisect_right(T, x)
    dist = []
    for s in [S[b-1], S[b]]:
        for t in [T[d-1], T[d]]:
            ans = min(ans, abs(x-s)+abs(s-t), abs(x-t)+abs(t-s))
    print(ans)

Submission status: Accepted

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

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

INF = 10 ** 12
s = [-INF] + [int(input()) for _ in range(A)] + [INF]
t = [-INF] + [int(input()) for _ in range(B)] + [INF]

ret = []
for _ in range(Q) :
    x = int(input())
    spos = bisect_left(s, x)
    tpos = bisect_left(t, x)
    ls, rs = s[spos-1], s[spos]
    lt, rt = t[tpos-1], t[tpos]
    if ls < lt :
        if rs < rt :
            ret.append(min(x-ls, rt-x, min(x-lt, rs-x)+rs-lt))
        else :
            ret.append(min(x-ls, rs-x))
    else :
        if rs < rt :
            ret.append(min(x-lt, rt-x))
        else :
            ret.append(min(x-lt, rs-x, min(x-ls, rt-x)+rt-ls))
    
for r in ret :
    print(r)

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right

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

S.sort()
T.sort()

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

    midS = bisect_right(S, x)
    midT = bisect_right(T, x)

    lS = S[midS - 1]
    rS = S[midS]
    lT = T[midT - 1]
    rT = T[midT]

    dist = min(
        max(rS, rT) - x,
        x - min(lS, lT),
        abs(rS - lT) + min(rS - x, x - lT),
        abs(rT - lS) + min(rT - x, x - lS)
    )

    ans.append(dist)

print(*ans, sep='\n')

Submission status: Accepted

Solution code:
import bisect

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

s=[-2*10**10]+[int(input()) for _ in range(a)]+[2*10**10]
t=[-2*10**10]+[int(input()) for _ in range(b)]+[2*10**10]
x=[int(input()) for _ in range(q)]

for i in range(q):
  j = bisect.bisect_left(s,x[i])
  al = x[i] - s[j-1]
  ar = s[j] - x[i]
  j = bisect.bisect_left(t,x[i])
  bl = x[i] - t[j-1]
  br = t[j] - x[i]
  l = min(max(al, bl), max(ar, br), 2*al+br, 2*ar+bl, 2*bl+ar, 2*br+al)
  print(l)

Submission status: Accepted

Solution code:
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
from bisect import bisect_left, bisect_right
import random
from itertools import permutations, accumulate, combinations
import sys
import string



INF = float('inf')
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.readline().split()
def S(): return sys.stdin.readline().strip()
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 10 ** 9 + 7


a, b, q = LI()
s_list = [-INF] + IR(a) + [INF]
t_list = [-INF] + IR(b) + [INF]
x_list = IR(q)


for x in x_list:
    right_shrine_index = bisect_left(s_list, x)
    left_shrine_index = right_shrine_index - 1
    right_temple_index = bisect_left(t_list, x)
    left_temple_index = right_temple_index - 1
    ret = INF
    ret = min(ret, max(s_list[right_shrine_index], t_list[right_temple_index]) - x)
    ret = min(ret, x - min(s_list[left_shrine_index], t_list[left_temple_index]))
    ret = min(ret, min(s_list[right_shrine_index] - x, x - t_list[left_temple_index]) * 2 + max(s_list[right_shrine_index] - x, x - t_list[left_temple_index]))
    ret = min(ret, min(t_list[right_temple_index] - x, x - s_list[left_shrine_index]) * 2 + max(t_list[right_temple_index] - x, x - s_list[left_shrine_index]))
    print(ret)

Submission status: Accepted

Solution code:
def nibun(D, x):
    return bisect.bisect_left(D, x)  # 場所返す

import bisect
import sys
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
mod = 10**9 + 7
inf = float('inf')
ans = int(0)
A,B,Q =LI()
s = [0]*A
t = [0]*B
x = [0]*Q
for i in range(A):
    s[i] = I()
for i in range(B):
    t[i] = I()
for i in range(Q):
    x[i] = I()

ansy = int(0)
for i in range(Q):
    Scandi = [inf] * 2
    Tcandi = [inf] * 2
    xc = x[i]
    k = nibun(s,xc)
    if k>0:
        Scandi[0] = xc - s[k-1]
    if k<A:
        Scandi[1] = s[k] - xc

    k = nibun(t,x[i])
    if k>0:
        Tcandi[0] = xc - t[k-1]
    if k<B:
        Tcandi[1] = t[k] - xc

    anscandi = []
    for i in range(2):
        anst = Scandi[i]*2 + Tcandi[i-1]
        anscandi.append(anst)
        anst = Scandi[i] + Tcandi[i-1]*2
        anscandi.append(anst)
    anst = max(Scandi[0],Tcandi[0])
    anscandi.append(anst)
    anst = max(Scandi[1],Tcandi[1])
    anscandi.append(anst)


    ans = min(anscandi)
    print(ans)
#    print(anscandi)

Submission status: Accepted

Solution code:
import bisect
a,b,q=map(int,input().split())
s=[]
t=[]
for i in range(a):
    s.append(int(input()))
for i in range(b):
    t.append(int(input()))
for i in range(q):
    x=int(input())
    si=bisect.bisect_left(s,x)
    ti=bisect.bisect_left(t,x)
    if si==a:
        sk=[s[a-1]]
    elif si==0:
        sk=[s[0]]
    else:
        sk=[s[si-1],s[si]]
    if ti==0:
        tk=[t[0]]
    elif ti==b:
        tk=[t[b-1]]
    else:
        tk=[t[ti-1],t[ti]]
    ans=1000000000000
    for f in sk:
        for g in tk:
            ans=min(ans,abs(x-f)+abs(f-g),abs(x-g)+abs(g-f))
    print(ans)

Submission status: Accepted

Solution code:
import bisect

inf = float("inf")
ans = 0

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

S.sort()
T.sort()


for x in X:
    ans = float('inf')
    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-t) + min(abs(x-t), abs(x-s))
            if d1 < ans:
                ans = d1
    print(ans)

Submission status: Accepted

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


def main():
    a,b,q = map(int,readline().split())
    A = [int(readline()) for i in range(a)]
    B = [int(readline()) for i in range(b)]
    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(readline())
        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: Accepted

Solution code:

import bisect

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

S = [int(input()) for i in range(A)]
S.insert(0, -float("inf"))
S.append(float("inf"))

T = [int(input()) for i in range(B)]
T.insert(0, -float("inf"))
T.append(float("inf"))

X = [int(input()) for i in range(Q)]

for x in X:
    ans = float("inf")
    idx_a = bisect.bisect_right(S, x)
    idx_b = bisect.bisect_right(T, x)
    
    for s in [S[idx_a-1], S[idx_a]]:
        for t in [T[idx_b-1], T[idx_b]]:
            temp = abs(s-t) + min(abs(x-s), abs(x-t))
            if temp < ans:
                ans = temp
    print(ans)

Submission status: Accepted

Solution code:
import bisect
from itertools import product

inf=float('inf')
a,b,q=map(int,input().split())
s=[-inf]+[int(input()) for i in range(a)]+[inf]
t=[-inf]+[int(input()) for i in range(b)]+[inf]
x=[int(input()) for i in range(q)]

for i in x:
    ids=bisect.bisect_right(s,i)
    idt=bisect.bisect_right(t,i)
    ans=inf
    for ss,tt in product(s[ids-1:ids+1],t[idt-1:idt+1]):
        check=min(abs(i-ss),abs(i-tt))+abs(ss-tt)
        ans=min(ans,check)
    print(ans)

Submission status: Accepted

Solution code:
# ABC119D - Lazy Faith
from bisect import bisect_right as bsr


def dist(x: int) -> int:
    i, j = bsr(S, x), bsr(T, x)
    ret = min(
        min(abs(s - x) + abs(t - s), abs(t - x) + abs(s - t))
        for s in S[i - 1 : i + 1]
        for t in T[j - 1 : j + 1]
    )
    return ret


def main():
    global S, T
    A, B, Q, *STX = map(int, open(0).read().split())
    INF = 1 << 60
    S, T, X = [-INF] + STX[:A] + [INF], [-INF] + STX[A : A + B] + [INF], STX[A + B :]
    ans = [dist(x) for x in X]
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# ABC119D - Lazy Faith
from bisect import bisect_right as bsr


def dist(x: int) -> int:
    i, j = bsr(S, x), bsr(T, x)
    ret = min(
        min(abs(s - x) + abs(t - s), abs(t - x) + abs(s - t))
        for s in (S[i - 1], S[i])
        for t in (T[j - 1], T[j])
    )
    return ret


def main():
    global S, T
    A, B, Q, *STX = map(int, open(0).read().split())
    INF = 1 << 60
    S, T, X = [-INF] + STX[:A] + [INF], [-INF] + STX[A : A + B] + [INF], STX[A + B :]
    ans = [dist(x) for x in X]
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# ABC119D - Lazy Faith
from bisect import bisect_left as bsl, bisect_right as bsr


def main():
    A, B, Q, *STX = map(int, open(0).read().split())
    INF = 1 << 60
    S, T, X = [-INF] + STX[:A] + [INF], [-INF] + STX[A : A + B] + [INF], STX[A + B :]
    ans = []
    for x in X:
        i, j = bsr(S, x), bsr(T, x)
        dist = min(
            min(abs(s - x) + abs(t - s), abs(t - x) + abs(s - t))
            for s in (S[i - 1], S[i])
            for t in (T[j - 1], T[j])
        )
        ans.append(dist)
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

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)]
x=[int(input()) for _ in range(Q)]
for i in x:
    si = bisect_left(s,i)
    ti = bisect_left(t,i)
    try:
        s1 = s[si-1]
    except:
        s1 = 10**11
    try:
        s0 = s[si]
    except:
        s0 = 10**11
    try:
        t1 = t[ti-1]
    except:
        t1 = 10**11
    try:
        t0 = t[ti]
    except:
        t0 = 10**11
    s0t0=abs(s0-i)+abs(t0-s0)
    s0t1=abs(s0-i)+abs(t1-s0)
    s1t0=abs(s1-i)+abs(t0-s1)
    s1t1=abs(s1-i)+abs(t1-s1)
    t0s0=abs(t0-i)+abs(t0-s0)
    t0s1=abs(t0-i)+abs(t0-s1)
    t1s0=abs(t1-i)+abs(t1-s0)
    t1s1=abs(t1-i)+abs(t1-s1)
    ans = min(s0t0,s0t1,s1t0,s1t1,t0s0,t0s1,t1s0,t1s1)
    print(ans)

Submission status: Accepted

Solution code:
import bisect

A, B, Q = map(int, input().split())
INF = 10 ** 18
s = [-INF] + [int(input()) for i in range(A)] + [INF]
t = [-INF] + [int(input()) for i in range(B)] + [INF]
for q in range(Q):
  x = int(input())
  b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
  res = INF
  for S in [s[b - 1], s[b]]:
    for T in [t[d - 1], t[d]]:
      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:
import bisect
A, B, Q = map(int, input().split())
INF = 10 ** 18
s = [-INF] + [int(input()) for i in range(A)] + [INF]
t = [-INF] + [int(input()) for i in range(B)] + [INF]

for q in range(Q):
    x = int(input())
    b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
    res = INF
    for S in [s[b - 1], s[b]]:
        for T in [t[d - 1], t[d]]:
            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:
import bisect

A,B,Q = map(int,input().split())
shrine = [-float('inf')]+[int(input()) for _ in range(A)]+[float('inf')]
temple = [-float('inf')]+[int(input()) for _ in range(B)]+[float('inf')]
query = [int(input()) for _ in range(Q)]

for q in query:
  s = bisect.bisect(shrine,q)
  t = bisect.bisect(temple,q)
  print(
      min(
        max(shrine[s],temple[t])-q, 
        q - min(shrine[s-1],temple[t-1]),
        (shrine[s]-q)*2+(q-temple[t-1]),
        (temple[t]-q)*2+(q-shrine[s-1]),
        (shrine[s]-q)+(q-temple[t-1])*2,
        (temple[t]-q)+(q-shrine[s-1])*2,
        )
        )

Submission status: Accepted

Solution code:
import bisect
A,B,Q=map(int,input().split())
inf=10**18
s=[-inf]
t=[-inf]
for i in range(A):
  s.append(int(input()))
for i in range(B):
  t.append(int(input()))
s.append(inf)
t.append(inf)

for i in range(Q):
  x=int(input())
  a,b=bisect.bisect(s,x),bisect.bisect(t,x)
  res=inf
  for j in [s[a-1],s[a]]:
    for k in [t[b-1],t[b]]:
      res=min(res,abs(j-x)+abs(k-j),abs(k-x)+abs(k-j))
  print(res)

Submission status: Accepted

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_right
for i in range(q):
  x = X[i]
  s_left = bisect_right(S, x) - 1
  s_right = bisect_right(S, x)
  t_left = bisect_right(T, x) - 1
  t_right = bisect_right(T, x)
  sl = S[s_left]
  sr = S[s_right]
  tl = T[t_left]
  tr = T[t_right]
  #print(X[i], S[s_left], S[s_right], T[t_right], T[t_left])
  l_rr = max(sr - x, tr - x)
  l_ll = max(x - sl, x - tl)
  l_rslt = (sr - x) + (sr - tl)
  l_rtls = (tr - x) + (tr - sl)
  l_lsrt = (x - sl) + (tr - sl)
  l_ltrs = (x - tl) + (sr - tl)
  print(min(l_rr, l_ll, l_rslt, l_rtls, l_lsrt, l_ltrs))

Submission status: Accepted

Solution code:
import bisect
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)


def main():
    A, B, Q = map(int, input().split())
    inf = float('inf')
    S = [-inf] + [int(input()) for _ in range(A)] + [inf]
    T = [-inf] + [int(input()) for _ in range(B)] + [inf]

    for q in range(Q):
        x = int(input())
        i = bisect.bisect_right(S, x)
        j = bisect.bisect_right(T, x)
        d = inf
        for s in [S[i-1], S[i]]:
            for t in [T[j-1], T[j]]:
                d1 = abs(s-x)+abs(s-t)
                d2 = abs(t-x)+abs(s-t)
                d = min(d, d1, d2)
        print(d)


if __name__ == '__main__':
    main()

Submission status: Accepted

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

INF = 10 ** 11
for x in X:
  ids = bisect.bisect_left(S,x)
  if ids == 0:
    sl = -INF
    sr = S[0]
  elif ids == A:
    sl = S[A-1]
    sr = INF
  else:
    sl = S[ids-1]
    sr = S[ids]
  idt = bisect.bisect_left(T,x)
  if idt == 0:
    tl = -INF
    tr = T[0]
  elif idt == B:
    tl = T[B-1]
    tr = INF
  else:
    tl = T[idt-1]
    tr = T[idt]
  print(min(max(x-sl,x-tl),(x-sl)+(tr-sl),(x-tl)+(sr-tl),(tr-x)+(tr-sl),(sr-x)+(sr-tl),max(sr-x,tr-x)))

Submission status: Accepted

Solution code:
import bisect
import itertools

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

# 簡略化のため常に左右に存在するようにしておく
INF = 10 ** 15
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)]

def solve(x):
  # xの位置
  i = bisect.bisect_left(S, x)
  j = bisect.bisect_left(T, x)
  result = INF
  # どの2つを目指すのか
  for s,t in itertools.product(S[i-1:i+1], T[j-1:j+1]):
    d = min(abs(s-x),abs(t-x)) + abs(t-s)
    result = min(result,d)
  return result

for x in X:
  answer = solve(x)
  print(answer)

Submission status: Accepted

Solution code:
import bisect
import itertools

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

for _ in range(Q):
    answer = INF
    x = int(input())
    si = bisect.bisect_left(S, x)    
    ti = bisect.bisect_left(T, x)
    for s, t in itertools.product(S[si-1:si+1], T[ti-1:ti+1]):
        d = min(abs(s-x), abs(t-x)) + abs(t-s)            
        answer = min(answer, d)
    print(answer)

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

for _ in range(Q):
    answer = float('inf')
    x = int(input())
    si = bisect.bisect_left(S, x)    
    ti = bisect.bisect_left(T, x)
    for s in [S[si-1], S[si]]:
        for t in [T[ti-1], T[ti]]:
            d = min(abs(s-x), abs(t-x)) + abs(t-s)            
            answer = min(answer, d)
    print(answer)

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

for _ in range(Q):
    answer = float('inf')
    x = int(input())
    si = bisect.bisect_left(S, x)    
    ti = bisect.bisect_left(T, x)
    for s in [S[si-1], S[si]]:
        for t in [T[ti-1], T[ti]]:
            d1 = abs(s - x) + abs(t - s)
            d2 = abs(t - x) + abs(t - s)
            answer = min(answer, d1, d2)
    print(answer)

Submission status: Accepted

Solution code:
# 二分探索
from bisect import bisect_left

INF = float('inf')

def f(x, s, t):
    result = INF
    i = bisect_left(s, x)
    if i > 0:
        j = bisect_left(t, s[i - 1])
        if j > 0:
            result = min(result, (x - s[i - 1]) + (s[i - 1] - t[j - 1]))
        if j < len(t):
            result = min(result, (x - s[i - 1]) + (t[j] - s[i - 1]))
    if i < len(s):
        j = bisect_left(t, s[i])
        if j > 0:
            result = min(result, (s[i] - x) + (s[i] - t[j - 1]))
        if j < len(t):
            result = min(result, (s[i] - x) + (t[j] - s[i]))
    return result


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

for i in range(Q):
    x = int(input())
    print(min(f(x, s, t), f(x, t, s)))

Submission status: Accepted

Solution code:


import bisect

A, B, Q = map(int, input().split())
S = [-float("inf")]
T = [-float("inf")]
X = []

for i in range(A):
    S.append(int(input()))
S.append(float("inf"))

for i in range(B):
    T.append(int(input()))
T.append(float("inf"))


for i in range(Q):
    X.append(int(input()))

for x in X:
    si = bisect.bisect_left(S, x)
    ti = bisect.bisect_left(T, x)
    
    s01 = [S[si-1], S[si]]
    t01 = [T[ti-1], T[ti]]
    
    ans = float("inf")
    for ss in s01:
        for tt in t01:
            l = abs(ss - tt) + min(abs(ss - x), abs(tt - x))
            ans = min(ans, l)
    print(ans)

Submission status: Accepted

Solution code:
import bisect

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

for _ in range(Q):
    x = int(input())
    si = bisect.bisect_right(S, x)
    ti = bisect.bisect_right(T, x)
    d = INF
    for s in [S[si-1], S[si]]:
        for t in [T[ti-1], T[ti]]:
            d1 = abs(s-x) + abs(t-s)
            d2 = abs(t-x) + abs(s-t)
            d = min(d, d1, d2)
    print(d)

Submission status: Accepted

Solution code:
import bisect

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

S.append(-INF)
S.append(INF)
T.append(-INF)
T.append(INF)

S.sort()
T.sort()

mini = INF

for _ in range(Q):
    x = int(input())
    #スタート地点より右にあって，一番近くにある神社のid
    s1 = bisect.bisect_right(S,x,)
    s2 = s1-1
    #スタート地点より右にあって，一番近くにある寺のid
    t1 = bisect.bisect_right(T,x,)
    t2 = t1-1
    for i in [S[s1],S[s2]]:
        mini = min(mini,abs(x-i)+min(abs(i-T[t1]),abs(i-T[t2])))
    for j in [T[t1],T[t2]]:
        mini = min(mini,abs(x-j)+min(abs(j-S[s1]),abs(j-S[s2])))
    print(mini)
    mini = INF

Submission status: Accepted

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

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