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())
INF = 10**18
shrines = [-INF] + [int(input()) for _ in range(a)] + [INF]
temples = [-INF] + [int(input()) for _ in range(b)] + [INF]

for _ in range(q):

    start = int(input())

    # スタート位置より右にある神社のうち、もっともスタート位置に近いもの
    shrine_east = shrines[bisect.bisect_right(shrines, start)]
    # スタート位置より右にある寺のうち、もっともスタート位置に近いもの
    temple_east = temples[bisect.bisect_right(temples, start)]

    # スタート位置より左にある神社のうち、もっともスタート位置に近いもの
    shrine_west = shrines[bisect.bisect_right(shrines, start) - 1]
    # スタート位置より左にある寺のうち、もっともスタート位置に近いもの
    temple_west = temples[bisect.bisect_right(temples, start) - 1]

    ans = INF

    for shrine in [shrine_east, shrine_west]:
        for temple in [temple_east,temple_west]:
            cur = min(abs(shrine-start), abs(temple-start)) + abs(shrine-temple)
            ans = min(ans,cur)

    print(ans)

Submission status: Accepted

Solution code:
import numpy as np
from bisect import bisect_left

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

def solve(x):

    Si, Ti = bisect_left(S, x), bisect_left(T, x)
    Sw, Se = abs(x-S[Si-1]), abs(x-S[Si])
    Tw, Te = abs(x-T[Ti-1]), abs(x-T[Ti])
    return min(max(Sw, Tw), max(Se, Te), 2*Tw+Se, 2*Sw+Te, 2*Se+Tw, 2*Te+Sw)

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

Submission status: Accepted

Solution code:
import sys
from bisect import bisect
F = sys.stdin
A, B, Q = map(int, F.readline().strip("\n").split(" "))
S, T =[None] * (A+2), [None] * (B+2)
S[0], T[0] = -10**20, -10**20
for i in range(A):
    S[i+1] = int(F.readline().strip("\n"))
for i in range(B):
    T[i+1] = int(F.readline().strip("\n"))
S[A+1] = 10**20
T[B+1] = 10**20
 
lenS, lenT = len(S), len(T)
Out = ""
for _ in range(Q):
    x = int(F.readline().strip("\n"))
    si, ti = bisect(S, x, 0, lenS), bisect(T, x, 0, lenT)
    sLength0, sLength1 = x - S[si-1], S[si] - x
    tLength0, tLength1 = x - T[ti-1], T[ti] - x
    Ans = min(max(sLength0, tLength0), max(sLength1, tLength1), sLength0 + tLength1 + min(sLength0, tLength1), sLength1 + tLength0 + min(sLength1, tLength0))
    Out += str(Ans) + "\n"
print(Out)

Submission status: Accepted

Solution code:
from itertools import product
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()))
  
Xs = sorted(X)

pos = 0
sl, tl = -1e18, -1e18
sr, tr = S[0], T[0]
si, ti, xi = 0, 0, 0 # index

XQ = {} # key=X,value=(x,sl,sr,tl,tr)を格納

for _ in range(int(5e5)):
  pos = min(sr,tr,Xs[xi]) 
  if pos == sr:
    sl = sr
    si += 1
    sr = S[si] if si < A else 1e18
  elif pos == tr:
    tl = tr
    ti += 1
    tr = T[ti] if ti < B else 1e18
  else:
    XQ[Xs[xi]] = [Xs[xi], sl, sr, tl, tr]
    xi += 1
    if xi >= Q:
      break

for i in range(Q):
  x, sl, sr, tl, tr = XQ[X[i]]
  sl, sr, tl, tr = sl-x, sr-x, tl-x, tr-x
  ans = 1e18
  ans = min(ans, abs(sl) + abs(sl-tl))
  ans = min(ans, abs(sl) + abs(sl-tr))
  ans = min(ans, abs(sr) + abs(sr-tl))
  ans = min(ans, abs(sr) + abs(sr-tr))
  ans = min(ans, abs(tl) + abs(tl-sl))
  ans = min(ans, abs(tl) + abs(tl-sr))
  ans = min(ans, abs(tr) + abs(tr-sl))
  ans = min(ans, abs(tr) + abs(tr-sr))
  print(ans)

Submission status: Accepted

Solution code:
A,B,Q = map(int, input().split())
inf = float("inf")
import sys
input = sys.stdin.readline
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)]

from bisect import bisect_left, bisect_right

for q in range(Q):
    x = X[q]

    i = bisect_left(S, x)
    j = bisect_left(T, x)
    left_S , right_S =  x - S[i-1], S[i] - x
    left_T , right_T =  x - T[j-1], T[j] - x

    res = min( 
            max(left_S, left_T),
            left_S + right_T + min(left_S, right_T),
            right_S + left_T + min(right_S, left_T),
            max(right_S, right_T) 
            )
    print(res)

Submission status: Accepted

Solution code:
import bisect

A, B, Q = map(int, input().split())
INF = 10 ** 11
s_list = [-INF] + [int(input()) for i in range(A)] + [INF]
t_list = [-INF] + [int(input()) for i in range(B)] + [INF]
for q in range(Q):
    x = int(input())
    near_right_s = bisect.bisect_right(s_list, x)
    near_right_t = bisect.bisect_right(t_list, x)
    min_distance = INF
    for s in [s_list[near_right_s - 1], s_list[near_right_s]]:
        for t in [t_list[near_right_t - 1], t_list[near_right_t]]:
            distance_1 = abs(s - x) + abs(t - s)
            distance_2 = abs(t - x) + abs(s - t)
            min_distance = min(min_distance, distance_1, distance_2)
    print(min_distance)

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]
s.sort()
t.sort()
answer = []
for i in range(Q):
    x = int(input())
    sk = bisect.bisect_left(s,x)-1
    tk = bisect.bisect_left(t,x)-1
    ptn1 = abs(s[sk]-x) + min(abs(t[tk]-s[sk]),abs(t[tk+1]-s[sk]))
    ptn2 = abs(s[sk+1]-x) + min(abs(t[tk]-s[sk+1]),abs(t[tk+1]-s[sk+1]))
    ptn3 = abs(t[tk]-x) + min(abs(s[sk]-t[tk]),abs(s[sk+1]-t[tk]))
    ptn4 = abs(t[tk+1]-x) + min(abs(s[sk]-t[tk+1]),abs(s[sk+1]-t[tk+1]))
    answer.append(min(ptn1,ptn2,ptn3,ptn4))
for i in answer:
    print(i)

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

for i in range(q):
  j=bisect.bisect_left(s, x[i])
  if j !=0 :
    kyori_hidari = (x[i]-s[j-1])
  else:
    kyori_hidari = float("inf")
  if j !=a :
    kyori_migi = (s[j]-x[i])
  else:
    kyori_migi = float("inf")  
    
  k=bisect.bisect_left(t, x[i])
  if k !=0 :
    kyori_hidari_t = (x[i]-t[k-1])
  else:
    kyori_hidari_t = float("inf")
  if k !=b :
    kyori_migi_t = (t[k]-x[i])
  else:
    kyori_migi_t = float("inf")
 #print(j,k,kyori_hidari,kyori_migi,kyori_hidari_t,kyori_migi_t)
  migi = max(kyori_migi,kyori_migi_t)
  hidari = max(kyori_hidari,kyori_hidari_t)
 #print(migi,hidari)
  print(min(migi,hidari,2*kyori_hidari+kyori_migi_t,2*kyori_hidari_t+kyori_migi,2*kyori_migi+kyori_hidari_t,2*kyori_migi_t+kyori_hidari))

Submission status: Accepted

Solution code:
import bisect
INF = 1000000000000000000

A,B,Q = map(int,input().split())
lA = []
lB = []
lQ = []
lA.append(-INF)
lB.append(-INF)

for i in range(A):
    a = int(input())
    lA.append(a)

for i in range(B):
    b = int(input())
    lB.append(b)

for i in range(Q):
    q = int(input())
    lQ.append(q)

lA.append(INF)
lB.append(INF)
    

for i in lQ:
    ar = bisect.bisect_right(lA,i)
    al = ar - 1

    br = bisect.bisect_right(lB,i)
    bl = br - 1

    ans = INF

    for S in [lA[al],lA[ar]]:
        for T in [lB[bl],lB[br]]:
            d1 = abs(S-i) + abs(T-S)
            d2 = abs(T-i) + abs(S-T)

            ans = min(ans,d1,d2)

    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())
    s=bisect.bisect_right(S,x)
    t=bisect.bisect_right(T,x)
    d=INF
    for i in [S[s-1],S[s]]:
        for j in [T[t-1],T[t]]:
            ds=abs(i-x)+abs(i-j)
            dt=abs(j-x)+abs(i-j)
            d=min(d,ds,dt)
    print(d)

Submission status: Accepted

Solution code:
import sys
import bisect
input = sys.stdin.readline
inf = float("inf")
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 i in range(q):
    x = int(input())
    idx_s = bisect.bisect_left(s, x)
    idx_t = bisect.bisect_left(t, x)

    indices_s = []
    indices_t = []

    indices_s.append(idx_s)
    indices_s.append(idx_s-1)

    indices_t.append(idx_t)
    indices_t.append(idx_t-1)

    ans = []
    for i in indices_s:
        for j in indices_t:
            l, r = min(s[i], t[j]), max(s[i], t[j])
            if x < l:
                ans.append(r-x)
            elif l <= x and x < r:
                ans.append(min(r-l+(x-l), r-l+(r-x)))
            else:
                ans.append(x-l)
    print(min(ans))

Submission status: Accepted

Solution code:
a, b, q = map(int, input().split())
listS = []
listT = []
listAns = []

def nibutan(listA, x):
    minY=0
    maxY=len(listA)-1
    while True:
        middle = (minY+maxY)//2
        if listA[middle] < x:
            if middle == len(listA)-1:
                return listA[middle-1], listA[middle]
                break
            else:
                if x < listA[middle+1] :
                    return listA[middle], listA[middle+1]
                    break
                else:
                    minY = middle
        else:
            if middle==0:
                return listA[middle], listA[middle+1]
                break
            else:
                if listA[middle-1] < x:
                    return listA[middle-1], listA[middle]
                    break
                else:
                    maxY = middle


index=0
while index < a:
    s = int(input())
    listS.append(s)
    index+=1
listS.reverse()
listS.append(-10**11)
listS.reverse()
listS.append(10**11)
index2=0
while index2 < b:
    t = int(input())
    listT.append(t)
    index2+=1
listT.reverse()
listT.append(-10**11)
listT.reverse()
listT.append(10**11)
index3=0
while index3 < q:
    x = int(input())
    #nibutan!
    sa, sb = nibutan(listS, x)
    ta, tb = nibutan(listT, x)
    listDis = [abs(sa-x)+abs(sa-ta), abs(ta-x)+abs(sa-ta), abs(sa-x)+abs(sa-tb), abs(tb-x)+abs(sa-tb),
               abs(sb-x)+abs(sb-ta), abs(ta-x)+abs(sb-ta), abs(sb-x)+abs(sb-tb), abs(tb-x)+abs(sb-tb)]
    minDist = min(listDis)
    listAns.append(minDist)
    index3+=1
for ans in listAns:
    print(ans)

Submission status: Accepted

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

from bisect import bisect_left

for x in X:
    Si,Ti = bisect_left(S,x),bisect_left(T,x)
    Sw,Se = abs(x-S[Si-1]),abs(x-S[Si])
    Tw,Te = abs(x-T[Ti-1]),abs(x-T[Ti])
    print(min(max(Sw,Tw),max(Se,Te),2*min(Sw,Te)+max(Sw,Te),2*min(Tw,Se)+max(Tw,Se)))

Submission status: Accepted

Solution code:
import bisect
import sys

f_inf = float('inf')


def cal(syurui, d, index):
    if d == 'e':
        return syurui[index]
    elif d == 'w':
        return syurui[index - 1]


A, B, Q = map(int, input().split())
s = [int(input()) for i in range(A)]
s.sort()
t = [int(input()) for i in range(B)]
t.sort()
ｓ.insert(0, -f_inf)
t.insert(0, -f_inf)
ｓ.append(f_inf)
t.append(f_inf)

for i in range(Q):
    x = int(sys.stdin.readline().rstrip('\n'))
    s_index = bisect.bisect_left(s, x)
    t_index = bisect.bisect_left(t, x)
    print(min(max(abs(x - s[s_index]), abs(x - t[t_index])), max(abs(x - s[s_index - 1]), abs(x - t[t_index - 1])), 2 * abs(x - s[s_index - 1]) + abs(x - t[t_index]),
              2 * abs(x - s[s_index]) + abs(x - t[t_index - 1]), abs(x - s[s_index - 1]) + 2 * abs(x - t[t_index]), abs(x - s[s_index]) + 2 * abs(x - t[t_index - 1])))

Submission status: Accepted

Solution code:
from bisect import bisect as bi
a,b,q = (int(i) for i in input().split())
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
inf = float("inf")
s,t = [-inf]+s+[inf],[-inf]+t+[inf]
def f(x):
    bs,bt = bi(s,x),bi(t,x)
    return min(x-min(s[bs-1],t[bt-1]),max(s[bs],t[bt])-x,t[bt]-s[bs-1]+min(t[bt]-x,x-s[bs-1]),s[bs]-t[bt-1]+min(s[bs]-x,x-t[bt-1]))
for i in range(q):
    x = int(input())
    print(f(x))

Submission status: Accepted

Solution code:
import sys
import bisect
A,B,Q = [int(n) for n in input().split()]
# N = int(input())
INF = 10 **18
s = [0]*A
t = [0]*B
s = [-INF] + [int(input()) for n in range(A)] + [INF]
t = [-INF] + [int(input()) for n in range(B)] + [INF]

for i 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:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 2019/2/24
Solved on 2019/2/24-25
@author: shinjisu
"""


# ABC 119
def getInt(): return int(input())


def getIntList(): return [int(x) for x in input().split()]


def zeros(n): return [0]*n


def getIntLines(n): return [int(input()) for i in range(n)]


def getIntMat(n):
    mat = []
    for i in range(n):
        mat.append(getIntList())
    return mat


# def zeros2(n, m): return [zeros(m)]*n
def zeros2(n, m):
    d2 = zeros(n)
    for i in range(n):
        d2[i] = zeros(m)
    return d2


ALPHABET = [chr(i+ord('a')) for i in range(26)]
DIGIT = [chr(i+ord('0')) for i in range(10)]
N1097 = 10**9 + 7
INF = 10**12


def dmp(x, cmt=''):
    global debug
    if debug:
        if cmt != '':
            print(cmt, ':  ', end='')
        print(x)
    return x


# valをlstにあるか lstは昇順にソートされている必要がある
# 一致する場合は添え字を返す しない場合は区間を構成する要素の大きい方の添え字
# [0]より小さい場合は0、[n-1]より大きい場合はnを通知する
def lookup_v1(val, lst):
    #dmp((val, lst),'lookup')
    for i in range(len(lst)):
        if val <= lst[i]:
            return i
    else:
        return len(lst)


def solve_v1(pos):
    global S, T
    dmp(pos,'pos')
    minD = INF
    # 神社->寺
    i1 = lookup(pos, S)
    i2 = lookup(S[i1-1], T)
    d1 = abs(T[i2-1]-S[i1-1]) + abs(S[i1-1]-pos)
    d2 = abs(T[i2]-S[i1-1]) + abs(S[i1-1]-pos)
    minD = min(minD, d1, d2)
    dmp(minD,'minD')
    i2 = lookup(S[i1], T)
    d1 = abs(T[i2-1]-S[i1]) + abs(S[i1]-pos)
    d2 = abs(T[i2]-S[i1]) + abs(S[i1]-pos)
    minD = min(minD, d1, d2)
    dmp(minD,'minD')
    # 寺->神社
    i1 = lookup(pos, T)
    i2 = lookup(T[i1-1], S)
    d1 = abs(S[i2-1]-T[i1-1]) + abs(T[i1-1]-pos)
    d2 = abs(S[i2]-T[i1-1]) + abs(T[i1-1]-pos)
    minD = min(minD, d1, d2)
    dmp(minD,'minD')
    i2 = lookup(T[i1], S)
    d1 = abs(S[i2-1]-T[i1]) + abs(T[i1]-pos)
    d2 = abs(S[i2]-T[i1]) + abs(T[i1]-pos) 
    minD = min(minD, d1, d2)
    dmp(minD,'minD')
    return minD


# v2
def getMinDist_v2(level, pos, ST, TS):
    dmp((level,pos),'level,pos')
    if level == 2:
        return INF
    minD = INF
    # 神社->寺
    is1, is2 = lookup(pos, ST)
    it1, it2 = lookup(ST[is1], TS)
    d1 = abs(TS[it1]-ST[is1]) + abs(ST[is1]-pos)
    d2 = abs(TS[it2]-ST[is1]) + abs(ST[is1]-pos)
    minD = min(minD, d1, d2)
    dmp(minD,'minD')
    if is1 != is2:
        dmp(is2, 'is2')
        it1, it2 = lookup(ST[is2], TS)
        d1 = abs(TS[it1]-ST[is2]) + abs(ST[is2]-pos)
        d2 = abs(TS[it2]-ST[is2]) + abs(ST[is2]-pos)
        minD = min(minD, d1, d2)
        dmp(minD,'minD')
    return min(minD, getMinDist(level+1, pos, TS, ST))


def solve_v2(pos):
    global S, T
    return getMinDist(0, pos, S, T)


# バイナリサーチ 区間を返す
def lookup(val, lst):
    dmp((val, lst), 'lookup')
    left = 0
    right = len(lst) - 1
    if val < lst[0]:
        return 0, 0
    elif val > lst[-1]:
        return len(lst)-1, len(lst)-1
    while left+1 < right:
        mid = (left+right) // 2
        if val <= lst[mid]:
            right = mid
        else:
            left = mid
    dmp((left, right))
    return left, right


def getMinDist(level, pos, ST, TS):
    dmp((level,pos),'level,pos')
    if level == 2:
        return INF
    minD = INF
    # 神社->寺
    d1 = abs(TS[it1]-ST[is1]) + abs(ST[is1]-pos)
    d2 = abs(TS[it2]-ST[is1]) + abs(ST[is1]-pos)
    minD = min(minD, d1, d2)
    dmp(minD,'minD')
    if is1 != is2:
        dmp(is2, 'is2')
        d1 = abs(TS[it1]-ST[is2]) + abs(ST[is2]-pos)
        d2 = abs(TS[it2]-ST[is2]) + abs(ST[is2]-pos)
        minD = min(minD, d1, d2)
        dmp(minD,'minD')
    return min(minD, getMinDist(level+1, pos, TS, ST))


def solve(pos):
    is1, is2 = lookup(pos, S)
    it1, it2 = lookup(pos, T)
    minD = INF
    d1 = abs(T[it1]-S[is1]) + abs(S[is1]-pos)
    d2 = abs(T[it2]-S[is1]) + abs(S[is1]-pos)
    d3 = abs(T[it1]-S[is2]) + abs(S[is2]-pos)
    d4 = abs(T[it2]-S[is2]) + abs(S[is2]-pos)
    d5 = abs(S[is1]-T[it1]) + abs(T[it1]-pos)
    d6 = abs(S[is2]-T[it1]) + abs(T[it1]-pos)
    d7 = abs(S[is1]-T[it2]) + abs(T[it2]-pos)
    d8 = abs(S[is2]-T[it2]) + abs(T[it2]-pos)
    minD = min(minD, d1, d2, d3, d4, d5, d6, d7, d8)

    dmp(minD)
    return minD


def probD():
    global S, T
    A, B, Q = getIntList()
    S = getIntLines(A)
    T = getIntLines(B)
    X = getIntLines(Q)
    dmp((A, B, Q), 'A, B, Q')
    dmp(S,'S')
    dmp(T,'T')
    dmp(X,'X')
    S = [-INF] + S + [INF]
    T = [-INF] + T + [INF]
    for x in X:
        print(solve(x))
    return ''


debug = False  # True False
print(probD())


def probA():
    S = input()
    dmp(S)
    y = int(S[0:4])
    m = int(S[5:7])
    d = int(S[8:10])
    dmp((y,m,d))
    HEI = 'Heisei'
    if y <= 2018:
        return HEI
    if m <= 4:
        return HEI
    else:
        return 'TBD'


def probB():
    N = getInt()
    dmp(N)
    sm = 0.0
    for i in range(N):
        x, u = [a for a in input().split()]
        dmp((x,u))
        if u == 'JPY':
            x = int(x)
        else:
            x = float(x) * 380000.0
        sm += x
    return sm


# 多重ループを再帰で実現
def loop(level, a, b, c, mp):
    global N, L, A, B, C, minMP
    if level == N:
        if min(a, b, c) == 0:
            return INF
        mp += abs(A-a) + abs(B-b) + abs(C-c) - 30  # 一本目にはMP不要
        dmp((minMP, mp), 'min, MP')
        minMP = min(minMP,mp)
        return minMP
    else:
        mp0 = loop(level+1, a, b, c, mp)
        mp1 = loop(level+1, a+L[level], b, c, mp+10)
        mp2 = loop(level+1, a, b+L[level], c, mp+10)
        mp3 = loop(level+1, a, b, c+L[level], mp+10)
        dmp((mp0, mp1, mp2, mp3))
        return min(mp0, mp1, mp2, mp3)


# 96msec
def probC():
    global N, L, A, B, C, minMP

    N, A, B, C = getIntList()
    L = []
    for i in range(N):
        L.append(getInt())
    dmp((N, A, B, C ))
    dmp(L)
    d = zeros(3)
    d = A, B, C
    dmp(d)
    minMP = INF
    return loop(0, 0, 0, 0, 0)


def gen2Bits(n):  # n個の0/1/2/3のリストを生成　[0]から変化
    bits = zeros(n)
    for i in range(4**n):
        for k in range(n):
            bits[k] = i % 4
            i //= 4
        yield bits


# 436msec
def probC_v2():
    N, A, B, C = getIntList()
    L = []
    for i in range(N):
        L.append(getInt())
    dmp((N, A, B, C))
    dmp(L)
    d = zeros(3)
    d = A, B, C
    dmp(d)
    minMP = INF
    for f in gen2Bits(N):
        dmp(f)
        mp = 0
        lg = zeros(4)
        for i in range(N):
            if lg[f[i]] > 0 and f[i] < 3:
                mp += 10
            lg[f[i]] += L[i]
            #dmp((i,lg,mp))
        #dmp(lg)
        if min(lg[:3]) == 0:  # 4番目は使用しない竹
            continue
        for i in range(3):
            mp += abs(lg[i]-d[i])
        dmp((minMP, mp), 'min, MP')
        minMP = min(minMP, mp)
    return minMP


def probC_v1():
    N, A, B, C = getIntList()
    L = []
    for i in range(N):
        L.append(getInt())
    dmp((N, A, B, C))
    dmp(L)
    d = zeros(3)
    d[0] = A
    d[1] = B
    d[2] = C
    dmp(d)
    minMP = INF
    for f in gen2Bits(N):
        dmp(f)
        mp = 0
        lg = zeros(4)
        for i in range(N):
            if lg[f[i]] > 0 and f[i] < 3:
                mp += 10
            lg[f[i]] += L[i]
            #dmp((i,lg,mp))
        #dmp(lg)
        allUsed = True
        for i in range(3):  # 4番目は使用しない竹
            if lg[i] == 0:
                allUsed = False
                break
            mp += abs(lg[i]-d[i])
        if not allUsed:
            continue
        dmp((minMP, mp))
        minMP = min(minMP, mp)
    return minMP

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
a,b,q = map(int, sys.stdin.readline().split())
S = []
for _ in range(a):
  S.append(int(sys.stdin.readline()))
T = []
for _ in range(b):
  T.append(int(sys.stdin.readline()))
X = []
for _ in range(q):
  X.append(int(sys.stdin.readline()))

INF = 10 ** 11
def dfs(direction, tors, pos, count):
  if tors == 1:
    L = T
  elif tors == -1:
    L = S
  i = bisect_left(L, pos)
  if i == len(L):
    if direction == 1:
      return INF
    elif direction == -1:
      res = abs(L[i-1]-pos)
      next_pos = L[i-1]
  elif L[i] == pos:
    res = 0
    next_pos = pos
  else:
    if direction == 1:
      res = abs(L[i]-pos)
      next_pos = L[i]
    elif direction == -1:
      if i == 0:
        return INF

      res = abs(L[i-1]-pos)
      next_pos = L[i-1]

  if count == 1:
    return res

  res0 = res + dfs(direction, tors*(-1), next_pos, count-1)
  res1 = res + dfs(direction*(-1), tors*(-1), next_pos, count-1)

  return min(res0, res1)

for x in X:
  res0 = dfs(1, 1, x, 2)
  res1 = dfs(-1, 1, x, 2)
  res2 = dfs(1, -1, x, 2)
  res3 = dfs(-1, -1, x, 2)

  sys.stdout.write('{}\n'.format(min(res0, res1, res2, res3)))

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
a,b,q = map(int, sys.stdin.readline().split())
S = []
for _ in range(a):
  S.append(int(sys.stdin.readline()))
T = []
for _ in range(b):
  T.append(int(sys.stdin.readline()))
X = []
for _ in range(q):
  X.append(int(sys.stdin.readline()))

INF = 10 ** 11
def dfs(direction, tors, pos, count):
  if tors == 1:
    L = T
  elif tors == -1:
    L = S
  i = bisect_left(L, pos)
  if i == len(L):
    if direction == 1:
      return INF
    elif direction == -1:
      res = abs(L[i-1]-pos)
      next_pos = L[i-1]
  elif L[i] == pos:
    res = 0
    next_pos = pos
  else:
    if direction == 1:
      res = abs(L[i]-pos)
      next_pos = L[i]
    elif direction == -1:
      if i == 0:
        return INF

      res = abs(L[i-1]-pos)
      next_pos = L[i-1]

  if count == 1:
    return res

  res0 = res + dfs(direction, tors*(-1), next_pos, count-1)
  res1 = res + dfs(direction*(-1), tors*(-1), next_pos, count-1)

  return min(res0, res1)

for x in X:
  res0 = dfs(1, 1, x, 2)
  res1 = dfs(-1, 1, x, 2)
  res2 = dfs(1, -1, x, 2)
  res3 = dfs(-1, -1, x, 2)

  print(min(res0, res1, res2, res3))

Submission status: Accepted

Solution code:
import bisect

INF = 2 ** 60

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

Submission status: Accepted

Solution code:
import bisect

A,B,Q = map(int,input().split())
INF = 10**12
S = [-INF]+[int(input()) for i in range(A)]+[INF]
T = [-INF]+[int(input()) for i in range(B)]+[INF]
for i in range(Q) :
    x = int(input())
    
    right_s = S[bisect.bisect_right(S,x)]
    right_t = T[bisect.bisect_right(T,x)]
    left_s = S[bisect.bisect_right(S,x) - 1]
    left_t = T[bisect.bisect_right(T,x) - 1]
    
    dist = []
    
    for i in [left_s,right_s] :
        for j in [left_t,right_t] :
            d = min(abs(x-i), abs(x-j)) + abs(i-j)
            dist.append(d)
    ans = min(dist)
    
    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]
loc = [int(input()) for i in range(Q)]
for i in range(len(loc)):
    x = loc[i]
    res = INF
    s_w, t_w = bisect.bisect_right(s,x), bisect.bisect_right(t,x)
    d1 = abs(s[s_w]-x) + abs(t[t_w]-s[s_w])
    d2 = abs(t[t_w]-x) + abs(s[s_w]-t[t_w])
    d3 = abs(s[s_w]-x) + abs(t[t_w-1]-s[s_w])
    d4 = abs(t[t_w-1]-x) + abs(t[t_w-1]-s[s_w])
    d5 = abs(s[s_w-1]-x) + abs(t[t_w]-s[s_w-1])
    d6 = abs(t[t_w]-x) + abs(s[s_w-1]-t[t_w])
    d7 = abs(s[s_w-1]-x) + abs(t[t_w-1]-s[s_w-1])
    d8 = abs(t[t_w-1]-x) + abs(s[s_w-1]-t[t_w-1])
    print(min(d1,d2,d3,d4,d5,d6,d7,d8))

Submission status: Accepted

Solution code:
def search(x, l, first, end):
    if end-first<=1:
        if x<l[first]:
            return -1
        elif x>l[end]:
            return end
        else:
            return first
    middle = (first+end)//2
    if x >= l[middle]:
        return search(x, l, middle, end)
    else:
        return search(x, l, first, middle)
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]
s.sort()
t.sort()
answer = []
for i in range(Q):
    x = int(input())
    sk = search(x,s,0,A)
    tk = search(x,t,0,B)
    ptn1 = abs(s[sk]-x) + min(abs(t[tk]-s[sk]),abs(t[tk+1]-s[sk]))
    ptn2 = abs(s[sk+1]-x) + min(abs(t[tk]-s[sk+1]),abs(t[tk+1]-s[sk+1]))
    ptn3 = abs(t[tk]-x) + min(abs(s[sk]-t[tk]),abs(s[sk+1]-t[tk]))
    ptn4 = abs(t[tk+1]-x) + min(abs(s[sk]-t[tk+1]),abs(s[sk+1]-t[tk+1]))
    answer.append(min(ptn1,ptn2,ptn3,ptn4))
for i in answer:
    print(i)

Submission status: Accepted

Solution code:
import bisect as bi
a, b, q = map(int, input().split())
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
u = [int(input()) for i in range(q)]

for x in u:
    c = []
    d = []
    tmp = bi.bisect_left(s, x)
    if tmp != a : c.append(s[tmp])
    if tmp != 0 : c.append(s[tmp-1])
    tmp = bi.bisect_left(t, x)
    if tmp != b : d.append(t[tmp])
    if tmp != 0 : d.append(t[tmp-1])
    ans = 2**64
    for e in c:
        for f in d:
            g = abs(x-e)
            h = abs(x-f)
            if (x-e)*(x-f) > 0:
                ans = min(ans, max(g, h))
            else:
                if g > h : g,h = h,g
                ans = min(ans, 2*g+h)
    print(ans)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
input=sys.stdin.readline
a,b,q=map(int,input().split())
S=[int(input()) for _ in range(a)]
T=[int(input()) for _ in range(b)]
X=[int(input()) for _ in range(q)]
INF=float('inf')
S=[-INF]+S+[INF]
T=[-INF]+T+[INF]
for x in X:
    s_e_idx=bisect_left(S,x)
    s_e,s_w=S[s_e_idx],S[s_e_idx-1]
    t_e_idx=bisect_left(T,x)
    t_e,t_w=T[t_e_idx],T[t_e_idx - 1]
    d=INF
    for s in [s_w,s_e]:
        for t in [t_w,t_e]:
            d_st=abs(s-x)+abs(t-s)
            d_ts=abs(t-x)+abs(s-t)
            d=min(d,d_st,d_ts)
    print(d)

Submission status: Accepted

Solution code:
A, B, Q = map(long, raw_input().split())
S = [long(raw_input()) for _ in range(A)]
T = [long(raw_input()) for _ in range(B)]
X = [long(raw_input()) for _ in range(Q)]
INF = 10**11

def meguru_bs(array, x):
  left = -1
  right = len(array)
  while right - left>1:
    mid = (left+right) / 2
    if array[mid] >= x:
      right = mid
    else:
      left = mid
  return right

for x in X:
  s_right = meguru_bs(S, x)
  s_nearests = [s_right-1, s_right]
  t_right = meguru_bs(T, x)
  t_nearests = [t_right-1, t_right]
  ans = INF
  for s in s_nearests:
    if s < 0 or s >= A:
      continue
    for t in t_nearests:
      if t < 0 or t >= B:
        continue
      ans = min(ans, abs(S[s]-x)+abs(T[t]-S[s]),abs(T[t]-x)+abs(S[s]-T[t]))
  print ans

Submission status: Accepted

Solution code:
A, B, Q = map(long, raw_input().split())
S = [long(raw_input()) for _ in range(A)]
T = [long(raw_input()) for _ in range(B)]
X = [long(raw_input()) for _ in range(Q)]
INF = 10**11
S = [-INF]+S+[INF]
T = [-INF]+T+[INF]

def meguru_bs(array, x):
  left = 0 #array[0:left] < x
  right = len(array)-1 #array[right:] >= x
  while right - left>1:
    mid = (left+right) / 2
    if array[mid] >= x:
      right = mid
    else:
      left = mid
  return right

for x in X:
  s_right = meguru_bs(S, x)
  s_nearests = [s_right-1, s_right]
  t_right = meguru_bs(T, x)
  t_nearests = [t_right-1, t_right]
  ans = INF
  for s in s_nearests:
    for t in t_nearests:
      ans = min(ans, abs(S[s]-x)+abs(T[t]-S[s]),abs(T[t]-x)+abs(S[s]-T[t]))
  print ans