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=[int(it) for it in input().split()]
dummy=10**20
s=[-dummy] + [int(input()) for it in range(a)] + [dummy]
t=[-dummy] + [int(input()) for it in range(b)] + [dummy]
x=[int(input()) for it in range(q)]

for xi in x:
    s_w = s[bisect.bisect_left(s, xi)-1]
    s_e = s[bisect.bisect_left(s, xi)]
    t_w = t[bisect.bisect_left(t, xi)-1]
    t_e = t[bisect.bisect_left(t, xi)]

    d = min(
        abs(xi - s_w) + abs(s_w - t_w),
        abs(xi - s_e) + abs(s_e - t_w),
        abs(xi - s_w) + abs(s_w - t_e),
        abs(xi - s_e) + abs(s_e - t_e),
        abs(xi - t_w) + abs(t_w - s_w),
        abs(xi - t_e) + abs(t_e - s_w),
        abs(xi - t_w) + abs(t_w - s_e),
        abs(xi - t_e) + abs(t_e - s_e)
    )
    print(d)

Submission status: Accepted

Solution code:
import bisect
import itertools

#n桁のm値のbitを生成
def bit(n, m):
    bit_list = list(itertools.product([i for i in range(m)], repeat=n))
    return bit_list

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


for i in range(Q):

    insert_index = bisect.bisect_left(s,x[i])
    if insert_index >= A:
        insert_index = insert_index -1
        tmp1 = s[insert_index]
        tmp2 = s[insert_index]
        
    else:   
        tmp1 = s[insert_index]
        tmp2 = s[insert_index-1]
    
    insert_index = bisect.bisect_left(t,x[i])
    if insert_index >= B:
        insert_index = insert_index -1
        tmp3 = t[insert_index]
        tmp4 = t[insert_index]
        
    else:
        tmp3 = t[insert_index]
        tmp4 = t[insert_index-1]
    
    result = 10 ** 11
    for j, k in ([0,1], [0,0], [1,0], [1,1]):
        tmp = 0
        if j == 0:
            tmp += abs(tmp1 - x[i])
            now = tmp1
        else:
            tmp += abs(tmp2 - x[i])
            now = tmp2
                
        if k == 0:
            tmp += abs(now - tmp3)
        else:
            tmp += abs(now - tmp4)
                
        result = min(tmp, result)
        
    for j, k in ([0,1], [0,0], [1,0], [1,1]):
        tmp = 0
        
        if k == 0:
            tmp += abs(x[i] - tmp3)
            now = tmp3
        else:
            tmp += abs(x[i]- tmp4)
            now = tmp4
            
        if j == 0:
            tmp += abs(now - tmp1)
        else:
            tmp += abs(now - tmp2)
                
        result = min(tmp, result)
                
    print(result)

Submission status: Accepted

Solution code:
def solve(a, b, q, al, bl, ql):
    sql = sorted(ql)
    adic = search(al, q, sql)
    bdic = search(bl, q, sql)
    qstep(adic, bdic, ql)


limit_begin = -1
limit_end = 10 ** 10 + 1
def search(tl, q, sql):
    z = list(zip([limit_begin] + tl, tl + [limit_end]))
    zi = 0
    dic = {}
    for e in sql:
        while(True):
            begin, end = z[zi]
            if (begin <= e) and (e <= end):
                dic[e] = (begin, end)
                break
            else:
                zi += 1
                if zi == (q + 1):
                    raise "system error"

    return dic

def qstep(adic, bdic, ql):
    
    for e in ql:
        asmall, abig = adic[e]
        bsmall, bbig = bdic[e]
        
        answer = 2 * (10 ** 10)
    
        # small , small
        if (asmall != limit_begin) and (bsmall != limit_begin):
            t = min(asmall,bsmall)
            v = e - t
            if v < answer:
                answer = v

        # big , big
        if (abig != limit_end) and (bbig != limit_end):
            t = max(abig,bbig)
            v = t - e
            if v < answer:
                answer = v

        # small , big
        if( asmall != limit_begin) and (bbig != limit_end):
            v = (bbig - asmall) + min(bbig - e, e - asmall)
            if v < answer:
                answer = v

        # big , small
        if( abig != limit_end) and (bsmall != limit_begin):
            v = (abig - bsmall) + min(abig - e, e - bsmall)
            if v < answer:
                answer = v

        print(answer)

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

al = []
for i in range(a):
    al.append(int(input()))
bl = []
for i in range(b):
    bl.append(int(input()))
ql = []
for i in range(q):
    ql.append(int(input()))

solve(a, b, q, sorted(al), sorted(bl), ql)

Submission status: Accepted

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:
    a, b = 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[a-1:a+1] for t in T[b-1:b+1]))

Submission status: Accepted

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


def binary_search(query, arr):
    low = 0
    high = len(arr)
    while high-low>1:
        mid = (low+high)//2
        if query>arr[mid]:
            low = mid
        else:
            high = mid
    return arr[low], arr[high]

def main():
    for x in X:
        s1, s2 = binary_search(x, S)
        t1, t2 = binary_search(x, T)
        ans = [ abs(t-s)+min(abs(t-x), abs(s-x)) \
            for t in [t1, t2] for s in [s1, s2] ]
        print(min(ans))
    return

main()

Submission status: Accepted

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)
    j1 = bisect.bisect_left(d, c[i - 1])
    j2 = bisect.bisect_left(d, c[i])
    return min(z - d[j1 - 1], z - c[i - 1] * 2 + d[j1], d[j2] - z, c[i] * 2 - z - d[j2 - 1])


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

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

    if idx_s == 0:
        indices_s.append(0)
    elif idx_s == a:
        indices_s.append(a-1)
    else:
        indices_s.append(idx_s)
        indices_s.append(idx_s-1)

    if idx_t == 0:
        indices_t.append(0)
    elif idx_t == b:
        indices_t.append(b-1)
    else:
        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:
import bisect
a,b,q = map(int,input().split())
s = [-float("infinity")] + [int(input()) for _ in range(a)] + [float("infinity")]
t = [-float("infinity")] + [int(input()) for _ in range(b)] + [float("infinity")]
q = [int(input()) for _ in range(q)]

for x in q:
  i = bisect.bisect(s,x)
  j = bisect.bisect(t,x)
  ans = float("infinity")

  for irange in [s[i],s[i-1]]:
    for jrange in [t[j],t[j-1]]:
      temp1 = abs(irange - x) + abs(jrange - irange)
      temp2 = abs(jrange - x) + abs(jrange - irange)
      ans = min(ans,temp1,temp2)
  print(ans)

Submission status: Accepted

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)]
for x in X:
    si = bisect_left(S,x); ti = bisect_left(T,x)
    ans = inf
    for s in [S[si-1],S[si]]:
        for t in [T[ti-1],T[ti]]:
            d1 = abs(s-x) + abs(t-s)
            d2 = abs(t-x) + abs(s-t)
            ans = min(ans,d1,d2)
    print(ans)

Submission status: Accepted

Solution code:
def d_lazy_faith(A, B, Q, S, T, X):
    from bisect import bisect_right

    # 出発地点の東西いずれかに神社または寺がないという状態を避けるため、
    # 自明に訪ねる意味がないような位置に寺社を建てる
    INF = float('inf')
    s = [-INF] + S + [INF]
    t = [-INF] + T + [INF]

    ans_tmp = []
    for x in X:
        b, d = bisect_right(s, x), bisect_right(t, x)
        res = INF
        # 出発地点xに対し、左右の神社どちらへ行くか？
        # 左右の寺のどちらへ行くか？
        # 寺と神社どちらを先に訪ねるか？
        # 8通りに対し最も距離が短かったものがクエリに対する答え
        for shrine in [s[b - 1], s[b]]:
            for temple in [t[d - 1], t[d]]:
                res = min(res,
                          abs(shrine - x) + abs(temple - shrine),
                          abs(temple - x) + abs(shrine - temple))
        ans_tmp.append(res)
    ans = '\n'.join(map(str, ans_tmp))
    return ans

A, B, Q = [int(i) for i in input().split()]
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
X = [int(input()) for _ in range(Q)]
print(d_lazy_faith(A, B, Q, S, T, X))

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-

from bisect import bisect_left

def main():
  N_a, N_b, N_q = map(int, input().strip().split(' '))
  As = list(map(int, [input().strip() for _ in range(N_a)]))
  Bs = list(map(int, [input().strip() for _ in range(N_b)]))
  Qs = list(map(int, [input().strip() for _ in range(N_q)]))

  for q in Qs:
    min_a_l = -(2*(10**10)+1)
    min_b_l = -(2*(10**10)+1)
    min_a_r = 2*(10**10)+1
    min_b_r = 2*(10**10)+1
    a_index = bisect_left(As, q)
    if len(As) > a_index-1 >= 0:
      min_a_l = As[a_index-1] - q
    if a_index < len(As):
      min_a_r = As[a_index] - q

    b_index = bisect_left(Bs, q)
    if len(Bs) > b_index-1 >= 0:
      min_b_l = Bs[b_index-1] - q
    if b_index < len(Bs):
      min_b_r = Bs[b_index] - q

    score = min([
      min_a_r if min_a_r > min_b_r else min_b_r,
      abs(min_a_l) if min_a_l < min_b_l else abs(min_b_l),
      2*min_a_r + abs(min_b_l) if min_a_r < abs(min_b_l) else min_a_r + 2*abs(min_b_l),
      2*abs(min_a_l) + abs(min_b_r) if abs(min_a_l) < abs(min_b_r) else abs(min_a_l) + 2*abs(min_b_r)])
    print(score)

  pass

if __name__=='__main__':
  main()

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left as bl
def I(a): return [-1<<50] + [int(sys.stdin.readline()) for i in range(a)] + [1<<50]
A, B, Q = map(int, input().split())
S, T = I(A), I(B)

for _ in range(Q):
    x = int(input())
    k, l = bl(S, x), bl(T, x)
    a, b, c, d = x-S[k-1], x-T[l-1], S[k]-x, T[l]-x
    print(min(max(a, b), max(c, d), 2*a+d, 2*d+a, 2*b+c, 2*c+b))

Submission status: Accepted

Solution code:
import sys
import bisect

A, B, Q = map(int, sys.stdin.readline().split())
INF = 10 ** 18
S = [-INF] + [int(sys.stdin.readline()) for _ in range(A)] + [INF]
T = [-INF] + [int(sys.stdin.readline()) for _ in range(B)] + [INF]
X = [int(sys.stdin.readline()) for _ in range(Q)]


# def binary_search(q, A):
#     l, r = 0, len(A)
#     while r - l > 1:
#         mid = (l + r) // 2
#         if q > A[mid]:
#             l = mid
#         else:
#             r = mid
#     return A[l], A[r]


def main():
    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]))
    return

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

for x in x_list:
    
    b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
    a = b - 1
    c = d - 1 
    ans = min(abs(s[a]-x) + min(abs(t[c]-s[a]), abs(t[d]-s[a])),
              abs(s[b]-x) + min(abs(t[c]-s[b]), abs(t[d]-s[b])),
              abs(t[c]-x) + min(abs(s[a]-t[c]), abs(s[b]-t[c])),
              abs(t[d]-x) + min(abs(s[a]-t[d]), abs(s[b]-t[d])))

    # for s in [s_list[a], s_list[b]]:
    #     for t in [t_list[c], t_list[d]]:
    #         dist1 = abs(s-x) + abs(t-s)
    #         dist2 = abs(t-x) + abs(t-s)
    #         ans = min(ans, dist1,dist2)
    print(ans)

Submission status: Accepted

Solution code:
import bisect
A,B,Q = map(int, input().split())
INF = 10**18
ss = [-INF] + [int(input()) for _ in range(A)] + [INF]
tt = [-INF] + [int(input()) for _ in range(B)] + [INF]
xx = [int(input()) for _ in range(Q)] 
for x in xx:
    b = bisect.bisect_right(ss, x)
    d = bisect.bisect_right(tt, x)
    ans=INF
    for s in [ss[b-1], ss[b]]:
        for t in [tt[d-1], tt[d]]:
            d1 = abs(s - x) + abs(t - s)
            d2 = abs(t - x) + abs(s - t)
            ans = min(ans, d1,d2)
    print(ans)

Submission status: Accepted

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
        else:
            ri = i
    return x - Array[ri - 1], Array[ri] - 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: Accepted

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 = INF
  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: Accepted

Solution code:
def check(startA, startB, S, T, a, b):
  pat1 = float("inf")
  if startA >= 0:
    pat1 = x - S[startA]
    if startB >= 0 and S[startA] > T[startB]:
      if startB != b - 1:
        pat1 += min(S[startA] - T[startB], T[startB + 1] - S[startA])
      else:
        pat1 += S[startA] - T[startB]
    elif startB == -1 and S[startA] < T[0]:
      pat1 += T[0] - S[startA]
  pat2 = float("inf")
  if startA != a - 1:
    pat2 = S[startA + 1] - x
    if startB != b - 1 and S[startA + 1] < T[startB + 1]:
      if startB != -1:
        pat2 += min(T[startB + 1] - S[startA + 1], S[startA + 1] - T[startB])
      else:
        pat2 += T[startB + 1] - S[startA + 1]
    elif startB == b - 1 and S[startA + 1] > T[b - 1]:
      pat2 +=  S[startA + 1] - T[b - 1]
  return min(pat1, pat2)
  
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)]
import bisect
for x in X:
  startA = bisect.bisect_left(S,x) - 1
  startB = bisect.bisect_left(T,x) - 1
  
  print(min(check(startA, startB, S, T, a, b), check(startB, startA, T, S, b, a)))

Submission status: Accepted

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

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

# xから見た際、最寄りの寺と神社を1件ずつ訪れる方法は以下のパターンが考えられる
# 1. 神社(正方向)→寺(正方向)
# 2. 神社(負方向)→寺(正方向)
# 3. 神社(正方向)→寺(負方向)
# 4. 神社(負方向)→寺(負方向)
# 5. 寺(正方向)→神社(正方向)
# 6. 寺(負方向)→神社(正方向)
# 7. 寺(正方向)→神社(負方向)
# 8. 寺(負方向)→神社(負方向)

d = [INF] * 8
for q in range(Q):
    x = int(input())
    # S,Tはソート済み
    # 二部探索で最寄りの神社を探す: bisectを用いる
    sp = bisect.bisect_left(S, x) # 正方向最寄神社のindex
    tp = bisect.bisect_left(T, S[sp]) # 正方向最寄寺のindex
    tn = tp - 1 # 負方向最寄寺のindex
    d[0] = abs(S[sp] - x) +  abs(S[sp]-T[tp])
    d[1] = abs(S[sp] - x) +  abs(S[sp]-T[tn])

    sn = sp - 1 # 負方向最寄神社のindex
    tp = bisect.bisect_left(T, S[sn]) # 正方向最寄寺のindex
    tn = tp - 1 # 負方向最寄寺のindex
    d[2] = abs(S[sn] - x) +  abs(S[sn]-T[tp])
    d[3] = abs(S[sn] - x) +  abs(S[sn]-T[tn])

    # 最寄りの寺を探す
    tp = bisect.bisect_left(T, x) # 正方向最寄寺のindex
    sp = bisect.bisect_left(S, T[tp]) # 正方向最寄神社のindex
    sn = sp - 1 # 負方向最寄神社のindex
    d[4] = abs(T[tp] - x) +  abs(T[tp]-S[sp])
    d[5] = abs(T[tp] - x) +  abs(T[tp]-S[sn])

    tn = tp - 1 # 負方向最寄寺のindex
    sp = bisect.bisect_left(S, T[tn]) # 正方向最寄神社のindex
    sn = sp - 1 # 負方向最寄神社のindex
    d[6] = abs(T[tn] - x) +  abs(T[tn]-S[sp])
    d[7] = abs(T[tn] - x) +  abs(T[tn]-S[sn])
    print(min(d))

Submission status: Accepted

Solution code:
import bisect


def main():
    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 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 = abs(S-x) + abs(T-S)
                d2 = abs(T-x) + abs(S-T)
                res = min(res, d1, d2)
        print(res)


if __name__ == "__main__":
    main()

Submission status: Accepted

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


def binary_search(q, A):
    l, r = 0, len(A)
    while r - l > 1:
        mid = (l + r) // 2
        if q > A[mid]:
            l = mid
        else:
            r = mid
    return A[l], A[r]


def main():
    for x in X:
        s1, s2 = binary_search(x, S)
        t1, t2 = binary_search(x, T)
        print(min(abs(s-t) + min(abs(s-x), abs(t-x)) for s in [s1, s2] for t in [t1, t2]))
    return

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect

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

for x in x_list:
    
    b, d = bisect.bisect_right(s_list, x), bisect.bisect_right(t_list, x)
    a = b - 1
    c = d - 1 
    ans = INF
    for s in [s_list[a], s_list[b]]:
        for t in [t_list[c], t_list[d]]:
            dist1 = abs(s-x) + abs(t-s)
            dist2 = abs(t-x) + abs(t-s)
            ans = min(ans, dist1,dist2)
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left as bl
def I(a): return [-1<<50] + [int(input()) for i in range(a)] + [1<<50]
A, B, Q = map(int, input().split())
S, T = I(A), I(B)

for _ in range(Q):
    x = int(input())
    k, l = bl(S, x), bl(T, x)
    a, b, c, d = x-S[k-1], x-T[l-1], S[k]-x, T[l]-x
    print(min(max(a, b), max(c, d), 2*a+d, 2*d+a, 2*b+c, 2*c+b))

Submission status: Accepted

Solution code:
from bisect import bisect_left

[A, B, Q] = list(map(int, input().split(" ")))
shrine_list = []
temple_list = []
question_list = []
for _ in range(A):
    shrine_list.append(int(input()))
for _ in range(B):
    temple_list.append(int(input()))
for _ in range(Q):
    question_list.append(int(input()))

minInf = - 1e11
inf = 1e11
shrine_list.insert(0, minInf)
shrine_list.append(inf)
temple_list.insert(0, minInf)
temple_list.append(inf)

for question in question_list:
    shrine_index = bisect_left(shrine_list, question)
    temple_index = bisect_left(temple_list, question)
    left_shrine = shrine_list[shrine_index - 1]
    right_shrine = shrine_list[shrine_index]
    left_temple = temple_list[temple_index - 1]
    right_temple = temple_list[temple_index]
    # left, left   left, right  right, left  right, right
    left_left = max(abs(question - left_shrine), abs(question - left_temple))
    right_right = max(abs(question - right_shrine), abs(question - right_temple))
    left_right = abs(question - left_shrine) + abs(question - right_temple) + min(abs(question - left_shrine),
                                                                                  abs(question - right_temple))
    right_left = abs(question - right_shrine) + abs(question - left_temple) + min(abs(question - right_shrine),
                                                                                  abs(question - left_temple))
    print(round(min(left_left, right_right, left_right, right_left)))

Submission status: Accepted

Solution code:
import sys

A, B, Q = map(int, sys.stdin.readline().split())
INF = 10 ** 18
S = [-INF] + [int(sys.stdin.readline()) for _ in range(A)] + [INF]
T = [-INF] + [int(sys.stdin.readline()) for _ in range(B)] + [INF]
X = [int(sys.stdin.readline()) for _ in range(Q)]


def binary_search(q, A):
    l, r = 0, len(A)
    while r-l>1:
        mid = (l + r) // 2
        if q > A[mid]:
            l = mid
        else:
            r = mid
    return A[l], A[r]


def main():
    for x in X:
        s1, s2 = binary_search(x, S)
        t1, t2 = binary_search(x, T)
        print(min(abs(s-t) + min(abs(s-x), abs(t-x)) for s in [s1, s2] for t in [t1, t2]))
    return

if __name__ == '__main__':
    main()

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 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 = abs(x-T) + abs(T-S) #t -> s
            d2 = abs(x-S) + abs(S-T) #s -> t
            res = min(res,d1,d2)
    print(res)

Submission status: Accepted

Solution code:

from bisect import bisect_left as bl
from sys import maxint as mi
A,B,Q=map(int,raw_input().split())
da=list()
for i in xrange(A):
	da.append(int(raw_input()))
db=list()
for i in xrange(B):
	db.append(int(raw_input()))
da.sort()
db.sort()

for i in xrange(Q):
	p=int(raw_input())
	a=bl(da,p)
	b=bl(db,p)
	v1,v2=mi if a>A-1 else da[a],mi if b>B-1 else db[b]
	x0=abs(v1-p)
	x0=x0+min(abs(v1-v2),mi if b+1>=B else abs(v1-db[b+1]),mi if b-1<0 else abs(v1-db[b-1]))
	x1=mi
	if a>0:
		x1=abs(da[a-1]-p)
		x1=x1+min(abs(da[a-1]-v2),mi if b+1>=B else abs(da[a-1]-db[b+1]),mi if b-1<0 else abs(da[a-1]-db[b-1]))
	x2=mi
	if a+1<A:
		x2=abs(da[a+1]-p)
		x2=x2+min(abs(da[a+1]-v2),mi if b+1>=B else abs(da[a+1]-db[b+1]),mi if b-1<0 else abs(da[a+1]-db[b-1]))
	v=min(x0,x1,x2)
	
	x0=abs(v2-p)
	x0=x0+min(abs(v1-v2),mi if a+1>=A else abs(v2-da[a+1]),mi if a-1<0 else abs(v2-da[a-1]))
	x1=mi
	if b>0:
		x1=abs(db[b-1]-p)
		x1=x1+min(abs(db[b-1]-v1),mi if a+1>=A else abs(db[b-1]-da[a+1]),mi if a-1<0 else abs(db[b-1]-da[a-1]))
	x2=mi
	if b+1<B:
		x2=abs(db[b+1]-p)
		x2=x2+min(abs(db[b+1]-v1),mi if a+1>=A else abs(db[b+1]-da[a+1]),mi if a-1<0 else abs(db[b+1]-da[a-1]))
	print min(v,x0,x1,x2)

Submission status: Accepted

Solution code:
import bisect
import sys

SENTINEL = 10 ** 12

a, b, q = list(map(int, input().split()))
lines = sys.stdin.readlines()
sss = [-SENTINEL] + list(map(int, lines[:a])) + [SENTINEL]
ttt = [-SENTINEL] + list(map(int, lines[a:a + b])) + [SENTINEL]
xxx = list(map(int, lines[a + b:]))

nearest_temples = [SENTINEL] + [0] * a + [SENTINEL]
nearest_shrines = [SENTINEL] + [0] * b + [SENTINEL]
for i, s in enumerate(sss[1:-1], start=1):
    ti = bisect.bisect(ttt, s)
    nearest_temples[i] = min(ttt[ti] - s, s - ttt[ti - 1])
for i, t in enumerate(ttt[1:-1], start=1):
    si = bisect.bisect(sss, t)
    nearest_shrines[i] = min(sss[si] - t, t - sss[si - 1])

buf = []
for x in xxx:
    si = bisect.bisect(sss, x)
    ti = bisect.bisect(ttt, x)
    ans = min(x - sss[si - 1] + nearest_temples[si - 1],
              sss[si] - x + nearest_temples[si],
              x - ttt[ti - 1] + nearest_shrines[ti - 1],
              ttt[ti] - x + nearest_shrines[ti])
    buf.append(ans)
print('\n'.join(map(str, buf)))

Submission status: Accepted

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]

results = ""
for _ in range(q):
    x = int(input())
    si = bisect.bisect_right(s, x)
    spos = [s[si], s[si - 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 or 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: Accepted

Solution code:
# -*- coding: utf-8 -*-
import math
import sys
import bisect

## input
a,b,q = map(int, sys.stdin.readline().rstrip().split())
s_s, t_s, x_s = [[-10**11], [-10**11], []]
for _ in range(a):
  s_s.append(int(sys.stdin.readline().rstrip()))
for _ in range(b):
  t_s.append(int(sys.stdin.readline().rstrip()))
for _ in range(q):
  x_s.append(int(sys.stdin.readline().rstrip()))
s_s.append(10**11)
t_s.append(10**11)


def solve(k):
  s_pos = bisect.bisect_left(s_s, k)
  t_pos = bisect.bisect_left(t_s, k)
  mn = 10**11
  for i in [s_s[s_pos-1], s_s[s_pos]]:
    for j in [t_s[t_pos-1], t_s[t_pos]]:
      mn = min(mn,abs(i-k)+abs(i-j), abs(j-k)+abs(i-j))
  return(mn)

if __name__ == "__main__":
  for x in x_s:
    print(solve(x))

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: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: Accepted

Solution code:
import bisect
INF = 10 ** 12

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

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
import bisect

A,B,Q = map(int,input().split())
S,T = [-10**18],[-10**18]

for i in range(A):
    S.append(int(input()))
S.append(10**18)
for i in range(B):
    T.append(int(input()))
T.append(10**18)

for q in range(Q):
    x = int(input())
    res = 10**18
    s_idx = bisect.bisect_right(S,x)
    t_idx = bisect.bisect_right(T,x)
    for s in [S[s_idx-1],S[s_idx]]:
        for t in [T[t_idx-1],T[t_idx]]:
            d1,d2 = abs(s-x)+abs(t-s),abs(t-x)+abs(s-t)
            res = min(res,d1,d2)
    print(res)

Submission status: Accepted

Solution code:
import bisect
A, B, Q = list(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()))
INF = 10 ** 12
S = [-INF] + S + [INF]
T = [-INF] + T + [INF]

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