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 bisect
import itertools
import sys

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 most_simRL(ds, x):
    index = bisect.bisect_left(ds, x)
    if index == 0:
        return [ds[0]]
    elif index == len(ds):
        return [ds[-1]]
    return ds[index-1:index+1]


def calc(a, b, x):
    return min(abs(a-x), abs(b-x)) + abs(a-b)


for x in X:
    s_RL = most_simRL(s, x)
    t_RL = most_simRL(t, x)
    ans = sys.maxsize
    for st in itertools.product(s_RL, t_RL):
        ans = min(ans, calc(st[0], st[1], x))
    print(ans)

Submission status: Accepted

Solution code:
import bisect
import itertools
import sys

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 most_simRL(ds, x):
    index = bisect.bisect_left(ds, x)
    if index == 0:
        return [ds[0]]
    elif index == len(ds):
        return [ds[-1]]
    return ds[index-1:index+1]


def calc(a, b, x):
    return min(abs(a-x), abs(b-x)) + abs(a-b)


for i in range(len(x)):
    s_RL = most_simRL(s, x[i])
    t_RL = most_simRL(t, x[i])
    ans = sys.maxsize
    for st in itertools.product(s_RL, t_RL):
        distance = calc(st[0], st[1], x[i])
        if ans > distance:
            ans = distance
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_right

A, B, Q = map(int, input().split())
INF = 10**18
s = [-INF] + [int(input()) for _ in range(A)] + [INF]
t = [-INF] + [int(input()) for _ in range(B)] + [INF]

for _ in range(Q):
    x = int(input())
    sh_r, te_r = bisect_right(s, x), bisect_right(t, x)
    sh_l, te_l = sh_r - 1, te_r - 1
    SR, SL, TR, TL = s[sh_r], s[sh_l], t[te_r], t[te_l]
    ans = INF
    for i in [SR, SL]:
        for j in [TR, TL]:
            dis = abs(i-x) + abs(i-j)
            dis = min(dis, abs(j-x) + abs(j-i))
            ans = min(ans, dis)
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect

INF = 10 ** 11

A, B, Q = [int(i) for i in input().split()]
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
X = [int(input()) for _ in range(Q)]
len_s = len(S)
len_t = len(T)

for x in X:
    sx = bisect(S, x)
    tx = bisect(T, x)

    east_s = INF
    west_s = -INF
    east_t = INF
    west_t = -INF
    if sx < len_s:
        east_s = S[sx] - x
    if sx > 0:
        west_s = S[sx-1] - x

    if tx < len_t:
        east_t = T[tx] - x
    if tx > 0:
        west_t = T[tx-1] - x

    candidates = []
    res = min(
        (east_t - west_s * 2),
        (east_t * 2 - west_s),
        (east_s - west_t * 2),
        (east_s * 2 - west_t),
        (max(east_t, east_s)),
        (-min(west_t, west_s))
    )
    print(res)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline

from bisect import bisect

inf = float('inf')

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

for x in X:
    ans = inf
    si = bisect(S,x)
    ti = bisect(T,x)
    for s in [S[si-1],S[si]]:
        for t in [T[ti-1],T[ti]]:
            res = abs(s-t) + min(abs(x-s),abs(x-t))
            ans = min(ans,res)
    print(ans)

Submission status: Accepted

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



def cost(start, s, t):
    if s == t:
        return abs(start - s)

    min_o = min(s, t)
    max_o = max(s, t)
    if start <= min_o:
        return max_o - start
    elif start <= max_o:
        return min(abs(start-min_o), abs(start-max_o)) + (max_o-min_o)
    else:
        return start - min_o


for start in x:
    s_r = bisect.bisect_right(s, start)
    s_l = s_r - 1
    t_r = bisect.bisect_right(t, start)
    t_l = t_r - 1


    res0 = cost(start, s[s_r], t[t_r])
    res1 = cost(start, s[s_r], t[t_l])
    res2 = cost(start, s[s_l], t[t_r])
    res3 = cost(start, s[s_l], t[t_l])
    print(min(res0, res1, res2, res3))

Submission status: Accepted

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

inf = float('inf')

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

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

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

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

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

        print(min_d)
        
    return


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

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
A, B, Q = list(map(int, input().split()))
S = [-int(1e11)] + [int(input()) for _ in range(A)] + [int(1e11)]
T = [-int(1e11)] + [int(input()) for _ in range(B)] + [int(1e11)]
X = [int(input()) for _ in range(Q)]

import bisect
for x in X:
  SL = S[bisect.bisect_left(S, x) -1]
  SR = S[bisect.bisect_right(S, x)]
  TL = T[bisect.bisect_left(T, x) -1]
  TR = T[bisect.bisect_right(T, x)]
  
  print(min(x-min(SL,TL), max(SR,TR)-x, TR+x-2*SL, SR+x-2*TL, 2*SR-x-TL, 2*TR-x-SL))

Submission status: Accepted

Solution code:
INF = 1e20

A, B, Q = [int(i) for i in input().split()]
S = [-INF] + [int(input()) for _ in range(A)] + [INF]
T = [-INF] + [int(input()) for _ in range(B)] + [INF]

from bisect import bisect_left

mins = []
for _ in range(Q):
    x = int(input())
    s = bisect_left(S, x)
    t = bisect_left(T, x)
    mi = INF
    for ss in [S[s], S[s - 1]]:
        for tt in [T[t], T[t - 1]]:
            mi = min(mi, abs(ss - x) + abs(tt - ss), abs(tt - x) + abs(ss - tt))
    mins.append(mi)
print(*mins, sep='\n')

Submission status: Accepted

Solution code:
INF = 1e20

A, B, Q = [int(i) for i in input().split()]
S = [-INF] + [int(input()) for _ in range(A)] + [INF]
T = [-INF] + [int(input()) for _ in range(B)] + [INF]
X = [int(input()) for _ in range(Q)]

from bisect import bisect_left

mins = []
for x in X:
    s = bisect_left(S, x)
    t = bisect_left(T, x)
    mi = INF
    for ss in [S[s], S[s - 1]]:
        for tt in [T[t], T[t - 1]]:
            mi = min(mi, abs(ss - x) + abs(tt - ss), abs(tt - x) + abs(ss - tt))
    mins.append(str(mi))
print("\n".join(mins))

Submission status: Accepted

Solution code:
INF = 1e20

A, B, Q = [int(i) for i in input().split()]
S = [-INF] + [int(input()) for _ in range(A)] + [INF]
T = [-INF] + [int(input()) for _ in range(B)] + [INF]
X = [int(input()) for _ in range(Q)]

from bisect import bisect_left

for x in X:
    s = bisect_left(S, x)
    t = bisect_left(T, x)
    mi = INF
    for ss in [S[s], S[s - 1]]:
        for tt in [T[t], T[t - 1]]:
            mi = min(mi, abs(ss - x) + abs(tt - ss), abs(tt - x) + abs(ss - tt))
    print(mi)

Submission status: Accepted

Solution code:
# -*- coding:utf-8 -*-
"""解説
二分探索 O(log(N))

あるxの地点での寺と神社に行くパターン数は、
・西に行き、寺か神社に行く
・東に行き、寺か神社に行く

その後、
・西に行き、寺か神社に行く
・東に行き、寺か神社に行く

の8パターンしかない。

"""
import bisect

def solve():
    A, B, Q = list(map(int, input().split()))
    S, T, X = [], [], []
    for i in range(A):
        S.append(int(input()))
    for i in range(B):
        T.append(int(input()))
    for i in range(Q):
        X.append(int(input()))
    INF = 10**11+1
    S.append(INF)
    S.append(-INF)
    T.append(INF)
    T.append(-INF)
    S.sort()
    T.sort()
    
    """
    ・x -> 最寄りのS -> 最寄りのT
    ・x -> 最寄りのT -> 最寄りのS
    のどちらか最小値が答え？
    """
    for q in range(Q):
        x = X[q]

        # x -> 左の神社 -> 寺パターン
        index = bisect.bisect_left(S, x)
        l_s_index, r_s_index = index-1, index

        tmp_ans = abs(S[l_s_index]-x)
        index_t = bisect.bisect_left(T, S[l_s_index])
        l_t_index, r_t_index = index_t-1, index_t
        ans = tmp_ans + abs(T[l_t_index]-S[l_s_index])
        ans = min(ans, tmp_ans + abs(T[r_t_index]-S[l_s_index]))

        # x -> 右の神社 -> 寺パターン
        tmp_ans = abs(S[r_s_index]-x)
        index_t = bisect.bisect_left(T, S[r_s_index])
        l_t_index, r_t_index = index_t-1, index_t
        ans = min(ans, tmp_ans+abs(T[l_t_index]-S[r_s_index]))
        ans = min(ans, tmp_ans+abs(T[r_t_index]-S[r_s_index]))

        # x -> 左の寺 -> 神社パターン
        index_t = bisect.bisect_left(T, x)
        l_t_index, r_t_index = index_t-1, index_t

        tmp_ans = abs(T[l_t_index]-x)
        index_s = bisect.bisect_left(S, T[l_t_index])
        l_s_index, r_s_index = index_s-1, index_s
        ans = min(ans, tmp_ans+abs(S[l_s_index]-T[l_t_index]))
        ans = min(ans, tmp_ans+abs(S[r_s_index]-T[l_t_index]))

        # x -> 右の寺 -> 神社パターン
        tmp_ans = abs(T[r_t_index]-x)
        index_s = bisect.bisect_left(S, T[r_t_index])
        l_s_index, r_s_index = index_s-1, index_s
        ans = min(ans, tmp_ans+abs(S[l_s_index]-T[r_t_index]))
        ans = min(ans, tmp_ans+abs(S[r_s_index]-T[r_t_index]))

        print(ans)


if __name__ == "__main__":
    solve()

Submission status: Accepted

Solution code:
import bisect

abq = input().split()
a = int(abq[0])
b = int(abq[1])
q = int(abq[2])
slist = [int(input()) for i in range(a)]
tlist = [int(input()) for i in range(b)]
xlist = [int(input()) for i in range(q)]


def get_nears(list_search, idx, val):
    if idx == 0:
        return (None, list_search[idx])

    try:
        list_search[idx]
    except IndexError:
        return (list_search[idx - 1], None)

    return (list_search[idx - 1], list_search[idx])


def get_min_distance(x, anear, bnear, mindis):
    if anear is None or bnear is None:
        return mindis

    dis = abs(x - anear)
    dis += abs(anear - bnear)

    if mindis is None:
        return dis
    return min(dis, mindis)


for x in xlist:
    sidx = bisect.bisect_left(slist, x)
    tidx = bisect.bisect_left(tlist, x)

    snear1, snear2 = get_nears(slist, sidx, x)
    tnear1, tnear2 = get_nears(tlist, tidx, x)

    mindis = None
    mindis = get_min_distance(x, snear1, tnear1, mindis)
    mindis = get_min_distance(x, snear1, tnear2, mindis)
    mindis = get_min_distance(x, snear2, tnear1, mindis)
    mindis = get_min_distance(x, snear2, tnear2, mindis)
    mindis = get_min_distance(x, tnear1, snear1, mindis)
    mindis = get_min_distance(x, tnear1, snear2, mindis)
    mindis = get_min_distance(x, tnear2, snear1, mindis)
    mindis = get_min_distance(x, tnear2, snear2, mindis)

    print(mindis)

Submission status: Accepted

Solution code:
import bisect

abq = input().split()
a = int(abq[0])
b = int(abq[1])
q = int(abq[2])
slist = [int(input()) for i in range(a)]
slist.sort()
tlist = [int(input()) for i in range(b)]
tlist.sort()
xlist = [int(input()) for i in range(q)]


def get_nears(list_search, idx, val):
    if idx == 0:
        return (None, list_search[idx])

    try:
        list_search[idx]
    except IndexError:
        return (list_search[idx - 1], None)

    return (list_search[idx - 1], list_search[idx])


def get_min_distance(x, anear, bnear, mindis):
    if anear is None or bnear is None:
        return mindis

    dis = abs(x - anear)
    dis += abs(anear - bnear)

    if mindis is None:
        return dis
    return min(dis, mindis)


for x in xlist:
    sidx = bisect.bisect_left(slist, x)
    tidx = bisect.bisect_left(tlist, x)

    snear1, snear2 = get_nears(slist, sidx, x)
    tnear1, tnear2 = get_nears(tlist, tidx, x)

    mindis = None
    mindis = get_min_distance(x, snear1, tnear1, mindis)
    mindis = get_min_distance(x, snear1, tnear2, mindis)
    mindis = get_min_distance(x, snear2, tnear1, mindis)
    mindis = get_min_distance(x, snear2, tnear2, mindis)
    mindis = get_min_distance(x, tnear1, snear1, mindis)
    mindis = get_min_distance(x, tnear1, snear2, mindis)
    mindis = get_min_distance(x, tnear2, snear1, mindis)
    mindis = get_min_distance(x, tnear2, snear2, mindis)

    print(mindis)

Submission status: Accepted

Solution code:
import bisect
import itertools

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]
X = [int(input()) for _ in range(Q)]

def solve(x):
  # xの位置
  i = bisect.bisect_left(S, x)
  j = bisect.bisect_left(T, x)
  result = INF
  # どの2つを目指すのか
  for s,t in itertools.product(S[i-1:i+1], T[j-1:j+1]):
    d = min(abs(s-x),abs(t-x)) + abs(t-s)
    result = min(result,d)
  return result

for x in X:
  answer = solve(x)
  print(answer)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
from itertools import product

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

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

    i = bisect_left(s, x)
    if i == 0:
        si = [i]
    elif i == A:
        si = [i - 1]
    else:
        si = [i - 1, i]

    j = bisect_left(t, x)
    if j == 0:
        tj = [j]
    elif j == B:
        tj = [j - 1]
    else:
        tj = [j - 1, j]

    ans = float('inf')
    for i, j in product(si, tj):
        ds = x - s[i]
        dt = x - t[j]
        if ds * dt > 0:
            d = max(abs(ds), abs(dt))
        else:
            ds, dt = abs(ds), abs(dt)
            if ds < dt:
                d = 2 * ds + dt
            else:
                d = ds + 2 * dt
        ans = min(ans, d)
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_right
a, b, q = map(int, input().split())
INF = 10 ** 18
s = [-INF]
for i in range(a):
    s.append(input())
s.append(INF)
s = [int(m) for m in s]#int型に直す
t = [-INF]
for i in range(b):
    t.append(input())
t.append(INF)
t = [int(m) for m in t]#int型に直す
x = []
for i in range(q):
    x.append(input())
x = [int(m) for m in x]#int型に直す

for i in range(q):
    b, d = bisect_right(s, x[i]), bisect_right(t, x[i])
    a, c = b - 1, d - 1
    res = INF
    for j in [a, b]:
        for k in [c, d]:
            res = min(res, abs(x[i] - s[j]) + abs(s[j] - t[k]), abs(x[i] - t[k]) + abs(t[k] - s[j]))
    print(res)

Submission status: Accepted

Solution code:
from bisect import bisect_left

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


for x_i in x:
    s_r_index = bisect_left(s, x_i)
    if s_r_index >= len(s):
        s_r = 1e18
    else:
        s_r = s[s_r_index]

    if s_r_index > 0:
        s_l = s[s_r_index-1]
    else:
        s_l = -1e18

    t_r_index = bisect_left(t, x_i)
    if t_r_index >= len(t):
        t_r = 1e18
    else:
        t_r = t[t_r_index]

    if t_r_index > 0:
        t_l = t[t_r_index-1]
    else:
        t_l = -1e18

    move_length = [abs(x_i-s_l)+abs(s_l-t_l),
                   abs(x_i-s_l)+abs(s_l-t_r),
                   abs(x_i-s_r)+abs(s_r-t_l),
                   abs(x_i-s_r)+abs(s_r-t_r),
                   abs(x_i-t_l)+abs(t_l-s_l),
                   abs(x_i-t_l)+abs(t_l-s_r),
                   abs(x_i-t_r)+abs(t_r-s_l),
                   abs(x_i-t_r)+abs(t_r-s_r)]
    print(min(move_length))

Submission status: Accepted

Solution code:
import bisect
from itertools import product

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

for _ in range(Q):
    x = int(input())
    idx1, idx2 = bisect.bisect_left(S, x), bisect.bisect_left(T, x)
    s_cand = [S[idx1 - 1], S[idx1]]
    t_cand = [T[idx2 - 1], T[idx2]]
    dist = INF
    for s, t in product(s_cand, t_cand):
        temp = min(abs(s - x), abs(t - x)) + abs(s - t)
        dist = min(dist, temp)
    print(dist)

Submission status: Accepted

Solution code:
import bisect
from itertools import product

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

for _ in range(Q):
    x = int(input())
    idx1 = bisect.bisect_left(S, x)
    s_cand = [S[idx1 - 1], S[idx1]]
    idx2 = bisect.bisect_left(T, x)
    t_cand = [T[idx2 - 1], T[idx2]]
    dist = 10**15
    for s, t in product(s_cand, t_cand):
        temp = min(abs(s - x), abs(t - x)) + abs(s - t)
        if temp < dist:
            dist = temp
    print(dist)

Submission status: Accepted

Solution code:
A, B, Q = map(int, input().split())
s = [int(input()) for _ in range(A)]
t = [int(input()) for _ in range(B)]
x = [int(input()) for _ in range(Q)]
INF = 10 ** 18


def bsearch(n, arr):
    l = 0
    r = len(arr)
    m = (l + r) // 2
    while l != m:
        if n <= arr[m]:
            r = m
        else:
            l = m
        m = (l + r) // 2
    return l


s = [-INF] + s + [INF]
t = [-INF] + t + [INF]

for i, x_i in enumerate(x):
    sa = bsearch(x_i, s)
    ta = bsearch(x_i, t)
    lmin = INF
    for si in range(sa, sa + 2):
        for ti in range(ta, ta + 2):
            l = min(abs(x_i - s[si]) + abs(s[si] - t[ti]), abs(x_i - t[ti]) + abs(t[ti] - s[si]))
            lmin = min(l, lmin)
    print(lmin)

Submission status: Accepted

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


def bsearch(n, arr):
    l = 0
    r = len(arr)
    m = (l + r) // 2
    while l != m:
        if n <= arr[m]:
            r = m
        else:
            l = m
        m = (l + r) // 2
    if r < len(arr) and abs(arr[l] - n) > abs(arr[r] - n):
        return r
    else:
        return l


def bsearch_l(n, arr):
    l = 0
    r = len(arr)
    m = (l + r) // 2
    while l != m:
        if n <= arr[m]:
            r = m
        else:
            l = m
        m = (l + r) // 2
    return l


def calc_distance(x, l, c, near_idx):
    ret = abs(x - l)
    if c == 's':
        next_l = t[near_idx]
    else:
        next_l = s[near_idx]
    ret += abs(next_l - l)
    return ret


st = []
for i, s_i in enumerate(s):
    t_i = bsearch(s_i, t)
    st.append((s_i, 's', t_i))

for i, t_i in enumerate(t):
    s_i = bsearch(t_i, s)
    st.append((t_i, 't', s_i))

st = sorted(st)
starr = sorted(s + t)

ans_list = []
for i, x_i in enumerate(x):
    st_i = bsearch_l(x_i, starr)
    l, c, near_idx = st[st_i]
    ans = calc_distance(x_i, l, c, near_idx)
    if st_i < len(st) - 1:
        l, c, near_idx = st[st_i + 1]
        ans = min(ans, calc_distance(x_i, l, c, near_idx))
    ans_list.append(ans)

for i, ans in enumerate(ans_list):
    print(ans)

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
from bisect import bisect
A,B,Q=map(int, input().split())
s=[int(input()) for _ in range(A)] + [99**99]
t=[int(input()) for _ in range(B)] + [99**99]
snt=[0]*A + [99**99]
tns=[0]*B + [99**99]
for i in range(A):
	p = bisect(t, s[i])
	snt[i] = min(abs(s[i] - t[p-1]), abs(s[i] - t[p]))
for i in range(B):
	p = bisect(s, t[i])
	tns[i] = min(abs(t[i] - s[p-1]), abs(t[i] - s[p]))
for _ in range(Q):
	x = int(input())
	ans = []
	p = bisect(s, x)
	ans.append(abs(s[p] - x) + snt[p])
	ans.append(abs(s[p-1] - x) + snt[p-1])
	p = bisect(t, x)
	ans.append(abs(t[p] - x) + tns[p])
	ans.append(abs(t[p-1] - x) + tns[p-1])
	print(min(ans))

Submission status: Accepted

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

for a in x:
    ans1 = 0
    ans2 = 0
    b = bisect.bisect_left(S,a)
    c = bisect.bisect_left(T,a)
    res = INF
    for s in [S[b-1],S[b]]:
        for t in [T[c-1],T[c]]:
            d1,d2 = abs(s-a)+abs(s-t),abs(t-a)+abs(s-t)
            res = min(res,d1,d2)
    print(res)

Submission status: Accepted

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

import bisect

INF = 1e11

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

for x in X:
    ans = INF
    iS, iT = bisect.bisect(S, x), bisect.bisect(T, x)

    for s in [S[iS - 1], S[iS]]:
        for t in [T[iT - 1], T[iT]]:
            a1, a2 = abs(s - x) + abs(s - t), abs(t - x) + abs(t - s)
            ans = min(ans, a1, a2)

    print(ans)

Submission status: Accepted

Solution code:
import bisect
import numpy as np
 
hint = list(map(int, input().split()))
s = [int(input()) for i in range(sum(hint))]
# print(s)

def search_min_pos(arr, target):
  index = bisect.bisect_left(arr, target)
  if 0 == index:
    dist = arr[index]
  else:
    dist = arr[index-1:index+1]
  if not isinstance(dist, list):
    dist = [dist]
  return dist

a_arr = s[:hint[0]]
b_arr = s[hint[0]:-hint[2]]
sum = 0
for t in s[-hint[2]:]:
  a_pos = search_min_pos(a_arr, t)
  b_pos = search_min_pos(b_arr, t)
  #print(t, a_pos, b_pos)
  min_dist = 10 ** 11
  for a in a_pos:
    b_against_a = search_min_pos(b_arr, a)
    for ba in b_against_a:
      min_dist = min([min_dist, abs(t-a)+abs(ba-a)])
  for b in b_pos:
    a_against_b = search_min_pos(a_arr, b)
    for ab in a_against_b:
      min_dist = min([min_dist, abs(t-b)+abs(ab-b)])
  print(min_dist)

Submission status: Accepted

Solution code:
import bisect
INF = 1e12
A, B, Q = map(int, input().split())
s_list = [-INF]
t_list = [-INF]
for i in range(A):
    s_list.append(int(input()))
for i in range(B):
    t_list.append(int(input()))
x_list = [int(input()) for i in range(Q)]
s_list.append(INF)
t_list.append(INF)

def calc_min_dist(x):
    s_index = bisect.bisect_right(s_list, x)
    t_index = bisect.bisect_right(t_list, x)
    tmp_s_right = s_list[s_index]
    tmp_s_left = s_list[s_index-1]
    tmp_t_right = t_list[t_index]
    # print("!!!", tmp_s_right, tmp_t_right)
    tmp_t_left = t_list[t_index-1]
    return min(abs(tmp_s_right-x)+abs(tmp_t_right-tmp_s_right),abs(tmp_s_right-x)+abs(tmp_t_left-tmp_s_right),
    abs(tmp_s_left-x)+abs(tmp_t_right-tmp_s_left),abs(tmp_s_left-x)+abs(tmp_t_left-tmp_s_left),
    abs(tmp_t_left-x)+abs(tmp_s_right-tmp_t_left), abs(tmp_t_left-x)+abs(tmp_s_left-tmp_t_left),
    abs(tmp_t_right-x)+abs(tmp_s_right-tmp_t_right), abs(tmp_t_right-x)+abs(tmp_s_left-tmp_t_right))

for x in x_list:
    print(calc_min_dist(x))

Submission status: Accepted

Solution code:
from bisect import bisect_left
a,b,q=map(int,input().split())
s=[]
t=[]
x=[]
s.append(-10**12)
t.append(-10**12)
for i in range(a):
    s.append(int(input()))
for i in range(b):
    t.append(int(input()))
s.append(10**12)
t.append(10**12)
for i in range(q):
    x=int(input())
    tmp_s=bisect_left(s,x)-1
    tmp_s_1=s[tmp_s]
    tmp_s_2=s[tmp_s+1]
    tmp_t=bisect_left(t,x)-1
    tmp_t_1=t[tmp_t]
    tmp_t_2=t[tmp_t+1]
    print(min(abs(x-tmp_s_1)+abs(tmp_s_1-tmp_t_1),
    abs(x-tmp_s_1)+abs(tmp_s_1-tmp_t_2),
    abs(x-tmp_s_2)+abs(tmp_s_2-tmp_t_1),
    abs(x-tmp_s_2)+abs(tmp_s_2-tmp_t_2),
    abs(x-tmp_t_1)+abs(tmp_t_1-tmp_s_1),
    abs(x-tmp_t_1)+abs(tmp_t_1-tmp_s_2),
    abs(x-tmp_t_2)+abs(tmp_t_2-tmp_s_1),
    abs(x-tmp_t_2)+abs(tmp_t_2-tmp_s_2)))

Submission status: Accepted

Solution code:
from bisect import bisect_left as bl
A,B,Q=map(int,input().split())
S=[]
T=[]
X=[]
INF=10**18
S.append(-INF)
T.append(-INF)
for i in range(A):
    S.append(int(input()))
for i in range(B):
    T.append(int(input()))
S.append(INF)
T.append(INF)
for i in range(Q):
    x=int(input())
    b,d=bl(S,x),bl(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:
a, b, q = [int(i) for i in input().split()]

INF = 10**18

temple = []
shrine = []
ques = []

for i in range(a):
    dist = int(input())
    temple.append(dist)
for i in range(b):
    dist = int(input())
    shrine.append(dist)
for i in range(q):
    ques.append(int(input()))

temple.sort()
shrine.sort()

temple = [-INF] + temple + [INF]
shrine = [-INF] + shrine + [INF]


def binary_insert(array,x):
    left = 0
    right = len(array) - 1
    while left <= right:
        mid = (left + right) // 2
        if array[mid] > x:
            right = mid - 1
        else:
            left = mid + 1
    return left



for i in range(q):
    score = 10**18
    y = ques[i]
    idx_temple = binary_insert(temple,y)
    idx_shrine = binary_insert(shrine,y)
    left_t = temple[idx_temple-1]
    right_t = temple[idx_temple]
    left_s = shrine[idx_shrine-1]
    right_s = shrine[idx_shrine]
    t = [left_t,right_t]
    s = [left_s,right_s]
    for ts in t:
        for ss in s:
            scoret = abs(y - ts) + abs(ts - ss)
            scores = abs(y - ss) + abs(ts - ss)
            score = min(score,scores,scoret)
    print(score)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect
def input():
	return sys.stdin.readline()[:-1]

def calc(x, i, j):
	prev = [s[i-1], s[i], t[j-1], t[j], s[i-1], s[i], t[j-1], t[j]]
	foll = [t[j-1], t[j-1], s[i-1], s[i-1], t[j], t[j], s[i], s[i]]
	res = 10**11
	for p, f in zip(prev, foll):
		res = min(res, abs(p-x) + abs(f-p))
	return res

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

for _ in range(q):
	x = int(input())
	print(calc(x, bisect(s, x), bisect(t, x)))

Submission status: Accepted

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

import sys
INT_MAX = sys.maxsize
s.insert(0, -1 * INT_MAX)
s.append(INT_MAX)
t.insert(0, -1 * INT_MAX)
t.append(INT_MAX)

import bisect
for xi in x:
    #print(xi)
    si = bisect.bisect_right(s, xi)
    #si = 0
    #for si, v in enumerate(s):
    #    if v > xi:
    #        break
    ti = bisect.bisect_right(t, xi)
    #ti = 0
    #for ti, v in enumerate(t):
    #    if v > xi:
    #        break
    #print(si, ti)
    sa = s[si]
    ta = t[ti]
    sb = s[si-1]
    tb = t[ti-1]
    #print(sa, sb,ta,tb)
    ans = min([
        abs(xi-sa)+abs(sa-ta),
        abs(xi-sa)+abs(sa-tb),
        abs(xi-sb)+abs(sb-ta),
        abs(xi-sb)+abs(sb-tb),
        abs(xi-ta)+abs(ta-sa),
        abs(xi-ta)+abs(ta-sb),
        abs(xi-tb)+abs(tb-sa),
        abs(xi-tb)+abs(tb-sb)
    ])
    print(ans)

Submission status: Accepted

Solution code:
import bisect
def adj(x,ks):
  idx=bisect.bisect_left(ks,x)
  return ks[idx-1],ks[idx]

def distance(x,a,b):
  return min(abs(x-a),abs(x-b))+abs(a-b)

def helper(x,ss,ts):
  temp1,temp2=adj(x,ts)
  shin1,shin2=adj(x,ss)
  t=min(distance(x,temp1,shin1),distance(x,temp2,shin1),distance(x,temp1,shin2),distance(x,temp2,shin2))
  return t

a,b,q=map(int,input().split())
t=10**20
ss=[-t]+[int(input()) for _ in range(a)]+[t]
ts=[-t]+[int(input()) for _ in range(b)]+[t]
qs=[int(input()) for _ in range(q)]
for x in qs:
  print(helper(x,ss,ts))