Problem:


Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.



Sample input:
2 3 4
100
600
400
900
1000
150
2000
899
799


Sample output:
350
1400
301
399

Submission status: Accepted

Solution code:
import sys

import numba as nb
import numpy as np

input = sys.stdin.readline


@nb.njit("i8(i8[:],i8)", cache=True)
def binary_search(a, key):
    """Meguru type binary search"""
    ng = -1
    ok = len(a)

    def is_ok(a, key, idx):
        if key <= a[idx]:
            return True
        else:
            return False

    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if is_ok(a, key, mid):
            ok = mid
        else:
            ng = mid

    return ok


@nb.njit("i8[:](i8,i8[:],i8[:],i8[:])", cache=True)
def solve(Q, S, T, X):
    ans = np.zeros(shape=Q, dtype=np.int64)
    INF = 10 ** 11
    for q, x in enumerate(X):
        min_dist = INF
        # x --> s --> t
        i = binary_search(S, x)
        if 0 < i:
            l_s = S[i - 1]
            dist_s = abs(x - l_s)
            j = binary_search(T, l_s)
            l_t, r_t = T[j - 1], T[j]
            dist_t = min(abs(l_s - l_t), abs(r_t - l_s)) if 0 < j else abs(r_t - l_s)
            min_dist = min(min_dist, dist_s + dist_t)
        r_s = S[i]
        dist_s = abs(r_s - x)
        j = binary_search(T, r_s)
        l_t, r_t = T[j - 1], T[j]
        dist_t = min(abs(r_s - l_t), abs(r_t - r_s)) if 0 < j else abs(r_t - r_s)
        min_dist = min(min_dist, dist_s + dist_t)

        # x --> t --> s
        i = binary_search(T, x)
        if 0 < i:
            l_t = T[i - 1]
            dist_t = abs(l_t - x)
            j = binary_search(S, l_t)
            l_s, r_s = S[j - 1], S[j]
            dist_s = min(abs(l_t - l_s), abs(r_s - l_t)) if 0 < j else abs(r_s - l_t)
            min_dist = min(min_dist, dist_s + dist_t)
        r_t = T[i]
        dist_t = abs(r_t - x)
        j = binary_search(S, r_t)
        l_s, r_s = S[j - 1], S[j]
        dist_s = min(abs(r_t - l_s), abs(r_s - r_t)) if 0 < j else abs(r_s - r_t)
        min_dist = min(min_dist, dist_s + dist_t)

        ans[q] = min_dist
    return ans


def main():
    A, B, Q = map(int, input().split())
    S = np.zeros(shape=A, dtype=np.int64)
    T = np.zeros(shape=B, dtype=np.int64)
    X = np.zeros(shape=Q, dtype=np.int64)
    for i in range(A):
        S[i] = int(input())
    for i in range(B):
        T[i] = int(input())
    for i in range(Q):
        X[i] = int(input())

    ans = solve(Q, S, T, X)
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys

import numba as nb
import numpy as np

input = sys.stdin.readline


@nb.njit("i8(i8[:],i8)", cache=True)
def binary_search(a, key):
    """Meguru type binary search"""
    ng = -1
    ok = len(a)

    def is_ok(a, key, idx):
        if key <= a[idx]:
            return True
        else:
            return False

    while (abs(ok - ng) > 1):
        mid = (ok + ng) // 2
        if is_ok(a, key, mid):
            ok = mid
        else:
            ng = mid

    return ok


@nb.njit("i8[:](i8,i8[:],i8[:],i8[:])", cache=True)
def solve(Q, S, T, X):
    ans = np.zeros(shape=Q, dtype=np.int64)
    for q, x in enumerate(X):
        min_dist = 10 ** 11
        # x --> s --> t
        i = binary_search(S, x)
        if 0 < i:
            l_s = S[i - 1]
            dist_s = abs(x - l_s)
            j = binary_search(T, l_s)
            l_t, r_t = T[j - 1], T[j]
            dist_t = min(abs(l_s - l_t), abs(r_t - l_s)) if 0 < j else abs(r_t - l_s)
            min_dist = min(min_dist, dist_s + dist_t)
        r_s = S[i]
        dist_s = abs(r_s - x)
        j = binary_search(T, r_s)
        l_t, r_t = T[j - 1], T[j]
        dist_t = min(abs(r_s - l_t), abs(r_t - r_s)) if 0 < j else abs(r_t - r_s)
        min_dist = min(min_dist, dist_s + dist_t)

        # x --> t --> s
        i = binary_search(T, x)
        if 0 < i:
            l_t = T[i - 1]
            dist_t = abs(l_t - x)
            j = binary_search(S, l_t)
            l_s, r_s = S[j - 1], S[j]
            dist_s = min(abs(l_t - l_s), abs(r_s - l_t)) if 0 < j else abs(r_s - l_t)
            min_dist = min(min_dist, dist_s + dist_t)
        r_t = T[i]
        dist_t = abs(r_t - x)
        j = binary_search(S, r_t)
        l_s, r_s = S[j - 1], S[j]
        dist_s = min(abs(r_t - l_s), abs(r_s - r_t)) if 0 < j else abs(r_s - r_t)
        min_dist = min(min_dist, dist_s + dist_t)

        ans[q] = min_dist
    return ans


def main():
    A, B, Q = map(int, input().split())
    S = np.zeros(shape=A, dtype=np.int64)
    T = np.zeros(shape=B, dtype=np.int64)
    X = np.zeros(shape=Q, dtype=np.int64)
    for i in range(A):
        S[i] = int(input())
    for i in range(B):
        T[i] = int(input())
    for i in range(Q):
        X[i] = int(input())

    ans = solve(Q, S, T, X)
    print("\n".join(map(str, ans)))


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import numpy as np
import sys
input = sys.stdin.buffer.readline

a, b, q = map(int,input().split())
ab = [[-1, -10**11], [-1, 10**11]]
aa = [-10**11, 10**11]
bb = [-10**11, 10**11]
for i in range(a):
    x = int(input())
    ab.append([0, x])
    aa.append(x)
    
for i in range(b):
    x = int(input())
    ab.append([1, x])
    bb.append(x)
ab = sorted(ab, key=lambda x:(x[1], x[0]))
aa.sort()
bb.sort()

ab_arr = np.array(ab)
ab_arr = ab_arr.T[1]

a_arr = np.array(aa)
b_arr = np.array(bb)

for cq in range(q):
    ans = 10**12
    s = int(input())
    ci = np.searchsorted(ab_arr, s)
    for cj in [ci, ci-1]:
        d = abs(ab_arr[cj] - s)
        flg = ab[cj][0]
        if flg:
            na = np.searchsorted(a_arr, ab_arr[cj])
            d2 = min(abs(a_arr[na] - ab_arr[cj]), abs(a_arr[na-1] - ab_arr[cj]))
            d += d2
        else:
            nb = np.searchsorted(b_arr, ab_arr[cj])
            d2 = min(abs(b_arr[nb] - ab_arr[cj]), abs(b_arr[nb-1] - ab_arr[cj]))
            d += d2
        ans = min(ans, d)
    print(ans)

Submission status: Accepted

Solution code:
import bisect
INF = 10**13
A, B, Q = map(int, input().split())
S = [int(input()) for a in range(A)]
T = [int(input()) for b in range(B)]
for q in range(Q):
    x = int(input())
    si = bisect.bisect_left(S, x)
    ti = bisect.bisect_left(T, x)
    Sq = [S[max(si-1, 0)], S[min(si, A-1)]]
    Tq = [T[max(ti-1, 0)], T[min(ti, B-1)]]
    ans = float('inf')
    for i in range(2):
        for j in range(2):
            s = Sq[i]
            t = Tq[j]
            if (s < x and t < x) or (x < s and x < t):
                xs, tx = abs(x-s), abs(x-t)
                ans = min(ans, max(xs, tx))
            else:
                xs, tx = abs(s-x), abs(t-x)
                ans = min(ans, min(xs, tx)*2 + max(xs, tx))

    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left
a,b,q = map(int,input().split())
INF = 10**15
s = [-INF] + sorted([int(input()) for _  in range(a)]) + [INF]
t = [-INF] + sorted([int(input()) for _  in range(b)]) + [INF]
#print(s,t)
for i in range(q):
    pro = int(input())
    s_index = bisect_left(s, pro)
    t_index = bisect_left(t, pro)
    s1,s2 = s[s_index-1] , s[s_index]
    t1,t2 = t[t_index-1] , t[t_index]
    #print(s1,s2,t1,t2)
    minimum = []
    kouho1 = abs(pro-s1)+ abs(s1-t1)
    minimum.append(kouho1)
    kouho2 = abs(pro-s1)+ abs(s1-t2)
    minimum.append(kouho2)
    kouho3 = abs(pro-t1)+ abs(t1-s1)
    minimum.append(kouho3)
    kouho4 = abs(pro-t2)+ abs(t2-s1)
    minimum.append(kouho4)
    kouho5 = abs(pro-s2)+ abs(s2-t1)
    minimum.append(kouho5)
    kouho6 = abs(pro-s2)+ abs(s2-t2)
    minimum.append(kouho6)
    kouho7 = abs(pro-t1)+ abs(s2-t1)
    minimum.append(kouho7)
    kouho8 = abs(pro-t2)+ abs(s2-t2)
    minimum.append(kouho8)
    print(min(minimum))

Submission status: Accepted

Solution code:
import bisect

a,b,q = map(int,input().split())
shrine = [-10**12, 10**12]
for _ in range(a):
    s = int(input())
    shrine.append(s)
shrine.sort()

temple = [-10**12, 10**12]
for _ in range(b):
    t = int(input())
    temple.append(t)
temple.sort()

for _ in range(q):
    x = int(input())
    sx = bisect.bisect_right(shrine,x)
    tx = bisect.bisect_right(temple,x)
    ans = 10**12
    #最適な経路はスタート地点から前後のshrine、templeを訪れる経路
    for i in [shrine[sx-1], shrine[sx]]:
        for j in [temple[tx-1], temple[tx]]:
            #caas_1はスタート→shrine→temple
            case_1 = abs(i-x)+abs(i-j)
            #caas_2はスタート→temple→shrine
            case_2 = abs(j-x)+abs(i-j)
            ans = min(ans,case_1,case_2)
            
    print(ans)

Submission status: Accepted

Solution code:
import bisect

a,b,q = map(int,input().split())
shrine = [-10**12, 10**12]
for _ in range(a):
    s = int(input())
    shrine.append(s)
shrine.sort()

temple = [-10**12, 10**12]
for _ in range(b):
    t = int(input())
    temple.append(t)
temple.sort()

for _ in range(q):
    x = int(input())
    sx = bisect.bisect_right(shrine,x)
    tx = bisect.bisect_right(temple,x)
    ans = 10**12
    for i in [shrine[sx-1], shrine[sx]]:
        for j in [temple[tx-1], temple[tx]]:
            case_1 = abs(i-x)+abs(i-j)
            case_2 = abs(j-x)+abs(i-j)
            ans = min(ans,case_1,case_2)
            
    print(ans)

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int, input().split())
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
X = [int(input()) for _ in range(Q)]

def D(a,b,c):
    return abs(a-b) + abs(b-c)

def getAns(x):
    ret = 10**18
    U = [S, T]
    for k in range(len(U)):
        u = U[k]
        v = U[(k-1)%2]
        idx = bisect.bisect_left(u, x)
        for i in [idx-1, idx]:
            if not 0<=i<len(u):
                continue
            idxx = bisect.bisect_left(v, u[i])
            for j in [idxx-1, idxx]:
                if 0<=j<len(v):
                    ret = min(ret, D(x, u[i], v[j]))
    return ret

for x in X:
    print(getAns(x))

Submission status: Accepted

Solution code:
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue

# import numpy as np

sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))


# ===CODE===



def main():
    a, b, q = ns()
    s = [ni() for _ in range(a)]
    t = [ni() for _ in range(b)]

    def disLR(a, idx):
        small = a[max(0, idx - 1)]
        large = a[min(len(a) - 1, idx)]
        return [small, large]

    for _ in range(q):
        ans = INF

        x = ni()

        idxs = bisect.bisect_left(s, x)
        a1 = disLR(s, idxs)

        idxt = bisect.bisect_left(t, x)
        a2 = disLR(t, idxt)

        for ta1 in a1:
            for ta2 in a2:
                tmp1 = abs(x - ta1) + abs(ta2 - ta1)
                tmp2 = abs(x - ta2) + abs(ta1 - ta2)
                ans = min(ans, tmp1, tmp2)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue

# import numpy as np

sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))


# ===CODE===

def disLR(a, idx):
    small = a[max(0, idx - 1)]
    large = a[min(len(a) - 1, idx)]
    return [small, large]


def main():
    a, b, q = ns()
    s = [ni() for _ in range(a)]
    t = [ni() for _ in range(b)]

    for _ in range(q):
        ans = INF

        x = ni()

        idxs = bisect.bisect_left(s, x)
        a1 = disLR(s, idxs)

        idxt = bisect.bisect_left(t, x)
        a2 = disLR(t, idxt)

        for ta1 in a1:
            for ta2 in a2:
                tmp1 = abs(x - ta1) + abs(ta2 - ta1)
                tmp2 = abs(x - ta2) + abs(ta1 - ta2)
                ans = min(ans, tmp1, tmp2)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue

# import numpy as np

sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))


# ===CODE===

def disLR(a, idx):
    small = a[max(0, idx - 1)]
    large = a[min(len(a) - 1, idx)]
    return small, large


def main():
    a, b, q = ns()
    s = [ni() for _ in range(a)]
    t = [ni() for _ in range(b)]

    for _ in range(q):
        ans = INF

        x = ni()
        tmpans = [0] * 4

        idxs = bisect.bisect_left(s, x)
        sml, lrg = disLR(s, idxs)
        tmpans[0] += abs(x - sml)
        tmpans[1] += abs(x - lrg)
        idxsml = bisect.bisect_left(t, sml)
        tmpans[0] += min([abs(sml - i) for i in disLR(t, idxsml)])
        idxlrg = bisect.bisect_left(t, lrg)
        tmpans[1] += min([abs(lrg - i) for i in disLR(t, idxlrg)])

        idxt = bisect.bisect_left(t, x)
        sml, lrg = disLR(t, idxt)
        tmpans[2] += abs(x - sml)
        tmpans[3] += abs(x - lrg)
        idxsml = bisect.bisect_left(s, sml)
        tmpans[2] += min([abs(sml - i) for i in disLR(s, idxsml)])
        idxlrg = bisect.bisect_left(s, lrg)
        tmpans[3] += min([abs(lrg - i) for i in disLR(s, idxlrg)])
        ans = min(ans, min(tmpans))
        print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

A, B, Q = MAP()
s = [-INF] + [INT() for _ in range(A)] + [INF]
t = [-INF] + [INT() for _ in range(B)] + [INF]

for _ in range(Q):
	x = INT()
	idx_s = bisect(s, x)
	idx_t = bisect(t, x)

	ans = INF
	for S, T in product([idx_s, idx_s-1], [idx_t, idx_t-1]):
		if min(s[S], t[T]) <= x <= max(s[S], t[T]):
			tmp = abs(s[S]-t[T]) + min(abs(x-s[S]), abs(x-t[T]))
		else:
			tmp = max(abs(x-s[S]), abs(x-t[T]))
		ans = min(ans, tmp)

	for S in [idx_s, idx_s-1]:
		for T in [idx_t, idx_t-1]:
			tmp = min(abs(x-s[S])+abs(s[S]-t[T]), abs(x-t[T])+abs(s[S]-t[T]))
			ans = min(ans, tmp)

	print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

A, B, Q = MAP()
s = [-INF] + [INT() for _ in range(A)] + [INF]
t = [-INF] + [INT() for _ in range(B)] + [INF]

for _ in range(Q):
	x = INT()
	idx_s = bisect(s, x)
	idx_t = bisect(t, x)

	ans = INF
	for S, T in product([idx_s, idx_s-1], [idx_t, idx_t-1]):
		if min(s[S], t[T]) <= x <= max(s[S], t[T]):
			tmp = abs(s[S]-t[T]) + min(abs(x-s[S]), abs(x-t[T]))
		else:
			tmp = max(abs(x-s[S]), abs(x-t[T]))
		ans = min(ans, tmp)

	print(ans)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def TUPLE(): return tuple(map(int, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7 
#mod = 998244353
from decimal import *
#import numpy as np
#decimal.getcontext().prec = 10

A, B, Q = MAP()
s = [INT() for _ in range(A)]
t = [INT() for _ in range(B)]

for _ in range(Q):
	x = INT()
	idx_s = bisect(s, x)
	idx_t = bisect(t, x)

	S = []
	T = []
	if 0 < idx_s:
		S.append(s[idx_s-1])
	if idx_s < A:
		S.append(s[idx_s])

	if 0 < idx_t:
		T.append(t[idx_t-1])
	if idx_t < B:
		T.append(t[idx_t])

	ans = INF
	for shrine, temple in product(S, T):
		if min(shrine, temple) <= x <= max(shrine, temple):
			tmp = abs(shrine-temple) + min(abs(x-shrine), abs(x-temple))
		else:
			tmp = max(abs(x-shrine), abs(x-temple))
		ans = min(ans, tmp)

	print(ans)

Submission status: Accepted

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

for i in range(q):
    x = int(input())
    s_ind = bisect_left(s, x)
    t_ind = bisect_left(t, x)
    
    res = inf
    for cand_s in [s[s_ind - 1], s[s_ind]]:
        for cand_t in [t[t_ind - 1], t[t_ind]]:
            st = abs(cand_s - cand_t)
            dx = min(abs(cand_s - x), abs(cand_t - x))
            
            res = min(res, st + dx)
    
    print(res)

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int, input().split())
INF=10**18
s =[-INF] + [int(input()) for i in range(A)] + [INF]
t =[-INF] + [int(input()) for i in range(B)] + [INF]
for q in range(Q):
  x = int(input())
  b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x) 
  res = INF
  for S in [s[b - 1], s[b]]:
    for T in [t[d - 1], t[d]]:
      d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T) 
      res = min(res, d1, d2)
  print(res)

Submission status: Accepted

Solution code:
def main():
    from bisect import bisect_left
    import sys
    input = sys.stdin.buffer.readline
    def near(A, x):
        return [A[(i:=bisect_left(A, x)) - 1], A[i]]
    a, b, q = map(int, input().split())
    INF = 10 ** 15
    S = [-INF] + [int(input()) for _ in range(a)] + [INF]
    T = [-INF] + [int(input()) for _ in range(b)] + [INF]
    for _ in range(q):
        x = int(input())
        print(min([min(abs(s - x) + abs(t - s), abs(t - x) + abs(s - t)) for s in near(S, x) for t in near(T, x)]))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    from bisect import bisect_left
    import sys
    input = sys.stdin.buffer.readline
    def dist(x, s, t):
        if s < x and t < x:
            return x - min(s, t)
        elif s > x and t > x:
            return max(s, t) - x
        else:
            if (ds := abs(x - s)) <= (dt := abs(x - t)):
                return 2 * ds + dt
            else:
                return ds + 2 * dt
    def near(A, x):
        if (i := bisect_left(A, x)) == 0:
            return [A[0], ]
        elif 0 < i < len(A):
            return [A[i - 1], A[i]]
        else:
            return [A[-1], ]
    a, b, q = map(int, input().split())
    S = [int(input()) for _ in range(a)]
    T = [int(input()) for _ in range(b)]
    for _ in range(q):
        x = int(input())
        ans = 100000000000
        for s in near(S, x):
            for t in near(T, x):
                ans = min(ans, dist(x, s, t))
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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)]
s.sort()
t.sort()
s=[float('INF')*(-1)]+s+[float('INF')]
t=[float('INF')*(-1)]+t+[float('INF')]
for i in range(q):
    x = int(input())
    sp=bisect_left(s,x)-1
    tp=bisect_left(t,x)-1
    s1=s[sp]
    t1=t[tp]
    s2=s[sp+1]
    t2=t[tp+1]
    print(min(max(x-s1,x-t1),max(s2-x,t2-x),x-s1+t2-s1,x-t1+s2-t1,s2-x+s2-t1,t2-x+t2-s1))

Submission status: Accepted

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

INF = 10 ** 18


def solve(s,t,x):
  ans = [0]*len(x)
  for i in range(len(x)):
    b = bisect.bisect_right(s,x[i])
    d = bisect.bisect_right(t,x[i])
    res = INF
    for S in [s[b-1],s[b]]:
      for T in [t[d-1],t[d]]:
        res = min(res,abs(S-x[i]) + abs(T-S),abs(T-x[i])+abs(T-S))
    ans[i] = res
  return ans



def main():
  A,B,Q = map(int,input().split())
  s = [-10**18] + [int(input()) for _ in range(A)] + [10**18]
  t = [-10**18] + [int(input()) for _ in range(B)] + [10**18]
  x = [int(input()) for _ in range(Q)]
  ans = solve(s,t,x)
  for i in range(Q):
    print(ans[i])
  return

if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
import bisect
INF=10**100

A,B,Q,*stx,=open(0).read().split()
A,B,Q=map(int,[A,B,Q])
slist=[-INF]+[int(stx[i]) for i in range(A)]+[INF]
tlist=[-INF]+[int(stx[i]) for i in range(A,A+B)]+[INF]
xlist=[int(stx[i]) for i in range(A+B,A+B+Q)]
oslist=[0]*2
otlist=[0]*2
sr_index=0
tr_index=0
for i in xlist:
    ans=INF
    sr_index=bisect.bisect_left(slist,i)
    oslist=[slist[sr_index-1],slist[sr_index]]
    tr_index=bisect.bisect_left(tlist,i)
    otlist=[tlist[tr_index-1],tlist[tr_index]]
    for j in oslist:
        for k in otlist:
            ans=min(ans,abs(j-i)+abs(k-j),abs(k-i)+abs(j-k))
    print(ans)

Submission status: Accepted

Solution code:
A, B, Q = map(int, input().split())
S = [-10**18]+sorted([int(input()) for _ in range(A)])+[10**18]
T = [-10**18]+sorted([int(input()) for _ in range(B)])+[10**18]
import bisect
for _ in range(Q):
  x = int(input())
  i = bisect.bisect_left(S, x)
  j = bisect.bisect_left(T, x)
  p, q, r, s = S[i-1], S[i], T[j-1], T[j]
  res = 10**18
  for a in (p, q):
    for b in (r, s):
      res = min(res, abs(x-a)+abs(a-b), abs(x-b)+abs(a-b))
  print(res)

Submission status: Accepted

Solution code:
from bisect import bisect

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

for i in range(q):
  x=int(input())
  s_inx=bisect(s,x)
  t_inx=bisect(t,x)

  s_l=s[s_inx-1]
  s_r=s[s_inx]

  t_l=t[t_inx-1]
  t_r=t[t_inx]

  ans=10**18
  for i in [s_l,s_r]:
    for j in [t_l,t_r]:
      d1=abs(i-x)+abs(j-i)
      d2=abs(j-x)+abs(i-j)
      ans=min(ans,d1,d2)

  print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect

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

for i in range(q):
  x=int(input())
  s_inx=bisect(s,x)
  t_inx=bisect(t,x)

  s_l=s[s_inx-1]
  s_r=s[s_inx]

  t_l=t[t_inx-1]
  t_r=t[t_inx]

  ans=10**18
  for i in [s_l,s_r]:
    for j in [t_l,t_r]:
      d1=abs(i-x)+abs(j-i)
      d2=abs(j-x)+abs(i-j)
      ans=min(ans,d1,d2)

  print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect

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

for i in range(q):
  x=int(input())
  s_inx=bisect(s,x)
  t_inx=bisect(t,x)

  s_l=s[s_inx-1]
  s_r=s[s_inx]

  t_l=t[t_inx-1]
  t_r=t[t_inx]

  ans=10**18
  for i in [s_l,s_r]:
    for j in [t_l,t_r]:
      ans=min(ans,abs(i-x)+abs(j-i))

  for i in [t_l,t_r]:
    for j in [s_l,s_r]:
      ans=min(ans,abs(i-x)+abs(j-i))

  print(ans)

Submission status: Accepted

Solution code:
from sys import stdin
nii=lambda:map(int,stdin.readline().split())
lnii=lambda:list(map(int,stdin.readline().split()))
from bisect import bisect

a,b,q=nii()
s=[-10**18]+[int(input()) for i in range(a)]+[10**18]
t=[-10**18]+[int(input()) for i in range(b)]+[10**18]

for i in range(q):
  x=int(input())
  s_inx=bisect(s,x)
  t_inx=bisect(t,x)

  s_l=s[s_inx-1]
  s_r=s[s_inx]

  t_l=t[t_inx-1]
  t_r=t[t_inx]

  ans=10**18
  for i in [s_l,s_r]:
    for j in [t_l,t_r]:
      ans=min(ans,abs(i-x)+abs(j-i))

  for i in [t_l,t_r]:
    for j in [s_l,s_r]:
      ans=min(ans,abs(i-x)+abs(j-i))

  print(ans)

Submission status: Accepted

Solution code:
def abc119_d():
    import sys
    read = sys.stdin.buffer.read
    inp = iter(map(int, read().split()))

    a = next(inp)
    b = next(inp)
    q = next(inp)
    S = [next(inp) for _ in range(a)]
    T = [next(inp) for _ in range(b)]

    from bisect import bisect_left
    inf = 10**12

    for _ in range(q):
        x = next(inp)
        si = bisect_left(S, x)
        ti = bisect_left(T, x)

        sl, sr = inf, inf
        tl, tr = inf, inf
        if 0 < si: sl = x - S[si-1]
        if si < a: sr = S[si] - x
        if 0 < ti: tl = x - T[ti-1]
        if ti < b: tr = T[ti] - x

        ans = inf
        ans = min(ans, max(sl, tl))
        ans = min(ans, max(sr, tr))
        ans = min(ans, 2 * min(sl, tr) + max(sl, tr))
        ans = min(ans, 2 * min(sr, tl) + max(sr, tl))
        print(ans)

if __name__ == '__main__':
    abc119_d()

Submission status: Accepted

Solution code:
# coding: utf-8

import bisect

A,B,Q = map(int, input().split())
*S, = [int(input()) for _ in range(A)]
*T, = [int(input()) for _ in range(B)]
*X, = [int(input()) for _ in range(Q)]

for x in X:
    # 2分探索で、「現在地」と神社群の位置関係を探る
    sx = bisect.bisect(S, x)
    # 現在地から見て東側で最も近い神社
    try:
        se = S[sx]
    except:
        # 東側に存在しない場合は、神社群の中での最東
        se = S[-1]
    # 現在地から見て西側で最も近い神社
    try:
        sw = S[sx-1]
    except:
        # 西側に存在しない場合は、神社群の中での最西
        sw = S[0]

    tx = bisect.bisect(T, x)
    # 現在地から見て東側で最も近いお寺
    try:
        te = T[tx]
    except:
        # 東側に存在しない場合は、お寺群の中での最東
        te = T[-1]
    # 現在地から見て西側で最も近いお寺
    try:
        tw = T[tx-1]
    except:
        # 西側に存在しない場合は、お寺群の中での最西
        tw = T[0]

    # 候補 (8通り) をシミュレーション
    # 東神社 -> 東寺
    # 東寺 -> 東神社
    # 東神社 -> 西寺
    # 西寺 -> 東神社
    # 西神社 -> 東寺
    # 東寺 -> 西神社
    # 西神社 -> 西寺
    # 西寺 -> 西神社
    routes = []
    for s in [se, sw]:
        for t in [te, tw]:
            routes.append(abs(s - x)+abs(t - s))
            routes.append(abs(t - x)+abs(s - t))

    # 最小距離を選ぶ
    print(min(routes))

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

A, B, Q = mapint()
Ss = [-10**20]+[int(input()) for _ in range(A)]+[10**20]
Ts = [-10**20]+[int(input()) for _ in range(B)]+[10**20]
Ss.sort()
Ts.sort()
from bisect import bisect_left

for _ in range(Q):
    x = int(input())
    xs = bisect_left(Ss, x)
    xt = bisect_left(Ts, x)

    rr = max(Ss[xs]-x, Ts[xt]-x)
    ll = max(x-Ss[xs-1], x-Ts[xt-1])
    lr = min(abs(x-Ss[xs-1])*2+abs(x-Ts[xt]), abs(x-Ts[xt-1])*2+abs(x-Ss[xs]))
    rl = min(abs(x-Ss[xs-1])+abs(x-Ts[xt])*2, abs(x-Ts[xt-1])+abs(x-Ss[xs])*2)
    print(min(rr, ll, rl, lr))