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:
a,b,q=map(int,input().split())
s=[-10**30]+[int(input())for _ in range(a)]+[10**30]
t=[-10**30]+[int(input())for _ in range(b)]+[10**30]
x=[int(input())for _ in range(q)]
from bisect import bisect_left,bisect_right
for xx in x:
  s1=s[bisect_right(s,xx)-1]
  s2=s[bisect_right(s,xx)]
  t1=t[bisect_right(t,xx)-1]
  t2=t[bisect_right(t,xx)]
  ans=[]
  ans.append(abs(s1-t1)+min(abs(xx-s1),abs(xx-t1)))
  ans.append(abs(s1-t2)+min(abs(xx-s1),abs(xx-t2)))
  ans.append(abs(s2-t1)+min(abs(xx-s2),abs(xx-t1)))
  ans.append(abs(s2-t2)+min(abs(xx-s2),abs(xx-t2)))
  print(min(ans))

Submission status: Accepted

Solution code:
from bisect import bisect_left as bl
def dist(p1,p2): return abs(p1-p2)
INF = 10**18
a,b,q = map(int,input().split())
S = [-INF]+[int(input()) for _ in range(a)]+[INF]
T = [-INF]+[int(input()) for _ in range(b)]+[INF]
X = [int(input()) for _ in range(q)]

for i in range(q):
    ans = INF
    s = bl(S,X[i])
    t = bl(T,X[i])
    p = ((s,t),(s-1,t-1))
    for ps,pt in p:
        if dist(X[i],S[ps]) < dist(X[i],T[pt]):
            pt = bl(T,S[ps])
            ans = min(ans , dist(X[i],S[ps])+min(dist(S[ps],T[pt]),dist(S[ps],T[pt-1])))
        else:
            ps = bl(S,T[pt])
            ans = min(ans , dist(X[i],T[pt])+min(dist(T[pt],S[ps]),dist(T[pt],S[ps-1])))
    print(ans)

Submission status: Accepted

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

from bisect import bisect_left, bisect_right

def main():
    A, B, Q = map(int, input().split())
    a = [int(input()) for _ in range(A)]
    b = [int(input()) for _ in range(B)]
    q = [int(input()) for _ in range(Q)]
    INF = 2*10**10
    a = [-INF] + a + [INF]
    b = [-INF] + b + [INF]

    for x in q:
        ai = bisect_left(a, x)
        ap = a[ai]-x
        am = x-a[ai-1]
        bi = bisect_left(b, x)
        bp = b[bi]-x
        bm = x-b[bi-1]

        ret = INF
        if max(ap,bp)<INF:
            ret = min(ret, max(ap, bp))
        if max(am,bm)<INF:
            ret = min(ret, max(am, bm))
        ret = min(ret, ap+2*bm, am+2*bp, bp+2*am, bm+2*ap)
        print(ret)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import bisect
A, B, Q = map(int, input().split())
S = [int(sys.stdin.readline().rstrip()) for _ in range(A)]
T = [int(sys.stdin.readline().rstrip()) for _ in range(B)]

def solver(S, A, x):
    d = []
    a = bisect.bisect_right(S, x)

    if a == A:
        d.append((-1, x - S[-1]))
    elif a == 0:
        d.append((1, S[0] - x))
    else:
        d.append((-1, x - S[a - 1]))
        d.append((1, S[a] - x))

    return d

for _ in range(Q):
    ans = 0
    x = int(sys.stdin.readline().rstrip())

    d_a = solver(S, A, x)
    d_b = solver(T, B, x)

    ans = 10**15
    for i, j in d_a:
        for k, l in d_b:
            if i == k:
                ans = min(ans, max(j, l))
            else:
                ans = min(ans, j + l + min(j, l))
    print(ans)

Submission status: Accepted

Solution code:
import sys
import math
def input():
    return sys.stdin.readline()[:-1]
a,b,q=map(int,input().split())
s=[int(input()) for i in range(a)]
t=[int(input()) for i in range(b)]
x=[int(input()) for i in range(q)]
import bisect

inf=10**11

def tansak(lis,lis2,dis):
    ind=bisect.bisect_left(lis,dis)
    ind2=bisect.bisect_left(lis2,dis)
    return ind,ind2

for i in range(q):
    now = x[i]
    ind,ind2 = tansak(s,t,now)
    if  ind==0:
        one=-inf
    else:
        one=s[ind-1]
    if ind==a:
        two=inf
    else:
        two=s[ind]
    if ind2==0:
        thr=-inf
    else:
        thr=t[ind2-1]
    if ind2==b:
        fo=inf
    else:
        fo=t[ind2]
    tmp1=max(two,fo)-now
    tmp2=2*two-thr-now
    tmp3=2*fo-one-now
    tmp4=now-min(one,thr)
    tmp5=now-thr+two-thr
    tmp6=now-one+fo-one
    print(min(tmp1,tmp2,tmp3,tmp4,tmp5,tmp6))

Submission status: Accepted

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

inf=10**11

def tansak(lis,lis2,dis):
    ind=bisect.bisect_left(lis,dis)
    ind2=bisect.bisect_left(lis2,dis)
    return ind,ind2

for i in range(q):
    now = x[i]
    ind,ind2 = tansak(s,t,now)
    if  ind==0:
        one=-inf
    else:
        one=s[ind-1]
    if ind==a:
        two=inf
    else:
        two=s[ind]
    if ind2==0:
        thr=-inf
    else:
        thr=t[ind2-1]
    if ind2==b:
        fo=inf
    else:
        fo=t[ind2]
    tmp1=max(two,fo)-now
    tmp2=2*two-thr-now
    tmp3=2*fo-one-now
    tmp4=now-min(one,thr)
    tmp5=now-thr+two-thr
    tmp6=now-one+fo-one
    print(min(tmp1,tmp2,tmp3,tmp4,tmp5,tmp6))

Submission status: Accepted

Solution code:
import bisect
def find_min_fuka_idx(lst, x):
  ok = -1
  ng = len(lst)
  while abs(ok-ng)>1:
    mid = (ok+ng)//2
    if x>=lst[mid]:
      ok = mid
    else:
      ng = mid
  return ng

a,b,q = map(int, input().split())
s = [-10**18]
s_mid = [int(input()) for i in range(a)]
s.extend(s_mid)
s.append(10**18)

t = [-10**18]
t_mid = [int(input()) for i in range(b)]
t.extend(t_mid)
t.append(10**18)

for i in range(q):
  x = int(input())
  si = bisect.bisect_right(s, x)
  tj = bisect.bisect_right(t, x)
  print(min(abs(x-s[si])+abs(s[si]-t[tj]),\
            abs(x-s[si])+abs(s[si]-t[tj-1]),\
           abs(x-t[tj])+abs(t[tj]-s[si]),\
            abs(x-t[tj])+abs(t[tj]-s[si-1]),\
            abs(x-s[si-1])+abs(s[si-1]-t[tj]),\
            abs(x-s[si-1])+abs(s[si-1]-t[tj-1]),\
           abs(x-t[tj-1])+abs(t[tj-1]-s[si]),\
            abs(x-t[tj-1])+abs(t[tj-1]-s[si-1])))

Submission status: Accepted

Solution code:
import bisect
A,B,Q=map(int,input().split())
INF=10**18
S=[-INF]+[int(input()) for i in range(A)]+[INF]
T=[-INF]+[int(input()) for i in range(B)]+[INF]
for q in range(Q):
    x=int(input())
    i=bisect.bisect_left(S,x)
    j=bisect.bisect_left(T,x)
    d=INF
    for s in [S[i-1],S[i]]:
        for t in [T[j-1],T[j]]:
            d1=abs(x-s)+abs(s-t)
            d2=abs(x-t)+abs(s-t)
            d=min(d,d1,d2)
    print(d)

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]
#print(s)
#print(t)
for _ in range(q):
    start = int(input())
    x = bisect.bisect_right(s, start)
    y = bisect.bisect_right(t, start)
    ans = inf
    for i in [s[x], s[x-1]]:
        for j in [t[y], t[y-1]]:
            res = min(abs(i-start) + abs(j-i), abs(j-start) + abs(i-j))
            ans = min(ans, res)
    print(ans)

Submission status: Accepted

Solution code:
"""
D - Lazy Faith
"""
# 解説を参考に作成（bisect）
import bisect


def solve():
    # データ読込
    A, B, Q = map(int, input().split())
    si = [-float('inf')] + [int(input()) for i in range(A)] + [float('inf')]
    ti = [-float('inf')] + [int(input()) for i in range(B)] + [float('inf')]
    xi = [int(input()) for i in range(Q)]
    # 問題計算
    for x in xi:
        txi = bisect.bisect_left(ti, x)
        left_t = ti[txi - 1]
        right_t = ti[txi]
        sxi = bisect.bisect_left(si, x)
        left_s = si[sxi - 1]
        right_s = si[sxi]
        print(min(abs(x - min(left_t, left_s)),
                  abs(x - max(right_t, right_s)),
                  abs(x - right_t) + abs(right_t - left_s),
                  abs(x - left_t) + abs(left_t - right_s),
                  abs(x - right_s) + abs(right_s - left_t),
                  abs(x - left_s) + abs(left_s - right_t)))


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import bisect

inf = 10**18

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

for i in x:
    a1 = s[bisect.bisect_right(s,i)]
    b1 = t[bisect.bisect_right(t,i)]
    a2 = s[bisect.bisect_right(s,i)-1]
    b2 = t[bisect.bisect_right(t,i)-1]
    ans = inf
    for j in [a1,a2]:
        for k in [b1,b2]:
            ans = min(ans,abs(i-j)+abs(j-k),abs(i-k)+abs(k-j))
    print(ans)

Submission status: Accepted

Solution code:
mod = 1000000007
eps = 10**-9
inf = 10**15


def main():
    import sys
    from bisect import bisect_left
    input = sys.stdin.buffer.readline

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

    for _ in range(Q):
        x = int(input())
        i = bisect_left(S, x)
        j = bisect_left(T, x)
        ans = []
        ans.append(x - S[i-1] + abs(S[i-1] - T[j-1]))
        ans.append(x - S[i-1] + abs(S[i-1] - T[j]))
        ans.append(x - T[j-1] + abs(T[j-1] - S[i-1]))
        ans.append(x - T[j-1] + abs(T[j-1] - S[i]))
        ans.append(S[i] - x + abs(S[i] - T[j-1]))
        ans.append(S[i] - x + abs(S[i] - T[j]))
        ans.append(T[j] - x + abs(T[j] - S[i-1]))
        ans.append(T[j] - x + abs(T[j] - S[i]))
        print(min(ans))


if __name__ == '__main__':
    main()

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

s.sort()
t.sort()

import bisect
#a=[0,2,3,4,67,8]
#a.sort()
for item in x:
    ss=bisect.bisect_left(s, item)
    tmp=[]
    if ss>0:
        tmp.append(s[ss-1])
    if ss<len(s):
        tmp.append(s[ss])
    tmp2=[]
    tt=bisect.bisect_left(t, item)
    if tt>0:
        tmp2.append(t[tt-1])
    if tt<len(t):
        tmp2.append(t[tt])
    #print(item,tmp2,tmp)
    result=10**18
    for item2 in tmp:
        for item3 in tmp2:
            #print(item,item2,item3)
            result=min(result,abs(item-item3)+abs(item3-item2),abs(item-item2)+abs(item3-item2))
    print(result)

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect, bisect_right
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]
start = [int(input()) for _ in range(q)]

for now_start in start:
    s_id = bisect_left(S, now_start)
    t_id = bisect_left(T, now_start)
    dist1 = abs(now_start - min(S[s_id - 1], T[t_id - 1]))
    dist2 = abs(now_start - max(S[s_id], T[t_id]))
    if max(S[s_id - 1], T[t_id - 1]) == S[s_id - 1]:
        dist3 = abs(now_start - S[s_id - 1]) + abs(T[t_id] - S[s_id - 1])
    elif max(S[s_id - 1], T[t_id - 1]) == T[t_id - 1]:
        dist3 = abs(now_start - T[t_id - 1]) + abs(S[s_id] - T[t_id - 1])
    if min(S[s_id], T[t_id]) == S[s_id]:
        dist4 = abs(now_start - S[s_id]) + abs(T[t_id - 1] - S[s_id])
    elif min(S[s_id], T[t_id]) == T[t_id]:
        dist4 = abs(now_start - T[t_id]) + abs(S[s_id - 1] - T[t_id])
    print(min(dist1, dist2, dist3, dist4))

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)]
s.sort()
t.sort()
#print(s)
#print(t)
#print(x)
from bisect import bisect_left

def search_st(xi, s, t):
    ret = 10 ** 15
    ls = len(s)
    lt = len(t)
    ss = bisect_left(s, xi)
    si = s[ss % ls]
    st = bisect_left(t, si)
    ti = t[st % lt]
    ret = min(ret, abs(xi - si) + abs(si - ti))
    #print(si, ti, ret)
    st -= 1
    ti = t[st % lt]
    ret = min(ret, abs(xi - si) + abs(si - ti))
    #print(si, ti, ret)
    ss -= 1
    si = s[ss % ls]
    st = bisect_left(t, si)
    ti = t[st % lt]
    ret = min(ret, abs(xi - si) + abs(si - ti))
    #print(si, ti, ret)
    st -= 1
    ti = t[st % lt]
    ret = min(ret, abs(xi - si) + abs(si - ti))
    #print(si, ti, ret)
    return ret

for i in range(q):
    xi = x[i]
    ans = 10 ** 15
    # sから先
    ans = min(ans, search_st(xi, s, t))
    ans = min(ans, search_st(xi, t, s))
    print(ans)

Submission status: Accepted

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

A, B, Q = map(int, input().split())
Shrine = [int(input()) for _ in range(A)]
Temple = [int(input()) for _ in range(B)]
X = [int(input()) for _ in range(Q)]
Shrine = [-100000000000] + Shrine + [100000000000]
Temple = [-100000000000] + Temple + [100000000000]

for x in X:
    nums = bisect.bisect_left(Shrine, x)
    tems = bisect.bisect_left(Temple, x)
    ans1 = max(abs(Shrine[nums]-x), abs(Temple[tems]-x))
    ans2 = max(abs(x - Shrine[nums-1]), abs(x - Temple[tems-1]))
    ans3 = abs(Shrine[nums]-x) * 2 + abs(x - Temple[tems-1])
    ans4 = abs(Temple[tems]-x) * 2 + abs(x - Shrine[nums-1])
    ans5 = abs(x - Shrine[nums-1]) * 2 + abs(Temple[tems]-x)
    ans6 = abs(x - Temple[tems-1]) * 2 + abs(Shrine[nums]-x)

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

Submission status: Accepted

Solution code:
import bisect,sys
input = sys.stdin.readline
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 i in range(q):
  x = int(input())
  i = bisect.bisect_right(s,x)
  j = bisect.bisect_right(t,x)
  print(min(max(s[i],t[j])-x,x-min(s[i-1],t[j-1]),min(s[i]-x,x-t[j-1])+s[i]-t[j-1],min(t[j]-x,x-s[i-1])+t[j]-s[i-1]))

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
def input(): return sys.stdin.readline().strip()

def main():
    A, B, Q = map(int, input().split())
    S = [-10**50]
    T = [-10**50]
    for _ in range(A): S.append(int(input()))
    for _ in range(B): T.append(int(input()))
    S.append(10**50)
    T.append(10**50)

    for _ in range(Q):
        x = int(input())
        idx1 = bisect_left(S, x)
        idx2 = bisect_left(T, x)
        ans = 10 ** 11
        cand1 = (x - S[idx1 - 1]) + abs(S[idx1 - 1] - T[idx2 - 1])
        ans = min(ans, cand1)
        cand2 = (x - S[idx1 - 1]) + (T[idx2] - S[idx1 - 1])
        ans = min(ans, cand2)
        cand3 = (S[idx1] - x) + (S[idx1] - T[idx2 - 1])
        ans = min(ans, cand3)
        cand4 = (S[idx1] - x) + abs(S[idx1] - T[idx2])
        ans = min(ans, cand4)
        cand5 = (x - T[idx2 - 1]) + abs(T[idx2 - 1] - S[idx1 - 1])
        ans = min(ans, cand5)
        cand6 = (x - T[idx2 - 1]) + (S[idx1] - T[idx2 - 1])
        ans = min(ans, cand6)
        cand7 = (T[idx2] - x) + (T[idx2] - S[idx1 - 1])
        ans = min(ans, cand7)
        cand8 = (T[idx2] - x) + abs(T[idx2] - S[idx1])
        ans = min(ans, cand8)
        print(ans)



if __name__ == "__main__":
    main()

Submission status: Accepted

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

import sys
# import math
# from string import ascii_lowercase, ascii_upper_case, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from copy import deepcopy                    # to copy multi-dimentional matrix without reference
# from fractions import gcd                    # for Python 3.4 (previous contest @AtCoder)


def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79...e+308
    # inf = 2 ** 64 - 1               # (for fast JIT compile in PyPy) 1.84...e+19
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    a, b, q = mi()
    shrine = [ii() for _ in range(a)]
    temple = [ii() for _ in range(b)]
    query = [ii() for _ in range(q)]

    shrine.sort()
    temple.sort()

    for x in query:
        ans = inf
        # print('')
        # 右にのみ進む
        if x <= shrine[-1] and x <= temple[-1]:
            dist = max(abs(x - shrine[bisect_left(shrine, x)]), abs(x - temple[bisect_left(temple, x)]))
            # print(dist)
            ans = min(ans, dist)
        # 左にのみ進む
        if shrine[0] <= x and temple[0] <= x:
            dist = max(abs(x - shrine[bisect_right(shrine, x) - 1]), abs(x - temple[bisect_right(temple, x) - 1]))
            # print(dist)
            ans = min(ans, dist)
        # 右で神社、左で寺を見つける
        if x <= shrine[-1] and temple[0] <= x:
            a = abs(x - shrine[bisect_left(shrine, x)])
            b = abs(x - temple[bisect_right(temple, x) - 1])
            dist = a + b + min(a, b)
            # print(dist)
            ans = min(ans, dist)
        # 右で寺、左で神社を見つける
        if x <= temple[-1] and shrine[0] <= x:
            a = abs(x - temple[bisect_left(temple, x)])
            b = abs(x - shrine[bisect_right(shrine, x) - 1])
            dist = a + b + min(a, b)
            # print(dist)
            ans = min(ans, dist)
        
        # print('ans')
        print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)


def main():
    a, b, q = list(map(int, readline().split()))
    s = [0] * (a + 2)
    t = [0] * (b + 2)
    d = [0] * (a + b + 2)

    for i in range(1, a + 1):
        dist = int(input())
        s[i] = dist
        d[i] = (dist, 0)

    s[0] = -INF
    s[a + 1] = INF

    for i in range(1, b + 1):
        dist = int(input())
        t[i] = dist
        d[a + i] = (dist, 1)

    t[0] = -INF
    t[b + 1] = INF

    d[0] = (-INF, 0)
    d[-1] = (INF, 0)

    d.sort()
    d2 = [k[0] for k in d]
    import bisect

    for _ in range(q):
        x = int(input())
        d_idx = bisect.bisect_left(d2, x)
        left = d[d_idx - 1]
        right = d[d_idx]
        res_left = x - left[0]
        res_right = right[0] - x

        if left[1] == 0:
            t_idx = bisect.bisect_left(t, left[0])
            tl = t[t_idx - 1]
            tr = t[t_idx]
            res_left += min(abs(left[0] - tl), abs(tr - left[0]))
        else:
            s_idx = bisect.bisect_left(s, left[0])
            sl = s[s_idx - 1]
            sr = s[s_idx]
            res_left += min(abs(left[0] - sl), abs(sr - left[0]))

        if right[1] == 0:
            t_idx = bisect.bisect_left(t, right[0])
            tl = t[t_idx - 1]
            tr = t[t_idx]
            res_right += min(abs(right[0] - tl), abs(tr - right[0]))
        else:
            s_idx = bisect.bisect_left(s, right[0])
            sl = s[s_idx - 1]
            sr = s[s_idx]
            res_right += min(abs(right[0] - sl), abs(sr - right[0]))
        print(min(res_left, res_right))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from bisect import bisect_left
INF = 10 ** 11

def main():
    A, B, Q = map(int, readline().rstrip().split())
    S = [-INF] + [int(readline()) for _ in range(A)] + [INF]
    T = [-INF] + [int(readline()) for _ in range(B)] + [INF]

    for _ in range(Q):
        x = int(readline())
        s_right_idx = bisect_left(S, x)
        s_left,  s_right = S[s_right_idx - 1], S[s_right_idx]
        
        t_right_idx = bisect_left(T, x)
        t_left,  t_right = T[t_right_idx - 1], T[t_right_idx]

        s_left_d, s_right_d = x - s_left, s_right - x
        t_left_d, t_right_d = x - t_left, t_right - x

        res1 = max(s_right_d, t_right_d)
        res2 = max(s_left_d, t_left_d)
        res3 = min(s_right_d * 2 + t_left_d, t_right_d * 2 + s_left_d)
        res4 = min(s_right_d + t_left_d * 2, t_right_d + s_left_d * 2)
        res = min(res1, res2, res3, res4)
        print(res)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
from bisect import bisect_left
INF = 10 ** 11

def main():
    A, B, Q = map(int, readline().rstrip().split())
    S = [int(readline()) for _ in range(A)]
    T = [int(readline()) for _ in range(B)]

    for _ in range(Q):
        x = int(readline())
        s_right_idx = bisect_left(S, x)
        if s_right_idx == 0:
            s_right = S[s_right_idx]
            s_left = -INF
        elif s_right_idx == A:
            s_left = S[s_right_idx-1]
            s_right = INF
        else:
            s_left,  s_right = S[s_right_idx - 1], S[s_right_idx]
        
        t_right_idx = bisect_left(T, x)
        if t_right_idx == 0:
            t_right = T[t_right_idx]
            t_left = -INF
        elif t_right_idx == B:
            t_left = T[t_right_idx-1]
            t_right = INF
        else:
            t_left,  t_right = T[t_right_idx - 1], T[t_right_idx]

        s_left_d, s_right_d = x - s_left, s_right - x
        t_left_d, t_right_d = x - t_left, t_right - x

        res1 = max(s_right_d, t_right_d)
        res2 = max(s_left_d, t_left_d)
        res3 = min(s_right_d * 2 + t_left_d, t_right_d * 2 + s_left_d)
        res4 = min(s_right_d + t_left_d * 2, t_right_d + s_left_d * 2)
        res = min(res1, res2, res3, res4)
        print(res)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect

A, B, Q = map(int, input().split())
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
for _ in range(Q):
    x = int(input())
    sr = min(bisect.bisect_left(S, x), A - 1)
    sl = max(sr - 1, 0)
    tr = min(bisect.bisect_left(T, x), B - 1)
    tl = max(tr - 1, 0)
    print(min(abs(x - S[sl]) + abs(S[sl] - T[tl]),
              abs(x - S[sl]) + abs(S[sl] - T[tr]),
              abs(x - S[sr]) + abs(S[sr] - T[tl]),
              abs(x - S[sr]) + abs(S[sr] - T[tr]),
              abs(x - T[tl]) + abs(T[tl] - S[sl]),
              abs(x - T[tl]) + abs(T[tl] - S[sr]),
              abs(x - T[tr]) + abs(T[tr] - S[sl]),
              abs(x - T[tr]) + abs(T[tr] - S[sr])))

Submission status: Accepted

Solution code:
from bisect import bisect_left


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

ans = []
for x in X:
    idx_s = bisect_left(S, x)
    idx_t = bisect_left(T, x)
    candidate = [max(abs(x - T[idx_t - 1]), abs(x - S[idx_s-1])),
                max(abs(x - S[idx_s]), abs(x - T[idx_t])),
                2*abs(x - S[idx_s-1]) + abs(x - T[idx_t]),
                2*abs(x - T[idx_t]) + abs(x - S[idx_s-1]),
                2*abs(x - T[idx_t-1]) + abs(x - S[idx_s]),
                2*abs(x - S[idx_s]) + abs(x - T[idx_t-1])
                ]
    ans.append(min(candidate))

print(*ans, sep="\n")

Submission status: Accepted

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

A,B,Q = map(int,(input().split()))
s = [[0]*3 for _ in range(A)]
t = [[0]*3 for _ in range(B)]
x = [[0]*3 for _ in range(Q)]
slen = []
tlen = []
road = []
for i in range(A):
    s[i][0] = int(input())
    slen.append(s[i][0])
    s[i][1] = "s"
    road.append(s[i])
for i in range(B):
    t[i][0] = int(input())
    tlen.append(t[i][0])
    t[i][1] = "t"
    road.append(t[i])
for i in range(Q):
    x[i][0] = int(input())
road.sort()

for i in range(len(s)):
    index = bisect.bisect_left(tlen,s[i][0])
    if index < B:
        s[i][2] = min(abs(s[i][0]-tlen[index-1]),abs(tlen[index]-s[i][0]))
    else:
        s[i][2] = abs(s[i][0]-tlen[index-1])
for i in range(len(t)):
    index = bisect.bisect_left(slen,t[i][0])
    if index < A:
        t[i][2] = min(abs(t[i][0]-slen[index-1]),abs(slen[index]-t[i][0]))
    else:
        t[i][2] = abs(t[i][0]-slen[index-1])

for i in range(Q):
    index = bisect.bisect_left(road,x[i])
    if index < A+B:
        print(min(abs(x[i][0]-road[index-1][0])+road[index-1][2],abs(x[i][0]-road[index][0])+road[index][2]))
    else:
        print(abs(x[i][0]-road[index-1][0])+road[index-1][2])

Submission status: Accepted

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


def upper(arr, x):
    # xよりも大きい最小のindexを返す
    if arr[0] > x:
        return 0
    high, low = len(arr), 0
    while high - low > 1:
        mid = (high + low) // 2
        if arr[mid] > x:
            high = mid
        else:
            low = mid
    return high


def lower(arr, x):
    # xよりも小さい最大のindexを返す
    if arr[-1] < x:
        return len(arr) - 1
    high, low = len(arr) - 1, -1
    while high - low > 1:
        mid = (high + low) // 2
        if arr[mid] < x:
            low = mid
        else:
            high = mid
    return low


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

for _ in range(Q):
    x = int(input())
    shr_u, shr_l = upper(s, x), lower(s, x)
    tmp_u, tmp_l = upper(t, x), lower(t, x)
    ans = 10 ** 18
    if shr_u != A and tmp_u != B:
        ans = min(ans, max(s[shr_u] - x, t[tmp_u] - x))
    if shr_l != -1 and tmp_l != -1:
        ans = min(ans, max(x - s[shr_l], x - t[tmp_l]))
    if shr_l != -1 and tmp_u != B:
        cost = t[tmp_u] - s[shr_l] + min(x - s[shr_l], t[tmp_u] - x)
        ans = min(ans, cost)
    if shr_u != A and tmp_l != -1:
        cost = s[shr_u] - t[tmp_l] + min(s[shr_u] - x, x - t[tmp_l])
        ans = min(ans, cost)
    print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
try:
    from typing import List
except ImportError:
    pass


def bisect(a: "List[int]", x: int):
    lb = 0
    rb = len(a) + 1
    while lb + 1 < rb:
        m = (lb + rb) // 2
        if a[m - 1] >= x:
            rb = m
        else:
            lb = m
    return lb


def solve(A: int, B: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):
    for xk in x:
        i = bisect(s, xk)
        j = bisect(t, xk)
        m = float("inf")
        if i > 0 and j > 0:
            m2 = max(xk - s[i - 1], xk - t[j - 1])
            m = min(m, m2)
        if i > 0 and j < B:
            ld = xk - s[i - 1]
            rd = t[j] - xk
            m2 = min(ld + ld + rd, ld + rd + rd)
            m = min(m, m2)
        if i < A and j > 0:
            rd = s[i] - xk
            ld = xk - t[j - 1]
            m2 = min(ld + ld + rd, ld + rd + rd)
            m = min(m, m2)
        if i < A and j < B:
            m2 = max(s[i] - xk, t[j] - xk)
            m = min(m, m2)
        print(m)


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    s = [int(next(tokens)) for _ in range(A)]  # type: "List[int]"
    t = [int(next(tokens)) for _ in range(B)]  # type: "List[int]"
    x = [int(next(tokens)) for _ in range(Q)]  # type: "List[int]"
    solve(A, B, Q, s, t, x)


if __name__ == '__main__':
    main()