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:
from bisect import bisect_left
A, B, Q = map(int, input().split())
minf, inf = -(10**18), 10**18
jinja = [minf] + [int(input()) for _ in range(A)] + [inf]
tera = [minf] + [int(input()) for _ in range(B)] + [inf]
ans = []
append = ans.append

for q in [int(input()) for _ in range(Q)]:
    i = bisect_left(jinja, q)
    j = bisect_left(tera, q)
    left_jinja, right_jinja = q-jinja[i-1], jinja[i]-q
    left_tera, right_tera = q-tera[j-1], tera[j]-q
 
    append(min(
        left_jinja if left_jinja > left_tera else left_tera,
        left_jinja + right_tera + (left_jinja if left_jinja < right_tera else right_tera),
        right_jinja + left_tera + (right_jinja if right_jinja < left_tera else left_tera),
        right_jinja if right_jinja > right_tera else right_tera
    ))
 
print(*ans, sep="\n")

Submission status: Accepted

Solution code:
import bisect as b


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

    len_s = A + 1
    len_t = B + 1

    for i in range(Q):
        xi = int(input())
        ind_s = b.bisect_left(s_list, xi)
        ws = s_list[ind_s - 1]
        es = s_list[ind_s]

        ind_t = b.bisect_left(t_list, xi)
        wt = t_list[ind_t - 1]
        et = t_list[ind_t]

        dist_list = [
                     xi - min(ws, wt),
                     max(es, et) - xi,
                     xi + es - wt * 2,
                     xi + et - ws * 2,
                     (es * 2) - wt - xi,
                     (et * 2) - ws - xi
                     ]

        print(min(dist_list))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import bisect
inf = 10**18
a, b, q = map(int, input().split())
s = [-inf] + [int(input()) for _ in range(a)] + [inf]
t = [-inf] + [int(input()) for _ in range(b)] + [inf]

for _ in range(q):
    x = int(input())
    i = bisect.bisect_right(s, x)
    j = bisect.bisect_right(t, x)
    ans = inf
    for s_x in [s[i-1], s[i]]:
        for t_x in [t[j-1], t[j]]:
            ans0 = abs(s_x - x) + abs(t_x - s_x)
            ans1 = abs(t_x - x) + abs(s_x - t_x)
            ans = min(ans, ans0, ans1)
    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()), i) for i in range(q)]
x = sorted(x)

def check(x, s0, s1, t0, t1):
    ans = float('inf')
    for x1, x2 in [(s0, t0), (s0, t1), (s1, t0), (s1, t1),
                   (t0, s0), (t0, s1), (t1, s0), (t1, s1)]:
        ans = min(ans, abs(x-x1)+abs(x1-x2))
    return ans

s0, t0 = -float('inf'), -float('inf')
s1, t1 = s[0], t[0]
i_s, i_t = 0, 0
answers = []
for x_i, i in x:
    while s1 < x_i and i_s < a-1:
        s0 = s1
        i_s += 1
        s1 = s[i_s]
    while t1 < x_i and i_t < b-1:
        t0 = t1
        i_t += 1
        t1 = t[i_t]
    ans = check(x_i, s0, s1, t0, t1)
    answers.append((i, ans))

for _, ans in sorted(answers):
    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:
import bisect
sn, tn, qn = map(int, input().split())

LARGE = -100000000
sa = []
ta = []
qa = []
for i in range(sn):
    sa.append(int(input()))
for i in range(tn):
    ta.append(int(input()))
for i in range(qn):
    qa.append(int(input()))

def find_nearest(q, al, s, e):
    idx = bisect.bisect_right(al, q)
    if idx == 0:
        return [al[0], al[0]]
    if idx == len(al):
        return [al[idx - 1], al[idx - 1]]
    return [al[idx - 1], al[idx]]

def move_cost(q, al, bl):
    a1, a2 = find_nearest(q, al, 0, len(al) - 1)
    b1, b2 = find_nearest(q, bl, 0, len(bl) - 1)

    def calc(x1, x2, x3):
        y1 = min(x1, x2)
        y2 = max(x1, x2)
        if x3 >= y1 and x3 <= y2:
            return abs(x1 - x2)
        return abs(x1 - x2) + abs(x2 - x3)
    return min(
        calc(q, a1, b1),
        calc(q, a1, b2),
        calc(q, a2, b1),
        calc(q, a2, b2),
        calc(q, b1, a1),
        calc(q, b1, a2),
        calc(q, b2, a1),
        calc(q, b2, a2),
    )

for q in qa:
    print(move_cost(q, sa, ta))

Submission status: Accepted

Solution code:
import bisect
A,B,Q = map(int,input().split())
INF = float('inf')
s = [-INF] + [int(input()) for i in range(A)] + [INF]
t = [-INF] + [int(input()) for i in range(B)] + [INF]
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:
import bisect
INF = float('inf')
A, B, Q = [int(_) for _ in input().split()]
S = [-INF] + [int(input()) for _ in range(A)] + [INF]
T = [-INF] + [int(input()) for _ in range(B)] + [INF]
X = [int(input()) for _ in range(Q)]
for x in X:
    i_sl = bisect.bisect_left(S, x)
    i_tl = bisect.bisect_left(T, x)
    D_sl = S[i_sl] - x
    D_tl = T[i_tl] - x
    D_sr = x - S[i_sl - 1]
    D_tr = x - T[i_tl - 1]
    print(
        min([
            max(D_sl, D_tl),
            max(D_sr, D_tr),
            min(D_sl, D_tr) + D_tr + D_sl,
            min(D_tl, D_sr) + D_sr + D_tl
        ]))

Submission status: Accepted

Solution code:
from bisect import bisect_left

A, B, Q = map(int, input().split())
s_list = [int(input()) for _ in range(A)]
t_list = [int(input()) for _ in range(B)]
x_list = [int(input()) for _ in range(Q)]

inf = float("inf")

s_list = [-inf] + s_list + [inf]
t_list = [-inf] + t_list + [inf]

for x in x_list:

    s_i = bisect_left(s_list, x)
    t_i = bisect_left(t_list, x)

    ans = inf
    for s in (s_list[s_i - 1], s_list[s_i]):
        for t in (t_list[t_i - 1], t_list[t_i]):
            d1 = abs(s - x) + abs(t - s)
            d2 = abs(t - x) + abs(s - t)
            ans = min(ans, d1, d2)
    print(ans)

Submission status: Accepted

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

"""
参考：https://img.atcoder.jp/abc119/editorial.pdf
・前計算しないで直接やる版
・INFがfloat('inf')だとダメで10**18にしたらいけた。INF-INFがnanになるからだった。
・上記を考慮して修正版
"""

import sys, re
from collections import deque, defaultdict, Counter
from math import sqrt, hypot, factorial, pi, sin, cos, radians, log10
if sys.version_info.minor >= 5: from math import gcd
else: from fractions import gcd 
from heapq import heappop, heappush, heapify, heappushpop
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul, xor
from copy import copy, deepcopy
from functools import reduce, partial
from fractions import Fraction
from string import ascii_lowercase, ascii_uppercase, digits
from datetime import date

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def round(x): return int((x*2+1) // 2)
def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD
def lcm(x, y): return (x * y) // gcd(x, y)
def lcm_list(nums): return reduce(lcm, nums, 1)
def gcd_list(nums): return reduce(gcd, nums, nums[0])
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

A,B,Q=MAP()

S=[-INF]*(A+2)
for i in range(A):
    S[i+1]=INT()
T=[-INF]*(B+2)
for i in range(B):
    T[i+1]=INT()
S[-1]=T[-1]=INF

for i in range(Q):
    dist1=dist2=dist3=dist4=INF
    x=INT()
    # 地点xから左に一番近い神社
    idx1=bisect_right(S, x)-1
    # 右に一番近い神社
    idx2=bisect_left(S, x)
    idx3=bisect_right(T, x)-1
    idx4=bisect_left(T, x)
    # idx1番目の神社に行く
    dist1=x-S[idx1]
    # idx1番目の神社から、xから右か左に一番近かった寺に行く
    if dist1!=INF: dist1+=min(abs(S[idx1]-T[idx3]), abs(S[idx1]-T[idx4]))
    dist2=S[idx2]-x
    if dist2!=INF: dist2+=min(abs(S[idx2]-T[idx3]), abs(S[idx2]-T[idx4]))
    dist3=x-T[idx3]
    if dist3!=INF: dist3+=min(abs(T[idx3]-S[idx1]), abs(T[idx3]-S[idx2]))
    dist4=T[idx4]-x
    if dist4!=INF: dist4+=min(abs(T[idx4]-S[idx1]), abs(T[idx4]-S[idx2]))
    print(min(dist1, dist2, dist3, dist4))

Submission status: Accepted

Solution code:
a,b,q=map(int,input().split())
s=[]
t=[]
x=[]        

import bisect  

for i in range(a):
    p=int(input())
    s.append(p)
for i in range(b):
    p=int(input())
    t.append(p)
s=[-100000000000000000]+s+[1000000000000000000]
t=[-100000000000000000]+t+[1000000000000000000]
for i in range(q):
    p=int(input())
    n=bisect.bisect_right(s,p)
    m=bisect.bisect_right(t,p)
    l=[p,s[n-1],s[n],t[m-1],t[m]]
    x.append(l)

for i in range(q):
    ans=1000000000000000
    for S in [x[i][1],x[i][2]]:
        for T in [x[i][3],x[i][4]]:
            d1=abs(S-x[i][0])+abs(T-S)
            d2=abs(T-x[i][0])+abs(S-T)
            ans=min(ans,d1,d2)
    print(ans)

Submission status: Accepted

Solution code:
import bisect

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

for x in xq:
    ans = INF
#     near_s = sa[np.argmin([abs(s-x) for s in sa])]
#     near_t = tb[np.argmin([abs(near_s-t) for t in tb])]
#     ans += abs(near_s-x)+abs(near_t-near_s)
    
#     ans2 = 0
#     near_t_2 = tb[np.argmin([abs(t-x) for t in tb])]
#     near_s_2 = sa[np.argmin([abs(near_t_2-s) for s in sa])]
#     ans2 += abs(near_t_2-x) + abs(near_s_2 -near_t_2)

    b, d = bisect.bisect_right(sa,x), bisect.bisect_right(tb,x)
    for S in [sa[b],sa[b-1]]:
        for T in [tb[d], tb[d-1]]:
            d1, d2 = abs(S-x) + abs(T-S), abs(T-x) + abs(T-S)
            ans = min(ans,d1,d2)
    
    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 j in range(b)] + [INF]
start = [int(input()) for i in range(q)]
for i in range(len(start)):
    tmp = start[i]
    s_w = bisect.bisect_right(s, tmp)
    t_w = bisect.bisect_right(t, tmp)
    a_1 = abs(s[s_w]- tmp) + abs(t[t_w-1]-s[s_w]) 
    a_2 = abs(s[s_w]- tmp) + abs(t[t_w] - s[s_w])
    a_3 = abs(s[s_w-1]-tmp) + abs(t[t_w-1]-s[s_w-1])
    a_4 = abs(s[s_w-1]-tmp) + abs(t[t_w]-s[s_w-1])
    a_5 = abs(t[t_w-1]- tmp) + abs(s[s_w]-t[t_w-1]) 
    a_6 = abs(t[t_w] - tmp) + abs( s[s_w]-t[t_w] )
    a_7 = abs(t[t_w-1]-tmp) + abs(s[s_w-1]-t[t_w-1])
    a_8 = abs(t[t_w]-tmp) + abs(s[s_w-1]-t[t_w])
    print(min(a_1,a_2,a_3,a_4,a_5,a_6,a_7,a_8))

Submission status: Accepted

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

'''計算方法
初期位置xから東西に一番近い神社をSa・Sb,寺をTa・Tbとする。
すると、これら4地点での組み合わせ8種類を全て試して、最小値を出せば良い。
（計算の都合上、神社・寺に東西のとても遠い地点Xa・Xbを用意しておく。）
'''

# 寺・神社の位置
INF = 10 ** 18

s = [-INF] + [int(input()) for i in range(A)] + [INF] # 神社の位置
t = [-INF] + [int(input()) for i in range(B)] + [INF]  # 寺の位置


# 1.初期位置xから、Sa・Sb・Ta・Tbを求める。
import bisect

for x in range(Q):
  output = INF
  X = int(input())
  s_b,t_b = bisect.bisect_right(s, X), bisect.bisect_right(t, X)
  
  for S in [s[s_b - 1], s[s_b]]: # 初期位置から一番近い神社二箇所    
    for T in [t[t_b - 1], t[t_b]]:# 初期位置から一番近い寺二箇所
      d1 = abs(S-X) + abs(T-S)
      d2 = abs(T-X) + abs(S-T)
      output = min(output, d1, d2)
  
  print(output)

Submission status: Accepted

Solution code:
import bisect

A, B, Q = list(map(int, raw_input().split()))

max_val = 10.0 ** 15

jinja = list()
jinja.append(-max_val)
for a in xrange(A): jinja.append(long(raw_input()))
jinja.append(max_val)
tera = list()
tera.append(-max_val)
for b in xrange(B): tera.append(long(raw_input()))
tera.append(max_val)

for q in xrange(Q):
    question = long(raw_input())
    idx_tera, idx_jinja = bisect.bisect_right(tera, question), bisect.bisect_right(jinja, question)

    cost = max_val
    for T in [tera[idx_tera-1], tera[idx_tera]]:
        for S in [jinja[idx_jinja-1], jinja[idx_jinja]]:
            d_T = abs(T - question) + abs(S - T) # pattern1: question -> T -> S
            d_S = abs(S - question) + abs(T - S) # pattern2: question -> S -> T
            cost = min(cost, d_T, d_S)
    print cost

Submission status: Accepted

Solution code:
import bisect

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

for _ in range(Q):
    x = int(input())
    s_right_index = bisect.bisect_right(s_list, x)
    s_right = s_list[s_right_index]
    s_left = s_list[s_right_index - 1]
    t_right_index = bisect.bisect_right(t_list, x)
    t_right = t_list[t_right_index]
    t_left = t_list[t_right_index - 1]

    dist = INF
    for s in [s_right, s_left]:
        for t in [t_right, t_left]:
            dist = min(dist, abs(s - t) + abs(s - x), abs(t - s) + abs(t - x))
    print(dist)

Submission status: Accepted

Solution code:
import bisect


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

virtual = 10**18

list_s = [-virtual] + [int(input()) for a in range(A)] + [virtual]
list_t = [-virtual] + [int(input()) for b in range(B)] + [virtual]

list_x = [int(input()) for q in range(Q)]

for q in range(Q):
	x = list_x[q]
	n, m = bisect.bisect_left(list_s, x), bisect.bisect_left(list_t, x)
	list_dist = []
	for S in [list_s[n-1], list_s[n]]:
		for T in [list_t[m-1], list_t[m]]:
			d_s = abs(S - x) + abs(S - T)
			d_t = abs(T - x) + abs(S - T)
			result = min(virtual, d_s, d_t)

			list_dist.append(result)
	
	min_result = min(list_dist)
	print(min_result)

Submission status: Accepted

Solution code:
from bisect import*
A,B=abs,bisect
a,b,q,*l=map(int,open(0).read().split())
f=2**60
s,t=[-f]+l[:a]+[f],[-f]+l[a:a+b]+[f]
for x in l[a+b:]:
  m=f
  i,j=B(s,x),B(t,x)
  for v in s[i-1:i+1]:
    for w in t[j-1:j+1]:
      m=min(m,A(x-v)+A(v-w),A(x-w)+A(w-v))
  print(m)

Submission status: Accepted

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

for q in range(Q):
    x = int(input())
    # return nearest index
    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:
import sys
import bisect
input = sys.stdin.readline

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

s = [-1 for i in range(a)]
t = [-1 for i in range(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()
for i in range(q):
	x = int(input())

	slidx = bisect.bisect_left(s, x) -1
	tlidx = bisect.bisect_left(t, x) -1
	sl = -20000000000
	tl = -20000000000
	sr = 20000000000
	tr = 20000000000
	if slidx >= 0:
		sl = s[slidx]
	if tlidx >= 0:
		tl = t[tlidx]

	if slidx < a-1:
		sr = s[slidx+1]
	if tlidx < b-1:
		tr = t[tlidx+1]
	sl = x - sl
	tl = x - tl
	sr = sr - x
	tr = tr - x
	#print([sl,tl,sr,tr])
	dist = min( [max(sl,tl), max(sr,tr), min(sr, sl)*2 + min(tr,tl), min(tr,tl)*2 + min(sr,sl)])
	print(dist)

Submission status: Accepted

Solution code:
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]
s.sort()
t.sort()
 
import bisect
import itertools
for _ in range(Q):
    pos = int(input())
    near_s = bisect.bisect_left(s, pos)-1
    near_t = bisect.bisect_left(t, pos)-1
    s1, s2 = s[near_s], s[near_s+1]
    t1, t2 = t[near_t], t[near_t+1]
    print(min(
        pos - min(s1,t1),
        max(s2,t2) - pos,
        (s2 - pos) + (s2 - t1),
        (pos - t1) + (s2 - t1),
        (t2 - pos) + (t2 - s1),
        (pos - s1) + (t2 - s1)
    ))

Submission status: Accepted

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

"""
参考：https://img.atcoder.jp/abc119/editorial.pdf
"""

import sys, re
from collections import deque, defaultdict, Counter
from math import sqrt, hypot, factorial, pi, sin, cos, radians, log10
if sys.version_info.minor >= 5: from math import gcd
else: from fractions import gcd 
from heapq import heappop, heappush, heapify, heappushpop
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul, xor
from copy import copy, deepcopy
from functools import reduce, partial
from fractions import Fraction
from string import ascii_lowercase, ascii_uppercase, digits
from datetime import date

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def round(x): return int((x*2+1) // 2)
def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD
def lcm(x, y): return (x * y) // gcd(x, y)
def lcm_list(nums): return reduce(lcm, nums, 1)
def gcd_list(nums): return reduce(gcd, nums, nums[0])
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

A,B,Q=MAP()

S=[-INF]*(A+2)
for i in range(A):
    S[i+1]=INT()
T=[-INF]*(B+2)
for i in range(B):
    T[i+1]=INT()
S[-1]=T[-1]=INF

for i in range(Q):
    dist1=dist2=dist3=dist4=INF
    x=INT()
    # 地点xから左に一番近い神社
    idx1=bisect_right(S, x)-1
    # 右に一番近い神社
    idx2=bisect_left(S, x)
    idx3=bisect_right(T, x)-1
    idx4=bisect_left(T, x)
    # idx番目の神社に行く
    dist1=x-S[idx1]
    # idx番目の神社から一番近い寺に行く
    dist1+=min(abs(S[idx1]-T[idx3]), abs(S[idx1]-T[idx4]))
    dist2=S[idx2]-x
    dist2+=min(abs(S[idx2]-T[idx3]), abs(S[idx2]-T[idx4]))
    dist3=x-T[idx3]
    dist3+=min(abs(T[idx3]-S[idx1]), abs(T[idx3]-S[idx2]))
    dist4=T[idx4]-x
    dist4+=min(abs(T[idx4]-S[idx1]), abs(T[idx4]-S[idx2]))
    print(min(dist1, dist2, dist3, dist4))

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)]
for i in range(q):
    ans = float("inf")
    x = int(input())
    index_s = bisect.bisect_left(s, x)
    index_t = bisect.bisect_left(t, x)
    if index_s > 0:
        s_m = s[index_s - 1]
        if index_t > 0:
            t_m = t[index_t - 1]
            ans = min(ans, x - min(s_m, t_m))
        if index_t < b:
            t_p = t[index_t]
            ans = min(ans, t_p * 2 - x - s_m)
            ans = min(ans, x + t_p - s_m * 2)
    if index_s < a:
        s_p = s[index_s]
        if index_t > 0:
            t_m = t[index_t - 1]
            ans = min(ans, s_p * 2 - x - t_m)
            ans = min(ans, x + s_p - t_m * 2)
        if index_t < b:
            t_p = t[index_t]
            ans = min(ans, max(s_p, t_p) - x)
    print(ans)

Submission status: Accepted

Solution code:
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]
s.sort()
t.sort()

import bisect
import itertools
for _ in range(Q):
    pos = int(input())
    s_near_id = bisect.bisect_left(s, pos)-1
    t_near_id = bisect.bisect_left(t, pos)-1
    print(min( min(abs(pos-s_pos)+abs(s_pos-t_pos), abs(pos-t_pos)+abs(t_pos-s_pos)) for s_pos, t_pos in itertools.product(s[s_near_id:s_near_id+2],t[t_near_id:t_near_id+2]) ))

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

inf = 10 ** 18

def get_near(tera_num, tera_data, start_point):
    index_right = bisect.bisect_right(tera_data, start_point)
    tera_pre, tera_after = tera_data[index_right], tera_data[index_right - 1]
    return tera_pre, tera_after

def calc_data(start_point, point_a, point_b, min_point):
    a = abs(start_point - point_a) + abs(point_a - point_b)
    b = abs(start_point - point_b) + abs(point_b - point_a)
    min_point = min(a, b, min_point)
    return min_point

def calc_ans(start_point, tera_pre, tera_after, jinja_pre, jinja_after):
    min_point = float('inf')
    min_point = calc_data(start_point, tera_pre, jinja_pre, min_point)
    min_point = calc_data(start_point, tera_pre, jinja_after, min_point)
    min_point = calc_data(start_point, tera_after, jinja_pre, min_point)
    min_point = calc_data(start_point, tera_after, jinja_after, min_point)
    return min_point


def start(tera_num, jinja_num, q_num, tera_data, jinja_data, q_data):
    for start_point in q_data:
        tera_pre, tera_after = get_near(tera_num, tera_data, start_point)
        jinja_pre, jinja_after = get_near(jinja_num, jinja_data, start_point)
        ans = calc_ans(start_point, tera_pre, tera_after, jinja_pre, jinja_after)
        print(ans)

def main():
    tera_num, jinja_num, q_num = list(map(int, input().split()))
    tera_data = [-inf] + [int(input()) for i in range(tera_num)] + [inf]
    jinja_data = [-inf] + [int(input()) for i in range(jinja_num)] + [inf]
    q_data = [int(input()) for i in range(q_num)]

    start(tera_num, jinja_num, q_num, tera_data, jinja_data, q_data)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))
rr = lambda N: [ri() for _ in range(N)]
INF = 10**18

A,B,Q=rl()
s = [-INF] + rr(A) + [INF]
t = [-INF] + rr(B) + [INF]
X= rr(Q)

import bisect
for x in X:
    s_i = bisect.bisect_left(s,x)
    t_i = bisect.bisect_left(t,x)
    s_l = x-s[s_i-1]
    s_r = s[s_i]-x
    t_l = x-t[t_i-1]
    t_r = t[t_i]-x
    ans = min(
        max(s_l,t_l), s_l+t_r+min(s_l,t_r), s_r+t_l+min(s_r,t_l), max(s_r,t_r)
    )
    print(ans)

Submission status: Accepted

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

import sys, re
from collections import deque, defaultdict, Counter
from math import sqrt, hypot, factorial, pi, sin, cos, radians, log10
if sys.version_info.minor >= 5: from math import gcd
else: from fractions import gcd 
from heapq import heappop, heappush, heapify, heappushpop
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul, xor
from copy import copy, deepcopy
from functools import reduce, partial
from fractions import Fraction
from string import ascii_lowercase, ascii_uppercase, digits
from datetime import date

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def round(x): return int((x*2+1) // 2)
def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD
def lcm(x, y): return (x * y) // gcd(x, y)
def lcm_list(nums): return reduce(lcm, nums, 1)
def gcd_list(nums): return reduce(gcd, nums, nums[0])
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

A,B,Q=MAP()

S=[-INF]*(A+2)
for i in range(A):
    S[i+1]=INT()
T=[-INF]*(B+2)
for i in range(B):
    T[i+1]=INT()
S[-1]=T[-1]=INF

# Si番目の神社から左に一番近い寺
L1=[INF]*(A+2)
# Si番目の神社から右に一番近い寺
R1=[INF]*(A+2)
for i in range(1, A+1):
    idx=bisect_right(T, S[i])-1
    if T[idx]!=0:
        L1[i]=S[i]-T[idx]
    idx=bisect_left(T, S[i])
    if T[idx]!=INF:
        R1[i]=T[idx]-S[i]

# Ti番目の寺から左に一番近い神社
L2=[INF]*(B+2)
# Ti番目の寺から右に一番近い神社
R2=[INF]*(B+2)
for i in range(1, B+1):
    idx=bisect_right(S, T[i])-1
    if S[idx]!=0:
        L2[i]=T[i]-S[idx]
    idx=bisect_left(S, T[i])
    if S[idx]!=INF:
        R2[i]=S[idx]-T[i]

for i in range(Q):
    dist1=dist2=dist3=dist4=INF
    x=INT()
    # 地点xから左に一番近い神社
    idx=bisect_right(S, x)-1
    # idx番目の神社に行く
    dist1=x-S[idx]
    # idx番目の神社から一番近い寺に行く
    dist1+=min(L1[idx], R1[idx])
    idx=bisect_left(S, x)
    dist2=S[idx]-x
    dist2+=min(L1[idx], R1[idx])
    idx=bisect_right(T, x)-1
    dist3=x-T[idx]
    dist3+=min(L2[idx], R2[idx])
    idx=bisect_left(T, x)
    dist4=T[idx]-x
    dist4+=min(L2[idx], R2[idx])
    print(min(dist1, dist2, dist3, dist4))

Submission status: Accepted

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

import sys, re
from collections import deque, defaultdict, Counter
from math import sqrt, hypot, factorial, pi, sin, cos, radians, log10
if sys.version_info.minor >= 5: from math import gcd
else: from fractions import gcd 
from heapq import heappop, heappush, heapify, heappushpop
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul, xor
from copy import copy, deepcopy
from functools import reduce, partial
from fractions import Fraction
from string import ascii_lowercase, ascii_uppercase, digits
from datetime import date

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def round(x): return int((x*2+1) // 2)
def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD
def lcm(x, y): return (x * y) // gcd(x, y)
def lcm_list(nums): return reduce(lcm, nums, 1)
def gcd_list(nums): return reduce(gcd, nums, nums[0])
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

A,B,Q=MAP()

S=[0]*(A+2)
for i in range(A):
    S[i+1]=INT()
T=[0]*(B+2)
for i in range(B):
    T[i+1]=INT()
S[-1]=T[-1]=INF

# Si番目の神社から左に一番近い寺
L1=[INF]*(A+2)
# Si番目の神社から右に一番近い寺
R1=[INF]*(A+2)
for i in range(1, A+1):
    idx=bisect_right(T, S[i])-1
    if T[idx]!=0:
        L1[i]=S[i]-T[idx]
    idx=bisect_left(T, S[i])
    if T[idx]!=INF:
        R1[i]=T[idx]-S[i]

# Ti番目の寺から左に一番近い神社
L2=[INF]*(B+2)
# Ti番目の寺から右に一番近い神社
R2=[INF]*(B+2)
for i in range(1, B+1):
    idx=bisect_right(S, T[i])-1
    if S[idx]!=0:
        L2[i]=T[i]-S[idx]
    idx=bisect_left(S, T[i])
    if S[idx]!=INF:
        R2[i]=S[idx]-T[i]

for i in range(Q):
    dist1=dist2=dist3=dist4=INF
    x=INT()
    # 地点xから左に一番近い神社
    idx=bisect_right(S, x)-1
    if S[idx]!=0:
        # idx番目の神社に行く
        dist1=x-S[idx]
        # idx番目の神社から一番近い寺に行く
        dist1+=min(L1[idx], R1[idx])
    idx=bisect_left(S, x)
    if S[idx]!=INF:
        dist2=S[idx]-x
        dist2+=min(L1[idx], R1[idx])
    idx=bisect_right(T, x)-1
    if T[idx]!=0:
        dist3=x-T[idx]
        dist3+=min(L2[idx], R2[idx])
    idx=bisect_left(T, x)
    if T[idx]!=INF:
        dist4=T[idx]-x
        dist4+=min(L2[idx], R2[idx])
    print(min(dist1, dist2, dist3, dist4))

Submission status: Accepted

Solution code:
ri = lambda: int(input())
rl = lambda: list(map(int,input().split()))

A,B,Q=rl()
s=[0]*(A+2)
t=[0]*(B+2)
X=[0]*Q
for i in range(1,A+1):
    s[i]=ri()
s[0],s[A+1]=-float('inf'),float('inf')
s.sort()
for i in range(1,B+1):
    t[i]=ri()
t[0],t[B+1]=-float('inf'),float('inf')
t.sort()
for i in range(Q):
    X[i]=ri()

import bisect
for x in X:
    s_i = bisect.bisect_left(s,x)
    t_i = bisect.bisect_left(t,x)
    s_l = x-s[s_i-1]
    s_r = s[s_i]-x
    t_l = x-t[t_i-1]
    t_r = t[t_i]-x
    ans = min(
        [max(s_l,t_l), s_l+t_r+min(s_l,t_r), s_r+t_l+min(s_r,t_l), max(s_r,t_r)]
    )
    print(ans)