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: Runtime Error

Solution code:
INF = 10**11
from bisect import bisect

A, B, Q = map(int, input().split())
s_array = [int(input()) if i != 0 else -INF for i in range(A + 1)]
s_array.append(INF)
t_array = [int(input()) if i != 0 else -INF for i in range(B + 1)]
t_array.append(INF)
q_array = [int(input()) for i in range(Q)]

# print(s_array, t_array, q_array)

ans_array = []
for q in q_array:
    s_index = bisect(s_array, q)
    t_index = bisect(t_array, q)
    method_a = q - min(s_array[s_index], t_array[t_index])
    method_b = max(s_array[s_index + 1], t_array[t_index + 1]) - q
    method_c = (q - s_array[s_index]) + (t_array[t_index + 1] - q) + min(
        (q - s_array[s_index]), (t_array[t_index + 1] - q))
    method_d = (q - t_array[t_index]) + (s_array[s_index + 1] - q) + min(
        (q - t_array[t_index]), (s_array[s_index + 1] - q))
    ans_array.append(min(method_a, method_b, method_c, method_d))

for ans in ans_array:
    print(ans)

Submission status: Runtime Error

Solution code:
class AvlTree:  # std::set
    def __init__(self, values=None):
        self.left = [-1]
        self.right = [-1]
        self.values = [-float("inf")]
        self.diff = [0]  # left - right
        self.size_l = [0]
        if values is not None:
            for v in values:
                self.add(v)

    def print(self):
        print(f"left  ={self.left}")
        print(f"right ={self.right}")
        print(f"values={self.values}")
        print(f"diff  ={self.diff}")
        print(f"dixr_l={self.size_l}")

    def rotate_right(self, idx_par, lr):  # lr: 親の左なら 0
        idx = self.left[idx_par] if lr==0 else self.right[idx_par]
        idx_l = self.left[idx]
        assert idx_l != -1  # 左の子が存在する

        # 部分木の大きさの計算
        self.size_l[idx] -= self.size_l[idx_l] + 1

        # 高さの計算
        a = self.diff[idx]
        b = self.diff[idx_l]  # 左の子の高さの差
        if b >= 0:
            na = a - 1 - b
            if na >= 0:
                nb = b - 1
            else:
                nb = a - 2
        else:
            na = a - 1
            if na >= 0:
                nb = b - 1
            else:
                nb = a + b - 2
        self.diff[idx] = na
        self.diff[idx_l] = nb

        # 回転
        self.left[idx] = self.right[idx_l]
        self.right[idx_l] = idx
        if lr==0:
            self.left[idx_par] = idx_l
        else:
            self.right[idx_par] = idx_l

    def rotate_left(self, idx_par, lr):  # lr: 親の左なら 0
        idx = self.left[idx_par] if lr==0 else self.right[idx_par]
        idx_r = self.right[idx]
        assert idx_r != -1  # 右の子が存在する

        # 部分木の大きさの計算
        self.size_l[idx_r] += self.size_l[idx] + 1

        # 高さの計算
        a = self.diff[idx]
        b = self.diff[idx_r]  # 右の子の高さの差
        if b <= 0:
            na = a + 1 - b
            if na <= 0:
                nb = b + 1
            else:
                nb = a + 2
        else:
            na = a + 1
            if na <= 0:
                nb = b + 1
            else:
                nb = a + b + 2
        self.diff[idx] = na
        self.diff[idx_r] = nb

        # 回転
        self.right[idx] = self.left[idx_r]
        self.left[idx_r] = idx
        if lr == 0:
            self.left[idx_par] = idx_r
        else:
            self.right[idx_par] = idx_r

    def add(self, x):  # insert
        idx = 0
        path = []
        path_left = []
        while idx != -1:
            path.append(idx)
            value = self.values[idx]
            if x == value:
                return  # 重複を許さない
            elif x < value:
                path_left.append(idx)
                idx = self.left[idx]
            else:
                idx = self.right[idx]

        if x < value:
            self.left[path[-1]] = len(self.values)
        else:
            self.right[path[-1]] = len(self.values)
        self.left.append(-1)
        self.right.append(-1)
        self.values.append(x)
        self.diff.append(0)
        self.size_l.append(0)

        for idx_ in path_left:
            self.size_l[idx_] += 1

        idx = path[-1]
        delta_diff = 1 if x < value else -1
        self.diff[idx] += delta_diff
        for idx, idx_par in zip(path[:0:-1], path[-2::-1]):
            diff = self.diff[idx]
            if diff == 0:
                return
            elif diff == 2:  # 右回転
                idx_l = self.left[idx]  # 左の子
                if self.diff[idx_l] == -1:  # 左右のパターン
                    self.rotate_left(idx, 0)
                self.rotate_right(idx_par, self.right[idx_par]==idx)
                return
            elif diff == -2:  # 左回転
                idx_r = self.right[idx]  # 右の子
                if self.diff[idx_r] == 1:  # 右左のパターン
                    self.rotate_right(idx, 1)
                self.rotate_left(idx_par, self.right[idx_par]==idx)
                return
            else:
                self.diff[idx_par] += 1 if self.left[idx_par]==idx else -1

    def remove(self):  # erase
        raise NotImplementedError

    def __contains__(self, x):  # count
        raise NotImplementedError

    def bisect_left(self, x):  # lower_bound
        idx = self.right[0]
        res = 0
        while idx != -1:
            value = self.values[idx]
            if value == x:
                return res + self.size_l[idx]
            elif value < x:
                res += self.size_l[idx] + 1
                idx = self.right[idx]
            else:
                idx = self.left[idx]
        return res

    def bisect_right(self):  # upper_bound
        raise NotImplementedError


from bisect import bisect_left
import sys
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)]
avl_S = AvlTree(S)
avl_T = AvlTree(T)

def f(x):
    if 0 <= x and A - 1 >= x:
        return True
    return False
def g(x):
    if 0 <= x and B - 1 >= x:
        return True
    return False

for i in range(Q):
    x = int(input())
    p = avl_S.bisect_left(x)
    m = avl_T.bisect_left(x)

    res = []
    if f(p) and g(m):
        res.append(max(T[m], S[p]) - x)
    if f(p) and g(m - 1):
        res.append(min(S[p] - x, x - T[m - 1]) + S[p] - T[m - 1])
    if f(p - 1) and g(m):
        res.append(T[m] - S[p - 1] + min(T[m] - x, x - S[p - 1]))
    if f(p - 1) and g(m - 1):
        res.append(x - min(T[m - 1], S[p - 1]))
    print(min(res))

Submission status: Runtime Error

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

#inf = math.inf
inf = 2 **31 - 1

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

def bsearch_sub(a, v, imin, imax):
	if imax < imin:
		return imax + 1
	else:
		imid = imin + (imax - imin) // 2
		if v < a[imid]:
			return bsearch_sub(a, v, imin, imid - 1)
		elif a[imid] <= v:
			return bsearch_sub(a, v, imid + 1, imax)

def bsearch(a, v):
	return bsearch_sub(a, v, 0, len(a) - 1)

#print(S)
#print(T)
#print()

for x in X:
	s, t = bsearch(S, x), bsearch(T, x)
	#print(s, t, x)
	s1, s2, t1, t2 = S[s - 1], S[s], T[t - 1], T[t]
	r = []
	for sv in [s1, s2]:
		for tv in [t1, t2]:
			r += [abs(x - sv) + abs(sv - tv)]
			r += [abs(x - tv) + abs(sv - tv)]
	print(min(r))

Submission status: Runtime Error

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

inf = math.inf

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

def bsearch_sub(a, v, imin, imax):
	if imax < imin:
		return imax + 1
	else:
		imid = imin + (imax - imin) // 2
		if v < a[imid]:
			return bsearch_sub(a, v, imin, imid - 1)
		elif a[imid] <= v:
			return bsearch_sub(a, v, imid + 1, imax)

def bsearch(a, v):
	return bsearch_sub(a, v, 0, len(a) - 1)

#print(S)
#print(T)
#print()

for x in X:
	s, t = bsearch(S, x), bsearch(T, x)
	#print(s, t, x)
	s1, s2, t1, t2 = S[s - 1], S[s], T[t - 1], T[t]
	r = []
	for sv in [s1, s2]:
		for tv in [t1, t2]:
			r += [abs(x - sv) + abs(sv - tv)]
			r += [abs(x - tv) + abs(sv - tv)]
	print(min(r))

Submission status: Runtime Error

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)]
inf = 10 ** 18

s = [-inf] + s + [inf]
t = [-inf] + t + [inf]

# def binsearch_l(seq, l, r, tar):
#     if r - l < 2: return l
#     #
#     m = l + (r - l + 1) // 2
#     # print("##", l, r, (m, seq[m]), tar)
#     if seq[m] <= tar:
#         return binsearch_l(seq, m, r, tar)
#     else:
#         return binsearch_l(seq, l, m, tar)

ans_Q = [None] * Q
i_last = j_last = 0
for idx, x_tmp in sorted(enumerate(x), key=lambda x: x[1]):
    i_l, i_r = 0, A + 2
    while i_r - i_l > 1:
        m = i_l + (i_r - i_l) // 2
        # print("##", i_l, i_r, (m, s[m]), x_tmp)
        if s[m] <= x_tmp:
            i_l = m
        else:
            i_r = m
    #
    j_l, j_r = 0, A + 2
    while j_r - j_l > 1:
        m = j_l + (j_r - j_l) // 2
        # print("##", j_l, j_r, (m, t[m]), x_tmp)
        if t[m] <= x_tmp:
            j_l = m
        else:
            j_r = m
    #
    ans = inf
    for i, j in ((i_l, j_l), (i_l + 1, j_l), (i_l, j_l + 1), (i_l + 1, j_l + 1)):
        if i < 1 or A < i: continue
        if j < 1 or B < j: continue
        ans_tmp_s = abs(x_tmp - s[i]) + abs(s[i] - t[j])
        ans_tmp_t = abs(x_tmp - t[j]) + abs(s[i] - t[j])
        ans_tmp = min(ans_tmp_s, ans_tmp_t)
        # print("#", x_tmp, s[i], t[j], ans_tmp)
        if ans > ans_tmp:
            ans = ans_tmp
    #
    i_last, j_last = i_l, j_l
    ans_Q[idx] = ans

for ansi in ans_Q: print(ansi)

Submission status: Runtime Error

Solution code:
r i in range(A):
    S.append(int(input()))

S = [-INF] + S + [INF]

T = []
for i in range(B):
    T.append(int(input()))

T = [-INF] + T + [INF]


for i in range(Q):
    x = int(input())
    
    d, b = bisect.bisect_right(S, x), bisect.bisect_right(T, x)
    
    res = INF
    for s in [S[d - 1], S[d]]:
        for t in [T[b - 1], T[b]]:
            res = min(res, 
                      abs(s - x) + abs(s - t),
                      abs(t - x) + abs(s - t))
            
    print(res)

Submission status: Runtime Error

Solution code:
import bisect

A, B, Q = [int(e) for e in input().split()]
ss = [int(input()) for _ in range(A)]
tt = [int(input()) for _ in range(B)]
xx = [int(input()) for _ in range(Q)]

for x in xx:
    buf = []
    # s right, t
    idx_s_right = min(bisect.bisect_left(ss, x), A-1)
    s_right = ss[idx_s_right]

    idx_st_right = min(bisect.bisect_left(tt, s_right), B-1)
    idx_st_left = max(0, idx_st_right - 1)
    t_right = tt[idx_st_right]
    t_left = tt[idx_st_left]

    buf.append(abs(s_right - x) + abs(t_right - s_right))
    buf.append(abs(s_right - x) + abs(t_left - s_right))
    s_right = None 
    t_right = None
    s_left = None
    t_left = None

    # s left, t
    idx_s_left = max(0, idx_s_right - 1)
    if idx_s_left != idx_s_right:
        s_left = ss[idx_s_left]

        idx_st_right = min(bisect.bisect_left(tt, s_left), B-1)
        idx_st_left = max(0, idx_st_right - 1)
        t_right = tt[idx_st_right]
        t_left = tt[idx_st_left]

        buf.append(abs(s_left - x) + abs(t_right - s_left))
        buf.append(abs(s_left - x) + abs(t_left - s_left))
    
        s_right = None 
        t_right = None
        s_left = None
        t_left = None

    # t right, r 
    idx_t_right = min(bisect.bisect_left(tt, x), B-1)
    t_right = tt[idx_t_right]

    idx_ts_right = min(bisect.bisect_left(ss, t_right), A-1)
    idx_ts_left = max(0, idx_ts_right - 1)
    s_right = ss[idx_ts_right]
    s_left = ss[idx_ts_left]

    buf.append(abs(t_right - x) + abs(s_right - t_right))
    buf.append(abs(t_right - x) + abs(s_left - t_right))
    
    s_right = None 
    t_right = None
    s_left = None
    t_left = None

    # s left, t
    idx_t_left = max(0, idx_t_right - 1)
    if idx_t_left != idx_t_right:
        t_left = ss[idx_t_left]

        idx_ts_right = min(bisect.bisect_left(ss, t_left), A-1)
        idx_ts_left = max(0, idx_ts_right - 1)
        s_right = tt[idx_ts_right]
        s_left = tt[idx_ts_left]

        buf.append(abs(t_left - x) + abs(s_right - t_left))
        buf.append(abs(t_left - x) + abs(s_left - t_left))

    print(min(buf))

Submission status: Runtime Error

Solution code:
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]


def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W


def ceil(a, b):
    return (a + b - 1) // b


# aとbの最大公約数
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)


# aとbの最小公倍数
def lcm(a, b):
    g = gcd(a, b)
    return a / g * b

class BisectWrapper:
    from typing import List
    from bisect import bisect, bisect_left, bisect_right

    def __init__(self):
        pass

    # aにxが存在するか
    @staticmethod
    def exist(a: List, x: int):
        i = bisect_left(a, x)
        if i != len(a) and a[i] == x:
            return True
        return False

    # xのindex(なければ-1)
    @staticmethod
    def index(a: List, x: int):
        i = bisect_left(a, x)
        if i != len(a) and a[i] == x:
            return i
        return -1

    # y < xのようなyの中でもっとも右のindex
    @staticmethod
    def index_lt(a: List, x: int):
        i = bisect_left(a, x)
        if i:
            return i - 1
        return -1

    # y < xのようなyの個数
    @staticmethod
    def num_lt(a: List, x: int):
        return bisect_left(a, x)

    # y <= xのようなyの中でもっとも右のindex
    @staticmethod
    def index_lte(a: List, x: int):
        i = bisect_right(a, x)
        if i:
            return i - 1
        return -1

    # y < xのようなyの個数
    @staticmethod
    def num_lte(a: List, x: int):
        return bisect_right(a, x)

    # y > xのようなyの中でもっとも左のindex
    @staticmethod
    def index_gt(a: List, x: int):
        i = bisect_right(a, x)
        if i != len(a):
            return i
        return -1

    # y > xのようなyの個数
    @staticmethod
    def num_gt(a: List, x: int):
        return len(a) - bisect_right(a, x)

    # y >= xのようなyの中でもっとも左のindex
    @staticmethod
    def index_gte(a: List, x: int):
        i = bisect_left(a, x)
        if i != len(a):
            return i
        return -1

    # y >= xのようなyの個数
    @staticmethod
    def num_gte(a: List, x: int):
        return len(a) - bisect_left(a, x)


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

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

        s_l = BisectWrapper.index_lte(S, x)
        s_r = BisectWrapper.index_gte(S, x)

        t_l = BisectWrapper.index_lte(T, x)
        t_r = BisectWrapper.index_gte(T, x)

        ans = INF
        if s_l != -1:
            if t_l != -1:
                s, t = S[s_l], T[t_l]
                ans = min(ans, abs(x - s) + abs(s - t))
                ans = min(ans, abs(x - t) + abs(t - s))
            if t_r != -1:
                s, t = S[s_l], T[t_r]
                ans = min(ans, abs(x - s) + abs(s - t))
                ans = min(ans, abs(x - t) + abs(t - s))
        elif s_r != -1:
            if t_l != -1:
                s, t = S[s_r], T[t_l]
                ans = min(ans, abs(x - s) + abs(s - t))
                ans = min(ans, abs(x - t) + abs(t - s))
            if t_r != -1:
                s, t = S[s_r], T[t_r]
                ans = min(ans, abs(x - s) + abs(s - t))
                ans = min(ans, abs(x - t) + abs(t - s))
            
        print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import bisect
a,b,q=map(int,input().split())
S,T=[],[]
for i in range(a):
  S.append(int(input()))
for i in range(b):
  T.append(int(input()))
def f(list,n):
  if n<list[0]:
    return [-float("inf"),list[0]]
  elif list[-1]<n:
    return [list[-1],float("inf")]
  else:
    i=bisect.bisect_left(list,n)
    return [list[i],list[i+1]]
def g(SS,TT,x):
  a,b,c,d=x-SS[0],SS[1]-x,x-TT[0],TT[1]-x
  dis1=max(a,c)
  dis2=min(2*a+d,2*d+a)
  dis3=max(b,d)
  dis4=min(2*b+c,2*c+b)
  return min([dis1,dis2,dis3,dis4])
for i in range(q):
  x=int(input())
  print(g(f(S,x),f(T,x),x))

Submission status: Runtime Error

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


import bisect

mas = max(s)
mis = min(s)
mat = max(t)
mit = min(t)

for i in range(Q):
    ans = 10**20

    if mis <= x[i]:
        s_index = bisect.bisect_left(s,x[i])
        s_index -= 1
        if mat >= s[s_index]:
            t_index = bisect.bisect_left(t,s[s_index])
            ans = min(ans, abs(x[i] - s[s_index]) + abs(t[t_index] - s[s_index]))

    if mit <= x[i]:
        t_index = bisect.bisect_left(t,x[i])
        t_index -= 1
        if mas >= t[t_index]:
            s_index = bisect.bisect_left(s,t[t_index])
            ans = min(ans, abs(x[i] - t[t_index]) + abs(t[t_index] - s[s_index]))

    if mas >= x[i]:
        s_index = bisect.bisect_left(s,x[i])
        if mit <= s[s_index]:
            t_index = bisect.bisect_left(t,s[s_index])
            t_index -= 1
            ans = min(ans, abs(x[i] - s[s_index]) + abs(t[t_index] - s[s_index]))

    if mat >= x[i]:
        t_index = bisect.bisect_left(t,x[i])
        if mis <= t[t_index]:
            s_index = bisect.bisect_left(s,t[t_index])
            s_index -= 1
            ans = min(ans, abs(x[i] - t[t_index]) + abs(t[t_index] - s[s_index]))

    if mas >= x[i] and mat >= x[i]:
        s_index = bisect.bisect_left(s,x[i])
        t_index = bisect.bisect_left(t,x[i])
        ans = min(ans,abs(x[i] - max(s[s_index],t[t_index])))

    if mis <= x[i] and mit <= x[i]:
 　　　　s_index = bisect.bisect_left(s,x[i])
        s_index -= 1
        t_index = bisect.bisect_left(t,x[i])
        t_index -= 1
        ans = min(ans,abs(x[i] - min(s[s_index],t[t_index])))
    print(ans)

Submission status: Runtime Error

Solution code:
for i in range(Q):
    x.append(int(input()))


import bisect

mas = max(s)
mis = min(s)
mat = max(t)
mit = min(t)

for i in range(Q):
    ans = 10**20

    if mis <= x[i]:
        s_index = bisect.bisect_left(s,x[i])
        s_index -= 1
        if mat >= s[s_index]:
            t_index = bisect.bisect_left(t,s[s_index])
            ans = min(ans, abs(x[i] - s[s_index]) + abs(t[t_index] - s[s_index]))

    if mit <= x[i]:
        t_index = bisect.bisect_left(t,x[i])
        t_index -= 1
        if mas >= t[t_index]:
            s_index = bisect.bisect_left(s,t[t_index])
            ans = min(ans, abs(x[i] - t[t_index]) + abs(t[t_index] - s[s_index]))

    if mas >= x[i]:
        s_index = bisect.bisect_left(s,x[i])
        if mit <= s[s_index]:
            t_index = bisect.bisect_left(t,s[s_index])
            t_index -= 1
            ans = min(ans, abs(x[i] - s[s_index]) + abs(t[t_index] - s[s_index]))

    if mat >= x[i]:
        t_index = bisect.bisect_left(t,x[i])
        if mis <= t[t_index]:
            s_index = bisect.bisect_left(s,t[t_index])
            s_index -= 1
            ans = min(ans, abs(x[i] - t[t_index]) + abs(t[t_index] - s[s_index]))

    if mas >= x[i] and mat >= x[i]:
        s_index = bisect.bisect_left(s,x[i])
        t_index = bisect.bisect_left(t,x[i])
        ans = min(ans,abs(x[i] - max(s[s_index],t[t_index])))

    if mis <= x[i] and mit <= x[i]:
 　　　　s_index = bisect.bisect_left(s,x[i])
        s_index -= 1
        t_index = bisect.bisect_left(t,x[i])
        t_index -= 1
        ans = min(ans,abs(x[i] - min(s[s_index],t[t_index])))
    print(ans)

Submission status: Runtime Error

Solution code:
a, b, q = map(int, input().split())
sno = [-10e6] + [int(input()) for _ in range(a)] + [10e6]
tno = [-10e6] + [int(input()) for _ in range(b)] + [10e6]
dis = [int(input()) for _ in range q]
 
for i in range(q):
 
    sl = 0
    sr = 0
    tl = 0
    tr = 0
 
    for j in range(a+2):
        if sno[j] >= dis[i]:
            sl = dis[i] - sno[j-1]
            sr = sno[j] - dis[i]
            break
        else:
            pass
 
    for k in range(b+2):
        if tno[k] >= dis[i]:
            tl = dis[i] - tno[k-1]
            tr = tno[k] - dis[i]
            break
        else:
            pass
 
    lds = max(sl, tl)
    rds = max(sr, tr)
    ans = min(lds, rds)
    print(ans)

Submission status: Runtime Error

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
    n = len(ls)
    width = n//2
    pos = n//2
    while True:
        width = (width+1)//2
        if ls[pos] < x < ls[pos+1]:
            index = pos
            break    
        elif x < ls[pos]:
            pos -= width
        elif ls[pos+1] < x:
            pos += width
    return index

for x in xs:
    sind = binarysearch(ss,x)
    tind = binarysearch(ts,x)
    
    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10
    
    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Runtime Error

Solution code:
import math
import bisect
import itertools
import sys


def most_simRL(ds, x):
    index = bisect.bisect_left(ds, x)
    if index == 0:
        return [ds[0]]
    elif index == len(ds):
        return [ds[-1]]
    return ds[index-1:index+1]

if __name__ == '__main__':
    A, B, Q = map(int, input().split())


    s_list = [-math.inf] + [int(input()) for i in range(A)] + [math.inf]
    t_list = [-math.inf] + [int(input()) for i in range(B)] + [math.inf]
    x_list = [int(input()) for i in range(Q)]


    for xi in x_list:
        s_RL = most_simRL(s_list, xi)
        t_RL = most_simRL(t_list, xi)

        answer = sys.maxsize

        for a, b in itertools.product(s_RL, t_RL):
            answer = min(answer, min(abs(xi-a), abs(xi-b)) + abs(a-b))

        print(answer)

Submission status: Runtime Error

Solution code:
if __name__ == '__main__':
    A, B, Q = map(int, input().split())

    s_list = [int(input()) for i in range(A)]
    t_list = [int(input()) for i in range(B)]
    x_list = [int(input()) for i in range(Q)]

    for xi in x_list:
        distance_ti_right_xi = [ti-xi for ti in t_list if ti >= xi]
        distance_ti_left_xi = [xi-ti for ti in t_list if ti <= xi]
        distance_si_right_xi = [si-xi for si in s_list if si >= xi]
        distance_si_left_xi = [xi-si for si in s_list if si <= xi]
        
        first_move = min(distance_si_left_xi, distance_si_right_xi, distance_ti_left_xi, distance_ti_right_xi)
        if first_move == distance_ti_left_xi or first_move == distance_si_left_xi:
            first_move = -1 * first_move
        xi += first_move

        if abs(first_move) == distance_si_left_xi or abs(first_move) == distance_si_right_xi:
            distance_ti_right_xi = [ti-xi for ti in t_list if ti >= xi]
            distance_ti_left_xi = [xi-ti for ti in t_list if ti <= xi]
            second_move = min(distance_ti_left_xi, distance_ti_right_xi)

        if abs(first_move) == distance_ti_left_xi or abs(first_move) == distance_ti_right_xi:
            distance_si_right_xi = [si-xi for si in s_list if si >= xi]
            distance_si_left_xi = [xi-si for si in s_list if si <= xi]
            second_move = min(distance_si_left_xi, distance_si_right_xi)
        answer = abs(first_move) + abs(second_move)
        print(answer)

Submission status: Runtime Error

Solution code:
a, b, q = map(int, input().split())
sno = [-1000000,]
tno = [-1000000,]
dis = []
 
for i in range(a):
    sno.append(int(input()))
sno.append(1000000)

for i in range(b):
    tno.append(int(input()))
tno.append(1000000)

for i in range(q):
    dis.append(int(input()))

for i in range(q):
 
    sl = 0
    sr = 0
    tl = 0
    tr = 0
 
    for j in range(a+1):
        if sno[j] >= dis[i]:
        	sl = dis[i] - sno[j-1]
            sr = sno[j] - dis[i]
            break
        else:
            pass
 
    for k in range(b):
        if tno[k] >= dis[i]:
        	tl = dis[i] - tno[k-1]
            tr = tno[k] - dis[i]
            break
        else:
            pass
 
    lds = max(sl, tl)
    rds = max(sr, tr)
    ans = min(lds, rds)
    print(ans)

Submission status: Runtime Error

Solution code:
a, b, q = map(int, input().split())
sno = []
tno = []
dis = []
 
for i in range(a):
    sno.append(int(input()))
    
for i in range(b):
    tno.append(int(input()))
    
for i in range(q):
    dis.append(int(input()))
    
for i in range(q):
      sl = 0
      sr = 0
      tl = 0
      tr = 0
      ch1 = 0
      ch2 = 0
 
      for j in range(a):
    	if ch1 != 0:
        	break
        else:
          if sno[j] >= dis[i]:
              if j == 0:
                  sl = 10000
                  sr = sno[0] - dis[i]
                  ch1 = ch1 + 1
                  break
              else:
                  sl = dis[i] - sno[j-1]
                  sr = sno[j] - dis[i]
                  ch1 = ch1 + 1
                  break
          else:
            pass
 
      for k in range(b):
    	if ch2 != 0:
        	break
        else:
          if tno[k] >= dis[i]:
              if k == 0:
                  tl = 10000
                  tr = tno[0] - dis[i]
                  ch2 = ch2 + 1
                  break
              else:
                tl = dis[i] - tno[k-1]
                tr = tno[k] - dis[i]
                ch2 = ch2 + 1
                break
          else:
            pass

      lds = max(sl, tl)
      rds = max(sr, tr)
      dis = min(lds, rds)
      print(dis)

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
import bisect

inf = float('inf')


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    s = [ int(next(tokens)) for _ in range(A) ]  # type: "List[int]"
    t = [ int(next(tokens)) for _ in range(B) ]  # type: "List[int]"
    for _ in range(Q):
        q = int(next(tokens))
        i_s = bisect.bisect(s, q)
        i_t = bisect.bisect(t, q)

        s_l = q - s[i_s-1] if i_s > 0 else inf
        s_r = s[i_s] - q if i_s < A else inf
        t_l = q - t[i_t-1] if i_t > 0 else inf
        t_r = t[i_t] - q if i_t < A else inf

        # 同じ方向に行く場合
        sltl = max([s_l, t_l])
        srtr = max([s_r, t_r])

        # 違う方向に行く場合
        sltr = min([s_l, t_r]) + sum([s_l, t_r])
        srtl = min([s_r, t_l]) + sum([s_r, t_l])

        min_d = min([sltl, srtr, sltr, srtl])

        print(min_d)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
#!/usr/bin/env python3
import sys
import bisect

inf = float('inf')

def solve(A: int, B: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):
    for q in x:
        i_s = bisect.bisect(s, q)
        i_t = bisect.bisect(t, q)

        s_l = q - s[i_s-1] if i_s > 0 else inf
        s_r = s[i_s] - q if i_s < A else inf
        t_l = t_l = q - t[i_t-1] if i_t > 0 else inf
        t_r = t[i_t] - q if i_t < A else inf

        # 同じ方向に行く場合
        sltl = max([s_l, t_l])
        srtr = max([s_r, t_r])

        # 違う方向に行く場合
        sltr = min([s_l, t_r]) + sum([s_l, t_r])
        srtl = min([s_r, t_l]) + sum([s_r, t_l])

        min_d = min([sltl, srtr, sltr, srtl])

        print(min_d)
        
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    s = [ int(next(tokens)) for _ in range(A) ]  # type: "List[int]"
    t = [ int(next(tokens)) for _ in range(B) ]  # type: "List[int]"
    x = [ int(next(tokens)) for _ in range(Q) ]  # type: "List[int]"
    solve(A, B, Q, s, t, x)

if __name__ == '__main__':
    main()