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:
from bisect import bisect_right
INFTY = 10**11
A,B,Q = map(int,input().split())
S = [int(input()) for _ in range(A)]
S.insert(0,-INFTY)
S.append(INFTY)
T = [int(input()) for _ in range(B)]
T.insert(0,-INFTY)
T.append(INFTY)
for _ in range(Q):
    x = int(input())
    indS = bisect_right(S,x)
    indT = bisect_right(T,x)
    d1 = x-S[indS-1]+abs(S[indS-1]-T[indT-1])
    d2 = x-S[indS-1]+abs(S[indS-1]-T[indT])
    d3 = S[indS]-x+abs(S[indS]-T[indT-1])
    d4 = S[indS]-x+abs(S[indS]-T[indT])
    d5 = x-T[indT-1]+abs(T[indT-1]-S[indS-1])
    d6 = x-T[indT-1]+abs(T[indT-1]-S[indS])
    d7 = T[indT]-x+abs(T[indT]-S[indS-1])
    d8 = T[indT]-x+abs(T[indT]-S[indS])
    print(min(d1,d2,d3,d4,d5,d6,d7,d8))

Submission status: Accepted

Solution code:
def main():
    from bisect import bisect_left
    A, B, Q = map(int, input().split())
    INF = 2 * 10 ** 10
    S = [-INF] + [int(input()) for _ in range(A)] + [INF]
    T = [-INF] + [int(input()) for _ in range(B)] + [INF]
    S_rev = [-s for s in S][::-1]
    T_rev = [-t for t in T][::-1]

    for q in range(Q):
        x = int(input())
        ans = 5 * 10 ** 10

        # Case1: 右に直進
        cost1_s = S[bisect_left(S, x)] - x
        cost1_t = T[bisect_left(T, x)] - x
        ans = min(ans, max(cost1_s, cost1_t))

        # Case2: 左に直進
        cost2_s = S_rev[bisect_left(S_rev, -x)] + x
        cost2_t = T_rev[bisect_left(T_rev, -x)] + x
        ans = min(ans, max(cost2_s, cost2_t))

        # Case3: 右でS、左でT
        cost3_s = S[bisect_left(S, x)] - x
        cost3_t = T_rev[bisect_left(T_rev, -x)] + x
        ans = min(ans, 2 * min(cost3_s, cost3_t) + max(cost3_s, cost3_t))

        # Case4: 右でT、左でS
        cost3_s = S_rev[bisect_left(S_rev, -x)] + x
        cost3_t = T[bisect_left(T, x)] - x
        ans = min(ans, 2 * min(cost3_s, cost3_t) + max(cost3_s, cost3_t))

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

"""
sとtのどちらを先にするか
左右どちらに走るか
の都合4パターンの最小値を選べばよい
"""

def minl(x):
    # sを選択
    idx = bisect.bisect_left(s, x)
    ret = 3*10**10
    if idx == 0:
        first = s[0] - x
        now = s[0]
        idx = bisect.bisect_left(t, now)
        if idx == 0:
            second = t[0] - now
        elif idx == b:
            second = now - t[b-1]
        else:
            second = min(now - t[idx-1], t[idx]-now)
        ret = min(ret, first+second)
    elif idx == a:
        first = x - s[a-1]
        now = s[a-1]
        idx = bisect.bisect_left(t, now)
        if idx == 0:
            second = t[0] - now
        elif idx == b:
            second = now - t[b-1]
        else:
            second = min(now - t[idx-1], t[idx]-now)
        ret = min(ret, first+second)
    else:
        for first_g in [s[idx-1], s[idx]]:
            first = abs(first_g - x)
            now = first_g
            idx = bisect.bisect_left(t, now)
            if idx == 0:
                second = t[0] - now
            elif idx == b:
                second = now - t[b-1]
            else:
                second = min(now - t[idx-1], t[idx]-now)
            ret = min(ret, first+second)
    
    # tを選択
    idx = bisect.bisect_left(t, x)
    if idx == 0:
        first = t[0] - x
        now = t[0]
        idx = bisect.bisect_left(s, now)
        if idx == 0:
            second = s[0] - now
        elif idx == a:
            second = now - s[a-1]
        else:
            second = min(now - s[idx-1], s[idx]-now)
        ret = min(ret, first+second)
    elif idx == b:
        first = x - t[b-1]
        now = t[b-1]
        idx = bisect.bisect_left(s, now)
        if idx == 0:
            second = s[0] - now
        elif idx == a:
            second = now - s[a-1]
        else:
            second = min(now - s[idx-1], s[idx]-now)
        ret = min(ret, first+second)
    else:
        for first_g in [t[idx-1], t[idx]]:
            first = abs(first_g - x)
            now = first_g
            idx = bisect.bisect_left(s, now)
            if idx == 0:
                second = s[0] - now
            elif idx == a:
                second = now - s[a-1]
            else:
                second = min(now - s[idx-1], s[idx]-now)
            ret = min(ret, first+second)
    return ret

for i in range(q):
    x = int(input())
    print(minl(x))

Submission status: Accepted

Solution code:
from bisect import bisect_left
# 初期入力
import sys
input = sys.stdin.readline  #文字列では使わない
A,B,Q = (int(i) for i in input().split())
st ={"s":[],"t":[]}
x =[0] *Q

for i in range(A):
    aa = int(input())
    st["s"].append(aa)
st["s"].append(10**11)

for i in range(B):
    bb = int(input())
    st["t"].append(bb)
st["t"].append(10**11)


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

#2分探索で近い神社と寺を探す
dist =[]
for xi in x:
    #スタート⇒神社
    xs =bisect_left(st["s"],xi)
    s_l =st["s"][xs-1] #スタート地点から近い神社（左）⓵
    s_r =st["s"][xs  ] #スタート地点から近い神社（右）⓶
    xs_l =abs(xi -s_l)  
    xs_r =abs(xi -s_r)    

    xs_l_t =bisect_left(st["t"],s_l ) 
    t_l =st["t"][xs_l_t -1] #⓵から近い寺（左）
    t_r =st["t"][xs_l_t   ] #⓵から近い寺（右）
    xs_l_t_l =abs(s_l -t_l) 
    xs_l_t_r =abs(s_l -t_r) 
    
    xs_r_t =bisect_left(st["t"],s_r ) 
    t_l =st["t"][xs_r_t -1] #⓶から近い寺（左）
    t_r =st["t"][xs_r_t   ] #⓶から近い寺（右）
    xs_r_t_l =abs(s_r -t_l) 
    xs_r_t_r =abs(s_r -t_r)
    ds =min(xs_l +xs_l_t_l ,xs_l +xs_l_t_r ,xs_r +xs_r_t_l ,xs_r +xs_r_t_r)

     #スタート⇒寺
    xs =bisect_left(st["t"],xi)
    s_l =st["t"][xs-1] #スタート地点から近い寺（左）⓷
    s_r =st["t"][xs  ] #スタート地点から近い寺（右）⓸
    xs_l =abs(xi -s_l)  
    xs_r =abs(xi -s_r)    

    xs_l_t =bisect_left(st["s"],s_l ) 
    t_l =st["s"][xs_l_t -1] #⓷から近い神社（左）
    t_r =st["s"][xs_l_t   ] #⓷から近い神社（右）
    xs_l_t_l =abs(s_l -t_l) 
    xs_l_t_r =abs(s_l -t_r) 
    
    xs_r_t =bisect_left(st["s"],s_r ) 
    t_l =st["s"][xs_r_t -1] #⓸から近い神社（左）
    t_r =st["s"][xs_r_t   ] #⓸から近い神社（右）
    xs_r_t_l =abs(s_r -t_l) 
    xs_r_t_r =abs(s_r -t_r)
    dt =min(xs_l +xs_l_t_l ,xs_l +xs_l_t_r ,xs_r +xs_r_t_l ,xs_r +xs_r_t_r)
    print(min(ds,dt))

Submission status: Accepted

Solution code:
import sys
import itertools
# import numpy as np
import time
import math
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)
 
INF = 10 ** 18
MOD = 10 ** 9 + 7
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

# map(int, input().split())

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

def bound(Z, z):
    l = 0
    r = len(Z) - 1
    while r - l > 1:
        m = (l + r) // 2
        if Z[m] >= z:
            r = m
        else:
            l = m
    return r

for x in X:
    s = [0] * 2
    s[0] = bound(S, x)
    s[1] = s[0] - 1

    t = [0] * 2
    t[0] = bound(T, x)
    t[1] = t[0] - 1

    ans = INF
    # print("--------------")
    for i in range(2):
        for j in range(2):
            val = 0
            if x >= S[s[i]] and x >= T[t[j]]:
                val = max(abs(x - S[s[i]]), abs(x - T[t[j]]))
            elif x <= S[s[i]] and x <= T[t[j]]:
                val = max(abs(x - S[s[i]]), abs(x - T[t[j]]))
            else:
                val = min(abs(x - S[s[i]]) * 2 + abs(x - T[t[j]]), abs(x - S[s[i]]) + abs(x - T[t[j]]) * 2)
            ans = min(ans, val)
    # print(x)
    # print(S[s[0]], S[s[1]])
    # print(T[t[0]], T[t[1]])
    # print("--------------")
    print(ans)

    # print(S[s1], S[s2], T[t1], T[t2], T[t3], T[t4])
    # val1 = abs(S[s1] - x) + abs(T[t1] - S[s1])
    # val2 = abs(S[s1] - x) + abs(T[t2] - S[s1])
    # val3 = abs(S[s2] - x) + abs(T[t3] - S[s2])
    # val4 = abs(S[s2] - x) + abs(T[t4] - S[s2])
    # print(min(val1, val2, val3, val4))

Submission status: Accepted

Solution code:
import bisect
a, b, q = map(int, input().split())
ss = [int(input()) for _ in range(a)]
ts = [int(input()) for _ in range(b)]
xs = [int(input()) for _ in range(q)]
ss = [-float('inf')] + ss + [float('inf')]
ts = [-float('inf')] + ts + [float('inf')]
for x in xs:
    s_r = bisect.bisect_left(ss, x)
    t_r = bisect.bisect_left(ts, x)
    s_l = s_r - 1
    t_l = t_r - 1
    res = float('inf')
    if ss[s_l] > ts[t_l]:
        res = min(res, x - ts[t_l], (x - ss[s_l])*2 + (ts[t_r] - x))
    elif ss[s_l] < ts[t_l]:
        res = min(res, x - ss[s_l], (x - ts[t_l])*2 + (ss[s_r] - x))
    else:
        res = min(res, (x - ss[s_l])*2 + (ss[s_r] - x), x - ss[s_l]*2 + (ts[t_r] - x))
    if ss[s_r] > ts[t_r]:
        res = min(res, ss[s_r] - x, (ts[t_r] - x)*2 + (x - ss[s_l]))
    elif ss[s_r] < ts[t_r]:
        res = min(res, ts[t_r] - x, (ss[s_r] - x)*2 + (x - ts[t_l]))
    else:
        res = min(res, (ss[s_r] - x)*2 + (x - ss[s_l]), (ss[s_r] - x)*2 + (x - ts[t_l]))
    print(res)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    a, b, q = map(int, input().split())
    S = [-f_inf] + list(int(input()) for _ in range(a)) + [f_inf]
    T = [-f_inf] + list(int(input()) for _ in range(b)) + [f_inf]

    for _ in range(q):
        res = f_inf
        x = int(input())

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


if __name__ == '__main__':
    resolve()

Submission status: Accepted

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

def main():
    A, B, Q = map(int, input().split())
    s = [int(input()) for _ in range(A)]
    t = [int(input()) for _ in range(B)]
    # print(s,t)
    s = [-10**12] + s + [10**12]
    t = [-10**12] + t + [10**12]

    for _ in range(Q):
        x = int(input())
        i = bisect_right(s,x)
        j = bisect_right(t,x)
        # print(i,j,x)
        ans = []

        ans.append(max(abs(s[i-1] - x), abs(t[j-1] - x)))
        ans.append(max(abs(s[i] - x), abs(t[j] - x)))
        ans.append(abs(s[i-1] - x) + abs(t[j] - x) + min(abs(s[i-1]-x), abs(t[j]-x)))
        ans.append(abs(s[i] - x) + abs(t[j-1] - x) + min(abs(s[i]-x), abs(t[j-1]-x)))

        print(min(ans))

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

for i in x:
    # 神社から先に行くパターン
    idx_s, idx_t = bisect_left(s, i), bisect_left(t, i)
    ans = dummy
    for j in [s[idx_s-1], s[idx_s]]:
        for k in [t[idx_t-1], t[idx_t]]:
            res1, res2 = abs(j - i) + abs(k - j), abs(k - i) + abs(j - k)
            ans = min(ans, res1, res2)
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left
A, B, Q = map(int, input().split())
s = [int(input()) for _ in range(A)]
t = [int(input()) for _ in range(B)]

s.sort()
t.sort()

for k in range(Q):
    x = int(input())
    ans = []
    ms = bisect_left(s, x)
    for i in [-1, 0]:
        if 0 <= ms + i <= A - 1:
            mt = bisect_left(t, s[ms + i])
            for j in [-1, 0]:
                if 0 <= mt + j <= B - 1:
                    ans.append(abs(s[ms + i] - x) + abs(t[mt + j] - s[ms + i]))
    mt = bisect_left(t, x)
    for i in [-1, 0]:
        if 0 <= mt + i <= B - 1:
            ms = bisect_left(s, t[mt + i])
            for j in [-1, 0]:
                if 0 <= ms + j <= A - 1:
                    ans.append(abs(t[mt + i] - x) + abs(s[ms + j] - t[mt + i]))
    print(min(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 sys

def I(): return int(sys.stdin.readline().rstrip())
def LI(): return list(map(int,sys.stdin.readline().rstrip().split()))  #空白あり

A,B,Q = LI()
inf = 10**12
s = [-inf]+[I() for _ in range(A)]+[inf]
t = [-inf]+[I() for _ in range(B)]+[inf]
x = [I() for _ in range(Q)]

from bisect import bisect

# xiより東にある神社・寺の中で最も西にあるもの、xiより西にある神社・寺の中で最も東にあるものだけがあると思えばよい

for i in range(Q):
    y = x[i]
    a = bisect(s,y)
    b = bisect(t,y)
    s1,s2,t1,t2 = s[a-1],s[a],t[b-1],t[b]
    z1 = abs(y-s1)+abs(s1-t1)
    z2 = abs(y-s1)+abs(s1-t2)
    z3 = abs(y-s2)+abs(s2-t1)
    z4 = abs(y-s2)+abs(s2-t2)
    z5 = abs(y-t1)+abs(t1-s1)
    z6 = abs(y-t1)+abs(t1-s2)
    z7 = abs(y-t2)+abs(t2-s1)
    z8 = abs(y-t2)+abs(t2-s2)
    print(min(z1,z2,z3,z4,z5,z6,z7,z8))

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 = sorted(S)
T = sorted(T)

for j in range(Q):
    x = int(input())
    a = S[bisect.bisect_left(S, x)-1]
    b = T[bisect.bisect_left(T, x)-1]
    if x <=S[-1]:
        a_ = S[bisect.bisect_right(S,x)]
    else:
        a_ = S[bisect.bisect_right(S,x)-1]
    if x <= T[-1]:
        b_ = T[bisect.bisect_right(T,x)]
    else:
        b_ = T[bisect.bisect_right(T,x)-1]
    y = min([abs(a-x)+abs(b-a),abs(a-x)+abs(b_-a),abs(a_-x)+abs(b-a_),abs(a_-x)+abs(b_-a_),
            abs(b-x)+abs(a-b),abs(b-x)+abs(a_-b), abs(b_-x)+abs(a-b_), abs(b_-x)+abs(b_-a_)])
    print(y)

Submission status: Accepted

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

a,b,q = map(int,readline().split())
s = [int(readline()) for i in range(a)]
t = [int(readline()) for i in range(b)]

for i in range(q):
  x = int(input())
  ss = bisect(s,x)
  if ss == 0:
    sR = s[0]
    sL = s[0]
  elif ss == len(s):
    sR = s[-1]
    sL = s[-1]
  else:
    sR = s[ss]
    sL = s[ss-1]
    
  sRt = bisect(t,sR)
  sLt = bisect(t,sL)
  if sRt == 0:
    sRtL = t[0]
  else:
    sRtL = t[sRt-1]
  if sLt == len(t):
    sLtR = t[-1]
  else:
    sLtR = t[sLt]
  if sRt == len(t):
    sRtR = t[-1]
  else:
    sRtR = t[sRt]
  if sLt == 0:
    sLtL = t[0]
  else:
    sLtL = t[sLt-1]
  chk = min(abs(x-sL)+abs(sL-sLtL),abs(x-sL)+abs(sL-sLtR),abs(x-sR)+abs(sR-sRtR),abs(x-sR)+abs(sR-sRtL))
  ss = bisect(t,x)
  if ss == 0:
    sR = t[0]
    sL = t[0]
  elif ss == len(t):
    sR = t[-1]
    sL = t[-1]
  else:
    sR = t[ss]
    sL = t[ss-1]
  sRt = bisect(s,sR)
  sLt = bisect(s,sL)
  if sRt == 0:
    sRtL = s[0]
  else:
    sRtL = s[sRt-1]
  if sLt == len(s):
    sLtR = s[-1]
  else:
    sLtR = s[sLt]
  if sRt == len(s):
    sRtR = s[-1]
  else:
    sRtR = s[sRt]
  if sLt == 0:
    sLtL = s[0]
  else:
    sLtL = s[sLt-1]  
  chk = min(chk,abs(x-sL)+abs(sL-sLtL),abs(x-sL)+abs(sL-sLtR),abs(x-sR)+abs(sR-sRtR),abs(x-sR)+abs(sR-sRtL))
  print(chk)

Submission status: Accepted

Solution code:
from bisect import bisect_left
a, b, q = map(int, input().split())
s = []
for _ in range(a):
    s.append(int(input()))
t = []
for _ in range(b):
    t.append(int(input()))
INF = 10**12
for _ in range(q):
    x = int(input())
    s_l = t_l = -INF
    s_r = t_r = INF
    tmp = bisect_left(s, x)
    if tmp>0:
        s_l = s[tmp-1]
    if tmp<a:
        s_r = s[tmp]
    tmp = bisect_left(t, x)
    if tmp>0:
        t_l = t[tmp-1]
    if tmp<b:
        t_r = t[tmp]
    ans = min(
        x-min(s_l, t_l),
        max(s_r, t_r)-x,
        s_r-t_l+min(s_r-x, x-t_l),
        t_r-s_l+min(t_r-x, x-s_l)
    )
    print(ans)

Submission status: Accepted

Solution code:
from bisect import *
A,B,Q=map(int,input().split())
INF=10**15
S=[-INF*10,-INF]
for i in range(A):
  S.append(int(input()))
S.append(INF)
S.append(INF*10)
T=[-INF*10,-INF]
for i in range(B):
  T.append(int(input()))
T.append(INF)
T.append(INF*10)
D,E,F,G,V,W,X,Y,Z,P=0,0,0,0,0,0,0,0,0,0
for i in range(Q):
  X=int(input())
  V=bisect_left(S,X)
  Y,Z=S[V-1],S[V]
  D,E=abs(X-Y),abs(X-Z)
  V,W=bisect_left(T,Y),bisect_left(T,Z)
  F,G=min(abs(Y-T[V-1]),abs(Y-T[V])),min(abs(Z-T[W-1]),abs(Z-T[W]))
  P=min(D+F,E+G)
  V=bisect_left(T,X)
  Y,Z=T[V-1],T[V]
  D,E=abs(X-Y),abs(X-Z)
  V,W=bisect_left(S,Y),bisect_left(S,Z)
  F,G=min(abs(Y-S[V-1]),abs(Y-S[V])),min(abs(Z-S[W-1]),abs(Z-S[W]))
  print(min(P,D+F,E+G))

Submission status: Accepted

Solution code:
import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def k(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def X(): return list(input())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
def gcd(*numbers): reduce(math.gcd, numbers)
sys.setrecursionlimit(10 ** 9)
mod = 10**9+7
count = 0
ans = 0

A, B, Q = I()
inf = float("inf")
s = [-inf]+sorted([k() for _ in range(A)])+[inf]
t = [-inf]+sorted([k() for _ in range(B)])+[inf]
aa = []

for i in range(Q):
    q = k()
    S = bisect.bisect(s,q)
    T = bisect.bisect(t,q)
    ans = inf
    for j in [s[S-1],s[S]]:
        for z in [t[T-1],t[T]]:
            x = abs(j-q)+abs(j-z)
            y = abs(z-q)+abs(j-z)
            ans = min(ans,x,y)
    aa.append(ans)

for i in aa:
    print(i)

Submission status: Accepted

Solution code:
a,b,q=map(int,input().split())
s=[int(input()) for _ in range(a)]
t=[int(input()) for _ in range(b)]
x=[int(input()) for _ in range(q)]
from bisect import bisect_left
for xi in x:
  ans=float('inf')
  si=bisect_left(s,xi)
  ti=bisect_left(t,xi)
  # 東に進むだけ
  if xi<=s[-1] and xi<=t[-1]:
    ans=min(ans,max(s[si]-xi,t[ti]-xi))
  # 西に進むだけ
  if xi>=s[0] and xi>=t[0]:
    ss=0 if si<a and xi-s[si]==0 else xi-s[si-1]
    tt=0 if ti<b and xi-t[ti]==0 else xi-t[ti-1]
    ans=min(ans,max(ss,tt))
    
  # 東に進んだあと西 or 西に進んだあと東
  # 西の神社、東の寺
  if s[0]<=xi and xi<=t[-1]:
    w=xi-s[si-1]
    e=t[ti]-xi
    tmp=2*min(w,e)+max(w,e)
    ans=min(ans,tmp)
  # 西の寺、東の神社
  if t[0]<=xi and xi<=s[-1]:
    w=xi-t[ti-1]
    e=s[si]-xi
    tmp=2*min(w,e)+max(w,e)
    ans=min(ans,tmp)
  print(ans)

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int, input().split())
s = list(int(input()) for _ in range(A))
t = list(int(input()) for _ in range(B))

for i in range(Q):
    ans = 10 ** 19
    x = int(input())
    stmp1 = bisect.bisect_left(s, x)
    for j in range(2):
        if stmp1 == 0 and j == 1:
            continue
        if stmp1 == A and j == 0:
            continue
        ttmp1 = bisect.bisect_left(t, s[stmp1 - j])
        ktmp = 10 ** 11
        if ttmp1 != 0:
            ktmp = min(ktmp, abs(s[stmp1 - j] - t[ttmp1 - 1]))
        if ttmp1 != B:
            ktmp = min(ktmp, abs(s[stmp1 - j] - t[ttmp1]))
        total = abs(x - s[stmp1 - j]) + ktmp
        ans = min(ans, total)

    ttmp1 = bisect.bisect_left(t, x)
    for j in range(2):
        if ttmp1 == 0 and j == 1:
            continue
        if ttmp1 == B and j == 0:
            continue
        stmp1 = bisect.bisect_left(s, t[ttmp1 - j])
        ktmp = 10 ** 11
        if stmp1 != 0:
            ktmp = min(ktmp, abs(t[ttmp1 - j] - s[stmp1 - 1]))
        if stmp1 != A:
            ktmp = min(ktmp, abs(t[ttmp1 - j] - s[stmp1]))
        total = abs(x - t[ttmp1 - j]) + ktmp
        ans = min(ans, total)
    print(ans)

Submission status: Accepted

Solution code:
import bisect

A, B, Q = map(int, input().split())
K = []
T = []
for i in range(A):
    K.append(int(input()))
for j in range(B):
    T.append(int(input()))
K.sort()
T.sort()
l_1 = len(K)
l_2 = len(T)

Ans = []
for i in range(Q):
    c = int(input())
    p = bisect.bisect_right(K, c)
    if p >= l_1:
        p -= 1
    dis_1 = abs(c - K[p-1])
    dis_2 = abs(c - K[p])
    q_1 = bisect.bisect_right(T, K[p-1])
    q_2 = bisect.bisect_right(T, K[p])
    if q_1 >= l_2:
        q_1 -= 1
    if q_2 >= l_2:
        q_2 -= 1
    result_1 = min([dis_1 + abs(K[p-1] - T[q_1-1]), dis_1 + abs(K[p-1] - T[q_1]), dis_2 + abs(K[p] - T[q_2-1]), dis_2 + abs(K[p] - T[q_2])])

    p = bisect.bisect_right(T, c)
    if p >= l_2:
        p -= 1
    dis_1 = abs(c - T[p-1])
    dis_2 = abs(c - T[p])
    q_1 = bisect.bisect_right(K, T[p-1])
    q_2 = bisect.bisect_right(K, T[p])
    if q_1 >= l_1:
        q_1 -= 1
    if q_2 >= l_1:
        q_2 -= 1
    result_2 = min([dis_1 + abs(T[p-1] - K[q_1-1]), dis_1 + abs(T[p-1] - K[q_1]), dis_2 + abs(T[p] - K[q_2-1]), dis_2 + abs(T[p] - K[q_2])])
    Ans.append(min(result_1, result_2))

for i in Ans:
    print(i)

Submission status: Accepted

Solution code:
import sys, os, math, bisect, itertools, collections, heapq, queue
# from scipy.sparse.csgraph import csgraph_from_dense, floyd_warshall
from decimal import Decimal
from collections import defaultdict, deque

# import fractions

sys.setrecursionlimit(10000000)

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: (x * y) // math.gcd(x, y)
# lcm = lambda x, y: (x * y) // fractions.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    A, B, Q = il()
    S = [-MAX, MAX]
    for _ in range(A):
        S.append(ii())
    S.sort()
    T = [-MAX, MAX]
    for _ in range(B):
        T.append(ii())
    T.sort()

    for _ in range(Q):
        q = ii()
        Srange = bisect.bisect_left(S, q)
        Trange = bisect.bisect_left(T, q)
        print(min(abs(q - S[Srange - 1]) + abs(S[Srange - 1] - T[Trange]),
                  abs(q - S[Srange - 1]) + abs(S[Srange - 1] - T[Trange - 1]),
                  abs(q - S[Srange]) + abs(S[Srange] - T[Trange - 1]),
                  abs(q - S[Srange]) + abs(S[Srange] - T[Trange]),
                  abs(q - T[Trange - 1]) + abs(T[Trange - 1] - S[Srange]),
                  abs(q - T[Trange - 1]) + abs(T[Trange - 1] - S[Srange - 1]),
                  abs(q - T[Trange]) + abs(T[Trange] - S[Srange - 1]),
                  abs(q - T[Trange]) + abs(T[Trange] - S[Srange])))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7


#############
# Main Code #
#############

A, B, Q = getNM()
# 神社
S = getArray(A)
# 寺
T = getArray(B)
query = getArray(Q)

S.insert(0, -float('inf'))
T.insert(0, -float('inf'))
S.append(float('inf'))
T.append(float('inf'))

def close(data, point):
    west = data[bisect_left(data, point) - 1]
    east = data[bisect_left(data, point)]

    return west, east

for i in range(Q):
    now = query[i]
    shrine_west, shrine_east = close(S, now)
    temple_west, temple_east = close(T, now)

    ww = now - min(shrine_west, temple_west)
    we_1 = (now - shrine_west) * 2 + (temple_east - now)
    we_2 = (now - temple_west) * 2 + (shrine_east - now)
    ee = max(shrine_east, temple_east) - now
    ew_1 = (shrine_east - now) * 2 + (now - temple_west)
    ew_2 = (temple_east - now) * 2 + (now - shrine_west)

    print(min(ww, we_1, we_2, ee, ew_1, ew_2))

Submission status: Accepted

Solution code:
from bisect import bisect_left,bisect
a,b,q = map(int,input().split())
jin = [-10**16]
for i in range(a):
    jin.append(int(input()))
jin.append(10**16)
tera = [-10**20]
for i in range(b):
    tera.append(int(input()))
tera.append(10**20)
for i in range(q):
    x = int(input())
    j = bisect(jin,x)
    t = bisect(tera,x)
    j1 = jin[j]
    j2 = jin[j-1]
    t1 = tera[t]
    t2 = tera[t-1]
    ans = min(abs(x-j1)+abs(j1-t1),abs(x-j1)+abs(j1-t2),abs(x-j2)+abs(j2-t1),abs(x-j2)+abs(j2-t2))
    ans = min(ans,abs(x-t1)+abs(t1-j1),abs(x-t1)+abs(t1-j2),abs(x-t2)+abs(t2-j1),abs(x-t2)+abs(t2-j2))
    print(ans)

Submission status: Accepted

Solution code:
import bisect

left_sentinel = -2 * (10 ** 10)
right_sentinel = 3 * (10 ** 10)

A, B, Q = map(int, input().split())
ss = [left_sentinel] + [int(input()) for _ in range(A)] + [right_sentinel]
ts = [left_sentinel] + [int(input()) for _ in range(B)] + [right_sentinel]

for _ in range(Q):
    x = int(input())
    s_index = bisect.bisect_left(ss, x)
    right_s = ss[s_index]
    left_s = ss[s_index - 1]
    t_index = bisect.bisect_left(ts, x)
    right_t = ts[t_index]
    left_t = ts[t_index - 1]
    ans = min(
        max(right_s, right_t) - x,
        right_s - left_t + min(right_s - x, x - left_t),
        right_t - left_s + min(right_t - x, x - left_s),
        x - min(left_s, left_t)
    )
    print(ans)