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 = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
query, X = [], {}

for i in range(Q):
    q = int(input())
    query.append(q)
    X[q] = i
query.sort()

near_s = [0 for _ in range(Q)]
near_t = [0 for _ in range(Q)]
j = 0
while j < Q and query[j] < S[0]:
    near_s[j] = [0, S[0]]
    j += 1    
for i in range(A-1):
    while j < Q and S[i] < query[j] < S[i+1]:
        near_s[j] = [S[i], S[i+1]]
        j += 1
near_s = near_s[:j] + [[S[A-1],0] for _ in range(Q-j)]

j = 0
while j < Q and query[j] < T[0]:
    near_t[j] = [0, T[0]]
    j += 1
for i in range(B-1):
    while j < Q and T[i] < query[j] < T[i+1]:
        near_t[j] = [T[i], T[i+1]]
        j += 1
near_t = near_t[:j] + [[T[B-1],0] for _ in range(Q-j)]

ans = [0]*Q
for i in range(Q):
    q, s0, s1, t0, t1 = query[i], near_s[i][0], near_s[i][1], near_t[i][0], near_t[i][1]
    l1 = q - min(s0, t0)
    l2 = max(s1, t1) - q
    l3 = s1 - t0 + min(s1 - q, q - t0)
    l4 = t1 - s0 + min(t1 - q, q - s0)
    if s0 == 0:
        l1, l4 = float('inf'), float('inf')
    if s1 == 0:
        l2, l3 = float('inf'), float('inf')
    if t0 == 0:
        l1, l3 = float('inf'), float('inf')
    if t1 == 0:
        l2, l4 = float('inf'), float('inf')
    ans[X[q]] = min(l1, l2, l3, l4)

for a in ans:
    print(a)

Submission status: Accepted

Solution code:
import bisect
a,b,q=map(int,input().split())
shrines=[-10**20]+[int(input()) for i in range(a)]+[10**20]
temples=[-10**20]+[int(input()) for i in range(b)]+[10**20]
for i in range(q):
    x=int(input())
    s=bisect.bisect_left(shrines,x)
    t=bisect.bisect_left(temples,x)
    Dsleft=x-shrines[s-1]
    Dtleft=x-temples[t-1]
    Dsright=shrines[s]-x
    Dtright=temples[t]-x
    print(min(max(Dsleft,Dtleft),max(Dsright,Dtright),Dsleft+Dtright+min(Dsleft,Dtright),Dsright+Dtleft+min(Dsright,Dtleft)))

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

from bisect import bisect_left

for _ in range(Q):
    ans = INF
    x = X[_]
    idxs = bisect_left(S, x)
    idxt = bisect_left(T, x)
    for s in [S[idxs-1], S[idxs]]:
        for t in [T[idxt-1], T[idxt]]:
            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:
A,B,Q = map(int,input().split())
S = [int(input()) for _ in range(A)]

T = [int(input()) for _ in range(B)]

X = [int(input()) for _ in range(Q)]

from bisect import bisect_left

for _ in range(Q):
    ans = 10**12
    x = X[_]
    idxs = bisect_left(S,x)
    idxt = bisect_left(T,x)

    if idxs < A and idxt < B:
        ans = min(ans, max(S[idxs],T[idxt])-x)
    if 0 <= idxs-1 and 0 <= idxt-1:
        ans = min(ans, x-min(S[idxs-1],T[idxt-1]))
    if idxs < A and 0 <= idxt-1:
        ans = min(ans, S[idxs]-T[idxt-1] + min(S[idxs]-x, x-T[idxt-1]))
    if idxt < B and 0 <= idxs-1:
        ans = min(ans, T[idxt]-S[idxs-1] + min(T[idxt]-x, x-S[idxs-1]))

    print(ans)

Submission status: Accepted

Solution code:
import bisect
import sys

read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines

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

for _ in range(q):
    x = int(input())
    s_i = bisect.bisect_left(s, x)
    t_i = bisect.bisect_left(t, x)

    s0, s1, t0, t1 = None, None, None, None
    ans = 10 ** 11
    if s_i > 0:
        s0 = x - s[s_i-1]
    if s_i < a:
        s1 = s[s_i] - x
    if t_i > 0:
        t0 = x - t[t_i-1]
    if t_i < b:
        t1 = t[t_i] - x

    if s0 is not None and t0 is not None:
        ans = min(ans, max(s0, t0))
    if s1 is not None and t1 is not None:
        ans = min(ans, max(s1, t1))
    if s0 is not None and t1 is not None:
        ans = min(ans, s0*2 + t1, t1*2 + s0)
    if s1 is not None and t0 is not None:
        ans = min(ans, s1*2 + t0, t0*2 + s1)

    print(ans)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from bisect import bisect_left as bl
a,b,q = map(int,input().split())

s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
s.insert(0,-10**12)
s.append(10**12)
t.insert(0,-10**12)
t.append(10**12)

for i in range(q):
    x = int(input())
    si = bl(s,x)
    ti = bl(t,x)
    ans = 10**12
    for j in range(si-1,si+1):
        for k in range(ti-1,ti+1):
            if s[j] <= t[k]:
                if t[k] <= x:
                    ans = min(ans,x-s[j])
                elif x <= s[j]:
                    ans = min(ans,t[k]-x)
                else:
                    ans = min(ans,min(x-s[j],t[k]-x)+t[k]-s[j])
            else:
                if s[j] <= x:
                    ans = min(ans,x-t[k])
                elif x <= t[k]:
                    ans = min(ans,s[j]-x)
                else:
                    ans = min(ans,min(x-t[k],s[j]-x)+s[j]-t[k])
    print(ans)

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
from bisect import bisect_left
import itertools

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# 番兵を左右に置いて、4通り試す
A, B, Q = lr()
INF = 10 ** 12
S = [-INF] + [ir() for _ in range(A)] + [INF]
T = [-INF] + [ir() for _ in range(B)] + [INF]
S.sort(); T.sort()
for _ in range(Q):
    x = ir()
    si = bisect_left(S, x)
    ti = bisect_left(T, x)
    answer = INF
    for s, t in itertools.product(S[si-1:si+1], T[ti-1:ti+1]):
        temp = min(abs(s-x), abs(t-x)) + abs(s-t)
        if temp < answer:
            answer = temp
    print(answer)
#

Submission status: Accepted

Solution code:
# coding: utf-8
import sys
from bisect import bisect_left

sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

# 番兵を左右に置いて、4通り試す
A, B, Q = lr()
INF = 10 ** 12
S = [-INF] + [ir() for _ in range(A)] + [INF]
T = [-INF] + [ir() for _ in range(B)] + [INF]
S.sort(); T.sort()
for _ in range(Q):
    x = ir()
    si = bisect_left(S, x)
    ti = bisect_left(T, x)
    temp = []
    temp.append(max(S[si], T[ti]) - x)
    y = abs(S[si] - x)
    z = abs(T[ti-1] - x)
    temp.append(min(y, z) * 2 + max(y, z))
    y = abs(S[si-1] - x)
    z = abs(T[ti] - x)
    temp.append(min(y, z) * 2 + max(y, z))
    temp.append(x - min(S[si-1], T[ti-1]))
    print(min(temp))

# 46

Submission status: Accepted

Solution code:
A,B,Q=map(int,input().split())
S=[int(input()) for i in range(A)]+[0,10**10+1]
T=[int(input()) for i in range(B)]+[0,10**10+1]
S=sorted(S)
T=sorted(T)
import bisect
for i in range(Q):
  x=int(input())
  si=bisect.bisect_left(S,x)
  if si==1:
    s1,s2=S[si],S[si]
  elif si==A+1:
    s1,s2=S[si-1],S[si-1]
  else:
    s1,s2=S[si-1],S[si]
  ti=bisect.bisect_left(T,x)
  if ti==1:
    t1,t2=T[ti],T[ti]
  elif ti==B+1:
    t1,t2=T[ti-1],T[ti-1]
  else:
    t1,t2=T[ti-1],T[ti]
  ans=min(abs(x-s1)+min(abs(s1-t1),abs(s1-t2)),
         abs(s2-x)+min(abs(s2-t1),abs(s2-t2)),
         abs(x-t1)+min(abs(t1-s1),abs(t1-s2)),
         abs(t2-x)+min(abs(t2-s1),abs(t2-s2)))
  print(ans)

Submission status: Accepted

Solution code:
nim, mike, kite = map(int, input().split())

INF = 10 ** 11 + 1
S = [-INF] + [int(input()) for _ in range(nim)] + [INF]
T = [-INF] + [int(input()) for _ in range(mike)] + [INF]
X = [int(input()) for _ in range(kite)]

def bsr(a, v):
	lo, hi = 0, len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if x < a[mid]: hi = mid
		else: lo = mid + 1
	return lo

for x in X:
	sr = bsr(S, x)
	sl = sr - 1
	tr = bsr(T, x)
	tl = tr - 1
	cost = []
	for m in [S[sr], S[sl]]:
		for n in [T[tr], T[tl]]:
			cost += [abs(x - m) + abs(m - n), abs(x - n) + abs(m - n)]
	print(min(cost))

Submission status: Accepted

Solution code:
import sys
 
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines
inf = float("INF")
a,b,q = map(int, input().split())
s = [None] * (a + 3)
s[0:2] = [-inf,-inf]
s[-1] = inf
t = [None] * (b + 3)
t[0:2] = [-inf,-inf]
t[-1] = inf
for i in range(a):
	s[i+2] = int(input())
for i in range(b):
	t[i+2] = int(input())

from bisect import bisect_left

dp0 = [None] * (a+3)
dp1 = [None] * (b+3)

def f(s,t,x,ss,i):
  if i == 0 and dp0[ss] != None: return abs(x - s[ss]) + dp0[ss]
  elif i == 1 and dp1[ss] != None: return abs(x - s[ss]) + dp1[ss]
  tr = bisect_left(t, s[ss])
  tl = tr - 1
  if i == 0: dp0[ss] = min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))
  if i == 1: dp1[ss] = min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))
  return abs(x - s[ss]) + min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))


for _ in range(q):
  ans = inf
  x = int(input())
  sr = bisect_left(s, x)
  ans = min(ans, f(s,t,x,sr,0))
  ans = min(ans, f(s,t,x,sr - 1,0))
  tr = bisect_left(t, x)
  ans = min(ans, f(t,s,x,tr,1))
  ans = min(ans, f(t,s,x,tr - 1,1))
  print(ans)

Submission status: Accepted

Solution code:
import sys
 
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines

def main():
  inf = float("INF")
  a,b,q = map(int, input().split())
  s = [None] * (a + 3)
  s[0:2] = [-inf,-inf]
  s[-1] = inf
  t = [None] * (b + 3)
  t[0:2] = [-inf,-inf]
  t[-1] = inf
  for i in range(a):
      s[i+2] = int(input())
  for i in range(b):
      t[i+2] = int(input())

  from bisect import bisect_right

  for _ in range(q):
    ans = inf
    x = int(input())
    sr = bisect_right(s, x)
    tr = bisect_right(t, x)    
    for si in (sr, sr-1):
      for ti in (tr, tr-1):
        ans = min(ans, abs(x-s[si]) + abs(s[si]-t[ti]), abs(x-t[ti]) + abs(s[si]-t[ti]))
    print(ans)
  
if __name__ == "__main__":
  main()

Submission status: Accepted

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

sl = [-float("inf")]
for _ in range(a):
    sl.append(int(input()))
sl.append(float("inf"))
tl = [-float("inf")]
for _ in range(b):
    tl.append(int(input()))
tl.append(float("inf"))
    
import bisect


for _ in range(q):
    x = int(input())
    index1 = bisect.bisect(sl, x) 
    index2 = bisect.bisect(tl, x)
    rs = abs(sl[index1] - x) 
    ls = abs(sl[index1-1] - x)
    rt = abs(tl[index2] - x)
    lt = abs(tl[index2-1] - x)
    ansl = []
    ansl.append(max(rs,rt))
    ansl.append(max(ls,lt))
    ansl.append(2*min(rs,lt)+max(rs,lt))
    ansl.append(2*min(ls,rt)+max(ls,rt))
    print(min(ansl))

Submission status: Accepted

Solution code:
jin,ter,q=map(int,input().split())
INF=10**19
jil,tel=[-INF]+[int(input()) for i in range(jin)]+[INF],[-INF]+[int(input()) for i in range(ter)]+[INF]
from bisect import bisect_right as bl
for _ in range(q):
    x=int(input())
    ans=INF
    b,d=bl(jil,x),bl(tel,x)
    for s in jil[b-1:b+1]:
        for t in tel[d-1:d+1]:
            ans=min(min(abs(x-s),abs(t-x))+abs(t-s),ans)
    print(ans)

Submission status: Accepted

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

# 左右の神社両方に行ってから最短の寺に行くパターンと、
# 左右の寺両方に行ってから最短の神社に行くパターン
# 両方を試して最小値を取る

S=[None] * A
T=[None] * B

for i in range(A):
  S[i] = int(input())
for i in range(B):
  T[i] = int(input())

import bisect

INF = 10**11
def getshortest(x,A,B):
  # xの両端のAをまず求める
  ind = bisect.bisect_right(A,x)
  dist_left = 0
  # 左に進む場合
  if ind == 0:
    dist_left = INF
  else:
    x2 = A[ind-1]
    dist_left = abs(x - A[ind-1])
    
    ind2 = bisect.bisect_right(B,x2)
    if ind2 == 0:
      dist_left += abs(B[0] - x2)
    elif ind2 == len(B):
      dist_left += abs(x2 - B[-1])
    else:
      dist_left += min(abs(x2 - B[ind2-1]),abs(B[ind2] - x2))
  
  dist_right = 0
  # 右に進む場合
  if ind == len(A):
    dist_right = INF
  else:
    x2 = A[ind]
    dist_right = abs(x - A[ind])
    
    ind2 = bisect.bisect_right(B,x2)
    if ind2 == 0:
      dist_right += abs(B[0] - x2)
    elif ind2 == len(B):
      dist_right += abs(x2 - B[-1])
    else:
      dist_right += min(abs(x2 - B[ind2-1]),abs(B[ind2] - x2))
  return (dist_left,dist_right)[dist_left > dist_right]
  
for i in range(Q):
  x = int(input())
  s = getshortest(x,S,T)
  t = getshortest(x,T,S)
  print((s,t)[t<s])

Submission status: Accepted

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

# 左右の神社両方に行ってから最短の寺に行くパターンと、
# 左右の寺両方に行ってから最短の神社に行くパターン
# 両方を試して最小値を取る

S=[None] * A
T=[None] * B

for i in range(A):
  S[i] = int(input())
for i in range(B):
  T[i] = int(input())

# print("S",S)
# print("T",T)
import bisect

INF = 10**11
def getshortest(x,A,B):
  # xの両端のAをまず求める
  ind = bisect.bisect_right(A,x)
  dist_left = 0
  # 左に進む場合
  if ind == 0:
    dist_left = INF
  else:
    x2 = A[ind-1]
    dist_left = abs(x - A[ind-1])
    
    ind2 = bisect.bisect_right(B,x2)
    if ind2 == 0:
      dist_left += abs(B[0] - x2)
    elif ind2 == len(B):
      dist_left += abs(x2 - B[-1])
    else:
      dist_left += min(abs(x2 - B[ind2-1]),abs(B[ind2] - x2))
  
  dist_right = 0
  # 右に進む場合
  if ind == len(A):
    dist_right = INF
  else:
    x2 = A[ind]
    dist_right = abs(x - A[ind])
    
    ind2 = bisect.bisect_right(B,x2)
    if ind2 == 0:
      dist_right += abs(B[0] - x2)
    elif ind2 == len(B):
      dist_right += abs(x2 - B[-1])
    else:
      dist_right += min(abs(x2 - B[ind2-1]),abs(B[ind2] - x2))
  return (dist_left,dist_right)[dist_left > dist_right]
  
for i in range(Q):
  x = int(input())
#  print("x",x)
  s = getshortest(x,S,T)
  t = getshortest(x,T,S)
  print((s,t)[t<s])

Submission status: Accepted

Solution code:
import sys
def main():
    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)]
    X=[int(input()) for _ in range(Q)]
    from bisect import bisect_left
    INF=10**11
    S=[-INF] + S + [INF]
    T=[-INF] + T + [INF]
    for x in X:
        sr = bisect_left(S, x)
        tr = bisect_left(T, x)
        sl,tl=sr-1,tr-1
        ans=INF
        ans = min(ans, abs(S[sl]-T[tl]) + min(abs(S[sl]-x), abs(T[tl]-x)))
        ans = min(ans, abs(S[sl]-T[tr]) + min(abs(S[sl]-x), abs(T[tr]-x)))
        ans = min(ans, abs(S[sr]-T[tl]) + min(abs(S[sr]-x), abs(T[tl]-x)))
        ans = min(ans, abs(S[sr]-T[tr]) + min(abs(S[sr]-x), abs(T[tr]-x)))
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
def main():
    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)]
    X=[int(input()) for _ in range(Q)]
    from bisect import bisect_left
    INF=10**11
    for x in X:
        sr = bisect_left(S, x)
        tr = bisect_left(T, x)
        sl,tl=sr-1,tr-1
        ans=INF
        if sl >= 0 and tl >= 0:
            ans = min(ans, abs(S[sl]-T[tl]) + min(abs(S[sl]-x), abs(T[tl]-x)))
        if sl >= 0 and tr < B:
            ans = min(ans, abs(S[sl]-T[tr]) + min(abs(S[sl]-x), abs(T[tr]-x)))
        if sr < A and tl >= 0:
            ans = min(ans, abs(S[sr]-T[tl]) + min(abs(S[sr]-x), abs(T[tl]-x)))
        if sr < A and tr < B:
            ans = min(ans, abs(S[sr]-T[tr]) + min(abs(S[sr]-x), abs(T[tr]-x)))
        print(ans)

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)]
from bisect import bisect_left,bisect_right
for i in range(q):
    idx_s=bisect_right(s,x[i])
    idx_t=bisect_right(t,x[i])
    ans=inf
    for ss in [s[idx_s-1],s[idx_s]]:
        for tt in [t[idx_t-1],t[idx_t]]:
            d1,d2=abs(ss-x[i])+abs(ss-tt),abs(tt-x[i])+abs(tt-ss)
            ans=min(ans,d1,d2)
    print(ans)

Submission status: Accepted

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

a, b, q = map(int, input().split())
S = [0]*a
T = [0]*b
for i in range(a):
    s = int(input())
    S[i] = s
for i in range(b):
    t = int(input())
    T[i] = t

S.sort()
T.sort()
S = [-10**18]+S+[10**18]
T = [-10**18]+T+[10**18]
import bisect
for i in range(q):
    x = int(input())
    ans = 10**18
    ids = bisect.bisect_right(S, x)
    idt = bisect.bisect_right(T, x)
    for ks in (-1, 0):
        for kt in (-1, 0):
            s = S[ids+ks]
            t = T[idt+kt]
            temp = min(abs(s-x)+abs(s-t), abs(t-x)+abs(s-t))
            ans = min(ans, temp)
    print(ans)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left

def solve():
    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)]
    Ans = [0] * Q
    for i in range(Q):
        x = int(input())
        si, ti = bisect_left(S, x), bisect_left(T, x)
        shortest_path = 10 ** 20
        if si < A and ti < B: shortest_path = min(shortest_path, max(S[si], T[ti]) - x)
        if si > 0 and ti > 0: shortest_path = min(shortest_path, x - min(S[si-1], T[ti-1]))
        if si > 0 and ti < B: shortest_path = min(shortest_path, T[ti] - S[si-1] + min(T[ti] - x, x - S[si-1]))
        if ti > 0 and si < A: shortest_path = min(shortest_path, S[si] - T[ti - 1] + min(S[si] - x, x - T[ti-1]))
        Ans[i] = shortest_path
    print("\n".join(map(str, Ans)))

    return 0

if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
from bisect import bisect_left,bisect_right
a,b,q=map(int,input().split())
s=[-(10**21)]+[int(input())for _ in range(a)]+[10**21]
t=[-(10**21)]+[int(input())for _ in range(b)]+[10**21]
for _ in range(q):
  x=int(input())
  s1,s2=s[bisect_right(s,x)-1],s[bisect_right(s,x)]
  t1,t2=t[bisect_right(t,x)-1],t[bisect_right(t,x)]
  ans=10**11
  for i in [s1,s2]:
    for j in [t1,t2]:
      ans=min(ans,abs(i-j)+min(abs(x-i),abs(x-j)))
  print(ans)

Submission status: Accepted

Solution code:
#!usr/bin/env python3
from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()]
def I(): return int(sys.stdin.buffer.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    a,b,q = LI()
    s = IR(a)
    t = IR(b)
    X = IR(q)
    for x in X:
        i = bisect.bisect_right(s,x)-1
        j = bisect.bisect_right(t,x)-1
        res = float("inf")
        if i >= 0:
            si = s[i]
            if j >= 0:
                tj = t[j]
                res = x-min(si,tj)
            if j+1 < b:
                tj = t[j+1]
                m = min(abs(si-x),abs(tj-x))+abs(tj-si)
                if m < res:
                    res = m
        if i+1 < a:
            si = s[i+1]
            if j >= 0:
                tj = t[j]
                m = min(abs(si-x),abs(tj-x))+abs(si-tj)
                if m < res:
                    res = m
            if j+1 < b:
                tj = t[j+1]
                res = min(res,max(si,tj)-x)
        print(res)
    return

#Solve
if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import sys
import bisect
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)
bl = bisect.bisect_left

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]


def path(x):
    sl = S[bl(S, x) - 1]
    sr = S[bl(S, x)]
    tl = T[bl(T, x) - 1]
    tr = T[bl(T, x)]

    res = 10 ** 18
    res = min(res, abs(x - sl) + abs(sl - tl))
    res = min(res, abs(x - sl) + abs(sl - tr))
    res = min(res, abs(x - sr) + abs(sr - tr))
    res = min(res, abs(x - sr) + abs(sr - tl))
    res = min(res, abs(x - tr) + abs(tr - sl))
    res = min(res, abs(x - tr) + abs(tr - sr))
    res = min(res, abs(x - tl) + abs(tl - sl))
    res = min(res, abs(x - tl) + abs(tl - sr))
    return res


X = [int(input()) for _ in range(Q)]
for x in X:
    print(path(x))

Submission status: Accepted

Solution code:
from bisect import bisect_right, bisect_left
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 _ in range(Q):
    x = int(input())

    lS, lT = S[bisect_right(S, x) - 1], T[bisect_right(T, x) - 1]
    rS, rT = S[bisect_left(S, x)], T[bisect_left(T, x)]

    ans = min(
        abs(lS - lT) + (x - max(lS, lT)),
        abs(rS - rT) + (min(rS, rT) - x),
        (rT - lS) + min(x - lS, rT - x),
        (rS - lT) + min(x - lT, rS - x)
    )

    print(ans)

Submission status: Accepted

Solution code:
import bisect
A,B,Q=map(int,input().split())
INF=10**12
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)
for i in range(Q):
  x=int(input())
  sl=[S[bisect.bisect_left(S,x)],S[bisect.bisect_left(S,x)-1]]
  tl=[T[bisect.bisect_left(T,x)],T[bisect.bisect_left(T,x)-1]]
  ans=[]
  for s in sl:
    for t in tl:
      ans.append(abs(x-s)+abs(s-t))
      ans.append(abs(x-t)+abs(t-s))
  print(min(ans))

Submission status: Accepted

Solution code:
import bisect
A,B,Q=map(int,input().split())
INF=10**12
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)
for i in range(Q):
  x=int(input())
  sh=S[bisect.bisect_left(S,x)]
  sl=S[bisect.bisect_left(S,x)-1]
  th=T[bisect.bisect_left(T,x)]
  tl=T[bisect.bisect_left(T,x)-1]
  a1=abs(x-sh)+abs(sh-th)
  a2=abs(x-sl)+abs(sl-th)
  a3=abs(x-sh)+abs(sh-tl)
  a4=abs(x-sl)+abs(sl-tl)
  a5=abs(x-th)+abs(th-sh)
  a6=abs(x-tl)+abs(tl-sh)
  a7=abs(x-th)+abs(th-sl)
  a8=abs(x-tl)+abs(tl-sl)
  print(min(a1,a2,a3,a4,a5,a6,a7,a8))

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
import bisect


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]

for i in range(Q):
    ans = INF
    x = int(input())
    s_right = bisect.bisect_right(s, x)
    t_right = bisect.bisect_right(t, x)

    s_left = s_right - 1
    t_left = t_right - 1

    for S in (s[s_left], s[s_right]):
        for T in (t[t_left], t[t_right]):
            ans = min(ans, abs(x-S) + abs(T-S), abs(x-T) + abs(S-T))

    print(ans)

Submission status: Accepted

Solution code:
import bisect
a,b,q = map(int,input().split())
s = [-10**11]+[int(input()) for _ in range(a)]+[10**11]
t = [-10**11]+[int(input()) for _ in range(b)]+[10**11]
for i in range(q):
  ans = 10**11
  x = int(input())
  l = bisect.bisect(s,x)
  m = bisect.bisect(t,x)
  arr = [[s[l-1],s[l]],[t[m-1],t[m]]]
  for i in range(4):
    S = 0
    now = x
    for j in range(2):
      t0 = now-arr[j][i >> j & 1]
      S += t0*((-1)**(t0<0))
      now -= t0
    if ans > S:
      ans = S
  for i in range(4):
    S = 0
    now = x
    for j in range(2):
      t0 = now-arr[1-j][i >> j & 1]
      S += t0*((-1)**(t0<0))
      now -= t0
    if ans > S:
      ans = S
  print(ans)

Submission status: Accepted

Solution code:


import bisect

def nearest(x, lst):
    p = bisect.bisect_left(lst, x)
    
    if p == 0:
        return lst[p], None
    if p == len(lst):
        return lst[p - 1], None
    if lst[p] == x:
        return lst[p], None
    return lst[p - 1], lst[p]
 

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

    slist = [int(input()) for _ in range(a)]
    tlist = [int(input()) for _ in range(b)]
    qlist = [int(input()) for _ in range(q)]

    near_s = {s: nearest(s, tlist) for s in slist}
    near_t = {t: nearest(t, slist) for t in tlist}

    anss = []
    for q in qlist:
        ans = float('inf')
        # 一番近いs->tの順の場合
        n = nearest(q, slist)
        for e in n:
            if not e: 
                continue
            for ee in near_s[e]:
                if not ee:
                    continue
                if ans > abs(q - e) + abs(ee - e):
                    ans = abs(q - e) + abs(ee - e)                            
        # 一番近いt->sの順の場合
        n = nearest(q, tlist)
        for e in n:
            if not e:
                continue
            for ee in near_t[e]:
                if not ee:
                    continue
                if ans > abs(q - e) + abs(ee - e):
                    ans = abs(q - e) + abs(ee - e)
        anss.append(ans)

    for ans in anss:
        print(ans)


submit()

Submission status: Accepted

Solution code:
from bisect import bisect_left
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 _ in range(q):
        x = int(input())
        sind = bisect_left(s, x)
        tind = bisect_left(t, x)
        
        res = INF
        for S in [s[sind-1], s[sind]]:
            for T in [t[tind-1], t[tind]]:
                d1 = abs(x-S) + abs(S-T)
                d2 = abs(x-T) + abs(T-S)
                res = min([res, d1, d2])
        print(res)
main()

Submission status: Accepted

Solution code:
from bisect import bisect_left

a, b, q = map(int, input().split())
S = []
T = []
X = []


def calc(x, a, b):
    return abs(a - b) + min(abs(x - a), abs(x - b))


for _ in range(a):
    S.append(int(input()))
for _ in range(b):
    T.append(int(input()))
for _ in range(q):
    x = int(input())

    basho1 = bisect_left(S, x)
    basho11 = min(basho1, a - 1)
    basho12 = basho11 - 1

    basho2 = bisect_left(T, x)
    basho21 = min(basho2, b - 1)
    basho22 = basho21 - 1
    ans = calc(x, S[basho11], T[basho21])
    ans = min(ans, calc(x, S[basho11], T[basho22]))
    ans = min(ans, calc(x, S[basho12], T[basho21]))
    ans = min(ans, calc(x, S[basho12], T[basho22]))
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
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())
    right_s = bisect.bisect_right(s, x)
    right_t = bisect.bisect_right(t, x)

    ans = INF
    
    for S in [s[right_s-1], s[right_s]]:
        for T in [t[right_t-1], t[right_t]]:
            ans = min(ans, abs(x-S) + abs(T-S), abs(x-T) + abs(S-T))

    print(ans)

Submission status: Accepted

Solution code:
import bisect
M = 10**12
a, b, q = [int(x) for x in input().split()]
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
for i in range(q):
  x = int(input())
  lst = []
  i_s = bisect.bisect_left(s, x)
  i_t = bisect.bisect_left(t, x)
  if i_s == 0:
    sl, sr = -M, s[i_s]
  elif i_s == a:
    sl, sr = s[i_s-1], M
  else:
    sl, sr = s[i_s-1], s[i_s]
  if i_t == 0:
    tl, tr = -M, t[i_t]
  elif i_t == b:
    tl, tr = t[i_t-1], M
  else:
    tl, tr = t[i_t-1], t[i_t]
  d = M
  for ss in [sl, sr]:
    for tt in [tl, tr]:
      d1 = abs(ss - x) + abs(ss - tt)
      d2 = abs(tt - x) + abs(ss - tt)
      d = min(d, d1, d2)
  print(d)