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:
#!/usr/bin/env python3
import sys


def solve(N: int, M: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):

    def binary_search(ary, val):
        n = len(ary)
        l = -1
        r = n
        while r - l > 1:
            mid = (l + r) // 2
            if ary[mid] >= val:
                r = mid
            else:
                l = mid
        if l == -1:
            return [ary[0]]
        if r == n:
            return [ary[n - 1]]
        return [ary[l], ary[r]]

    for q in x:
        ret = float('inf')
        a_pos = binary_search(s, q)
        b_pos = binary_search(t, q)
        for a in a_pos:
            for b in b_pos:
                ret = min(ret, abs(a - q) + abs(b - a))
                ret = min(ret, abs(b - q) + abs(a - b))
        print(ret)
    return


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

Submission status: Accepted

Solution code:
import bisect

a, b, q = map(int, input().split())
INF = 3*10**10
S = [int(input()) for _ in range(a)]

S = [-INF] + S[:] + [INF]
T = [int(input()) for _ in range(b)]
T = [-INF] + T[:] + [INF]

for _ in range(q):
    x = int(input())
    i = bisect.bisect_left(S, x) 
    j = bisect.bisect_left(T, x) 
    A = [max(S[i]-x, T[j]-x), max(x-S[i-1], x-T[j-1]), S[i]-T[j-1]+min(S[i]-x, x-T[j-1]), T[j]-S[i-1]+min(x-S[i-1], T[j]-x)]
    print(min(A))

Submission status: Accepted

Solution code:
import bisect


a, b, q = map(int, input().split())
s_list = [-100000000000000000]
t_list = [-100000000000000000]

for i in range(a):
    s = int(input())
    s_list.append(s)
for j in range(b):
    t = int(input())
    t_list.append(t)
s_list.append(100000000000000000)
t_list.append(100000000000000000)

for i in range(q):
    x = int(input())
    s_pos = bisect.bisect_left(s_list, x)
    t_pos = bisect.bisect_left(t_list, x)
    
    s_cand1 = x - s_list[s_pos-1]
    s_cand2 = s_list[s_pos] - x
    t_cand1 = x - t_list[t_pos-1]
    t_cand2 = t_list[t_pos] - x
    
    dist1 = max(s_cand1, t_cand1)
    dist2 = max(s_cand2, t_cand2)
    dist3 = min(s_cand1, t_cand2)*2 + max(s_cand1, t_cand2)
    dist4 = min(s_cand2, t_cand1)*2 + max(s_cand2, t_cand1)
    
    print(min(dist1, dist2, dist3, dist4))

Submission status: Accepted

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

def f(S,T):
    res = 10**30 
    s = bisect_left(S,x)

    ans = 0
    t = bisect_left(T,S[s-1])
    ans += abs(x-S[s-1])+min(abs(S[s-1]-T[t-1]),abs(S[s-1]-T[t]))
    if ans <= res:
        res = ans
    
    ans = 0
    t = bisect_left(T,S[s])
    ans += abs(x-S[s])+min(abs(S[s]-T[t-1]),abs(S[s]-T[t]))
    if ans <= res:
        res = ans

    return res


for i in range(q):
    x = int(input())
    print(min(f(S,T),f(T,S)))

Submission status: Accepted

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

def f(S,T):
    res = INF
    s = bisect.bisect_left(S,x)
    for i in range(2):
    	for j in range(2):
            t = bisect.bisect_left(T,S[s-i])
            ans= abs(x-S[s-i])+abs(S[s-i]-T[t-j])
            if ans < res:
                res = ans
    return res

for i in range(q):
    x = int(input())
    print(min(f(S,T),f(T,S)))

Submission status: Accepted

Solution code:
import bisect

def calc_distance(frm, x, y):
	return min(abs(frm - x), abs(frm - y) ) + abs(x - y)

def calc_2points(frm, us):
	idx = bisect.bisect_left(us, frm)
	return us[idx - 1], us[idx]

def calc_min(ss, ts, x):
	s1, s2 = calc_2points(x, ss)
	t1, t2 = calc_2points(x, ts)
	ans = min(calc_distance(x, s1, t1), calc_distance(x, s1, t2), calc_distance(x, s2, t1), calc_distance(x, s2, t2))
	return ans

INF = 10 ** 20
a, b, q = list(map(int, input().split()))
ss = [-INF] + [int(input()) for _ in range(a)] + [INF]
ts = [-INF] + [int(input()) for _ in range(b)] + [INF]
xs = [int(input()) for _ in range(q)]

for x in xs:
	print(calc_min(ss, ts, x))

Submission status: Accepted

Solution code:
import bisect

def calc_distance(frm, x, y):
	#frmからx, yのに地点を通るのに必要な距離を計算する
	return min(abs(frm - x), abs(frm - y) ) + abs(x - y)

def calc_both_end(frm, us):
	#地点frmに囲まれた2点を返す。
	#片側しか囲われていない場合は最寄の2点
	if len(us) == 1:
		return us[0], us[0]

	idx = bisect.bisect_left(us, frm)
	if idx == 0:
		return us[0], us[1]
	elif idx == len(us):
		return us[len(us) - 2], us[len(us) - 1]
	else:
		return us[idx - 1], us[idx]

def find(ss, ts, x):
	s1, s2 = calc_both_end(x, ss)
	t1, t2 = calc_both_end(x, ts)
	ans = min(calc_distance(x, s1, t1), calc_distance(x, s1, t2), calc_distance(x, s2, t1), calc_distance(x, s2, t2))
	return ans

a, b, q = list(map(int, input().split()))
ss = [int(input()) for _ in range(a)]
ts = [int(input()) for _ in range(b)]
xs = [int(input()) for _ in range(q)]

for x in xs:
	print(find(ss, ts, x))

Submission status: Accepted

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

def f(S,T):
    res = 10**30 
    s = bisect_left(S,x)

    ans = 0
    t = bisect_left(T,S[s-1])
    ans += abs(x-S[s-1])+min(abs(S[s-1]-T[t-1]),abs(S[s-1]-T[t]))
    if ans <= res:
        res = ans
    
    ans = 0
    t = bisect_left(T,S[s])
    ans += abs(x-S[s])+min(abs(S[s]-T[t-1]),abs(S[s]-T[t]))
    if ans <= res:
        res = ans

    return res


for i in range(q):
    x = int(input())
    print(min(f(S,T),f(T,S)))

Submission status: Accepted

Solution code:
from bisect import bisect_left
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]

def f(S,T):
    res = 10**30 
    s = bisect_left(S,x)

    ans = 0
    t = bisect_left(T,S[s-1])
    ans += abs(x-S[s-1])+min(abs(S[s-1]-T[t-1]),abs(S[s-1]-T[t]))
    if ans <= res:
        res = ans
    
    ans = 0
    t = bisect_left(T,S[s])
    ans += abs(x-S[s])+min(abs(S[s]-T[t-1]),abs(S[s]-T[t]))
    if ans <= res:
        res = ans

    return res


for i in range(q):
    x = int(input())
    print(min(f(S,T),f(T,S)))

Submission status: Accepted

Solution code:
import itertools
A,B,Q = [int(_) for _ in input().split(" ")]
s_array = [int(input()) for _ in range(A)]
t_array = [int(input()) for _ in range(B)]                                                  
x = [int(input()) for _ in range(Q)]

def binary_search(arr,point,start,end):
    pivot = (start+end)//2
    if end -start > 1:
        if arr[pivot] <point :
            return binary_search(arr,point,pivot,end)
        else:
            return binary_search(arr,point,start,pivot)
    else:
        return start
    
def find_closest_path(s_1,s_2,t_1,t_2,point):
    shortest = 10**11
    for s,t in itertools.product([s_1,s_2],[t_1,t_2]):
        length = min(abs(point-t), abs(point -s )) + abs(s - t)
        if length < shortest:
            shortest = length 
    return shortest 


for i in range(Q):
    s_idx = binary_search(s_array,x[i],0,len(s_array)-1)
    t_idx = binary_search(t_array,x[i],0,len(t_array)-1)
    if len(s_array)>1:
        s_1,s_2 = s_array[s_idx],s_array[s_idx+1] 
    else:
        s_1,s_2 = s_array[0],s_array[0]
    if len(t_array)>1:
        t_1,t_2 = t_array[t_idx],t_array[t_idx+1]    
    else:
        t_1,t_2 = t_array[0],t_array[0]
    answer = find_closest_path(s_1,s_2,t_1,t_2,x[i])
    print(answer)

Submission status: Accepted

Solution code:
from bisect import*
a,b,q=map(int,input().split())
a1=[int(input())for i in range(a)]
b1=[int(input())for i in range(b)]
q=[int(input())for i in range(q)]
 
a1=[-20**10]+a1+[20**10]
b1=[-20**10]+b1+[20**10]
 
for i in q:
    x=bisect_left(a1,i)
    y=bisect_left(b1,i)
    low =i-min(a1[x-1],b1[y-1])
    high=max(a1[x],b1[y])-i
    turn1=min(a1[x]-i,i-b1[y-1])+abs(a1[x]-b1[y-1])
    turn2=min(b1[y]-i,i-a1[x-1])+abs(b1[y]-a1[x-1])
    print(min(low,high,turn1,turn2))

Submission status: Accepted

Solution code:
from bisect import*
a,b,q=map(int,input().split())
a1=[int(input())for i in range(a)]
b1=[int(input())for i in range(b)]
q=[int(input())for i in range(q)]

mama=max(a1[-1],b1[-1])
mami=min(a1[-1],b1[-1])
mimi=min(a1[0],b1[0])
mima=max(a1[0],b1[0])

a1=[-20**10]+a1+[20**10]
b1=[-20**10]+b1+[20**10]

#print(mama,mami,mima,mimi)
for i in q:
    if i>=mama:
        print(i-mami)
    elif i<=mimi:
        print(mima-i)
    else:
        x=bisect_left(a1,i)
        y=bisect_left(b1,i)
        #print(a1[x-1],a1[x],b1[y-1],b1[y])
        low =i-min(a1[x-1],b1[y-1])
        high=max(a1[x],b1[y])-i
        turn1=min(a1[x]-i,i-b1[y-1])+abs(a1[x]-b1[y-1])
        turn2=min(b1[y]-i,i-a1[x-1])+abs(b1[y]-a1[x-1])
        print(min(low,high,turn1,turn2))
#print(a1,b1,q)

Submission status: Accepted

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

import bisect

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

X = [-int(1e12)] + sorted([int(input()) for _ in range(A)]) + [int(1e12)]
Y = [-int(1e12)] + sorted([int(input()) for _ in range(B)]) + [int(1e12)]

i = 1
j = 1
pos = []
near = []
if X[1] > Y[1]:
    pos.append(Y[1])
    near.append(X[1] - Y[1])
    j = 2
else:
    pos.append(X[1])
    near.append(Y[1] - X[1])
    i = 2
while True:
    if X[i] > Y[j]:
        pos.append(Y[j])
        near.append(min(X[i] - Y[j], Y[j] - X[i-1]))
        j += 1
    else:
        pos.append(X[i])
        near.append(min(Y[j] - X[i], X[i] - Y[j-1]))
        i += 1
        
    if i >= (A + 1) and j >= (B + 1):
        break

pos = [-int(1e12)] + pos + [int(1e12)]
near = [int(1e12)] + near + [int(1e12)]
    
for _ in range(Q):
    x = int(input())
    insert_index = bisect.bisect_left(pos, x)
    if pos[insert_index] - x + near[insert_index] > x - pos[insert_index-1] + near[insert_index-1]:
        print(x - pos[insert_index-1] + near[insert_index-1])
    else:
        print(pos[insert_index] - x + near[insert_index])

Submission status: Accepted

Solution code:
import bisect

s_len, t_len, q = map(int, input().split())

shrines = []
temples = []
for _ in range(s_len):
    shrines.append(int(input()))
for _ in range(t_len):
    temples.append(int(input()))


def distance(s_i, t_i, x):
    """
    s_i と t_i を最短でまわる距離。無効なインデックスなら inf を返す
    """
    if 0 <= s_i < s_len and 0 <= t_i < t_len:
        s = shrines[s_i]
        t = temples[t_i]
        if s >= x <= t:
            return max(s, t) - x
        elif s <= x >= t:
            return x - min(s, t)
        else:
            return abs(s - t) + min(abs(x - t), abs(x - s))
    else:
        return float('inf')


def solve(x):
    s_i = bisect.bisect_left(shrines, x)
    t_i = bisect.bisect_left(temples, x)
    return min([
        distance(s_i, t_i, x),
        distance(s_i, t_i - 1, x),
        distance(s_i - 1, t_i, x),
        distance(s_i - 1, t_i - 1, x),
    ])


for _ in range(q):
    print(solve(int(input())))

Submission status: Accepted

Solution code:
from bisect import bisect_left


def solve(string):
    a, b, q, *stx = map(int, string.split())
    bignum = 3 * 10**10
    s = [-bignum] + stx[:a] + [bignum]
    t = [-bignum] + stx[a:a + b] + [bignum]
    ans = []
    for _x in stx[-q:]:
        i, j = bisect_left(s, _x), bisect_left(t, _x)
        ls, rs = _x - s[i - 1], s[i] - _x
        lt, rt = _x - t[j - 1], t[j] - _x
        ans.append(str(min(max(rs, rt), max(ls, lt), rt + ls + min(rt, ls),
                           rs + lt + min(rs, lt))))
    return "\n".join(ans)


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
from bisect import bisect_left


def solve(string):
    a, b, q, *stx = map(int, string.split())
    bignum = 3 * 10**10
    s = [-bignum] + stx[:a] + [bignum]
    t = [-bignum] + stx[a:a + b] + [bignum]
    ans = []
    for _x in stx[-q:]:
        i_s, i_t = bisect_left(s, _x), bisect_left(t, _x)
        ls, rs = _x - s[i_s - 1], s[i_s] - _x
        lt, rt = _x - t[i_t - 1], t[i_t] - _x
        ans.append(str(min(max(rs, rt), max(ls, lt), rt + ls + min(rt, ls),
                           rs + lt + min(rs, lt))))
    return "\n".join(ans)


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
from bisect import bisect_left


def solve(string):
    a, b, q, *stx = map(int, string.split())
    s = [-10**10] + stx[:a] + [2 * 10**10]
    t = [-10**10] + stx[a:a + b] + [2 * 10**10]
    x = dict([])
    ans = []
    i_s = 0
    i_t = 0
    # for _x in stx[-q:]:
    for _x in sorted(stx[-q:]):
        # """
        while s[i_s] < _x:
            i_s += 1
        while t[i_t] < _x:
            i_t += 1
        # """
        # i_s, i_t = bisect_left(s, _x), bisect_left(t, _x)
        ls, rs = _x - s[i_s - 1], s[i_s] - _x
        lt, rt = _x - t[i_t - 1], t[i_t] - _x
        r_max = rs if rs > rt else rt
        l_max = ls if ls > lt else lt
        # ans.append(
        x[_x] = str(
            min(r_max, l_max, rt + ls + (rt if rt < ls else ls),
                rs + lt + (rs if rs < lt else lt)))
    return "\n".join([x[_x] for _x in stx[-q:]])
    # return "\n".join(ans)


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
from bisect import bisect_left


def solve(string):
    a, b, q, *stx = map(int, string.split())
    s = [-10**10] + stx[:a] + [2 * 10**10]
    t = [-10**10] + stx[a:a + b] + [2 * 10**10]
    # x = dict([])
    ans = []
    i_s = 0
    i_t = 0
    for _x in stx[-q:]:
        """
        while s[i_s] < _x:
            i_s += 1
        while t[i_t] < _x:
            i_t += 1
        """
        i_s, i_t = bisect_left(s, _x), bisect_left(t, _x)
        ls, rs = _x - s[i_s - 1], s[i_s] - _x
        lt, rt = _x - t[i_t - 1], t[i_t] - _x
        r_max = rs if rs > rt else rt
        l_max = ls if ls > lt else lt
        ans.append(
            str(
                min(r_max, l_max, rt + ls + (rt if rt < ls else ls),
                    rs + lt + (rs if rs < lt else lt))))
    # return "\n".join([str(x[_x]) for _x in stx[-q:]])
    return "\n".join(ans)


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
from bisect import bisect_left


def solve(string):
    a, b, q, *stx = map(int, string.split())
    s = [-10**10] + stx[:a] + [2 * 10**10]
    t = [-10**10] + stx[a:a + b] + [2 * 10**10]
    # x = dict([])
    ans = []
    i_s = 0
    i_t = 0
    for _x in stx[-q:]:
        """
        while s[i_s] < _x:
            i_s += 1
        while t[i_t] < _x:
            i_t += 1
        """
        i_s, i_t = bisect_left(s, _x), bisect_left(t, _x)
        ls, rs = _x - s[i_s - 1], s[i_s] - _x
        lt, rt = _x - t[i_t - 1], t[i_t] - _x
        r_max = max(rs, rt)
        l_max = max(ls, lt)
        """
        x[_x] = min([
            r_max - _x, _x - l_min, rt - ls + min(rt - _x, _x - ls),
            rs - lt + min(rs - _x, _x - lt)
        ])
        """
        ans.append(
            str(
                min(r_max, l_max, rt + ls + (rt if rt < ls else ls),
                    rs + lt + (rs if rs < lt else lt))))
    # return "\n".join([str(x[_x]) for _x in stx[-q:]])
    return "\n".join(ans)


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
from bisect import bisect_left


def solve(string):
    a, b, q, *stx = map(int, string.split())
    s = [-10**10] + stx[:a] + [2 * 10**10]
    t = [-10**10] + stx[a:a + b] + [2 * 10**10]
    # x = dict([])
    ans = []
    i_s = 0
    i_t = 0
    for _x in stx[-q:]:
        """
        while s[i_s] < _x:
            i_s += 1
        while t[i_t] < _x:
            i_t += 1
        """
        i_s, i_t = bisect_left(s, _x), bisect_left(t, _x)
        ls, rs = _x - s[i_s - 1], s[i_s] - _x
        lt, rt = _x - t[i_t - 1], t[i_t] - _x
        r_max = max(rs, rt)
        l_max = max(ls, lt)
        """
        x[_x] = min([
            r_max - _x, _x - l_min, rt - ls + min(rt - _x, _x - ls),
            rs - lt + min(rs - _x, _x - lt)
        ])
        """
        ans.append(str(min([r_max, l_max, rt + ls + min(rt, ls), rs + lt + min(rs, lt)])))
    # return "\n".join([str(x[_x]) for _x in stx[-q:]])
    return "\n".join(ans)


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
from bisect import bisect_left


def solve(string):
    a, b, q, *stx = map(int, string.split())
    s = [-10**10] + stx[:a] + [2 * 10**10]
    t = [-10**10] + stx[a:a + b] + [2 * 10**10]
    # x = dict([])
    ans = []
    i_s = 0
    i_t = 0
    for _x in stx[-q:]:
        """
        while s[i_s] < _x:
            i_s += 1
        while t[i_t] < _x:
            i_t += 1
        """
        i_s, i_t = bisect_left(s, _x), bisect_left(t, _x)
        ls, rs = s[i_s - 1], s[i_s]
        lt, rt = t[i_t - 1], t[i_t]
        r_max = max(rs, rt) - _x
        l_min = _x - min(ls, lt)
        """
        x[_x] = min([
            r_max - _x, _x - l_min, rt - ls + min(rt - _x, _x - ls),
            rs - lt + min(rs - _x, _x - lt)
        ])
        """
        ans.append(
            str(
                min([
                    r_max, l_min, rt - ls + min(rt - _x, _x - ls), rs - lt + min(rs - _x, _x - lt)
                ])))
    # return "\n".join([str(x[_x]) for _x in stx[-q:]])
    return "\n".join(ans)


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
from bisect import bisect_left


def solve(string):
    a, b, q, *stx = map(int, string.split())
    s = [-10**10] + stx[:a] + [2 * 10**10]
    t = [-10**10] + stx[a:a + b] + [2 * 10**10]
    ans = []
    for _x in stx[-q:]:
        i_s, i_t = bisect_left(s, _x), bisect_left(t, _x)
        ls, rs = s[i_s - 1], s[i_s]
        lt, rt = t[i_t - 1], t[i_t]
        r_max = max(rs, rt)
        l_min = min(ls, lt)
        ans.append(
            str(
                min([
                    r_max - _x, _x - l_min, rt - ls + min(rt - _x, _x - ls),
                    rs - lt + min(rs - _x, _x - lt)
                ])))
    return "\n".join(ans)


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
from bisect import bisect_left


def solve(string):
    a, b, q, *stx = map(int, string.split())
    s = [-10**10] + stx[:a] + [2 * 10**10]
    t = [-10**10] + stx[a:a + b] + [2 * 10**10]
    # x = dict([])
    ans = []
    i_s = 0
    i_t = 0
    for _x in stx[-q:]:
        """
        while s[i_s] < _x:
            i_s += 1
        while t[i_t] < _x:
            i_t += 1
        """
        i_s, i_t = bisect_left(s, _x), bisect_left(t, _x)
        ls, rs = s[i_s - 1], s[i_s]
        lt, rt = t[i_t - 1], t[i_t]
        r_max = max(rs, rt)
        l_min = min(ls, lt)
        """
        x[_x] = min([
            r_max - _x, _x - l_min, rt - ls + min(rt - _x, _x - ls),
            rs - lt + min(rs - _x, _x - lt)
        ])
        """
        ans.append(
            str(
                min([
                    r_max - _x, _x - l_min, rt - ls + min(rt - _x, _x - ls),
                    rs - lt + min(rs - _x, _x - lt)
                ])))
    # return "\n".join([str(x[_x]) for _x in stx[-q:]])
    return "\n".join(ans)


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
from bisect import bisect_left


def solve(string):
    a, b, q, *stx = map(int, string.split())
    s = [-10**10] + stx[:a] + [2 * 10**10]
    t = [-10**10] + stx[a:a + b] + [2 * 10**10]
    x = dict([])
    i_s = 0
    i_t = 0
    for _x in sorted(set(stx[-q:])):
        """
        while s[i_s] < _x:
            i_s += 1
        while t[i_t] < _x:
            i_t += 1
        """
        i_s, i_t = bisect_left(s, _x), bisect_left(t, _x)
        ls, rs = s[i_s - 1], s[i_s]
        lt, rt = t[i_t - 1], t[i_t]
        r_max = max(rs, rt)
        l_min = min(ls, lt)
        x[_x] = min([
            r_max - _x, _x - l_min, rt - ls + min(rt - _x, _x - ls),
            rs - lt + min(rs - _x, _x - lt)
        ])
    return "\n".join([str(x[_x]) for _x in stx[-q:]])


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
def solve(string):
    a, b, q, *stx = map(int, string.split())
    s = [-10**10] + stx[:a] + [2 * 10**10]
    t = [-10**10] + stx[a:a + b] + [2 * 10**10]
    x = dict([])
    i_s = 0
    i_t = 0
    for _x in sorted(set(stx[-q:])):
        while s[i_s] < _x:
            i_s += 1
        while t[i_t] < _x:
            i_t += 1
        ls, rs = s[i_s - 1], s[i_s]
        lt, rt = t[i_t - 1], t[i_t]
        r_max = max(rs, rt)
        l_min = min(ls, lt)
        x[_x] = min([
            r_max - _x, _x - l_min, rt - ls + min(rt - _x, _x - ls),
            rs - lt + min(rs - _x, _x - lt)
        ])
    return "\n".join([str(x[_x]) for _x in stx[-q:]])


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
def solve(string):
    a, b, q, *stx = map(int, string.split())
    s = [-10**10]+stx[:a] + [2 * 10**10]
    t = [-10**10]+stx[a:a + b] + [2 * 10**10]
    x = {_q: -1 for _q in stx[-q:]}
    i_s = 0
    i_t = 0
    for _x in sorted(x.keys()):
        while s[i_s] < _x:
            i_s += 1
        while t[i_t] < _x:
            i_t += 1
        l_s, r_s = s[i_s - 1], s[i_s]
        l_t, r_t = t[i_t - 1], t[i_t]
        r_max = max(r_s, r_t)
        l_min = min(l_s, l_t)
        x[_x] = min([
            r_max - _x, _x - l_min, r_t - l_s + min(r_t - _x, _x - l_s),
            r_s - l_t + min(r_s - _x, _x - l_t)
        ])
    return "\n".join([str(x[_x]) for _x in stx[-q:]])


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

Solution code:
def solve(string):
    a, b, q, *stx = map(int, string.split())
    s = sorted(stx[:a] + [-10**10, 2 * 10**10])
    t = sorted(stx[a:a + b] + [-10**10, 2 * 10**10])
    x = {_q: -1 for _q in stx[-q:]}
    i_s = 0
    i_t = 0
    for _x in sorted(x.keys()):
        while s[i_s] < _x:
            i_s += 1
        while t[i_t] < _x:
            i_t += 1
        l_s, r_s = s[i_s - 1], s[i_s]
        l_t, r_t = t[i_t - 1], t[i_t]
        r_max = max(r_s, r_t)
        l_min = min(l_s, l_t)
        x[_x] = min([
            r_max - _x, _x - l_min, r_t - l_s + min(r_t - _x, _x - l_s),
            r_s - l_t + min(r_s - _x, _x - l_t)
        ])
    return "\n".join([str(x[_x]) for _x in stx[-q:]])


if __name__ == '__main__':
    n, m, l = map(int, input().split())
    print(solve('{} {} {}\n'.format(n, m, l) + '\n'.join([input() for _ in range(n + m + l)])))

Submission status: Accepted

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


# def getNearestIndexOf(query: int, s: "List[int]"):
#     findTarget = s
#     while len(findTarget) != 1:
#         if len(findTarget) == 2:
#             if abs(findTarget[0] - query) < abs(findTarget[1] - query):
#                 findTarget = [findTarget[0]]
#             else:
#                 findTarget = [findTarget[1]]
#             continue
#         middle = int(len(findTarget)/2)
#         if findTarget[middle] > query:
#             findTarget = findTarget[0:middle + 1]
#         else:
#             findTarget = findTarget[middle:]
#     #print(f"▫️{query} from {s} -> {findTarget[0]}")
#     return findTarget[0]


# def getCostByOrder(begin: int, s: "List[int]", t: "List[int]"):
#     nc = 0
#     nx = bisect.b
#     nc += abs(nx-begin)
#     nx2 = getNearestIndexOf(nx, s)
#     nc += abs(nx2 - nx)
#     return nc


def solve(A: int, B: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):
    s = [-1 * 10**18] + s + [10**18]
    t = [-1 * 10**18] + t + [10 ** 18]
    for query in x:
        nearS = bisect.bisect_right(s, query)
        nearT = bisect.bisect_right(t, query)
        res = 10 ** 18
        for S in [s[nearS - 1], s[nearS]]:
            for T in [t[nearT - 1], t[nearT]]:
                d1 = abs(T - query) + abs(T - S)
                d2 = abs(S - query) + abs(T - S)
                res = min(res, d1, d2)
        print(res)
    return


# Generated by 1.1.3 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()

Submission status: Accepted

Solution code:
import sys
input=sys.stdin.readline
A=list(map(int,input().split()))
S,T,X=[[int(input()) for i in range(A[j])] for j in range(3)]
def binary(a,l,):
	low=0
	high=len(l)-1
	while high-low>1:
		mid=(low+high)//2
		if l[mid]<a:
			low=mid
		else:
			high=mid
	return [l[high],l[low]]
			
for x in X:
	s=set(binary(x,S))
	t=set(binary(x,T))
	Min=20000000000
	for i in s:
		for j in t:
			Min=min(Min,min(abs(x-i),abs(x-j))+abs(i-j))
	print(Min)

Submission status: Accepted

Solution code:
A=list(map(int,input().split()))
S,T,X=[[int(input()) for i in range(A[j])] for j in range(3)]
def binary(a,l,):
	low=0
	high=len(l)-1
	while high-low>1:
		mid=(low+high)//2
		if l[mid]<a:
			low=mid
		else:
			high=mid
	return [l[high],l[low]]
			
for x in X:
	s=set(binary(x,S))
	t=set(binary(x,T))
	Min=20000000000
	for i in s:
		for j in t:
			Min=min(Min,min(abs(x-i),abs(x-j))+abs(i-j))
	print(Min)

Submission status: Accepted

Solution code:
import bisect
import sys
input = sys.stdin.readline
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]
ans = ['' for _ in range(q)]
for i in range(q):
    x = int(input())
    idxs = bisect.bisect(s, x)
    idxt = bisect.bisect(t, x)
    ans[i] = str(min(x - min(s[idxs - 1], t[idxt -1]),
                     x - s[idxs - 1] + (t[idxt] - s[idxs - 1]),
                     t[idxt] - x + (t[idxt] - s[idxs - 1]),
                     x - t[idxt - 1] + (s[idxs] - t[idxt - 1]),
                     s[idxs] - x + (s[idxs] - t[idxt - 1]),
                     max(s[idxs], t[idxt]) - x,
                     x - min(s[idxs - 1], t[idxt -1])))
print('\n'.join(ans))