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 sys
import bisect

def main():
  input = sys.stdin.readline
  inf = pow(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]
  
  for _ in range(q):
    x = int(input())
    i = bisect.bisect_left(s, x)
    j = bisect.bisect_left(t, x)
    ans = inf
    for l in range(-1, 1):
      for m in range(-1, 1):
        sub = min([abs(x-s[i+l]), abs(x-t[j+m])])+abs(s[i+l]-t[j+m])
        if ans > sub:
          ans = sub
    print(ans)

if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
import bisect

a, b, q = list(map(int, input().split(' ')))
inf = float('inf')

sa = [None] * a
for i in range(a):
    sa[i] = (int(input()))

tb = [None] * b
for i in range(b):
    tb[i] = (int(input()))

xq = [None] * q
for i in range(q):
    xq[i] = (int(input()))

sa = [-inf] + sa + [inf]
tb = [-inf] + tb + [inf]

for x in xq:
    result = float('inf')

    l = bisect.bisect_left(sa, x)
    m = bisect.bisect_left(tb, x)

    for v in [sa[l - 1], sa[l]]:
        for w in [tb[m - 1], tb[m]]:
            o = abs(x - v) + abs(v - w)
            p = abs(x - w) + abs(w - v)
            result = min(result, o, p)

    print(result)

Submission status: Accepted

Solution code:
import sys

def main():
  input = sys.stdin.readline
  a, b, q = map(int, input().split())
  s = [0]*a
  for i in range(a):
    s[i] = int(input())
  
  t = [0]*b
  for i in range(b):
    t[i] = int(input())

  s_near = [0]*a
  k = 0
  for i in range(a):
    if k == b-1:
      s_near[i] = abs(s[i]-t[b-1])
      continue
    while True:
      sub = min([abs(s[i]-t[k]), abs(s[i]-t[k+1])])
      if sub == abs(s[i]-t[k+1]):
        k += 1
        if k == b-1:
          s_near[i] = sub
          break
        continue
      else:
        s_near[i] = sub
        break
  
  t_near = [0]*b
  k = 0
  for i in range(b):
    if k == a-1:
      t_near[i] = abs(t[i]-s[a-1])
      continue
    while True:
      sub = min([abs(t[i]-s[k]), abs(t[i]-s[k+1])])
      if sub == abs(t[i]-s[k+1]):
        k += 1
        if k == a-1:
          t_near[i] = sub
          break
        continue
      else:
        t_near[i] = sub
        break
  
  
  for i in range(q):
    x = int(input())
    if x <= s[0]:
      sub1 = s[0]-x+s_near[0]
    elif x >= s[a-1]:
      sub1 = x-s[a-1]+s_near[a-1]
    else:
      l, r = 0, a
      while r-l > 1:
        k = (r+l)//2
        if x <= s[k]:
          r = k
        else:
          l = k
      sub1 = min([s[r]-x+s_near[r], x-s[l]+s_near[l]])
    
    
    if x <= t[0]:
      sub2 = t[0]-x+t_near[0]
    elif x >= t[b-1]:
      sub2 = x-t[b-1]+t_near[b-1]
    else:
      l, r = 0, b
      while r-l > 1:
        k = (r+l)//2
        if x <= t[k]:
          r = k
        else:
          l = k
      sub2 = min([t[r]-x+t_near[r], x-t[l]+t_near[l]])
    ans = min([sub1, sub2])
    print(ans)


if __name__ == "__main__":
  main()

Submission status: Accepted

Solution code:
import itertools


def solve(x, s_pair, t_pair):
    assert 2 == len(s_pair) == len(t_pair)
    min_dist = 10**11  # large number
    for s, t in itertools.product(s_pair, t_pair):
        min_dist = min([
            min_dist,
            abs(x - s) + abs(s - t),
            abs(x - t) + abs(t - s)
        ])
    return min_dist


def binary_search(x, li):
    lower = 0
    upper = len(li) - 1
    while abs(upper - lower) > 1:
        mid = (lower + upper) // 2
        if li[mid] < x:
            lower = mid
        else:
            upper = mid
    return (li[lower], li[upper])


def main():
    A, B, Q = list(map(int, input().split(' ')))
    s_list = [int(input()) for _ in range(A)]
    s_list.sort()
    t_list = [int(input()) for _ in range(B)]
    t_list.sort()
    x_list = [int(input()) for _ in range(Q)]
    for x in x_list:
        s_pair = binary_search(x, s_list)
        t_pair = binary_search(x, t_list)
        print(solve(x, s_pair, t_pair))


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

Submission status: Accepted

Solution code:
from bisect import bisect_right


a, b, q = map(int, input().split())
INF = 10 ** 18
J = [-INF] + [int(input()) for _ in range(a)] + [INF]
T = [-INF] + [int(input()) for _ in range(b)] + [INF]

for _ in range(q):
  s = int(input())
  b, d = bisect_right(J, s), bisect_right(T, s)
  res = INF
  for j in [J[b - 1], J[b]]:
    for t in [T[d - 1], T[d]]:
      d1, d2 = abs(j - s) + abs(t - j), abs(t - s) + abs(j - t)
      res = min(res, d1, d2)
  print(res)

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 i in range(Q):
    x = int(input())
    s = bisect.bisect_left(S, x)
    t = bisect.bisect_left(T, x)
    saisyo = float("inf")
    for j in [S[s], S[s-1]]:
        for k in [T[t], T[t-1]]:
            saisyo = min(saisyo, abs(j-x)+abs(k-j), abs(k-x)+abs(j-k))
    print(saisyo)

Submission status: Accepted

Solution code:
import bisect
INF = 10**15
A, B, Q = map(int, input().split())
s = [-INF] + [int(input()) for _ in range(A)] + [INF]
t = [-INF] + [int(input()) for _ in range(B)] + [INF]
for i in range(Q):
  x = int(input())
  sw = bisect.bisect_right(s, x)-1 #xより西で一番近い(同じ場所でもいい)神社の番号
  se = sw + 1 #xより東で一番近い神社の番号
  tw = bisect.bisect_right(t, x)-1
  te = tw + 1
  res = INF
  for S in [s[sw], s[se]]:
    for T in [t[tw], t[te]]:
      d1, d2 = abs(x-S) + abs(T-S), abs(x-T) + abs(S-T)
      res = min(res, d1, d2)
  print(res)

Submission status: Accepted

Solution code:
# Python3 (3.4.3)
import sys
input = sys.stdin.readline

# -------------------------------------------------------------
# function
# -------------------------------------------------------------


# -------------------------------------------------------------
# main
# -------------------------------------------------------------
A,B,Q = map(int,input().split())
S = [-float("inf")] + [int(input()) for _ in range(A)] + [float("inf")] # 両端にダミーを追加
T = [-float("inf")] + [int(input()) for _ in range(B)] + [float("inf")] # 両端にダミーを追加
X = [int(input()) for _ in range(Q)]
 
from bisect import bisect_left

for x in X:
    Si,Ti = bisect_left(S,x),bisect_left(T,x)
    Sw,Se = abs(x-S[Si-1]),abs(x-S[Si])
    Tw,Te = abs(x-T[Ti-1]),abs(x-T[Ti])
    ans = [0]*4
    ans[0] = max(Sw,Tw) # 両方ともwest
    ans[1] = max(Se,Te) # 両方ともeast
    ans[2] = 2*min(Sw,Te)+max(Sw,Te) # SwとTeの近い方に行き、反転して行ってない方に行く 
    ans[3] = 2*min(Tw,Se)+max(Tw,Se) # TwとSeの近い方に行き、反転して行ってない方に行く 
    print(min(ans))

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)]
s.append(2*10**10+1)
t.append(2*10**10+1)
import bisect
for i in range(Q):
  a=bisect.bisect_left(s,X[i])
  b=bisect.bisect_left(t,X[i])
  s1,s2=s[a-1],s[a]
  t1,t2=t[b-1],t[b]
  ans=10**10*2
  for k in [s[a],s[a-1]]:
    for j in [t[b],t[b-1]]:
      d=abs(k-j)+min(abs(k-X[i]),abs(j-X[i]))
      ans=min(ans,d)
  print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left

a, b, q = [int(i) for i in input().split()]

s_list = [int(input()) for _ in range(a)]
t_list = [int(input()) for _ in range(b)]

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

    temp_s_t_list = [10 ** 11] * 4
    
    si = bisect_left(s_list, x)
    if si < a:
        temp_s_t_list[0] = s_list[si] - x
    if si > 0:
        temp_s_t_list[1] = s_list[si - 1] - x
    
    ti = bisect_left(t_list, x)
    if ti < b:
        temp_s_t_list[2] = t_list[ti] - x
    if ti > 0:
        temp_s_t_list[3] = t_list[ti - 1] - x

    ans = 10 ** 11 * 3
    for s_x, t_x in [(temp_s_t_list[0], temp_s_t_list[2]), (temp_s_t_list[0], temp_s_t_list[3]), (temp_s_t_list[1], temp_s_t_list[2]), (temp_s_t_list[1], temp_s_t_list[3])]:
        temp_s_x = s_x
        s_x = abs(s_x)
        temp_t_x = t_x
        t_x = abs(t_x)
        if temp_s_x // s_x == temp_t_x // t_x:
            temp = max(s_x, t_x)
        else:
            temp = s_x + t_x + min(s_x, t_x)

        if ans > temp:
            ans = temp
    print(ans)

Submission status: Accepted

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

for i in range(Q):
    bs=bisect_left(s,x[i])
    bt=bisect_left(t,x[i])
    sli=[];bli=[]
    if(bs!=A):
        sli.append(s[bs])
    if(bs!=0):
        sli.append(s[bs-1])
    if(bt!=B):
        bli.append(t[bt])
    if(bt!=0):
        bli.append(t[bt-1])

    res=10**30
    for p in itertools.product(sli,bli):
        if(p[0]<=x[i] and p[1]<=x[i]):
            res=min(res,x[i]-min(p))
        elif(p[0]>=x[i] and p[1]>=x[i]):
            res=min(res,max(p)-x[i])
        else:
            res=min([res,abs(p[1]-x[i])*2+abs(p[0]-x[i]),abs(p[1]-x[i])+abs(p[0]-x[i])*2])
    print(res)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left


def input():
    return sys.stdin.readline().strip()


sys.setrecursionlimit(20000000)


def main():
    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())
        s_index = bisect_left(S, x)
        if s_index == 0:
            S1 = S[s_index]
            S2 = S[s_index]
        elif s_index == A:
            S1 = S[s_index - 1]
            S2 = S[s_index - 1]
        else:
            S1 = S[s_index]
            S2 = S[s_index - 1]

        t_index = bisect_left(T, x)
        if t_index == 0:
            T1 = T[t_index]
            T2 = T[t_index]
        elif t_index == B:
            T1 = T[t_index - 1]
            T2 = T[t_index - 1]
        else:
            T1 = T[t_index]
            T2 = T[t_index - 1]
        answer = float("inf")
        for s in [S1, S2]:
            for t in [T1, T2]:
                r = min(abs(x - s) + abs(t - s), abs(x - t) + abs(t - s))
                if answer > r:
                    answer = r
        print(answer)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_left
import sys


sys.setrecursionlimit(10 ** 6)
INF = float("inf")
MOD = 10 ** 9 + 7


def input():
    return sys.stdin.readline().strip()


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

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

        i = bisect_left(S, x)
        if i == 0:
            s_left = None
        else:
            s_left = S[i - 1]
        if i < A:
            s_right = S[i]
        else:
            s_right = None

        j = bisect_left(T, x)
        if j == 0:
            t_left = None
        else:
            t_left = T[j - 1]

        if j < B:
            t_right = T[j]
        else:
            t_right = None

        # 左にいきっぱなし
        if s_left is not None and t_left is not None:
            ans1 = x - min(s_left, t_left)
        else:
            ans1 = INF

        # みぎにいきっぱなし
        if s_right is not None and t_right is not None:
            ans2 = max(s_right, t_right) - x
        else:
            ans2 = INF

        # 右神社 左寺
        if s_right is not None and t_left is not None:
            ans3 = min(s_right - x + s_right - t_left, x - t_left + s_right - t_left)
        else:
            ans3 = INF

        # 右寺，左神社
        if t_right is not None and s_left is not None:
            ans4 = min(t_right - x + t_right - s_left, x - s_left + t_right - s_left)
        else:
            ans4 = INF

        a = min(ans1, ans2, ans3, ans4)
        ans.append(a)

    for a in ans:
        print(a)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import bisect
a,b,q=map(int,input().split())
S=[];T=[]
for _ in range(a):
    s=int(input())
    S.append(s)
for _ in range(b):
    t=int(input())
    T.append(t)
S.append(10**12)
T.append(10**12)

for _ in range(q):
    x=int(input())
    idx_s=bisect.bisect_left(S,x)
    idx_t=bisect.bisect_left(T,x)
    se=S[idx_s]
    sw=S[idx_s-1]
    te=T[idx_t]
    tw=T[idx_t-1]

    ans=float("inf")
    for ss in [se,sw]:
        for tt in [te,tw]:
            ans=min(ans,abs(ss-x)+abs(tt-ss),abs(tt-x)+abs(tt-ss))
    print(ans)

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

Submission status: Accepted

Solution code:
import bisect

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

for i in range(1,A+1):
    S[i]=int(input())

for i in range(1,B+1):
    T[i]=int(input())

for i in range(Q):
    x=int(input())
    b,d=bisect.bisect_right(S,x), bisect.bisect_right(T,x)
    ans=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)
            ans=min(ans,d1,d2)
    print(ans)

Submission status: Accepted

Solution code:
import bisect

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

for i in range(Q):
    x=int(input())
    b,d=bisect.bisect_right(S,x), bisect.bisect_right(T,x)
    ans=float("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)
            ans=min(ans,d1,d2)
    print(ans)

Submission status: Accepted

Solution code:
# D - Lazy Faith

import bisect
INF = 10**18
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())

for x in X:
    #print(x)
    idxS = bisect.bisect_left(S, x)
    #print('idxS', idxS)
    if idxS==0:
        leftS = INF
        rightS = S[idxS] - x
    elif idxS==A:
        leftS = x - S[idxS-1]
        rightS = INF
    else:
        leftS = x - S[idxS-1]
        rightS = S[idxS] - x
    #print(leftS, rightS)
    idxT = bisect.bisect_left(T, x)
    if idxT==0:
        leftT = INF
        rightT = T[idxT] -x
    elif idxT==B:
        leftT = x - T[idxT-1]
        rightT = INF
    else:
        leftT = x - T[idxT-1]
        rightT = T[idxT] - x
    #print(leftT, rightT)
    ans = max(leftS, leftT)
    ans = min(ans, max(rightS, rightT))
    ans = min(ans, leftS * 2 + rightT)
    ans = min(ans, leftT * 2 + rightS)
    ans = min(ans, leftS + rightT * 2)
    ans = min(ans, leftT + rightS * 2)
    print(ans)

Submission status: Accepted

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

def main():
    a,b,q = map(int,input().split())
    s = []
    t = []
    s1 = []
    t1 = []

    for _ in range(a):
        s.append(int(input()))
    for _ in range(b):
        t.append(int(input()))

    for i in range(a-1):
        s1.append((s[i]+s[i+1])/2)
    for i in range(b-1):
        t1.append((t[i]+t[i+1])/2)

    for _ in range(q):
        x = int(input())
        s_index = bisect.bisect_left(s1, x)
        t_index = bisect.bisect_left(t1, x)
        xs = []
        xt = []
        for i in range(-2, 3):
            if 0 <= s_index + i < a:
                xs.append(s[s_index+i])
            if 0 <= t_index + i < b:
                xt.append(t[t_index+i])
        ans = 10**20
        for i in xs:
            for j in xt:
                ans = min(ans, abs(x-i) + abs(i-j), abs(x-j) + abs(j-i))

        print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

a,b,q = map(int,input().split())
s = []
t = []
s1 = []
t1 = []

for _ in range(a):
    s.append(int(input()))
for _ in range(b):
    t.append(int(input()))

for i in range(a-1):
    s1.append((s[i]+s[i+1])/2)
for i in range(b-1):
    t1.append((t[i]+t[i+1])/2)

for _ in range(q):
    x = int(input())
    s_index = bisect.bisect_left(s1, x)
    t_index = bisect.bisect_left(t1, x)
    xs = []
    xt = []
    for i in range(-2, 3):
        if 0 <= s_index + i < a:
            xs.append(s[s_index+i])
        if 0 <= t_index + i < b:
            xt.append(t[t_index+i])
    ans = 10**20
    for i in xs:
        for j in xt:
            ans = min(ans, abs(x-i) + abs(i-j), abs(x-j) + abs(j-i))

    print(ans)

Submission status: Accepted

Solution code:
import sys
import os
import math
import bisect

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

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

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

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


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

    A, B, Q = il()
    J = [-MAX] + [ii() for _ in range(A)] + [MAX]
    T = [-MAX] + [ii() for _ in range(B)] + [MAX]
    que = [ii() for _ in range(Q)]
    for q in que:
        a = bisect.bisect_left(J, q)
        b = bisect.bisect_left(T, q)
        ret = MAX
        for j in J[a - 1:a + 1]:
            for t in T[b - 1:b + 1]:
                ret = min(ret, abs(j - q) + abs(t - j), abs(t - q) + abs(j - t))
        print(ret)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect
inf = 10**18
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()))
s = [-1*inf] + s + [inf]
t = [-1*inf] + t + [inf]
for i in range(q):
  x = int(input())
  index_s = bisect.bisect_left(s, x)
  index_t = bisect.bisect_right(t, x)
  s1 = abs(s[index_s]-x)#xより右側で一番近い神社までの距離
  s2 = abs(s[index_s-1]-x)#xより左側で~
  t1 = abs(t[index_t]-x)#xより右側で~寺~
  t2 = abs(t[index_t-1]-x)#xより左側で~
  print(min([max(s1, t1), max(s2, t2), 2*s1+t2, 2*t2+s1, 2*s2+t1, 2*t1+s2]))

Submission status: Accepted

Solution code:
from bisect import bisect_left
A, B, Q = map(int,input().split())
INF = 2 * 10 ** 10
S = [-INF]
T = [-INF]
for _ in range(A):
    S.append(int(input()))
S.append(INF)
for _ in range(B):
    T.append(int(input()))
T.append(INF)
for _ in range(Q):
    x = int(input())
    s = bisect_left(S, x)
    t = bisect_left(T, x)
    ans = min(max(S[s], T[t]) - x, x - min(S[s-1], T[t-1]), 2 * S[s] - T[t-1] - x, 2 * T[t] - S[s-1] - x, T[t] + x - 2 * S[s-1], S[s] + x - 2 * T[t-1])
    print(ans)

Submission status: Accepted

Solution code:
import sys,queue,math,copy,itertools,bisect,collections,heapq
sys.setrecursionlimit(10**7)
INF = 10**18
MOD = 10**9 + 7
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
_LI = lambda : [int(x)-1 for x in sys.stdin.readline().split()]
NI = lambda : int(sys.stdin.readline())

A,B,Q = LI()
s = [NI() for _ in range(A)]
t = [NI() for _ in range(B)]
x = [NI() for _ in range(Q)]

s.sort()
t.sort()
s = [-2*INF,-INF] + s + [INF,2*INF]
t = [-2*INF,-INF] + t + [INF,2*INF]

for p in x:
    ans = INF

    si = bisect.bisect_left(s,p)
    s1 = s[si-1]
    s2 = s[si]

    ti1 = bisect.bisect_left(t,s1)
    t11 = t[ti1-1]
    ans = min(ans,p - t11)
    t12 = t[ti1]
    ans = min(ans,(p - s1) + (t12 - s1)  * (t12 > p))

    ti2 = bisect.bisect_left(t,s2)
    t21 = t[ti2-1]
    ans = min(ans,(s2 - p) + (s2 - t21) * (t21 < p))
    t22 = t[ti2]
    ans = min(ans, t22 - p)

    ti = bisect.bisect_left(t, p)
    t1 = t[ti - 1]
    t2 = t[ti]

    si1 = bisect.bisect_left(s, t1)
    s11 = s[si1 - 1]
    ans = min(ans, p - s11)
    s12 = s[si1]
    ans = min(ans, (p - t1) + (s12 - t1) * (s12 > p))

    si2 = bisect.bisect_left(s, t2)
    s21 = s[si2 - 1]
    ans = min(ans, (t2 - p) + (t2 - s21) * (s21 < p))
    s22 = s[si2]
    ans = min(ans, s22 - p)

    print (ans)

Submission status: Accepted

Solution code:
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

from bisect import bisect_left

a, b, q = map(int, readline().split())
s = [int(readline()) for _ in range(a)]
t = [int(readline()) for _ in range(b)]
s.sort()
t.sort()
inf = float('inf')
for i in range(q):
    x = int(readline())
    ans = inf
    index_s = bisect_left(s, x)
    index_t = bisect_left(t, x)
    if index_s > 0 and index_t > 0:
        ans = min(ans, x - min(s[index_s - 1], t[index_t - 1]))
    if index_s < a and index_t < b:
        ans = min(ans, max(s[index_s], t[index_t]) - x)
    if index_s > 0 and index_t < b:
        ans = min(ans, min((x - s[index_s - 1]) * 2 + t[index_t] - x, x - s[index_s - 1] + (t[index_t] - x) * 2))
    if index_s < a and index_t > 0:
        ans = min(ans, min((s[index_s] - x) * 2 + x - t[index_t - 1], s[index_s] - x + (x - t[index_t - 1]) * 2))
    print(ans)

Submission status: Accepted

Solution code:
#template
def inputlist(): return [int(k) for k in input().split()]
def intinput(): return int(input())
#template
A,B,Q = inputlist()
s = [0]*A
t = [0]*B
x = [0]*Q
for i in range(A):
    s[i] = intinput()
for i in range(B):
    t[i] = int(input())
for i in range(Q):
    x[i] = intinput()
s.sort()
t.sort()
ans = [0]*Q
from bisect import bisect_left
for i in range(Q):
    xa = x[i]
    s0,s1 = -1,10**18+1
    t0,t1 = -1,10**18+1
    index_s = bisect_left(s,xa)
    index_t = bisect_left(t,xa)
    if index_s == 0:
        s1 = s[0]
    if index_t == 0:
        t1 = t[0]
    if index_s == A:
        s0 = s[-1]
    if index_t == B:
        t0 = t[-1]
    if index_s != 0 and index_s != A:
        s0 = s[index_s-1]
        s1 = s[index_s]
    if index_t != 0 and index_t != B:
        t0 = t[index_t-1]
        t1 = t[index_t]
    if s0 == -1 or t1 == 10**18+1:
        d1 = 10**18+1
        d2 = 10**18+1
    if s0 != -1 and t1 != 10**18+1:
        d1 = (xa-s0)*2+(t1-xa)
        d2 = (t1-xa)*2+(xa-s0)
    if t0 == -1 or s1 == 10**18+1:
        d3 = 10**18+1
        d4 = 10**18+1
    if t0 != -1 and s1 != 10**18+1:
        d3 = (xa-t0)*2+(s1-xa)
        d4 = (s1-xa)*2+(xa-t0)
    m1 = min(s0,t0)
    M1 = max(s1,t1)
    if m1 == -1:
        d5 = 10**18+1
    if m1 != -1:
        d5 = abs(xa-m1)
    if M1 == 10**18+1:
        d6 = 10**18+1
    if M1 != 10**18+1:
        d6 = abs(xa-M1)
    ans[i] = min(d1,d2,d3,d4,d5,d6)
for i in range(Q):
    print(ans[i])

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)]
x = [int(input()) for _ in range(q)]
inf = pow(10, 12)
s.insert(0, -inf)
s.append(inf)
t.insert(0, -inf)
t.append(inf)
for i in x:
    u, v = bisect.bisect_left(s, i), bisect.bisect_left(t, i)
    s1, s2 = s[u - 1], s[u]
    t1, t2 = t[v - 1], t[v]
    d1 = max(i - s1, i - t1)
    d2 = max(s2 - i, t2 - i)
    d3 = max(i - s1, t2 - i) + 2 * min(i - s1, t2 - i)
    d4 = max(i - t1, s2 - i) + 2 * min(i - t1, s2 - i)
    print(min(d1, d2, d3, d4))

Submission status: Accepted

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

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

def readInts():
  return list(map(int,input().split()))
def main():
    a,b,q = readInts()
    S = [-float("inf")] + [int(input()) for _ in range(a)] + [float("inf")]
    #S = sorted(S)
    T = [-float("inf")] + [int(input()) for _ in range(b)] + [float("inf")]
    for i in range(q):
        ans = float("inf")
        x = int(input())
        Sl = bisect.bisect_left(S,x)
        Tl = bisect.bisect_left(T,x)
        # 4通り試して一番小さいもの!!
        for s in (S[Sl-1],S[Sl]):
            for t in (T[Tl-1],T[Tl]):
                # 最小値、いったんsに行ってs-t, いったんtに行ってt-s で最小値を求める
                ans = min(ans,abs(s-x) + abs(s-t),abs(t-x)+abs(s-t))
        print(ans)
    # print(ans)
    #T = sorted(T)
    # for i in range(q):
    #     x = int(input())
    #     ans = 0
    #     now = x
    #     Sa = float("inf")
    #     Ta = float("inf")
    #     Sidx = bisect.bisect_right(S,x)
    #     Tidx = bisect.bisect_right(T,x)
    #     #print("-!-",x,Sidx,S)
    #     #print("-?-",x,Tidx,T)
    #     # ------------------------------------
    #     if Sidx < len(S):
    #         Sa = abs(S[Sidx] - x)
    #         Si = Sidx
    #     if Sidx - 1 >= 0:
    #         if Sa > abs(S[Sidx-1] - x):
    #             Sa = abs(S[Sidx-1] - x)
    #             Si = Sidx - 1
    #     # ------------------------------------
    #     if Tidx < len(T):
    #         if Ta > abs(T[Tidx] - x):
    #             Ta = abs(T[Tidx] - x)
    #             Ti = Tidx
    #     if Tidx - 1 >= 0:
    #         if Ta > abs(T[Tidx-1] - x):
    #             Ta = abs(T[Tidx-1] - x)
    #             Ti = Tidx - 1
    #     # ------------------------------------
    #     print(S,S[Si])
    #     print(T,T[Ti])
    #     mid = abs((S[Si] - T[Ti]))
    #     if abs(mid + Sa) < abs(mid + Ta):
    #         now = S[Si]
    #         ans += Sa
    #         jin = False
    #     else:
    #         print('?')
    #         if Ti - 1 >= 0:
    #             t =
    #             now = T[Ti]
    #             ans += Ta
    #             jin = True
    #     mi_ = float("inf")
    #     if jin:# 次神社を調べろ
    #         Sidx = bisect.bisect_right(S,now)
    #         if Sidx < len(S):
    #             mi_ = abs(now - S[Sidx])
    #         if Sidx - 1 >= 0:
    #             mi_ = min(mi_, abs(now - S[Sidx-1]))
    #         ans += mi_
    #     else:
    #         Tidx = bisect.bisect_right(T,now)
    #         if Tidx < len(T):
    #             mi_ = abs(now - T[Tidx])
    #         if Tidx - 1 >= 0:
    #             mi_ = min(mi_, abs(now - T[Tidx-1]))
    #         ans += mi_
    #     print(ans)
    #     print("--next--")

if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
import bisect
a, b, q = map(int, input().split())
s = [int(input()) for _i in range(a)]
t = [int(input()) for _i in range(b)]
s.append(float('inf'))
s.insert(0, -float('inf'))
t.append(float('inf'))
t.insert(0, -float('inf'))
x = [int(input()) for _i in range(q)]

for i in x:
    n = bisect.bisect_right(s, i)
    m = bisect.bisect_right(t, i)
    print(min([abs(max([s[n], t[m]])-i), min([abs(i-s[n-1]), abs(i-t[m])])+abs(s[n-1]-t[m]), min([abs(i-s[n]), abs(i-t[m-1])])+abs(s[n]-t[m-1]), abs(i-min(s[n-1], t[m-1]))]))

Submission status: Accepted

Solution code:
import bisect
a, b, q = map(int, input().split())
s = [int(input()) for _i in range(a)]
t = [int(input()) for _i in range(b)]
s.append(float('inf'))
s.insert(0, -float('inf'))
t.append(float('inf'))
t.insert(0, -float('inf'))
x = [int(input()) for _i in range(q)]

for i in x:
    n = bisect.bisect_right(s, i)
    m = bisect.bisect_right(t, i)
    e = abs(max([s[n], t[m]])-i)
    f = abs(i-min(s[n-1], t[m-1]))
    g = min([abs(i-s[n]), abs(i-t[m-1])])+abs(s[n]-t[m-1])
    h = min([abs(i-s[n-1]), abs(i-t[m])])+abs(s[n-1]-t[m])
    print(min([e, f, g, h]))