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: Time Limit Exceeded

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(x,seq):
	width=[0,len(seq)-1]
	if len(seq)<=1:
		return [0,0]
	if x<=seq[0]:
		return [0,0]
	elif x>=seq[width[1]]:
		return [width[1],width[1]]
	else:
		while(width[1]-width[0]>1):
			center=(sum(width)//2)
			if x>=seq[center]:
				width=[center,width[1]]
			else:
				width=[width[0],center]
	if x==seq[width[0]]:
		return [width[0],width[0]]
	elif x==seq[width[1]]:
		return [width[1],width[1]]
	else:
		return width

for i in range(Q):
	x=int(input())
	Nb_s0=s[bin_search(x,s)[0]]
	Nb_s1=s[bin_search(x,s)[1]]
	Nb_t0=t[bin_search(x,t)[0]]
	Nb_t1=t[bin_search(x,t)[1]]

	k1=abs(Nb_s0-x)+abs(Nb_t0-Nb_s0)
	k2=abs(Nb_s1-x)+abs(Nb_t0-Nb_s1)
	k3=abs(Nb_s0-x)+abs(Nb_t1-Nb_s0)
	k4=abs(Nb_s1-x)+abs(Nb_t1-Nb_s1)
	k5=abs(Nb_t0-x)+abs(Nb_t0-Nb_s0)
	k6=abs(Nb_t1-x)+abs(Nb_t1-Nb_s1)
	k7=abs(Nb_t0-x)+abs(Nb_t0-Nb_s1)
	k8=abs(Nb_t1-x)+abs(Nb_t1-Nb_s0)
	print(min(k1,k2,k3,k4,k5,k6,k7,k8))

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left
a, b, q = map(int, input().split())
S = [int(input()) for i in range(a)]
T = [int(input()) for i in range(b)]
for _ in range(q):
    x = int(input())
    i = bisect_left(S, x)
    j = bisect_left(T, x)
    if i == 0:
        s = [S[0]]
    elif i == len(S):
        s = [S[-1]]
    else:
        s =[S[i - 1], S[i]]
    if j == 0:
        t = [T[0]]
    elif j == len(T):
        t = [T[-1]]
    else:
        t =[T[j - 1], T[j]]
    ans = []
    for i in range(len(s)):
        for j in range(len(t)):
            ans.append(abs(x - s[i]) + abs(s[i] - t[j]))
    for j in range(len(t)):
        for i in range(len(s)):
            ans.append(abs(x - t[j]) + abs(t[j] - s[i]))
    print(min(ans))

Submission status: Time Limit Exceeded

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) - 1
    t_index = bisect(t_array, q) - 1
    # print(s_index,t_index)
    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))
    print(min(method_a, method_b, method_c, method_d))

Submission status: Time Limit Exceeded

Solution code:
def bisect_search(x, L):
    if x <= L[0]:
        return 0
    elif x > L[-1]:
        return len(L)

    idx = len(L) // 2
    if x <= L[idx]:
        y = bisect_search(x, L[:idx])
    else:
        y = idx + bisect_search(x, L[idx:])
    return y

a, b, q = map(int, input().split())
INF = 10 ** 11
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]

ans = []
for xi in x:
    s_idx = bisect_search(xi, s)
    t_idx = bisect_search(xi, t)
    yi = []
    for j in range(2):
        sj = s[s_idx - j]
        for k in range(2):
            tk = t[t_idx - k]
            d = min(abs(xi - sj), abs(xi - tk)) + abs(sj - tk)
            yi.append(d)
    ans.append(min(yi))
for ansi in ans:
    print(ansi)

Submission status: Time Limit Exceeded

Solution code:
# tab
class AvlTree:  # std::set
	def __init__(self, values=None, sorted_=False):
		if values is None:
			self.left = [-1]
			self.right = [-1]
			self.values = [-float("inf")]
			self.diff = [0]  # left - right
			self.size_l = [0]
		else:
			n = len(values)
			self.left = [-1] * (n+1)
			self.right = [-1] * (n+1)
			self.values = [-float("inf")] + values
			self.diff = [0] * (n+1)  # left - right
			self.size_l = [0] * (n+1)
			if not sorted_:
				values.sort()

			st = [[1, n+1, 0]]
			while len(st) > 0:
				l, r, idx_par = st.pop()  # 半開区間
				c = (l+r) // 2
				if self.values[c] < self.values[idx_par]:
					self.left[idx_par] = c
				else:
					self.right[idx_par] = c
				siz = r - l
				if siz & -siz == siz and siz != 1:  # 2冪だったら
					self.diff[c] = 1
				siz_l = c - l
				self.size_l[c] = siz_l
				if siz_l > 0:
					st.append([l, c, c])
					c1 = c + 1
					if c1 < r:  # 左にノードがなければ右には必ず無いので
						st.append([c1, r, c])

	# 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

		self.diff[path[-1]] += 1 if x < value else -1
		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, True)
avl_T = AvlTree(T, True)

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: Time Limit Exceeded

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

INF = 10 ** 11 + 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 bsr(a, v, lo=0, hi=None):
	if hi == None:
		hi = len(a) - 1
	if hi < lo:
		return lo
	mi = (lo + hi) // 2
	if v < a[mi]:
		return bsr(a, v, lo, mi - 1)
	else:
		return bsr(a, v, mi + 1, hi)

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

#for x in X:
for _ in range(Q):
	x = int(input())
	sr = bsr(S, x)
	sl = sr - 1
	tr = bsr(T, x)
	tl = tr - 1
	#print(sr, sl, tr, tl)
	#print(S[sr], S[sl], T[tr], T[tl])
	cost = []
	for m in [S[sr], S[sl]]:
		for n in [T[tr], T[tl]]:
			cost += [abs(x - m) + abs(m - n), abs(x - n) + abs(m - n)]
	#print(sr, sl, tr, tl, cost)
	print(min(cost))
	#break

Submission status: Time Limit Exceeded

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

INF = 10 ** 11 + 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 bsr(a, v, lo=0, hi=None):
	if hi == None:
		hi = len(a) - 1
	if hi < lo:
		return lo
	mi = (lo + hi) // 2
	if v < a[mi]:
		return bsr(a, v, lo, mi - 1)
	else:
		return bsr(a, v, mi + 1, hi)

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

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

Submission status: Time Limit Exceeded

Solution code:
# %2
class AvlTree:  # std::set
    def __init__(self, values=None, sorted_=False):
        if values is None:
            self.left = [-1]
            self.right = [-1]
            self.values = [-float("inf")]
            self.diff = [0]  # left - right
            self.size_l = [0]
        else:
            n = len(values)
            self.left = [-1] * (n+1)
            self.right = [-1] * (n+1)
            self.values = [-float("inf")] + values
            self.diff = [0] * (n+1)  # left - right
            self.size_l = [0] * (n+1)
            if not sorted_:
                values.sort()

            st = [[1, n+1, 0]]
            while len(st) > 0:
                l, r, idx_par = st.pop()  # 半開区間
                c = (l+r) % 2
                if self.values[c] < self.values[idx_par]:
                    self.left[idx_par] = c
                else:
                    self.right[idx_par] = c
                siz = r - l
                if siz & -siz == siz and siz != 1:  # 2冪だったら
                    self.diff[c] = 1
                siz_l = c - l
                self.size_l[c] = siz_l
                if siz_l > 0:
                    st.append([l, c, c])
                    c1 = c + 1
                    if c1 < r:  # 左にノードがなければ右には必ず無いので
                        st.append([c1, r, c])

    # 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

        self.diff[path[-1]] += 1 if x < value else -1
        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, True)
avl_T = AvlTree(T, True)

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: Time Limit Exceeded

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: Time Limit Exceeded

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 bsearch_sub(a, v, imin, imax):
	if imax < imin:
		return (imax, imin)
	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)
		else:
			return (imid, imid)

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

#print(S, T)
for x in X:
	s = bsearch(S, x)
	sb, sd = [], []
	if 0 <= s[0] < A:
		sb += [S[s[0]]]
		sd += [S[s[0]] - x]
	if 0 <= s[1] < A:
		sb += [S[s[1]]]
		sd += [S[s[1]] - x]

	t = bsearch(T, x)
	tb, td = [], []
	if 0 <= t[0] < B:
		tb += [T[t[0]]]
		td += [T[t[0]] - x]
	if 0 <= t[1] < B:
		tb += [T[t[1]]]
		td += [T[t[1]] - x]

	r = []
	for sn in sd:
		for tn in td:
			if sn < 0 and tn < 0:
				r += [max([-sn, -tn])]
			elif 0 < sn and 0 < tn:
				r += [max([sn, tn])]
			else:
				r += [min([abs(sn), abs(tn)]) * 2 + max([abs(sn), abs(tn)])]
	print(min(r))

	#print(x, s, sb, sd)
	#print(x, t, tb, td)
	#print(x, bsearch(S, x), sb, bsearch(T, x), tb)

Submission status: Time Limit Exceeded

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]

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 = i_last, 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 = j_last, B + 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: Time Limit Exceeded

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) // 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 = binsearch_l(s, i_last, A + 1, x_tmp)
    j_l = binsearch_l(t, j_last, B + 1, x_tmp)
    #
    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: Time Limit Exceeded

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) // 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 = []
i_last = j_last = 0
for idx, x_tmp in sorted(enumerate(x), key=lambda x: x[1]):
    i_l = binsearch_l(s, i_last, A + 1, x_tmp)
    j_l = binsearch_l(t, j_last, B + 1, x_tmp)
    #
    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.append((idx, ans))

for idx, ansi in sorted(ans_Q, key=lambda x: x[0]):
    print(ansi)

Submission status: Time Limit Exceeded

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.insert(0, -inf)
s.insert(A + 1, inf)
t.insert(0, -inf)
t.insert(B + 1, inf)

def binsearch_l(seq, l, r, tar):
    if r - l < 2: return l
    #
    m = l + (r - l) // 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)

for x_tmp in x:
    i_l = binsearch_l(s, 0, A + 2, x_tmp)
    j_l = binsearch_l(t, 0, B + 2, x_tmp)
    #
    i_l = 1 if i_l < 1 else (A - 1 if i_l > A - 1 else i_l)
    j_l = 1 if j_l < 1 else (B - 1 if j_l > B - 1 else j_l)
    #
    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)):
        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
    #
    print(ans)