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
input=sys.stdin.readline

a,b,q=map(int,input().split())
A=[]
for i in range(a):
    A.append(int(input()))
B=[]
for i in range(b):
    B.append(int(input()))
Q={}
for i in range(q):
    Q[int(input())]=i
X=sorted(Q)

C=[]
now=0
for i in range(a):
    while now<b and A[i]>=B[now]:
        now+=1
    if now==0:
        C.append(abs(A[i]-B[0]))
    elif now==b:
        C.append(abs(A[i]-B[b-1]))
    else:
        C.append(min(abs(A[i]-B[now-1]),abs(A[i]-B[now])))
D=[]
now=0
for i in range(b):
    while now<a and B[i]>=A[now]:
        now+=1
    if now==0:
        D.append(abs(B[i]-A[0]))
    elif now==a:
        D.append(abs(B[i]-A[a-1]))
    else:
        D.append(min(abs(B[i]-A[now-1]),abs(B[i]-A[now])))

Y=[]
now=0
for i in range(q):
    while now<b and X[i]>=B[now]:
        now+=1
    if now==0:
        Y.append(abs(X[i]-B[0])+D[0])
    elif now==b:
        Y.append(abs(X[i]-B[b-1])+D[b-1])
    else:
        Y.append(min(abs(X[i]-B[now-1])+D[now-1],
                     abs(X[i]-B[now])+D[now]))
Z=[]
now=0
for i in range(q):
    while now<a and X[i]>=A[now]:
        now+=1
    if now==0:
        Z.append(abs(X[i]-A[0])+C[0])
    elif now==a:
        Z.append(abs(X[i]-A[a-1])+C[a-1])
    else:
        Z.append(min(abs(X[i]-A[now-1])+C[now-1],
                     abs(X[i]-A[now])+C[now]))
        
Ans=[0]*q
for i in range(q):
    x=Q[X[i]] #番号
    Ans[x]=min(Y[i],Z[i])
for ans in Ans:
    print(ans)

Submission status: Accepted

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

S = [0]*A
for i in range(A):
  S[i] = int(input())

T = [0]*B
for i in range(B):
  T[i] = int(input())

import bisect
ans = []
for i in range(Q):
  mini = 10**11
  x = int(input())
  indS = bisect.bisect(S,x)
  indT = bisect.bisect(T,x)
  if indS != A: #Sの右
    if indT != B:
        mini = min(max(S[indS],T[indT])-x,mini) #右右
        # print('rr',mini)
    if indT != 0:
        mini = min(S[indS]-T[indT-1]+min(S[indS]-x,x-T[indT-1]),mini) #右左
        # print('rl',mini)
  if indS != 0: #Sの左
    if indT != B:
        mini = min(T[indT]-S[indS-1]+min(x-S[indS-1],T[indT]-x),mini)  #左右
        # print('lr',mini)
    if indT != 0:
        mini = min(x-min(S[indS-1],T[indT-1]),mini) #左左
        # print('ll',mini)
  ans.append(mini)



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

Submission status: Accepted

Solution code:
import bisect
a,b,q=map(int,input().split())
A=[-1*(10**12)]
B=[-1*(10**12)]
for i in range(a):
    A.append(int(input()))
for i in range(b):
    B.append(int(input()))

A.append(10**12)
B.append(10**12)

for i in range(q):
    x=int(input())
    ia=bisect.bisect_right(A,x)

    ms=A[ia-1]
    ps=A[ia]
    
    ib=bisect.bisect_right(B,x)
    
    mt=B[ib-1]
    pt=B[ib]
        
    ans=min(x-min(ms,mt),max(ps,pt)-x,(ps-mt)+min(ps-x,x-mt),(pt-ms)+min(pt-x,x-ms))
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_right
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]
X = [int(input()) for _ in range(Q)]
for x in X:
    b, d =  bisect_right(S, x), bisect_right(T, x)
    ans = INF
    for s in [S[b - 1], S[b]]:
        for t in [T[d - 1], T[d]]:
            d1, d2 = abs(s - x) + abs(s - t), abs(t - x) + abs(s - t)
            ans = min(ans, d1, d2)
    print(ans)

Submission status: Accepted

Solution code:
import bisect
import itertools

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

def solve(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) # tがsとxの間に入るか否か
    result = min(result,d)
  return result

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

Submission status: Accepted

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

import bisect

def main():
    a, b, q = map(int, input().split())
    huge = 10 ** 18
    s = [-huge] + [int(input()) for i in range(a)] + [huge]
    t = [-huge] + [int(input()) for i in range(b)] + [huge]
    for i in range(q):
        x = int(input())
        b = bisect.bisect_right(s, x)
        d = bisect.bisect_right(t, x)
        res = huge
        for sh in s[b - 1:b + 1]:
            for te in t[d - 1:d + 1]:
                d1 = abs(sh - x) + abs(sh - te)
                d2 = abs(te - x) + abs(sh - te)
                res = min(res, d1, d2)
        print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import bisect
a,b,q = map(int,input().split())
s = [int(input()) for _ in range(a)]
t = [int(input()) for _ in range(b)]
for i in range(q):
    x = int(input())
    index1 = bisect.bisect(s,x)
    index2 = bisect.bisect(t,x)
    cands = []
    if index1 != 0:
        sl = x-s[index1-1]
    if index1 != a:
        sr = s[index1]-x
    if index2 != 0:
        tl = x-t[index2-1]
    if index2 != b:
        tr = t[index2]-x
    if index1 != 0:
        if index2 != 0:
            cands.append(max(sl,tl))
        if index2 != b:
            cands.append(sl*2+tr)
            cands.append(tr*2+sl)
    if index1 != a:
        if index2 != 0:
            cands.append(sr*2+tl)
            cands.append(sr+tl*2)
        if index2 != b:
            cands.append(max(sr,tr))
    print(min(cands))

Submission status: Accepted

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby
    #from itertools import product
    from bisect import bisect_left,bisect_right
    import heapq
    from math import floor, ceil
    #from operator import itemgetter

    #inf = 10**17
    #mod = 10**9 + 7

    a,b,q = map(int, input().split())
    s = [int(input()) for _ in range(a)] + [-10**20, 10**20]
    t = [int(input()) for _ in range(b)] + [-10**20, 10**20]
    s.sort()
    t.sort()

    for _ in range(q):
        pos = int(input())
        l_s = bisect_left(s, pos)
        l_t = 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)

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)]
t=[int(input()) for i in range(b)]
s.sort()
t.sort()
for _ in range(q):
  x=int(input())
  idx1=bisect.bisect_left(s,x)
  idx2=bisect.bisect_left(t,x)
  d=[]
  if idx1<a and idx2<b:
    d.append(max(s[idx1]-x,t[idx2]-x))
  if 1<=idx1 and 1<=idx2:
    d.append(max(x-s[idx1-1],x-t[idx2-1]))
  if 1<=idx1 and idx2<b:
    d.append((t[idx2]-x)*2+x-s[idx1-1])
    d.append((x-s[idx1-1])*2+t[idx2]-x)
  if idx1<a and 1<=idx2:
    d.append((s[idx1]-x)*2+x-t[idx2-1])
    d.append((x-t[idx2-1])*2+s[idx1]-x)
  print(min(d))

Submission status: Accepted

Solution code:
import sys
from bisect import *
from heapq import *
from collections import *
from itertools import *
from functools import *
from math import *
from fractions import *

sys.setrecursionlimit(100000000)
input = lambda: sys.stdin.readline().rstrip()

def main():
    A, B, Q = map(int, input().split())
    s, t = [], []
    for _ in range(A):
        s.append(int(input()))
    for _ in range(B):
        t.append(int(input()))
    for _ in range(Q):
        x = int(input())
        i = bisect_left(s, x)
        j = bisect_left(t, x)
        # visit s[i - 1] or s[i]
        # visit t[j - 1] or t[j]
        s_candidates = [s[k] for k in [i - 1, i] if 0 <= k < A]
        t_candidates = [t[k] for k in [j - 1, j] if 0 <= k < B]
        ans = float('inf')
        for s_candidate in s_candidates:
            for t_candidate in t_candidates:
                right = max(x, s_candidate, t_candidate) - x
                left = x - min(x, s_candidate, t_candidate)
                ans = min(ans, min(right, left) * 2 + max(right, left))
        print(ans)






main()

Submission status: Accepted

Solution code:
from bisect import bisect_left
a, b, q = map(int, input().split())
inf = 10**18
shrine = [-inf] + [int(input()) for _ in range(a)] + [inf]
temple = [-inf] + [int(input()) for _ in range(b)] + [inf]

for _ in range(q):
    ans = inf
    x = int(input())
    index_s = bisect_left(shrine, x)
    index_t = bisect_left(temple, x)

    for s in [shrine[index_s-1], shrine[index_s]]:
        for t in [temple[index_t-1], temple[index_t]]:
            ans = min(
                ans,
                abs(x-s) + abs(s-t),
                abs(x-t) + abs(s-t)
            )

    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right
a, b, q = map(int, input().split())
inf = 10**18
shrine = [-inf] + [int(input()) for _ in range(a)] + [inf]
temple = [-inf] + [int(input()) for _ in range(b)] + [inf]

for _ in range(q):
    ans = inf
    x = int(input())
    index_s = bisect_left(shrine, x)
    index_t = bisect_right(temple, x)
    
    for s in [shrine[index_s-1], shrine[index_s]]:
        for t in [temple[index_t-1], temple[index_t]]:
            ans = min(
                ans,
                abs(x-s) + abs(s-t),
                abs(x-t) + abs(s-t)
            )

    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right
a, b, q = map(int, input().split())
inf = 10**18
shrine = [-inf] + [int(input()) for _ in range(a)] + [inf]
temple = [-inf] + [int(input()) for _ in range(b)] + [inf]

for _ in range(q):
    ans = inf
    x = int(input())
    index_s = bisect_left(shrine, x)
    index_t = bisect_right(temple, x)
    for i in range(index_s-1, index_s+1):
        s = shrine[i]
        i_t = index_t
        t0, t1 = temple[i_t-1], temple[i_t]
        ans = min(
            ans,
            abs(x - s) + abs(s - t0),
            abs(x - s) + abs(s - t1),
        )

    for i in range(index_t-1, index_t+1):
        t = temple[i]
        i_s = index_s
        s0 = shrine[i_s - 1]
        s1 = shrine[i_s]
        ans = min(
            ans,
            abs(x - t) + abs(t - s0),
            abs(x - t) + abs(t - s1),
        )

    print(ans)

Submission status: Accepted

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

a=[-float("inf")]
b=[-float("inf")]
for i in range(A):
    a.append(int(input()))
for i in range(B):
    b.append(int(input()))   
a+=[float("inf")]
b+=[float("inf")]

for i in range(Q):
    q = int(input())
    x = bisect.bisect_left(a, q)
    y = bisect.bisect_left(b, q)
    ans = float("inf")
    for j in [a[x-1], a[x]]:
        for k in [b[y-1], b[y]]:
            ans1 = abs(j-q)+abs(j-k)
            ans2 = abs(k-q)+abs(j-k)
            ans = min(ans, ans1, ans2)
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
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 _ in range(q):
    x = int(input())
    i = bisect.bisect_right(s,x)
    j = bisect.bisect_right(t,x)
    d = INF
    for si in [s[i-1],s[i]]:
        for ti in [t[j-1],t[j]]:
            d1 = abs(x-si)+abs(ti-si)
            d2 = abs(x-ti)+abs(ti-si)
            d = min(d,d1,d2)
    print(d)

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)]
x = [int(input()) for _ in range(q)]
s.sort()
t.sort()

import bisect

for i in x:
    s_idx = bisect.bisect_right(s, i)
    ans = 10 ** 18
    if s_idx == 0:
        s_ = [s[0]]
    elif s_idx >= a:
        s_ = [s[-1]]
    else:
        s_ = [s[s_idx], s[s_idx - 1]]
    for j in s_:
        tmp = abs(i - j)
        t_idx = bisect.bisect_right(t, j)
        if t_idx == 0:
            tmp += abs(j - t[0])
        elif t_idx >= b:
            tmp += abs(j - t[-1])
        else:
            tmp += min(abs(j - t[t_idx]), abs(j - t[t_idx - 1]))
        ans = min(tmp, ans)
    
    t_idx = bisect.bisect_right(t, i)
    if t_idx == 0:
        t_ = [t[0]]
    elif t_idx >= b:
        t_ = [t[-1]]
    else:
        t_ = [t[t_idx], t[t_idx - 1]]
    for j in t_:
        tmp = abs(i - j)
        s_idx = bisect.bisect_right(s, j)
        if s_idx == 0:
            tmp += abs(j - s[0])
        elif s_idx >= a:
            tmp += abs(j - s[-1])
        else:
            tmp += min(abs(j - s[s_idx]), abs(j - s[s_idx - 1]))
        ans = min(tmp, ans)
    print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/python
# coding: utf-8
import os
from sys import stdin, stdout

if(os.getenv('__LOCAL__')):
    __dirname = os.path.dirname(__file__)
    __basename = os.path.splitext(os.path.basename(__file__))[0]
    __inputname = './input/' + __basename + '.txt'
    __outputname = './output/' + __basename + '.txt'
    __input_path = os.path.join(__dirname, __inputname)
    __output_path = os.path.join(__dirname, __outputname)
    stdin = open(__input_path)
    # stdout = open(__output_path, "w")

def main():
    A, B, Q = map(int, stdin.readline().rstrip().split(' '))
    s = list()
    t = list()
    s.append(-1e12)
    t.append(-1e12)
    s += [int(stdin.readline()) for _ in range(A)]
    t += [int(stdin.readline()) for _ in range(B)]
    X = [int(stdin.readline()) for _ in range(Q)]
    ansvec = list()
    s.append(1e12)
    t.append(1e12)
    # stdout.write("{}\n".format(s))
    # stdout.write("{}\n".format(t))
    # stdout.write("{}\n".format(X))
    for x in X:
        ls = 0
        rs = A+2
        lt = 0
        rt = B+2
        while(rs-ls>1):
            mids=(ls+rs)//2
            if(s[mids]<=x):
                ls = mids
            else:
                rs = mids

        while(rt-lt>1):
            midt=(lt+rt)//2
            if(t[midt]<=x):
                lt = midt
            else:
                rt = midt

        if(t[lt]<=s[ls] and s[rs]<=t[rt]):
            ans = min(abs(t[lt]-x),abs(t[rt]-x))
        elif(s[ls]<=t[lt] and t[rt]<=s[rs]):
            ans = min(abs(s[ls]-x),abs(s[rs]-x))
        elif(s[ls]<=t[lt] and s[rs]<=t[rt]):
            ans = min(abs(s[ls]-x),abs(t[rt]-x), 2*abs(s[rs]-x)+abs(t[lt]-x), 2*abs(t[lt]-x)+abs(s[rs]-x))
        elif(t[lt]<=s[ls] and t[rt]<=s[rs]):
            ans = min(abs(t[lt]-x),abs(s[rs]-x), 2*abs(s[ls]-x)+abs(t[rt]-x), 2*abs(t[rt]-x)+abs(s[ls]-x))
        ansvec.append(ans)

    for a in ansvec:
        stdout.write("{}\n".format(a))

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 i in range(A)] + [INF]
T = [-INF] + [int(input()) for i in range(B)] + [INF]
for q in range(Q):
  x = int(input())
  i =bisect.bisect_right(S,x)
  j =bisect.bisect_right(T,x)
  d=INF
  for s in [S[i-1],S[i]]:
    for t in [T[j-1],T[j]]:
      d1 = abs(s-x) + abs(s-t)
      d2 = abs(t-x) + abs(s-t)
      d = min(d,d1,d2)
      
  print(d)

Submission status: Accepted

Solution code:
import sys
import bisect

input = sys.stdin.readline


def main():
    A, B, Q = [int(x) for x in input().split()]
    S = [int(input()) for _ in range(A)]
    T = [int(input()) for _ in range(B)]
    for _ in range(Q):
        x = int(input())
        si = bisect.bisect_left(S, x)
        ti = bisect.bisect_left(T, x)
        sl = -float("inf")
        if si != 0:
            sl = S[si - 1]
        sr = float("inf")
        if si != A:
            sr = S[si]
        tl = -float("inf")
        if ti != 0:
            tl = T[ti - 1]
        tr = float("inf")
        if ti != B:
            tr = T[ti]

        tmp1 = max(x - sl, x - tl)
        tmp2 = max(sr, tr) - x
        tmp3 = 2 * (x - sl) + tr - x
        tmp4 = 2 * (x - tl) + sr - x
        tmp5 = x - sl + 2 * (tr - x)
        tmp6 = x - tl + 2 * (sr - x)

        print(min(tmp1, tmp2, tmp3, tmp4, tmp5, tmp6))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# なぜかうまくいかない
import sys, re, os
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from fractions import gcd
from bisect import bisect, bisect_right, bisect_left

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def S_MAP(): return map(str, input().split())
def LIST(): return list(map(int, input().split()))
def S_LIST(): return list(map(str, input().split()))
 
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

A, B, Q = MAP()
S = [INT() for i in range(A)]
T = [INT() for i in range(B)]
X = [INT() for i in range(Q)]
S.insert(0, -INF)
S.append(INF)
T.insert(0, -INF)
T.append(INF)

for x in X:
    s = bisect(S, x)
    t = bisect(T, x)
    # print(s, t)
    # a = min(x - S[s-1], S[s] - x)
    # b = min(x - T[t-1], T[t] - x)
    res = INF
    for a in [S[s-1], S[s]]:
        for b in [T[t-1], T[t]]:
            res = min(res, min(abs(a - x) + abs(b - a), abs(x - b) + abs(b - a)))
    print(res)

Submission status: Accepted

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

INF = 10**18

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]

for _ in range(Q):
    x = int(input())
    si = bisect_left(S,x)
    ti = bisect_left(T,x)
    res = INF
    res = min(res, max(S[si] - x, T[ti] - x))
    res = min(res, max(x - S[si - 1], x - T[ti - 1]))
    res = min(res, x + T[ti] - 2 * S[si - 1])
    res = min(res, -x + 2 * T[ti] - S[si - 1])
    res = min(res, x + S[si] - 2 * T[ti - 1])
    res = min(res, -x + 2 * S[si] - T[ti - 1])
    print(res)

Submission status: Accepted

Solution code:
import bisect

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

for _ in range(Q):
  x = int(input())
  s_ = bisect.bisect_right(S, x)
  t_ = bisect.bisect_right(T, x)
  s_min = x-S[max(s_-1, 0)]
  s_max = S[min(s_, A-1)]-x
  t_min = x-T[max(t_-1, 0)]
  t_max = T[min(t_, B-1)]-x
  #print(s_min, s_max, t_min, t_max)
  if s_min < 0:
    s_min =  3 * 10 ** 10 + 7
  if s_max < 0:
    s_max = 3 * 10 ** 10 + 7
  if t_min < 0:
    t_min = 3 * 10 ** 10 + 7
  if t_max < 0:
    t_max = 3 * 10 ** 10 + 7
  print(min([
    max(s_min, t_min), 
    max(s_max, t_max), 
    s_min + t_max + min(s_min, t_max),
    s_max + t_min + min(s_max, t_min)
  ]))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

A,B,Q = list(map(int, input().rstrip().split()))
s_list = [-10**11] + [int(input().strip()) for _ in range(A)] + [10**11]
t_list = [-10**11] + [int(input().strip()) for _ in range(B)] + [10**11]
x_list = [int(input().strip()) for _ in range(Q)]
#-----

# x_dic={ x : [a1,a2,b1,b2]}
#    距離xに対して、最も近い神社・寺のindexを保存
#      a1(xより西の最寄りの神社)、a2(xより東の最寄りの神社)
#      b1(xより西の最寄りの寺)、  b2(xより東の最寄りの寺)
x_dic={}

x_sort = sorted(x_list)

i_x=0
for i in range(len(s_list) - 1):
    
    while s_list[i] <= x_sort[i_x] <= s_list[i+1]:
        x_dic[x_sort[i_x]] = [i,(i+1)]
        i_x += 1
        
        if i_x > len(x_sort)-1: break
    if i_x > len(x_sort)-1: break
    

i_x=0
for i in range(len(t_list) - 1):
    
    while t_list[i] <= x_sort[i_x] <= t_list[i+1]:
        x_dic[x_sort[i_x]].extend( [i,(i+1)] )
        i_x += 1
        
        if i_x > len(x_sort)-1: break
    if i_x > len(x_sort)-1: break


for x in x_list:
    dist_min=10**11
    
    for s in x_dic[x][0:2]:
        for t in x_dic[x][2:4]:
            diff1 = abs(s_list[s] - x) + abs(t_list[t] - s_list[s])
            diff2 = abs(t_list[t] - x) + abs(s_list[s] - t_list[t])
            dist_min = min(dist_min, diff1, diff2)
    
    print(dist_min)

Submission status: Accepted

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

from bisect import bisect_left
from bisect import bisect_right

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

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

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

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

INF = float('inf')

for x in X:
    index_ls = bisect_left(s,x)
    index_lt = bisect_left(t,x)
    index_rs = bisect_right(s,x)
    index_rt = bisect_right(t,x)
    ans = INF
    right_s = INF
    left_s = -INF
    right_t = INF
    left_t = -INF

    if index_ls < a: right_s = s[index_ls]
    if index_lt < b: right_t = t[index_lt]
    if index_rs > 0: left_s = s[index_rs-1]
    if index_rt > 0: left_t = t[index_rt-1]

    ans1 = max(right_s-x,right_t-x)
    ans2 = max(x-left_s,x-left_t)
    ans3 = right_s-x + right_s-left_t
    ans4 = right_t-x + right_t-left_s
    ans5 = x-left_t + right_s-left_t
    ans6 = x-left_s + right_t-left_s

    print(min(ans1,ans2,ans3,ans4,ans5,ans6))

Submission status: Accepted

Solution code:
import bisect
import itertools
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")
for x_ in x:
  ind_s = bisect.bisect_left(s,x_)
  ind_t = bisect.bisect_left(t,x_)
  s_l = s[ind_s-1] if ind_s > 0 else -INF
  s_r = s[ind_s] if ind_s < a else INF
  t_l = t[ind_t-1] if ind_t > 0 else -INF
  t_r = t[ind_t] if ind_t < b else INF
  ans = INF
  for s_ in [s_l,s_r]:
    for t_ in [t_l,t_r]:
      if abs(s_-x_)>abs(t_-x_):
        sub1,sub2 = t_,s_
      else:
        sub1,sub2 = s_,t_
      ans = min(ans,abs(sub1-x_)+abs(sub1-sub2))
  print(ans)

Submission status: Accepted

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

from bisect import bisect

for i in range(q):
    y=bisect(s,x[i])
    z=bisect(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
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)]

bLeft = bisect.bisect_left

for x in X:
    si = bLeft(S, x)
    sleft = float('inf')
    sright = float('inf')
    if si != 0:
        sleft = x-S[si-1]
    if si != A:
        sright = S[si]-x

    ti = bLeft(T, x)
    tleft = float('inf')
    tright = float('inf')
    if ti != 0:
        tleft = x-T[ti-1]
    if ti != B:
        tright = T[ti]-x

    ans1 = max(sleft, tleft)
    ans2 = max(sright, tright)
    ans3 = min(min(sleft, sright), min(tleft, tright)) + min(sleft, sright) + min(tleft, tright)
    print(min(ans1, ans2, ans3))

Submission status: Accepted

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


def main():
    A, B, Q = map(int, readline().split())
    inf = 10 ** 18
    s = [-inf] + [int(readline()) for _ in range(A)] + [inf]
    t = [-inf] + [int(readline()) for _ in range(B)] + [inf]
    for q in range(Q):
        x = int(readline())
        b, d = bisect.bisect_right(s, x), bisect.bisect_left(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)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
a,b,q=map(int,input().split())
s=[-10**11]
t=[-10**11]
for i in range(a):
	s.append(int(input()))
s.append(10**11)
for i in range(b):
	t.append(int(input()))
t.append(10**11)
import bisect
for i in range(q):
	x=int(input())
	s_l=bisect.bisect_left(s,x)
	t_l=bisect.bisect_left(t,x)
	ans1=x-min(s[s_l-1],t[t_l-1])
	ans2=max(s[s_l],t[t_l])-x
	ans3=min(s[s_l]-x,x-t[t_l-1])+s[s_l]-t[t_l-1]
	ans4=min(t[t_l]-x,x-s[s_l-1])+t[t_l]-s[s_l-1]
	print(min(ans1,ans2,ans3,ans4))

Submission status: Accepted

Solution code:
from bisect import bisect_left

INF = 10 ** 11

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

for e in x:
    si = bisect_left(s, e)
    ti = bisect_left(t, e)

    ans = INF
    for ss in [s[si-1], s[si]]:
        for tt in [t[ti-1], t[ti]]:
            d1 = abs(e - ss) + abs(ss - tt)
            d2 = abs(e - tt) + abs(tt - ss)
            ans = min(ans, d1, d2)

    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left

INF = 10 ** 11

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

for e in x:
    si = bisect_left(s, e)
    ti = bisect_left(t, e)
    sl, sr = s[si-1], s[si]
    tl, tr = t[ti-1], t[ti]

    ans = INF
    ans = min(ans, e - min(sl, tl))
    ans = min(ans, max(sr, tr) - e)
    ans = min(ans, e - sl + tr - sl)
    ans = min(ans, e - tl + sr - tl)
    ans = min(ans, sr - e + sr - tl)
    ans = min(ans, tr - e + tr - sl)

    print(ans)

Submission status: Accepted

Solution code:
def main():
    INF=10**11
    from bisect import bisect_left
    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]

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

Submission status: Accepted

Solution code:
import sys
import bisect
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)]
#print(s,end=" s\n")
#print(t,end=" t\n")
for _ in range(q):
  x=int(input())
  sr=bisect.bisect_left(s,x)
  sr=sr-1 if sr==len(s) else sr
  sl=sr-1 if sr>0 else sr 
  tr=bisect.bisect_left(t,x)
  tr=tr-1 if tr==len(t) else tr
  tl=tr-1 if tr>0 else tr
 # print(sl,sr,tl,tr)
  def f(i,j):
    #print( abs(x-s[i]),abs(x-t[j]))
    return min(abs(x-s[i]),abs(x-t[j]))+abs(t[j]-s[i])
#  print(x)
#  print(f(sl,tl),f(sl,tr),f(sr,tl),f(sr,tr))
  ans=min(f(sl,tl),f(sl,tr),f(sr,tl),f(sr,tr))
  print(ans)

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

for _ in range(q):
  x = int(input())
  s_bi = bisect.bisect_right(S, x)
  t_bi = bisect.bisect_right(T, x)
  s_left = S[s_bi-1] if s_bi>0 else -float("inf")
  s_right = S[s_bi] if s_bi<a else float("inf")
  t_left = T[t_bi-1] if t_bi>0 else -float("inf")
  t_right = T[t_bi] if t_bi<b else float("inf")
  c = x - min(s_left, t_left)
  d = max(s_right, t_right) - x
  e = t_right - s_left + min(x-s_left, t_right-x)
  f = s_right - t_left + min(x-t_left, s_right-x)
  ans = min(c, d, e, f)
  print(ans)

Submission status: Accepted

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

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 _ in range(Q):
    x = int(input())
    i = bisect(s, x)
    j = bisect(t, x)
    ans = INF
    for a in [s[i-1], s[i]]:
        for b in [t[j-1], t[j]]:
            ans = min(ans, abs(a-x)+abs(b-a), abs(b-x)+abs(a-b))
    print(ans)