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
from bisect import bisect_left,bisect_right
sys.setrecursionlimit(10**9)
INF=10**18
MOD=10**9+7
def input():
    return sys.stdin.readline().rstrip()

def main():
    A,B,Q=map(int,input().split())
    s=[-INF]+sorted([int(input()) for _ in range(A)])+[INF]
    t=[-INF]+sorted([int(input()) for _ in range(B)])+[INF]
    for _ in range(Q):
        x=int(input())
        Sr=bisect_left(s,x)
        Sl=Sr-1
        Tr=bisect_left(t,x)
        Tl=Tr-1
        l=[[s[Sr],s[Sl]],[t[Tr],t[Tl]]]
        ans=INF
        for k in range(2):
            for i in range(2):
                for j in range(2):
                    tmp=abs(x-l[k][i])+abs(l[k][i]-l[not k][j])
                    ans=min(ans,tmp)
        print(ans)
    

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
INF=pow(10,16)

A,B,Q=[int(x) for x in str(input()).split()]
s=[-INF]+[int(input()) for x in range(A)]+[INF]
t=[-INF]+[int(input()) for x in range(B)]+[INF]

for i in range(Q):
  temp=int(input())
  start1=0
  end1=A+1
  while start1!=end1-1:
    mid=(start1+end1)//2
    if s[mid]>=temp:
      end1=mid
    else:
      start1=mid
  
  start2=0
  end2=B+1
  while start2!=end2-1:
    mid=(start2+end2)//2
    if t[mid]>=temp:
      end2=mid
    else:
      start2=mid



  mi=INF
  for i in [s[end1-1],s[end1]]:
    for j in [t[end2-1],t[end2]]:
      mi=min(mi,abs(temp-i)+abs(i-j))
      mi=min(mi,abs(temp-j)+abs(i-j))
  print(mi)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_right
input = sys.stdin.readline
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]

for i in range(q):
    x = int(input())
    c, d = bisect_right(S, x), bisect_right(T, x)
    ans = INF
    for s in S[c-1:c+1]:
        for t in T[d-1:d+1]:
            ans = min( ans, abs(t-x)+abs(s-t), abs(s-x)+abs(t-s) )
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
A,B,Q=map(int,input().split())
s=[(-1)*float("inf")]
for i in range(A):
    s.append(int(input()))
s.append(float("inf"))
t=[(-1)*float("inf")]
for i in range(B):
    t.append(int(input()))
t.append(float("inf"))
#print(s)
#print(t)
x=[0]*Q
for i in range(Q):
    x[i]=int(input())
from bisect import bisect_left as bl
for i in range(Q):
    ans=float("inf")
    sx=bl(s,x[i])
    tx=bl(t,x[i])
    #print(sx,tx)
    if s[sx]>=t[tx] :
        ans=min(s[sx]-x[i],ans)
    if s[sx]<t[tx] :
        ans=min(t[tx]-x[i],ans)
    #print("1",ans)
    if s[sx-1]>=t[tx-1] :
        ans=min(x[i]-t[tx-1],ans)
    if s[sx-1]<t[tx-1] :
        ans=min(x[i]-s[sx-1],ans)
    #print("2",ans,sx,tx)
    """
    print(s[sx]-x[i]+2*(x[i]-t[tx-1]))
    print(t[tx]-x[i]+2*(x[i]-s[sx-1]))"""

    ans=min(t[tx]-x[i]+2*(x[i]-s[sx-1]),s[sx]-x[i]+2*(x[i]-t[tx-1]),ans)
    ans=min(2*(t[tx]-x[i])+x[i]-s[sx-1],2*(s[sx]-x[i])+x[i]-t[tx-1],ans)

    print(ans)

Submission status: Accepted

Solution code:
from bisect 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)]
def d(x, y, z): return abs(x - y) + abs(y - z)
for x in X:
    ans = float("inf")
    i = bisect(S, x)
    if i < A:
        j = bisect(T, S[i])
        if j < B:
            ans = min(ans, d(x, S[i], T[j]))
        if j > 0:
            ans = min(ans, d(x, S[i], T[j-1]))
    if i > 0:
        j = bisect(T, S[i-1])
        if j < B:
            ans = min(ans, d(x, S[i-1], T[j]))
        if j > 0:
            ans = min(ans, d(x, S[i-1], T[j-1]))
    j = bisect(T, x)
    if j < B:
        i = bisect(S, T[j])
        if i < A:
            ans = min(ans, d(x, T[j], S[i]))
        if i > 0:
            ans = min(ans, d(x, T[j], S[i-1]))
    if j > 0:
        i = bisect(S, T[j-1])
        if i < A:
            ans = min(ans, d(x, T[j-1], S[i]))
        if i > 0:
            ans = min(ans, d(x, T[j-1], S[i-1]))
    print(ans)

Submission status: Accepted

Solution code:
import bisect

a,b,q = map(int, input().split())
s = [-(10 ** 21)] + [int(input()) for i in range(a)] + [10 ** 21]
t = [-(10 ** 21)] + [int(input()) for i in range(b)] + [10 ** 21]
x = [int(input()) for i in range(q)]

for i in x:
  bs = bisect.bisect_left(s,i)
  bt = bisect.bisect_left(t,i)
  p_s,p_t = i-s[bs-1], i-t[bt-1]
  n_s,n_t = s[bs]-i, t[bt]-i
  a = max(p_s, p_t)
  b = max(n_s, n_t)
  c = n_t + p_s + min(p_s,n_t)
  d = n_s + p_t + min(p_t,n_s)
  print(min(a,b,c,d))

Submission status: Accepted

Solution code:
from bisect import bisect_right

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

for _ in range(Q):
    x = int(input())
    b,d = bisect_right(s,x), bisect_right(t,x)

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

Submission status: Accepted

Solution code:
import bisect
import cmath
import heapq
import itertools
import math
import operator
import os
import re
import string
import sys
from collections import Counter, deque, defaultdict
from copy import deepcopy
from decimal import Decimal
from fractions import gcd
from functools import lru_cache, reduce
from operator import itemgetter, mul, add, xor

import numpy as np

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

sys.setrecursionlimit(10 ** 9)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
# MOD = 998244353


A, B, Q = list(map(int, sys.stdin.buffer.readline().split()))
S = [int(sys.stdin.buffer.readline()) for _ in range(A)]
T = [int(sys.stdin.buffer.readline()) for _ in range(B)]
X = [int(sys.stdin.buffer.readline()) for _ in range(Q)]

st_i = np.searchsorted(T, S).tolist()
ts_i = np.searchsorted(S, T).tolist()
st = []
ts = []

for s, i in zip(S, st_i):
    d = INF
    if 0 < i:
        d = min(d, abs(T[i - 1] - s))
    if i < len(T):
        d = min(d, abs(T[i] - s))
    st.append(d)
for t, i in zip(T, ts_i):
    d = INF
    if 0 < i:
        d = min(d, abs(S[i - 1] - t))
    if i < len(S):
        d = min(d, abs(S[i] - t))
    ts.append(d)

ans = []
for x in X:
    d = INF
    si = bisect.bisect_left(S, x)
    if 0 < si:
        d = min(d, abs(S[si - 1] - x) + st[si - 1])
    if si < len(S):
        d = min(d, abs(S[si] - x) + st[si])
    ti = bisect.bisect_left(T, x)
    if 0 < ti:
        d = min(d, abs(T[ti - 1] - x) + ts[ti - 1])
    if ti < len(T):
        d = min(d, abs(T[ti] - x) + ts[ti])
    ans .append(d)

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

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)]
#print("S:", S)
#print("T:", T)

answer1 = []
answer2 = []

for x in X:
  
  answer = 10 ** 12
  
  i1 = bisect.bisect_right(S, x) - 1
  i2 = (i1 + 1) % A
  S1 = S[i1]
  S2 = S[i2]  
  dist1 = abs(x - S1)
  dist2 = abs(x - S2)
  #print("dist1, dist2:", dist1, dist2)
  
  i11 = bisect.bisect_right(T, S1) - 1
  i12 = (i11 + 1) % B
  T11 = T[i11]
  T12 = T[i12]
  dist11 = abs(S1 - T11)
  dist12 = abs(S1 - T12)
  #print("dist11, dist12:", dist11, dist12)
    
  i21 = bisect.bisect_right(T, S2) - 1
  i22 = (i21 + 1) % B
  T21 = T[i21]
  T22 = T[i22]
  dist21 = abs(S2 - T21)
  dist22 = abs(S2 - T22)
  #print("dist21, dist22:", dist21, dist22)
  
  dist = min(dist1 + min(dist11, dist12), dist2 + min(dist21, dist22))
  answer1.append(dist)
  
S, T = T, S
A, B = B, A

for x in X:
  
  answer = 10 ** 15

  i1 = bisect.bisect_right(S, x) - 1
  i2 = (i1 + 1) % A
  S1 = S[i1]
  S2 = S[i2]  
  dist1 = abs(x - S1)
  dist2 = abs(x - S2)
  #print("dist1, dist2:", dist1, dist2)
  
  i11 = bisect.bisect_right(T, S1) - 1
  i12 = (i11 + 1) % B
  T11 = T[i11]
  T12 = T[i12]
  dist11 = abs(S1 - T11)
  dist12 = abs(S1 - T12)
  #print("dist11, dist12:", dist11, dist12)
    
  i21 = bisect.bisect_right(T, S2) - 1
  i22 = (i21 + 1) % B
  T21 = T[i21]
  T22 = T[i22]
  dist21 = abs(S2 - T21)
  dist22 = abs(S2 - T22)
  #print("dist21, dist22:", dist21, dist22)
  
  dist = min(dist1 + min(dist11, dist12), dist2 + min(dist21, dist22))
  answer2.append(dist)

for i in range(Q):
  print(min(answer1[i], answer2[i]))

Submission status: Accepted

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

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

s = [-10**11]
t = [-10**11]
for i in range(a):
    s.append(int(input()))
for i in range(b):
    t.append(int(input()))
s.append(10**11)
t.append(10**11)

for i in range(q):
    x = int(input())
    zin = bisect.bisect_left(s, x)
    tera = bisect.bisect_left(t, x)
    ans = 10**11
    ans = min(ans, max(x-s[zin-1], x-t[tera-1]))
    ans = min(ans, min(s[zin]-x, x-t[tera-1])*2 + max(s[zin]-x, x-t[tera-1]))
    ans = min(ans, min(t[tera]-x, x-s[zin-1])*2 + max(t[tera]-x, x-s[zin-1]))
    ans = min(ans, max(s[zin]-x, t[tera]-x))
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_right


def solve():
    A, B, Q, *stx = map(int, open(0).read().split())
    INF = 10 ** 12
    s, t, x = [-INF] + stx[:A] + [INF], [-INF] + stx[A:A + B] + [INF], stx[A + B:]
    
    for xi in x:
        b, d = bisect_right(s, xi), bisect_right(t, xi)
        ans = INF
        for si in [s[b - 1], s[b]]:
            for ti in [t[d - 1], t[d]]:
                d1, d2 = abs(si - xi) + abs(ti - si), abs(ti - xi) + abs(si - ti)
                ans = min(ans, d1, d2)
        print(ans)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
# TLEするので、自前で用意せずに、ライブラリ使おう
# https://juppy.hatenablog.com/entry/2019/02/24/ABC119_-D_Lazy_Faith-_Python_%E7%AB%B6%E6%8A%80%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%9F%E3%83%B3%E3%82%B0_Atcoder

import bisect
A, B, Q = map(int, input().split())
S = sorted([int(input()) for i in range(A)])
T = sorted([int(input()) for i in range(B)])
X = [int(input()) for i in range(Q)]

s_size = A
t_size = B
inf = 99999999999999

for x in X:
  s_index = bisect.bisect_left(S, x)
  s_left = S[s_index - 1] if s_index > 0 else None
  s_right = S[s_index] if s_index < s_size else None
  t_index = bisect.bisect_left(T, x)
  t_left = T[t_index - 1] if t_index > 0 else None
  t_right = T[t_index] if t_index < t_size else None

  ans = inf

  sl = [s_left, s_right]
  tl = [t_left, t_right]

  for s in sl:
    if not s: continue
    c1 = abs(x - s)
    for t in tl:
      if not t: continue
      ans = min(ans, c1 + abs(s-t))


  for t in tl:
    if not t: continue
    c1 = abs(x - t)
    for s in sl:
      if not s: continue
      ans = min(ans, c1 + abs(s-t))

  print(ans)

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
mod2 = 998244353
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

a,b,c = inpl()
x = [-INF] + inpln(a) + [INF]
y = [-INF] + inpln(b) + [INF]
z = inpln(c)

def f(x,y,q):
    res = INF
    qq = []
    cs = bisect.bisect_left(x,q)
    qq.append((x[cs],abs(q - x[cs])))
    qq.append((x[cs-1],abs(q - x[cs-1])))
    while qq:
        now, dist = qq.pop()
        cs = bisect.bisect_left(y,now)
        res = min(res,dist+abs(now - y[cs]))
        res = min(res,dist+abs(now - y[cs-1]))
    return res

for q in z:
    print(min(f(x,y,q),f(y,x,q)))

Submission status: Accepted

Solution code:
from collections import Counter,defaultdict,deque
from heapq import heappop,heappush,heapify
import sys,bisect,math,itertools,fractions,pprint
sys.setrecursionlimit(10**8)
mod = 10**9+7
mod2 = 998244353
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpln(n): return list(int(sys.stdin.readline()) for i in range(n))

a,b,c = inpl()
x = inpln(a)
y = inpln(b)
z = inpln(c)

def f(x,y,q):
    res = INF
    qq = []
    cs = bisect.bisect_left(x,q)
    if cs == 0:
        dist = abs(q - x[0])
        qq.append((x[0],dist))
    elif cs == len(x):
        dist = abs(q - x[-1])
        qq.append((x[-1],dist))
    else:
        qq.append((x[cs],abs(q - x[cs])))
        qq.append((x[cs-1],abs(q - x[cs-1])))
    # if q == 2000:
    #     print(qq,cs)
    while qq:
        now, dist = qq.pop()
        cs = bisect.bisect_left(y,now)
        # print(cs)
        if cs == 0:
            res = min(res,dist+abs(now - y[0]))
        elif cs == len(y):
            res = min(res,dist+abs(now - y[-1]))
        else:
            res = min(res,dist+abs(now - y[cs]))
            res = min(res,dist+abs(now - y[cs-1]))
    return res

for q in z:
    print(min(f(x,y,q),f(y,x,q)))

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

def bin_search(a, x):
    n = len(a)
    l, r = -1, n
    while r - l > 1:
        i = (l + r) // 2
        if a[i] >= x: r = i
        else: l = i
    res = []
    if l != -1: res.append(a[l])
    if r != n: res.append(a[r])
    return res

for _ in range(q):
    x = int(input())
    ans = float("inf")
    for p1 in bin_search(s, x):
        for p2 in bin_search(t, x):
            ans = min(ans, abs(p1-x) + abs(p2-p1), abs(p2-x) + abs(p1-p2))
    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)]
def BinaryIndexSearch_floor(p, SL):
	"""
	search the minimum number among the larger numbers than the ginven nymber "n". 
	return the index of it under the list sorted.
	"""
	#SL = sorted(L)
	l = 0
	r = len(SL) - 1

	while True:
		if l == r:
			if SL[l] > p:
				return l
			else:
				return -1
		elif r-l == 1:
			if SL[l] > p:
				return l
			elif SL[r] > p:
				return r
			else:
				return -1

		center = l + ((r-l) // 2)

		if SL[center] <= p:
			l = center + 1
			continue

		else:
			r = center
			continue

def BinaryIndexSearch_ceil(p, SL):
	#SL = sorted(L)
	l = 0
	r = len(SL) - 1

	while True:
		if l == r:
			if SL[l] < p:
				return l
			else:
				return -1
		elif r-l == 1:
			if SL[r] < p:
				return r
			elif SL[l] < p:
				return l
			else:
				return -1
		center = l + ((r-l) // 2)

		if SL[center] < p:
			l = center 
			continue

		else:
			r = center - 1
			continue

inf = float("inf")
for i in range(Q):
	xx = x[i]
	I_s_r = BinaryIndexSearch_floor(xx, s)
	I_t_r = BinaryIndexSearch_floor(xx, t)
	I_s_l = A-1 if I_s_r == -1 else I_s_r - 1
	I_t_l = B-1 if I_t_r == -1 else I_t_r - 1

	s_r = inf if I_s_r == -1 else s[I_s_r] - xx
	t_r = inf if I_t_r == -1 else t[I_t_r] - xx
	s_l = inf if I_s_l == -1 else xx - s[I_s_l]
	t_l = inf if I_t_l == -1 else xx - t[I_t_l]

	ans = []

	ans.append(min(s_r,t_l) + s_r + t_l)
	ans.append(min(t_r,s_l) + t_r + s_l)
	ans.append(max(s_r,t_r))
	ans.append(max(s_l,t_l))

	print(min(ans))

Submission status: Accepted

Solution code:
import bisect
a,b,q=map(int,input().split())
A=[-10**11]
for i in range(a):
  A.append(int(input()))
A.append(10**11)
B=[-10**11]
for i in range(b):
  B.append(int(input()))
B.append(10**11)
for i in range(q):
  x=int(input())
  c=bisect.bisect_left(A,x,hi=len(A))
  d=bisect.bisect_left(B,x,hi=len(B))
  ans=min(abs(A[c-1]-x)+abs(B[d-1]-A[c-1]),abs(A[c-1]-x)+abs(B[d]-A[c-1]),abs(A[c]-x)+abs(B[d-1]-A[c]),abs(A[c]-x)+abs(B[d]-A[c]),abs(B[d-1]-x)+abs(B[d-1]-A[c-1]),abs(B[d-1]-x)+abs(B[d-1]-A[c]),abs(B[d]-x)+abs(B[d]-A[c-1]),abs(B[d]-x)+abs(B[d]-A[c]))
  print(ans)

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

answer1 = []
for i in range(Q):
  ii = bisect.bisect_right(S, X[i])
  s1, s2 = ii - 1, ii % A
  d1, d2 = abs(X[i] - S[s1]), abs(X[i] - S[s2])
  
  jj1 = bisect.bisect_right(T, S[s1])
  t11, t12 = jj1 - 1, jj1 % B
  dd11, dd12 = abs(S[s1] - T[t11]), abs(S[s1] - T[t12])

  jj2 = bisect.bisect_right(T, S[s2])
  t21, t22 = jj2 - 1, jj2 % B
  dd21, dd22 = abs(S[s2] - T[t21]), abs(S[s2] - T[t22])
  
  answer1.append(min(d1 + min(dd11, dd12), d2 + min(dd21, dd22)))

S, T = T, S
A, B = B, A
answer2 = []
for i in range(Q):
  ii = bisect.bisect_right(S, X[i])
  s1, s2 = ii - 1, ii % A
  d1, d2 = abs(X[i] - S[s1]), abs(X[i] - S[s2])
  
  jj1 = bisect.bisect_right(T, S[s1])
  t11, t12 = jj1 - 1, jj1 % B
  dd11, dd12 = abs(S[s1] - T[t11]), abs(S[s1] - T[t12])

  jj2 = bisect.bisect_right(T, S[s2])
  t21, t22 = jj2 - 1, jj2 % B
  dd21, dd22 = abs(S[s2] - T[t21]), abs(S[s2] - T[t22])
  
  answer2.append(min(d1 + min(dd11, dd12), d2 + min(dd21, dd22)))

for i in range(Q):
  print(min(answer1[i], answer2[i]))

Submission status: Accepted

Solution code:
def main():
  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)]
  S.insert(0,-float("inf"))
  S.append(float("inf"))
  T.insert(0,-float("inf"))
  T.append(float("inf"))
  for i in range(Q):
    ans = float("inf")
    #shrine start
    plc_id = bisect.bisect_left(S,X[i])
    right = bisect.bisect_left(T,S[plc_id])
    left = bisect.bisect_left(T,S[plc_id-1])
    left_d = abs(X[i] - S[plc_id-1])
    right_d = abs(X[i] - S[plc_id])
    ans = min(ans,left_d + min(abs(S[plc_id-1] - T[left-1]),abs(S[plc_id-1]-T[left])))
    ans = min(ans,right_d + min(abs(S[plc_id] - T[right-1]),abs(S[plc_id]-T[right])))
    #temple start
    plc_id = bisect.bisect_left(T,X[i])
    right = bisect.bisect_left(S,T[plc_id])
    left = bisect.bisect_left(S,T[plc_id-1])
    left_d = abs(X[i] - T[plc_id-1])
    right_d = abs(X[i] - T[plc_id])
    ans = min(ans,left_d + min(abs(T[plc_id-1] - S[left-1]),abs(T[plc_id-1]-S[left])))
    ans = min(ans,right_d + min(abs(T[plc_id] - S[right-1]),abs(T[plc_id]-S[right])))
    print(ans)
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)]
X = [int(input()) for _ in range(Q)]
S.insert(0,-float("inf"))
S.append(float("inf"))
T.insert(0,-float("inf"))
T.append(float("inf"))
for i in range(Q):
  ans = float("inf")
  #shrine start
  plc_id = bisect.bisect_left(S,X[i])
  right = bisect.bisect_left(T,S[plc_id])
  left = bisect.bisect_left(T,S[plc_id-1])
  one = abs(X[i] - S[plc_id-1])
  two = abs(X[i] - S[plc_id])
  ans = min(ans,one + min(abs(S[plc_id-1] - T[left-1]),abs(S[plc_id-1]-T[left])))
  ans = min(ans,two + min(abs(S[plc_id] - T[right-1]),abs(S[plc_id]-T[right])))
  #temple start
  plc_id = bisect.bisect_left(T,X[i])
  right = bisect.bisect_left(S,T[plc_id])
  left = bisect.bisect_left(S,T[plc_id-1])
  one = abs(X[i] - T[plc_id-1])
  two = abs(X[i] - T[plc_id])
  ans = min(ans,one + min(abs(T[plc_id-1] - S[left-1]),abs(T[plc_id-1]-S[left])))
  ans = min(ans,two + min(abs(T[plc_id] - S[right-1]),abs(T[plc_id]-S[right])))
  print(ans)

Submission status: Accepted

Solution code:
import sys
import bisect


def solve():
    readline = sys.stdin.buffer.readline
    mod = 10 ** 9 + 7
    a, b, q = list(map(int, readline().split()))
    s = [int(readline()) for _ in range(a)]
    t = [int(readline()) for _ in range(b)]
    x = [int(readline()) for _ in range(q)]
    for xv in x:
        sp = bisect.bisect_left(s, xv)
        tp = bisect.bisect_left(t, xv)
        ss = s[sp] if sp == 0 else 10 ** 20 if sp == len(s) else s[sp-1]
        ss -= xv
        se = 10 ** 20 if sp == 0 else s[sp-1] if sp == len(s) else s[sp]
        se -= xv
        ts = t[tp] if tp == 0 else 10 ** 20 if tp == len(t) else t[tp-1]
        ts -= xv
        te = 10 ** 20 if tp == 0 else t[tp-1] if tp == len(t) else t[tp]
        te -= xv
        mt = 10 ** 20
        for sv in [ss, se]:
            for tv in [ts, te]:
                if sv * tv < 0:
                    mt = min(mt, abs(sv) + abs(tv) + min(abs(sv), abs(tv)))
                else:
                    mt = min(mt, max(abs(sv), abs(tv)))
        print(mt)


if __name__ == '__main__':
    solve()

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


for i in range(q):
    st = x[i]
    #print('----------------')
    #print(st)

    #s_t
    sr = bisect.bisect_left(s, st)
    sl = sr - 1
    ans_s = 10**20
    for j in [sr, sl]:
        if 0 <= j <= a-1:
            tmp = abs(st - s[j])
            tr = bisect.bisect_left(t, s[j])
            tl = tr - 1
            for k in [tr, tl]:
                if 0 <= k <= b-1:
                    #print(tmp+abs(s[j] - t[k]))
                    ans_s = min(ans_s, tmp+abs(s[j] - t[k]))
    #print(' ')
    #t_s
    tr = bisect.bisect_left(t, st)
    tl = tr - 1
    ans_t = 10**20
    for j in [tr, tl]:
        if 0 <= j <= b-1:
            tmp = abs(st - t[j])
            sr = bisect.bisect_left(s, t[j])
            sl = sr - 1
            for k in [sr, sl]:
                if 0 <= k <= a-1:
                    #print(tmp+abs(s[k] - t[j]))
                    ans_t = min(ans_t, tmp+abs(s[k] - t[j]))
    
    print(min(ans_s, ans_t))
    #print('---------------------')

Submission status: Accepted

Solution code:
def p_d():
    from bisect import 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]
    ans = []
    for _ in range(Q):
        x = int(input())
        b, d = bisect_right(s, x), bisect_right(t, x)
        res = INF
        for S in [s[b - 1], s[b]]:
            for T in [t[d - 1], t[d]]:
                d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
                res = min((d1, d2, res))
        ans.append(str(res))
    print("\n".join(ans))


if __name__ == '__main__':
    p_d()

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
import bisect

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

god=[-10**18]
for _ in range(A):
    god.append(int(input()))
god.append(10**18)

buddha=[-10**18]
for _ in range(B):
    buddha.append(int(input()))
buddha.append(10**18)

#print(god,buddha)
for _ in range(Q):
    q=int(input())
    g_i=bisect.bisect_left(god, q)
    b_i=bisect.bisect_left(buddha, q)
    #print(g_i,b_i)
    
    ans=10**18
    G=[god[g_i-1],god[g_i]]
    B=[buddha[b_i-1],buddha[b_i]]
    for g in G:
        for b in B:
            ans=min(ans,abs(q-g)+abs(g-b),abs(q-b)+abs(b-g))
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left

def main():
    A, B, Q = map(int, input().split())
    S = [0] * A
    T = [0] * B
    for i in range(A):
        S[i] = int(input())
    for i in range(B):
        T[i] = int(input())
    
    for _ in range(Q):
        x = int(input())
        s_cnt = bisect_left(S,x)
        t_cnt = bisect_left(T,x)
        s_cand = []
        t_cand = []
        if s_cnt == 0:
            s_cand.append(S[s_cnt])
        elif s_cnt == A:
            s_cand.append(S[s_cnt-1])
        else:
            s_cand.append(S[s_cnt])
            s_cand.append(S[s_cnt-1])
        if t_cnt == 0:
            t_cand.append(T[t_cnt])
        elif t_cnt == B:
            t_cand.append(T[t_cnt-1])
        else:
            t_cand.append(T[t_cnt])
            t_cand.append(T[t_cnt-1])
        d = float('inf')
        for i in s_cand:
            for j in t_cand:
                tmp = abs(x - i) + abs(i - j)
                d = min(d, tmp)

        for i in t_cand:
            for j in s_cand:
                tmp = abs(x - i) + abs(i - j)
                d = min(d, tmp)
        print(d)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
import bisect
from itertools import zip_longest
from operator import itemgetter
readline = sys.stdin.readline
a,b,q = map(int, input().split(' '))
S = [int(readline()) for _ in range(a)]
T = [int(readline()) for _ in range(b)]
Q = [int(readline()) for _ in range(q)]
st = list(zip_longest([],S,fillvalue = 1))+list(zip_longest([],T,fillvalue = 2))
st.sort(key=itemgetter(1))
st_plc = [x[1] for x in st]
for i,x in enumerate(Q):
    nb = bisect.bisect(st_plc, x)
    if nb == 0:
        print(max(S[0],T[0])-x)
    elif nb == a+b:
        print(x-min(S[-1],T[-1]))
    else:
        if st[nb-1][0] == 1:
            nb2 = bisect.bisect(T,st_plc[nb-1])
            if nb2 == 0:
                ans1 = (x-st_plc[nb-1])*2 + (T[0]-x)
            elif nb2 == b:
                ans1 = x-T[-1]
            else:
                ans1 = x-st_plc[nb-1] + min(T[nb2]-st_plc[nb-1],st_plc[nb-1]-T[nb2-1])
        elif st[nb-1][0] == 2:
            nb2 = bisect.bisect(S,st_plc[nb-1])
            if nb2 == 0:
                ans1 = (x-st_plc[nb-1])*2 + (S[0]-x)
            elif nb2 == a:
                ans1 = x-S[-1]
            else:
                ans1 = x-st_plc[nb-1] + min(S[nb2]-st_plc[nb-1],st_plc[nb-1]-S[nb2-1])
        if st[nb][0] == 1:
            nb2 = bisect.bisect(T,st_plc[nb])
            if nb2 == 0:
                ans2 = T[0]-x
            elif nb2 == b:
                ans2 = (st_plc[nb]-x)*2 + (x-T[-1])
            else:
                ans2 = st_plc[nb]-x + min(T[nb2]-st_plc[nb],st_plc[nb]-T[nb2-1])
        elif st[nb][0] == 2:
            nb2 = bisect.bisect(S,st_plc[nb])
            if nb2 == 0:
                ans2 = S[0]-x
            elif nb2 == a:
                ans2 = (st_plc[nb]-x)*2 + (x-S[-1])
            else:
                ans2 = st_plc[nb]-x + min(S[nb2]-st_plc[nb],st_plc[nb]-S[nb2-1])
        print(min(ans1,ans2))

Submission status: Accepted

Solution code:
import bisect
import sys
input = sys.stdin.readline
A, B, Q = map(int, 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())
    ret = 2 * 10**10
    a = bisect.bisect_left(s, x)
    tmp = 0
    if a < len(s):
        tmp = abs(s[a] - x)
        ab = bisect.bisect_left(t, s[a])
        if ab < len(t):
            tmp2 = abs(t[ab] - s[a])
            ret = min(ret, tmp + tmp2)

        if ab > 0:
            tmp2 = abs(t[ab - 1] - s[a])
            ret = min(ret, tmp + tmp2)
    if a > 0:
        a -= 1
        tmp = 0
        tmp = abs(s[a] - x)
        ab = bisect.bisect_left(t, s[a])
        if ab < len(t):
            tmp2 = abs(t[ab] - s[a])
            ret = min(ret, tmp + tmp2)

        if ab > 0:
            tmp2 = abs(t[ab - 1] - s[a])
            ret = min(ret, tmp + tmp2)

    b = bisect.bisect_left(t, x)
    tmp = 0
    if b < len(t):
        tmp = abs(t[b] - x)
        ba = bisect.bisect_left(s, t[b])
        if ba < len(s):
            tmp2 = abs(s[ba] - t[b])
            ret = min(ret, tmp + tmp2)
        if ba > 0:
            tmp2 = abs(s[ba - 1] - t[b])
            ret = min(ret, tmp + tmp2)
    if b > 0:
        b -= 1
        tmp = abs(t[b] - x)
        ba = bisect.bisect_left(s, t[b])
        if ba < len(s):
            tmp2 = abs(s[ba] - t[b])
            ret = min(ret, tmp + tmp2)

        if ba > 0:
            tmp2 = abs(s[ba - 1] - t[b])
            ret = min(ret, tmp + tmp2)
    print(ret)

Submission status: Accepted

Solution code:
a,b,q=map(int,input().split())
import bisect
inf=10**18
s=[int(input()) for _ in range(a)]
t=[int(input()) for _ in range(b)]
x=[int(input()) for _ in range(q)]
s=[-inf]+s+[inf]
t=[-inf]+t+[inf]
for q in x:
    c,d=bisect.bisect_left(s,q),bisect.bisect_left(t,q)
    ans=float("inf")
    for i in [c,c-1]:
        for j in [d,d-1]:
            ans=min(ans,abs(s[i]-t[j])+abs(q-s[i]),abs(s[i]-t[j])+abs(q-t[j]))
    print(ans)