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: Wrong Answer

Solution code:
A, B, Q = list(map(int, input().split()))
# もし神社(寺)が1つしかなかった場合に両端に仮想の神社を建築して処理の一貫性を保つ。かりにこれが選ばれても最大のコストなので最終的に最適になることはない。
INF = 10 ** 18

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

from bisect import bisect_right
from itertools import product

for q in range(Q):  # 各問に答える
    x = int(input())  # 位置の指定
    s_idx, t_idx = bisect_right(S, x), bisect_right(T, x)
    ans = INF
    # 左右の神社と寺のの組み合わせ
    for s, t in product(S[s_idx - 1:s_idx + 1], T[t_idx - 1:t_idx + 1]):
        t_root = abs(s - x) + abs(s - t)  # 寺から最初に回るルート
        s_root = abs(s - x) + abs(s - t)
        ans = min(ans, t_root, s_root)
    # 最小をとって終わり
    print(ans)

'''
bisect_right

ソートされた順序を保ったまま x を a に挿入できる点を探し当てます。リストの中から検索する部分集合を指定するには、パラメータの lo と hi を使います。デフォルトでは、リスト全体が使われます。x がすでに a に含まれている場合、挿入点は既存のどのエントリーよりも後(右)になります。戻り値は、list.insert() の第一引数として使うのに適しています。a はすでにソートされているものとします。


In[3]: A
Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In[4]: bisect.bisect_right(A, 2.5)
Out[4]: 3

In[5]: bisect.bisect_right(A, 3)
Out[5]: 4
'''

Submission status: Wrong Answer

Solution code:
import numpy as np
import bisect
a,b,q = map(int,input().split())
s = np.array([-np.inf]+[int(input()) for i in range(a)]+[np.inf])
t = np.array([-np.inf]+[int(input()) for i in range(b)]+[np.inf])
x = np.array([int(input()) for i in range(q)])


  
def distance(s,t,xi):
  s_ = bisect.bisect_left(s,xi)
  s_m = s[s_-1]-xi
  s_p = s[s_]-xi
  t_ = bisect.bisect_left(t,xi)
  t_m = t[t_-1]-xi
  t_p = t[t_]-xi
  
  return min(abs(min(s_m,t_m)),abs(t_p-s_m)+min(abs(t_p),abs(s_m))\
         ,abs(max(t_p,s_p)),abs(s_p-t_m)+min(abs(s_p),abs(s_p)))
 
for i in x:
  print(int(distance(s,t,i)))

Submission status: Wrong Answer

Solution code:
import bisect
INF=10**18
A,B,Q=map(int,input().split())
s=[int(input()) for i in range(A)]
t=[int(input()) for i in range(B)]
s=[-INF]+s+[INF]
t=[-INF]+t+[INF]
for q in range(Q):
    X=int(input())
    t1=bisect.bisect_right(t,X)
    l1=X-t[t1]
    if (t[t1]-X)>(X-t[t1-1]):
        l1=X-t[t1-1]
    s1=bisect.bisect_right(s,X)
    l2=X-s[s1]
    if (s[s1]-X)>(X-s[s1-1]):
        l2=X-s[s1-1]
    l3=bisect.bisect_right(s,X-l1)
    l4=bisect.bisect_right(t,X-l2)
    print(min(abs(l1)+min(s[l3]-X+l1,X-l1-s[l3-1]),abs(l2)+min(t[l4]-X+l2,X-l2-t[l4-1])))

Submission status: Wrong Answer

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

from collections import deque
import itertools as it
import sys
import math

sys.setrecursionlimit(1000000)

INF = 10 ** 18

A, B, Q = map(int, raw_input().split())
s = [(int(input()), 0) for i in range(A)]
t = [(int(input()), 1) for i in range(B)]
x = [(int(input()), i + 2) for i in range(Q)]
ls = sorted(s + t + x)

for i in range(A + B + Q):
  pass
print 0

Submission status: Wrong Answer

Solution code:
A, B, Q = map(int, input().split())
s_list = [int(input()) for a in range(A)]
t_list = [int(input()) for b in range(B)]
x_list = [int(input()) for q in range(Q)]

for x in x_list:
    s_distance = min(list(map(lambda n: abs(n - x), s_list)))
    s_index = list(map(lambda n: abs(n - x), s_list)).index(s_distance)
    t_distance = min(list(map(lambda n: abs(n - x), t_list)))
    t_index = list(map(lambda n: abs(n - x), t_list)).index(t_distance)
    if s_distance < t_distance:
        next_x = s_list[s_index]
        t_distance_2 = min(list(map(lambda n: abs(n - next_x), t_list)))
        print(s_distance + t_distance_2)
    elif s_distance > t_distance:
        next_x = t_list[t_index]
        s_distance_2 = min(list(map(lambda n: abs(n - next_x), s_list)))
        print(t_distance + s_distance_2)
    else:
        next_x_1 = s_list[s_index]
        next_x_2 = t_list[t_index]
        s_distance_2 = min(list(map(lambda n: abs(n - next_x_2), s_list)))
        t_distance_2 = min(list(map(lambda n: abs(n - next_x_1), t_list)))
        if s_distance + t_distance_2 < s_distance_2 + t_distance:
            print(s_distance + t_distance_2)
        else:
            print(t_distance + s_distance_2)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left
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())
    shrine1 = bisect_left(s,x[i])
    shrine2 = shrine1 - 1
    temple1 = bisect_left(t,x[i])
    temple2 = temple1 - 1
    a = float('inf')
    if shrine1 == len(s):
        s1,s2 = (x[i] - s[-1]),float('inf')
    elif shrine1 == 0:
        s1,s2 = float('inf'),(s[0] - x[i])
    
    else:
        s1,s2 = x[i] - s[shrine2],s[shrine1] - x[i]

    if temple1 == len(t):
        t1,t2 = (x[i] - t[-1]),float('inf')

    elif temple1 == 0:
        t1,t2 = float('inf'),(t[0] - x[i])
    else:
        t1,t2 = x[i] - t[temple2],t[temple1] - x[i]
    print(min([ max(s2,s1) , max(t1,s1) , min(s1,t2)*2+max(s1,t2), min(s2,t1)*2+max(s2,t1) ]))

Submission status: Wrong Answer

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 i in range(q):
    x = int(input())
    xs = bisect.bisect(s,x)
    xt = bisect.bisect(t,x)
    
    S = [s[xs-1],s[xs]]
    T = [t[xt-1],t[xt]]
    ans = []
    for j in range(2):
        for k in range(2):
            ans.append(abs(S[j]-x) + abs(S[j]-T[k]))
            ans.append(abs(T[j]-x) + abs(T[j]-S[k]))
    print(min(ans))

Submission status: Wrong Answer

Solution code:
import bisect
A, B, Q = map(int, input().split())
s = [-10**10 - 1, -10**10] + [int(input()) for _ in range(A)] + [2*10**10]
t = [-10**10 - 1, -10**10] + [int(input()) for _ in range(B)] + [2*10**10]
x = [int(input()) for _ in range(Q)]


def func(c, d, z):
    i = bisect.bisect_left(c, z)
    j = bisect.bisect_left(d, z)
    if c[i - 1] < d[j - 1] and c[i] < d[j]:
        return min(z - c[i - 1], z + c[i] - 2 * d[j - 1], 2 * c[i] - z - d[j - 1], d[j] - z)
    elif c[i - 1] < d[j - 1] and c[i] > d[j]:
        return min(z - c[i - 1], z + c[i] - 2 * d[j - 1], 2 * d[j] - z - c[i - 1], c[i] - z)
    elif c[i - 1] > d[j - 1] and c[i] < d[j]:
        return min(z - d[j - 1], z + d[j] - 2 * c[i - 1], 2 * c[i] - z - d[j - 1], d[j] - z)
    else:
        return min(z - d[j - 1], z + d[j] - 2 * c[i - 1], 2 * d[j] - z - c[i - 1], c[i] - z)


for z in x:
    print(func(s, t, z))

Submission status: Wrong Answer

Solution code:
import bisect

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

for x in X:
    ids, idt = bisect.bisect_right(S, x), bisect.bisect_right(T, x)
    print(min(abs(s-t) + min(abs(s-x), abs(t-x))
              for s in S[ids-1:ids+1] for t in T[idt-1:idt+1]))

Submission status: Wrong Answer

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 i in range(q):
    x = int(input())
    xs = bisect.bisect(s,x)
    xt = bisect.bisect(t,x)

    ds = []
    ds.append([s[xs-1],abs(x-s[xs-1])])
    ds.append([s[xs],abs(x-s[xs])])
    
    dt = []
    dt.append([t[xt-1],abs(x-t[xt-1])])
    dt.append([t[xt],abs(x-t[xt])])

    ans = []
    for j in range(len(ds)):
        for k in range(len(dt)):
            ans.append(ds[j][1] + abs(dt[k][0]-ds[j][0]))
            
    for j in range(len(dt)):
        for k in range(len(ds)):
            ans.append(dt[j][1] + abs(ds[k][0]-dt[j][0]))
    print(min(ans))

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left
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]
x = [int(input()) for i in range(Q)]
def diff(l):
    d = [l[i+1]-l[i] for i in range(len(l)-1)]
    return d
for x_i in x:
    ns = bisect_left(s,x_i); nt = bisect_left(t,x_i)
    sl = s[ns-1]; sr = s[ns]
    tl = t[nt-1]; tr = t[nt]
    if tl <= sl <= x_i and x_i <= sr <= tr:
        l = [tl,sr,x_i,sr,tr]
        a,b,c,d = diff(l)
        comp = (a+b,c+d)
    elif sl <= tl <= x_i and x_i <= sr <= tr:
        l = [sl,tl,x_i,sr,tr]
        a,b,c,d = diff(l)
        comp = (a+b,2*b+c,b+2*c,c+d)
    elif tl <= sl <= x_i and x_i <= tr <= sr:
        l = [tl,sl,x_i,tr,sr]
        a,b,c,d = diff(l)
        comp = (a+b,2*b+c,b+2*c,c+d)
    elif sl <= tl <= x_i and x_i <= tr <= sr:
        l = [sl,tl,x_i,tr,sr]
        a,b,c,d = diff(l)
        comp = (a+b,c+d)
    ans = min(comp)
    print(ans)

Submission status: Wrong Answer

Solution code:
A, B, Q = map(int, input().split())
s = [-10**10] + [int(input()) for _ in range(A)] + [2*10**10, 2*10**10 + 1]
t = [-10**10] + [int(input()) for _ in range(B)] + [2*10**10, 2*10**10 + 1]
x = [int(input()) for _ in range(Q)]


def searchindex(p, z):
    for i, d in enumerate(p):
        if d > z:
            return i - 1


def func(c, d, z):
    i = searchindex(c, z)
    j1 = searchindex(d, c[i])
    j2 = searchindex(d, c[i + 1])
    return min(z - d[j1], z - c[i] * 2 + d[j1 + 1], d[j2 + 1] - z, c[i + 1] * 2 - z - d[j2])


ans = []
for z in x:
    ans.append(min(func(s, t, z), func(t, s, z)))

print(ans)

Submission status: Wrong Answer

Solution code:
import bisect

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

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

for i in range(Q):
  x = int(input())
  b = bisect.bisect_right(s, x)
  d = bisect.bisect_right(t, x)
  dist = 0
  for sb in [s[b - 1], s[b]]:
    for td in [t[d - 1], t[d]]:
      d1, d2 = abs(x - sb) + abs(sb - td), abs(x - td) + abs(td - sb)
      dist = min(dist, d1, d2)
  print(dist)

Submission status: Wrong Answer

Solution code:
import bisect
import math
A,B,Q = map(int,input().split())
a = []
b = []
x = []
for i in range(A):
  a.append(int(input()))
for j in range(B):
  b.append(int(input()))
for k in range(Q):
  x.append(int(input()))
a.insert(0,-(10**15))
a.append(10**15)
b.insert(0,-(10**15))
b.append(10**15)
for k in range(Q):  
  terafirst = 0
  jinjyafirst = 0
  p = bisect.bisect_left(a,x[k])
  q = bisect.bisect_left(b,x[k])
  terafirst = min(abs(x[k]-a[p-1]),abs(x[k]-a[p]))
  if abs(x[k]-a[p-1])<abs(x[k]-a[p]):
    r = bisect.bisect_left(b,a[p-1])
    terafirst += min(abs(b[r-1]-a[p-1]),abs(b[r]-a[p-1]))
  else:
    s = bisect.bisect_left(b,a[p])
    terafirst += min(abs(b[s-1]-a[p]),abs(b[s]-a[p]))
      
  jinjyafirst = min(abs(x[k]-b[q-1]),abs(x[k]-b[q]))
  if abs(x[k]-b[q-1])<abs(x[k]-b[q]):
    t = bisect.bisect_left(a,b[q-1])
    jinjyafirst += min(abs(a[t-1]-b[q-1]),abs(a[t]-b[q-1]))
  else:
    u = bisect.bisect_left(a,b[q])
    jinjyafirst += min(abs(a[u-1]-b[q]),abs(a[u]-b[q]))
  print(min(terafirst,jinjyafirst))

Submission status: Wrong Answer

Solution code:
def inpl():
    return list(map(int, input().split()))


def binary_search(Array, x):
    le = 0
    ri = len(Array)
    if ri == 1 or x <= Array[0]:
        return x - Array[0], Array[0] - x
    elif x >= Array[-1]:
        return x - Array[-1], Array[-1] - x
    while ri - le > 0:
        i = (le + ri) // 2
        if (Array[i] == x):
            return 0, 0
        elif (Array[i] < x):
            le = i + 1
            zou = True
        else:
            ri = i
            zou = False
    if zou is True:
        return x - Array[ri - 1], Array[ri] - x
    else:
        return x - Array[ri], Array[ri + 1] - x


A, B, Q = inpl()
shrine = [int(input()) for _ in range(A)]
temple = [int(input()) for _ in range(B)]
query = [int(input()) for _ in range(Q)]

# shrine.sort()
# temple.sort()
slr = [0, 0]
tlr = [0, 0]
for q in query:
    slr[0], slr[1] = binary_search(shrine, q)
    tlr[0], tlr[1] = binary_search(temple, q)

    ans = 10**15
    for sdir, tdir in zip(slr, tlr):
        if sdir < 0 or tdir < 0:
            continue
        ans = min(ans, max(sdir, tdir))
    for sdir, tdir in [[slr[0], tlr[1]], [slr[1], tlr[0]]]:
        if sdir < 0 or tdir < 0:
            continue
        ans = min(ans, sdir + tdir + min(sdir, tdir))

    print(ans)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_right
A,B,Q = map(int,input().split())
S = [-float("inf")] + list(int(input()) for i in range(A)) + [float("inf")]
T = [-float("inf")] + list(int(input()) for i in range(B)) + [float("inf")]

for i in range(Q) :
    x = int(input())
    
    ind_s_right = bisect_right(S,x)
    ind_t_right = bisect_right(T,x)
    ind_s_left = ind_s_right - 1
    ind_t_left = ind_t_right - 1
    
    res = []
    
    for s in [S[ind_s_left], S[ind_s_right]] :
        for t in [T[ind_t_left], T[ind_t_right]] :
            dist = min(abs(x-s),abs(x-t)) + abs(s-t)
            res.append(dist)
    print(min(res))

Submission status: Wrong Answer

Solution code:
import bisect

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

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

for x in range(Q):
  b = bisect.bisect_right(s, x)
  d = bisect.bisect_right(t, x)
  dist = 0
  for sb in [s[b - 1], s[b]]:
    for td in [t[d - 1], t[d]]:
      d1, d2 = abs(x - sb) + abs(sb - td), abs(x - td) + abs(td - sb)
      dist = min(dist, d1, d2)
  print(dist)

Submission status: Wrong Answer

Solution code:
import bisect


def search(arry, target):
    left = 0
    right = len(arry) - 1
    while left <= right:
        mid = (left + right) // 2
        if mid == len(arry) - 1:
            return mid
        if arry[mid] <= target < arry[mid+1]:
            break
        elif arry[mid] > target:
            right = mid - 1
        else:
            left = mid + 1
    if target - arry[mid] < arry[mid+1] - target:
        return mid
    else:
        return mid + 1


def near(a, t):
    # return bisect.bisect_right(a, t) - 1
    return a[search(a, t)]

def near2(a, t):
    n = bisect.bisect_left(a, t)
    f, s = a[n-1], a[n]
    return f if t-f < s-t else s

near = near2

def walk(x):
    # print("target:", x)
    near_a = near(a_s, x)
    near_a_b = near(b_s, near_a)
    sum_ab = abs(near_a - x) + abs(near_a_b - near_a)
    # print("a", near_a, "ab", near_a_b, sum_ab)
    near_b = near(b_s, x)
    near_b_a = near(a_s, near_b)
    sum_ba = abs(near_b - x) + abs(near_b_a - near_b)
    # print("b", near_b, "ba", near_b_a, sum_ba)
    return sum_ab if sum_ab < sum_ba else sum_ba

INF = 10 ** 20
A, B, Q = map(int, input().split())
a_s = []
b_s = []
# q_s = []
for _ in range(A):
    a_s.append(int(input()))
for _ in range(B):
    b_s.append(int(input()))

a_s = [-INF] + a_s + [INF]
b_s = [-INF] + b_s + [INF]

# print("===")
for _ in range(Q):
    q = int(input())
    print(walk(q))

Submission status: Wrong Answer

Solution code:
import bisect


def search(arry, target):
    left = 0
    right = len(arry) - 1
    while left <= right:
        mid = (left + right) // 2
        if mid == len(arry) - 1:
            return mid
        if arry[mid] <= target < arry[mid+1]:
            break
        elif arry[mid] > target:
            right = mid - 1
        else:
            left = mid + 1
    if target - arry[mid] < arry[mid+1] - target:
        return mid
    else:
        return mid + 1


def near(a, t):
    # return bisect.bisect_right(a, t) - 1
    return a[search(a, t)]

def near2(a, t):
    n = bisect.bisect_left(a, t)
    f, s = a[n-1], a[n]
    return f if t-f < s-t else s

near = near2

def walk(x):
    # print("target:", x)
    near_a = near(a_s, x)
    near_a_b = near(b_s, near_a)
    sum_ab = abs(near_a - x) + abs(near_a_b - near_a)
    # print("a", near_a, "ab", near_a_b, sum_ab)
    near_b = near(b_s, x)
    near_b_a = near(a_s, near_b)
    sum_ba = abs(near_b - x) + abs(near_b_a - near_b)
    # print("b", near_b, "ba", near_b_a, sum_ba)
    return sum_ab if sum_ab < sum_ba else sum_ba

INF = 10 ** 13
A, B, Q = map(int, input().split())
a_s = []
b_s = []
# q_s = []
for _ in range(A):
    a_s.append(int(input()))
for _ in range(B):
    b_s.append(int(input()))

a_s = [-INF] + a_s + [INF]
b_s = [-INF] + b_s + [INF]

# print("===")
for _ in range(Q):
    q = int(input())
    print(walk(q))

Submission status: Wrong Answer

Solution code:
import bisect

def bl(A,x):
    return bisect.bisect_left(A,x)

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

O = []
for i in range(Q):
    x = int(input())
    s = 0
    t = 0
    
    xs = bl(S,x)
    xt = bl(T,x)
    st = 0
    ts = 0
    
    XtoS = 0
    XtoT = 0
    StoT = 0
    TtoS = 0
    
    if xs==A:xs-=1
    if xt==B:xt-=1
    if xs==0 or abs(x-S[xs]) < abs(x-S[xs-1]):
        XtoS = abs(x-S[xs])
        s = S[xs]
        st = bl(T,S[xs])
    else:
        XtoS = abs(x-S[xs-1])
        s = S[xs-1]
        st = bl(T,S[xs-1])
    if xt==0 or abs(x-T[xt]) < abs(x-T[xt-1]):
        XtoT = abs(x-T[xt])
        t = T[xt]
        ts = bl(S,T[xt])
    else:
        XtoT = abs(x-T[xt-1])
        t = T[xt-1]
        ts = bl(S,T[xt-1])

    if ts==A:ts-=1
    if st==B:st-=1
    if ts==0 or abs(t-S[ts]) < abs(t-S[ts-1]):
        TtoS = abs(t-S[ts])
    else:
        TtoS = abs(t-S[ts-1])
    if st==0 or abs(s-T[st]) < abs(s-T[st-1]):
        StoT = abs(s-T[st])
    else:
        StoT = abs(s-T[st-1])
        
    #print(XtoS+StoT,XtoT+TtoS)
    O.append(min([XtoS+StoT,XtoT+TtoS]))
    
for o in O:
    print(o)

Submission status: Wrong Answer

Solution code:
import bisect


def search(arry, target):
    left = 0
    right = len(arry) - 1
    while left <= right:
        mid = (left + right) // 2
        if mid == len(arry) - 1:
            return mid
        if arry[mid] <= target < arry[mid+1]:
            break
        elif arry[mid] > target:
            right = mid - 1
        else:
            left = mid + 1
    if target - arry[mid] < arry[mid+1] - target:
        return mid
    else:
        return mid + 1


def near(a, t):
    # return bisect.bisect_right(a, t) - 1
    return a[search(a, t)]

def near2(a, t):
    n = bisect.bisect_left(a, t)
    f,s = t-a[n-1] ,a[n]-t
    return f if f < s else s

def walk(x):
    # print("target:", x)
    near_a = near(a_s, x)
    near_a_b = near(b_s, near_a)
    sum_ab = abs(near_a - x) + abs(near_a_b - near_a)
    # print("a", near_a, "ab", near_a_b, sum_ab)
    near_b = near(b_s, x)
    near_b_a = near(a_s, near_b)
    sum_ba = abs(near_b - x) + abs(near_b_a - near_b)
    # print("b", near_b, "ba", near_b_a, sum_ba)
    return sum_ab if sum_ab < sum_ba else sum_ba


A, B, Q = map(int, input().split())
a_s = []
b_s = []
# q_s = []
for _ in range(A):
    a_s.append(int(input()))
for _ in range(B):
    b_s.append(int(input()))
print("===")
for _ in range(Q):
    q = int(input())
    print(walk(q))

Submission status: Wrong Answer

Solution code:
def inpl():
    return list(map(int, input().split()))


def binary_search(Array, x):
    le = 0
    ri = len(Array)
    if ri == 1 or x <= Array[0]:
        return x - Array[0], Array[0] - x
    elif x >= Array[-1]:
        return x - Array[-1], Array[-1] - x
    while ri - le > 0:
        i = (le + ri) // 2
        if (Array[i] == x):
            return 0, 0
        elif (Array[i] < x):
            le = i + 1
            zou = True
        else:
            ri = i
            zou = False
    if zou is True:
        return x - Array[ri - 1], Array[ri] - x
    else:
        return x - Array[ri], Array[ri + 1] - x


A, B, Q = inpl()
shrine = [int(input()) for _ in range(A)]
temple = [int(input()) for _ in range(B)]
query = [int(input()) for _ in range(Q)]

# shrine.sort()
# temple.sort()
slr = [0, 0]
tlr = [0, 0]
for q in query:
    slr[0], slr[1] = binary_search(shrine, q)
    tlr[0], tlr[1] = binary_search(temple, q)

    ans = 10**12
    for sdir, tdir in zip(slr, tlr):
        if sdir < 0 or tdir < 0:
            continue
        ans = min(ans, max(sdir, tdir))
    for sdir, tdir in [[slr[0], tlr[1]], [slr[1], tlr[0]]]:
        if sdir < 0 or tdir < 0:
            continue
        ans = min(ans, sdir + tdir + min(sdir, tdir))

    print(ans)

Submission status: Wrong Answer

Solution code:
def inpl():
    return list(map(int, input().split()))


def binary_search(Array, x):
    le = 0
    ri = len(Array)
    if ri == 1 or x <= Array[0]:
        return x - Array[0], Array[0] - x
    elif x >= Array[-1]:
        return x - Array[-1], Array[-1] - x
    while ri - le > 0:
        i = (le + ri) // 2
        if (Array[i] == x):
            return 0, 0
        elif (Array[i] < x):
            le = i + 1
            zou = True
        else:
            ri = i
            zou = False
    if zou is True:
        return x - Array[ri - 1], Array[ri] - x
    else:
        return x - Array[ri], Array[ri + 1] - x


A, B, Q = inpl()
shrine = [int(input()) for _ in range(A)]
temple = [int(input()) for _ in range(B)]
query = [int(input()) for _ in range(Q)]

# shrine.sort()
# temple.sort()
slr = [0, 0]
tlr = [0, 0]
for q in query:
    slr[0], slr[1] = binary_search(shrine, q)
    tlr[0], tlr[1] = binary_search(temple, q)

    ans = 10**12
    for sdir, tdir in zip(slr, tlr):
        if sdir < 0 or tdir < 0:
            continue
        ans = min(ans, max(sdir, tdir))
    for sdir, tdir in [[slr[0], tlr[1]], [slr[1], tlr[1]]]:
        if sdir < 0 or tdir < 0:
            continue
        ans = min(ans, sdir + tdir + min(sdir, tdir))

    print(ans)

Submission status: Wrong Answer

Solution code:
import bisect
import math
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]

s.sort()
t.sort()

def near(x, buildings):
    left, right = 0, len(buildings) - 1

    while right - left > 1:
        center = (left + right) // 2
        value = buildings[center]
        if x < value:
            right = center
        elif x > value:
            left = center
        else:
            return center
    return left if abs(x - buildings[left]) < abs(x - buildings[right]) else right


results = ""
for _ in range(q):
    x = int(input())
    # si = near(x, s)
    # svalue = s[si]
    # spos = [svalue, s[si + 1]] if svalue < x else [svalue, s[si - 1]]
    si = bisect.bisect_right(s, x)
    spos = [s[si], s[si - 1]]


    # ti = near(x, t)
    # tvalue = t[ti]
    # tpos = [tvalue, t[ti + 1]] if tvalue < x else [tvalue, t[ti - 1]]
    ti = bisect.bisect_right(t, x)
    tpos = [t[ti], t[ti - 1]]

    result = float("inf")
    for svalue in spos:
        for tvalue in tpos:
            if svalue == tvalue == inf:
                continue
            result = min(
                abs(x - svalue) + abs(svalue - tvalue),
                abs(x - tvalue) + abs(tvalue - svalue),
                result
            )

    results += str(result) + "\n"
print(results)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left

abq = list(map(int, input().split()))
s = sorted([int(input()) for i in range(abq[0])])
t = sorted([int(input()) for i in range(abq[1])])
x = [int(input()) for i in range(abq[2])]

for i in range(abq[2]):
    
    s_r_i = bisect_left(s, x[i])
    if s_r_i < len(s):  
        s_r = s[s_r_i]
    else:
        s_r = None
    
    t_r_i = bisect_left(t, x[i])
    if t_r_i < len(t):
        t_r = t[t_r_i]
    else:
        t_r = None
    
    s_l_i = bisect_left(s, x[i]) - 1
    if 0 <= s_l_i <len(s):
        s_l = s[s_l_i]
    else:
        s_l = None
    
    t_l_i = bisect_left(t, x[i]) - 1
    if 0 <= t_l_i < len(t):
        t_l = t[t_l_i]
    else:
        t_l = None
    
    if s_r != None and t_r != None:
        route1 = max(abs(x[i] - s_r), abs(x[i] - t_r))
    else:
        route1 = 10**10
    
    if s_r != None and t_l != None:
        route2 = min(abs(x[i] - s_r), abs(x[i] - t_l))*2 + max(abs(x[i] - s_r), abs(x[i] - t_l))
    else:
        route2 = 10**10
    
    if s_l != None and t_r != None:
        route3 = min(abs(x[i] - s_l), abs(x[i] - t_r))*2 + max(abs(x[i] - s_l), abs(x[i] - t_r))
    else:
        route3 = 10**10 
        
    if s_l != None and t_l != None:
        route4 = max(abs(x[i] - s_l), abs(x[i] - t_l))
    else:
        route4 = 10**10
        
    print(min(route1,route2,route3,route4))

Submission status: Wrong Answer

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)
    a, c = max(b-1, 0), max(d-1, 0)

    res = INF
    print(a, b, c, d)
    for S in s[b-1:b+1]:
        for T in t[d-1:d+1]:
            d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
            res = min(res, d1, d2)
    print(res)

Submission status: Wrong Answer

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

s.sort()
t.sort()

def near(x, buildings):
    left, right = 0, len(buildings) - 1

    while right - left > 1:
        center = (left + right) // 2
        value = buildings[center]
        if x < value:
            right = center
        elif x > value:
            left = center
        else:
            return center
    return left if abs(x - buildings[left]) < abs(x - buildings[right]) else right


results = ""
for _ in range(q):
    x = int(input())
    si = near(x, s)
    svalue = s[si]
    spos = [svalue, s[si + 1]] if svalue < x else [svalue, s[si - 1]]
    ti = near(x, t)
    tvalue = t[ti]
    tpos = [tvalue, t[ti + 1]] if tvalue < x else [tvalue, t[ti - 1]]

    result = float("inf")
    for svalue in spos:
        for tvalue in tpos:
            if svalue == tvalue == inf:
                continue
            result = min(
                abs(x - svalue) + abs(svalue - tvalue),
                abs(x - tvalue) + abs(tvalue - svalue),
                result
            )

    results += str(result) + "\n"
print(results)

Submission status: Wrong Answer

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 = min(bisect.bisect_right(s, x), A+1), \
        min(bisect.bisect_right(t, x), B+1)
    a, c = max(b-1, 0), max(d-1, 0)

    res = INF
    print(a, b, c, d)
    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: Wrong Answer

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

s.sort()
t.sort()

def near(x, buildings):
    left, right = 0, len(buildings) - 1

    while right - left > 1:
        center = (left + right) // 2
        value = buildings[center]
        if x < value:
            right = center
        elif x > value:
            left = center
        else:
            return center
    return left if abs(x - buildings[left]) < abs(x - buildings[right]) else right


results = ""
for _ in range(q):
    x = int(input())
    si = near(x, s)
    svalue = s[si]
    spos = [svalue, s[si + 1]] if svalue < x else [svalue, s[si - 1]]
    ti = near(x, t)
    tvalue = t[ti]
    tpos = [tvalue, t[ti + 1]] if tvalue < x else [tvalue, t[ti - 1]]

    result = float("inf")
    for svalue in spos:
        for tvalue in tpos:
            v1 = abs(x - svalue) + abs(svalue - tvalue)
            v2 = abs(x - tvalue) + abs(tvalue - svalue)
#             result = min(
#                 float("inf") if math.isnan(v1) else v1,
#                 float("inf") if math.isnan(v2) else v2,
#                 result
#             )
# 
    results += str(result) + "\n"
print(results)