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
 
a, b, q = map(int, input().split())
s = sorted([int(input()) for i in range(a)])
t = sorted([int(input()) for i in range(b)])

s = [-9e20] + s + [9e20]
t = [-9e20] + t + [9e20]
 
for i in range(q):
    x = int(input())
    p = bisect.bisect_left(s,x)
    m = bisect.bisect_left(t,x)
    
    ll = max(s[p], t[m]) - x
    lr = min(s[p] * 2 - t[m-1] - x, t[m] * 2 - s[p-1] - x)
    rl = min(s[p] - t[m-1] * 2 + x, t[m] - s[p-1] * 2 + x)
    rr = x - min(s[p-1], t[m-1])

    print(min(ll, lr, rl, rr))

Submission status: Accepted

Solution code:
import bisect

A,B,Q = list(map(int,input().split()))
INF = 10 ** 18
shrine_list = [-INF] + [int(input()) for _ in range(A)] + [INF]
temple_list = [-INF] + [int(input()) for _ in range(B)] + [INF]
question_list = [int(input()) for _ in range(Q)]
for i in range(Q):
    x = question_list[i]
    index_s = bisect.bisect_right(shrine_list,x)
    index_t = bisect.bisect_right(temple_list,x)
    most_east_shrine = shrine_list[index_s - 1]
    most_east_temple = temple_list[index_t - 1]
    most_west_shrine = shrine_list[index_s]
    most_west_temple = temple_list[index_t]
    likelyhood_list = []
    likelyhood_list.append(abs(x - most_east_shrine) + abs(most_east_shrine - most_east_temple))
    likelyhood_list.append(abs(x - most_east_temple) + abs(most_east_shrine - most_east_temple))
    likelyhood_list.append(abs(x - most_east_shrine) + abs(most_east_shrine - most_west_temple))
    likelyhood_list.append(abs(x - most_west_temple) + abs(most_east_shrine - most_west_temple))
    likelyhood_list.append(abs(x - most_west_shrine) + abs(most_west_shrine - most_east_temple))
    likelyhood_list.append(abs(x - most_east_temple) + abs(most_west_shrine - most_east_temple))
    likelyhood_list.append(abs(x - most_west_shrine) + abs(most_west_shrine - most_west_temple))
    likelyhood_list.append(abs(x - most_west_temple) + abs(most_west_shrine - most_west_temple))
    print(min(likelyhood_list))

Submission status: Accepted

Solution code:
import numpy as np
import math
import sys
import bisect
sys.setrecursionlimit(10000000)
INF = 1e11

def main():
    # 入力処理
    A, B, Q = [int(c) for c in 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()))
    S.append(INF)
    T.append(INF)

    for i, x in enumerate(X):
        # s -> t
        sa = bisect.bisect_left(S, x) - 1
        sb = sa + 1

        # t -> s
        tc = bisect.bisect_left(T, x) - 1
        td = tc + 1
        distance = INF
        for s in [sa, sb]:
            for t in [tc, td]:
                dis1 = abs(x - S[s]) + abs(S[s] - T[t])
                dis2 = abs(x - T[t]) + abs(T[t] - S[s])
                distance = min(dis1, dis2, distance)
        print(distance)



if __name__ == '__main__':
    main()

Submission status: Accepted

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

a,b,q = map(int,input().split())

ans = 10**100

s = [-ans] + [int(input()) for i in range(a)] + [ans]
t = [-ans] + [int(input()) for i in range(b)] + [ans]
#x = [int(input()) for i in range(q)]


ans = 10**100

for i in range(q):
    x = int(input())
    ans = 10**100
    s_idx = bisect.bisect_left(s,x)
    t_idx = bisect.bisect_left(t,x)
    s_idx -= 1
    t_idx -= 1
    #print(x[i],s_idx,t_idx)
    for j in s[s_idx+0],s[s_idx+1]:
        for k in t[t_idx+0],t[t_idx+1]:
            ans = min(ans,abs(x - j) + abs(j - k),abs(x - k) + abs(j - k))
            
    print(ans)

Submission status: Accepted

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

a,b,q = map(int,input().split())

ans = 10**100

s = [-ans] + [int(input()) for i in range(a)] + [ans]
t = [-ans] + [int(input()) for i in range(b)] + [ans]
x = [int(input()) for i in range(q)]


ans = 10**100

for i in range(q):
    ans = 10**100
    s_idx = bisect.bisect_left(s,x[i])
    t_idx = bisect.bisect_left(t,x[i])
    s_idx -= 1
    t_idx -= 1
    #print(x[i],s_idx,t_idx)
    for j in s[s_idx+0],s[s_idx+1]:
        for k in t[t_idx+0],t[t_idx+1]:
            ans = min(ans,abs(x[i] - j) + abs(j - k),abs(x[i] - k) + abs(j - k))
            
    print(ans)

Submission status: Accepted

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

a,b,q = map(int,input().split())

ans = 10**100

s = [-ans] + [int(input()) for i in range(a)] + [ans]
t = [-ans] + [int(input()) for i in range(b)] + [ans]
x = [int(input()) for i in range(q)]


ans = 10**100

for i in range(q):
    ans = 10**100
    s_idx = bisect.bisect_left(s,x[i])
    t_idx = bisect.bisect_left(t,x[i])
    s_idx -= 1
    t_idx -= 1
    #print(x[i],s_idx,t_idx)
    for j in range(2):
        for k in range(2):
            ans = min(ans,abs(x[i] - s[s_idx+j]) + abs(s[s_idx+j] - t[t_idx+k]),abs(x[i] - t[t_idx+k]) + abs(s[s_idx+j] - t[t_idx+k]))
            
    print(ans)

Submission status: Accepted

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

a,b,q = map(int,input().split())

s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
#x = [int(input()) for i in range(q)]

ans = 10**100

for i in range(q):
    x = int(input())
    ans = 10**100
    s_idx = bisect.bisect_left(s,x)
    t_idx = bisect.bisect_left(t,x)
    s_idx -= 1
    t_idx -= 1
    #print(x[i],s_idx,t_idx)
    for j in range(2):
        for k in range(2):
            ans = min(ans,abs(x - s[min(s_idx+j,a-1)]) + abs(s[min(s_idx+j,a-1)] - t[min(t_idx+k,b-1)]),abs(x - t[min(t_idx+k,b-1)]) + abs(s[min(s_idx+j,a-1)] - t[min(t_idx+k,b-1)]))
            
    print(ans)

Submission status: Accepted

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

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

a,b,q = map(int,input().split())
s = []
t = []
for i in range(a):
    S = int(input())
    s.append(S)
for i in range(b):
    T = int(input())
    t.append(T)
s.sort()
t.sort()
 
for i in range(q):
    x = int(input())
    p = bisect.bisect_left(s,x)
    m = bisect.bisect_left(t,x)
    
    res = []
    if f(p) and g(m):
        res.append(max(t[m],s[p])-x)
    if f(p) and g(m-1):
        res.append(min(s[p]-x,x-t[m-1])+s[p]-t[m-1])
    if f(p-1) and g(m):
        res.append(t[m]-s[p-1]+min(t[m]-x,x-s[p-1]))
    if f(p-1) and g(m-1):
        res.append(x-min(t[m-1],s[p-1]))
    print(min(res))

Submission status: Accepted

Solution code:
import bisect

a,b,q = map(int,input().split())

s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
x = [int(input()) for i in range(q)]

ans = 10**100

for i in range(q):
    ans = 10**100
    s_idx = bisect.bisect_left(s,x[i])
    t_idx = bisect.bisect_left(t,x[i])
    s_idx -= 1
    t_idx -= 1
    #print(x[i],s_idx,t_idx)
    for j in range(2):
        for k in range(2):
            ans = min(ans,abs(x[i] - s[min(s_idx+j,a-1)]) + abs(s[min(s_idx+j,a-1)] - t[min(t_idx+k,b-1)]),abs(x[i] - t[min(t_idx+k,b-1)]) + abs(s[min(s_idx+j,a-1)] - t[min(t_idx+k,b-1)]))
            
    print(ans)

Submission status: Accepted

Solution code:
import bisect

a,b,q = map(int,input().split())

s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
x = [int(input()) for i in range(q)]

ans = 10**100

for i in range(q):
    ans = 10**100
    s_idx = bisect.bisect_left(s,x[i])
    t_idx = bisect.bisect_left(t,x[i])
    s_idx -= 1
    t_idx -= 1
    #print(x[i],s_idx,t_idx)
    for j in range(2):
        for k in range(2):
            ans = min(ans,abs(x[i] - s[min(s_idx+j,a-1)]) + abs(s[min(s_idx+j,a-1)] - t[min(t_idx+k,b-1)]))
            ans = min(ans,abs(x[i] - t[min(t_idx+k,b-1)]) + abs(s[min(s_idx+j,a-1)] - t[min(t_idx+k,b-1)]))
            
    print(ans)

Submission status: Accepted

Solution code:
INF = 25*10**9
import bisect
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()))
s.append(INF)
s.insert(0,-INF)
t.append(INF)
t.insert(0,-INF)    
for i in range(q):
    a1 = bisect.bisect_left(s,x[i])
    b1 = bisect.bisect_left(t,x[i])
    c1 = max(s[a1],t[b1])-x[i]
    c2 = x[i]-min(s[a1-1],t[b1-1])
    c3 = 2 * s[a1]-x[i]-t[b1-1]
    c4 = 2 * t[b1]-x[i]-s[a1-1]
    c5 = s[a1]+x[i]-2*t[b1-1]
    c6 = t[b1]+x[i]-2*s[a1-1]
    print(min(c1,c2,c3,c4,c5,c6))

Submission status: Accepted

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

a, b, q = map(int, input().split())
INF = 10 ** 11
s = [int(input()) for _ in range(a)] + [INF]
t = [int(input()) for _ in range(b)] + [INF]
x = [[int(input()), int(i), INF, INF, INF, INF] for i in range(q)]
x.sort(key=lambda x: x[0])
si = 0
ti = 0
for i in range(q):
    xi = x[i][0]
    while xi > s[si]:
        si += 1
    ls = abs(xi - s[si - 1])
    rs = abs(xi - s[si])

    while xi > t[ti]:
        ti += 1
    lt = abs(xi - t[ti - 1])
    rt = abs(xi - t[ti])

    x[i][2] = ls
    x[i][3] = rs
    x[i][4] = lt
    x[i][5] = rt

x.sort(key=lambda x: x[1])
for xi, i, ls, rs, lt, rt in x:
    ans = min(max(ls, lt),
              max(rs, rt),
              min(ls, rt) * 2 + max(ls, rt),
              min(rs, lt) * 2 + max(rs, lt))
    print(ans)

Submission status: Accepted

Solution code:
a, b, q = map(int, input().split())
INF = 10 ** 11
s = [int(input()) for _ in range(a)] + [INF]
t = [int(input()) for _ in range(b)] + [INF]
x = [[int(input()), int(i), INF, INF, INF, INF] for i in range(q)]
x.sort(key=lambda x: x[0])
si = 0
ti = 0
for i in range(q):
    xi = x[i][0]
    while xi > s[si]:
        si += 1
    ls = abs(xi - s[si - 1])
    rs = abs(xi - s[si])

    while xi > t[ti]:
        ti += 1
    lt = abs(xi - t[ti - 1])
    rt = abs(xi - t[ti])

    x[i][2] = ls
    x[i][3] = rs
    x[i][4] = lt
    x[i][5] = rt

x.sort(key=lambda x: x[1])
for xi, i, ls, rs, lt, rt in x:
    ans = min(max(ls, lt),
              max(rs, rt),
              min(ls, rt) * 2 + max(ls, rt),
              min(rs, lt) * 2 + max(rs, lt))
    print(ans)

Submission status: Accepted

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

a, b, q = map(int, input().split())
s = [0] * a
t = [0] * b
x = [0] * q
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())
sorted(s)
sorted(t)

for xx in x:
    ind = bisect(s, xx)
    ss = []
    if ind > 0:
        ss.append(s[ind-1])
    if ind < a:
        ss.append(s[ind])
    tt = []
    ind = bisect(t, xx)
    if ind > 0:
        tt.append(t[ind-1])
    if ind < b:
        tt.append(t[ind])
    ans = float('inf')
    for y in ss:
        ind = bisect(t, y)
        tmpt = []
        if ind > 0:
            tmpt.append(abs(y-t[ind - 1]))
        if ind < b:
            tmpt.append(abs(y-t[ind]))
        st = min(tmpt)
        tmp = abs(xx-y) + st
        if tmp < ans:
            ans = tmp
    for y in tt:
        ind = bisect(s, y)
        tmps = []
        if ind > 0:
            tmps.append(abs(y-s[ind - 1]))
        if ind < a:
            tmps.append(abs(y-s[ind]))
        ts = min(tmps)
        tmp = abs(xx-y) + ts
        if tmp < ans:
            ans = tmp
    print(ans)

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int, input().split())
S_list = [int(input()) for i in range(A)]
T_list = [int(input()) for i in range(B)]
X_list = [int(input()) for i in range(Q)]


# print("---------------")
for X in X_list:
    # 両側の最も近い寺、神社を調べる
    left_S_index = bisect.bisect(S_list, X)
    if left_S_index == 0:
        left_S = -10**11
    else:
        left_S = S_list[left_S_index-1]
    if left_S_index <= A-1:
        right_S = S_list[left_S_index]
    else:
        right_S = 10 ** 11

    left_T_index = bisect.bisect(T_list, X)
    if left_T_index == 0:
        left_T = -10 ** 11
    else:
        left_T = T_list[left_T_index-1]

    if left_T_index <= B-1:
        right_T = T_list[left_T_index]
    else:
        right_T = 10 ** 11

    a1 = right_T-X + abs(right_S-right_T)  # 右寺　右神社
    a2 = right_T-X + abs(left_S-right_T)  # 右寺　左神社
    a3 = X-left_T + abs(right_S-left_T)  # 左寺　右神社
    a4 = X-left_T + abs(left_S-left_T)  # 左寺　左神社
    a5 = right_S-X + abs(right_T-right_S)  # 右神社　右寺
    a6 = right_S-X + abs(left_T-right_S)  # 右神社　左寺
    a7 = X-left_S + abs(right_T-left_S)  # 左神社　右寺
    a8 = X-left_S + abs(left_T-left_S)  # 左神社　左寺

    print(min(a1, a2, a3, a4, a5, a6, a7, a8))

Submission status: Accepted

Solution code:
# encoding:utf-8
import copy
import random
import bisect #bisect_left　これで二部探索の大小検索が行える
import fractions #最小公倍数などはこっち
import math
import sys
import bisect

mod = 10**13
# sys.setrecursionlimit(mod) # 再帰回数上限はでdefault1000

def LI(): return list(map(int, sys.stdin.readline().split()))

A,B,Q = LI()
s = [0 for i in range(A)]
t = [0 for i in range(B)]
x = [0 for i in range(Q)]
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())


def solve(pos):
    ans1,ans2,ans3,ans4 = mod,mod,mod,mod
    s_left = bisect.bisect_left(s,pos)-1
    t_left = bisect.bisect_left(t,pos)-1
    # print("s",s_left,"t",t_left)
    if s_left >= 0 and t_left >= 0:
        ans1 = pos - min(s[s_left],t[t_left])
    if s_left+1 < A and t_left >= 0:
        ans2 = s[s_left+1] - t[t_left] + min(s[s_left+1]-pos, pos - t[t_left])
    if t_left + 1 < B and s_left>= 0:
        ans3 = t[t_left+1] - s[s_left] + min(t[t_left+1] - pos, pos-s[s_left])
    if s_left+1 < A and t_left+1 < B:
        ans4 = max(s[s_left+1],t[t_left+1]) - pos
    # print(ans1,ans2,ans3,ans4)
    ans = min(ans1,ans2,ans3,ans4)
    return ans


for i in range(Q):
    print(solve(x[i]))

Submission status: Accepted

Solution code:
A,B,Q = map(int,input().split())
S = [-10**11] + [int(input()) for _ in [0]*A] + [10**11]
T = [-10**11] + [int(input()) for _ in [0]*B] + [10**11]
X = [int(input()) for _ in [0]*Q]

def binary_search(A,func):
    l = 0
    r = len(A)-1
    if func(0,A):return -1
    if not func(r,A):return r
    while l+1<r:
        i = (l+r)//2
        if func(i,A):
            r = i
        else:
            l = i
    return l

for x in X:
    a = binary_search(S,lambda i,A:A[i]>=x)
    s = S[a:a+2]
    b = binary_search(T,lambda i,A:A[i]>=x)
    t = T[b:b+2]
    print(min(x-min(s[0],t[0]),
              max(s[1],t[1])-x,
              x-s[0]+t[1]-x+min(x-s[0],t[1]-x),
              x-t[0]+s[1]-x+min(x-t[0],s[1]-x) ))

Submission status: Accepted

Solution code:
A,B,Q = map(int,input().split())
S = [-10**11]
S.extend(int(input()) for _ in [0]*A)
S.extend([10**11])
T = [-10**11]
T.extend(int(input()) for _ in [0]*B)
T.extend([10**11])
X = [int(input()) for _ in [0]*Q]

def binary_search(A,func):
    l = 0
    r = len(A)-1
    if func(0,A):return -1
    if not func(r,A):return r
    while l+1<r:
        i = (l+r)//2
        if func(i,A):
            r = i
        else:
            l = i
    return l

for x in X:
    a = binary_search(S,lambda i,A:A[i]>=x)
    s = S[a:a+2]
    b = binary_search(T,lambda i,A:A[i]>=x)
    t = T[b:b+2]
    print(min(x-min(s[0],t[0]),
              max(s[1],t[1])-x,
              x-s[0]+t[1]-x+min(x-s[0],t[1]-x),
              x-t[0]+s[1]-x+min(x-t[0],s[1]-x) ))

Submission status: Accepted

Solution code:
from bisect import bisect
a,b,q=map(int,input().split())
INF=10**11+7
ls=[-INF]+[int(input()) for _ in range(a)]+[INF]
lt=[-INF]+[int(input()) for _ in range(b)]+[INF]
lq=[int(input()) for _ in range(q)]
for i in lq:
    inds=bisect(ls,i)
    indt=bisect(lt,i)
    s1,s2=i-ls[inds-1],ls[inds]-i
    t1,t2=i-lt[indt-1],lt[indt]-i
    print(min(max(s1,t1),max(s2,t2),min(2*s1+t2,s1+2*t2),min(2*t1+s2,t1+2*s2)))

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

for q in range(Q):
    x = int(input())
    i = bisect_left(S, x)
    j = bisect_left(T, x)

    sl, sr = x-S[i-1], S[i]-x
    tl, tr = x-T[j-1], T[j]-x

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

Submission status: Accepted

Solution code:
import bisect

INF = 10 ** 18
A, B, Q = map(int, input().split())
shrine_list = [-INF] + [int(input()) for i in range(A)] + [INF]
temple_list = [-INF] + [int(input()) for i in range(B)] + [INF]
question_list = [int(input()) for i in range(Q)]
for q in question_list:
    b, d = bisect.bisect_right(shrine_list, q), bisect.bisect_right(temple_list, q)
    ans = INF
    for s in [shrine_list[b - 1], shrine_list[b]]:
        for t in [temple_list[d - 1], temple_list[d]]:
            ans = min(abs(q - s) + abs(t - s), abs(q - t) + abs(s - t), ans)
    print(ans)

'''
二分検索
深さ優先検索
幅優先検索
累積和
尺取法
動的計画法
mod
XOR
データ構造
'''

Submission status: Accepted

Solution code:
import math
import bisect
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)]
Ss.sort()
Ts.sort()
ss = len(Ss)
ts = len(Ts)
for x in Xs:
    si = bisect.bisect_right(Ss,x)
    ti = bisect.bisect_right(Ts, x)
    cands = [[],[]]
    if si > 0:
        cands[0].append(Ss[si-1])
    if si < ss:
        cands[0].append(Ss[si])
    if ti > 0:
        cands[1].append(Ts[ti-1])
    if ti < ts:
        cands[1].append(Ts[ti])
    anss = []
    temp = 0
    for i in [0,1]:
        for t1 in cands[i]: #最初による所
            for t2 in cands[1-i]: #次に寄る所
                temp = abs(x-t1) +  abs(t2-t1)
                anss.append(temp)
    print(min(anss))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**7)
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return sys.stdin.readline().strip()
INF = 10 ** 18
MOD = 10 ** 9 + 7

A, B, Q = LI()
s_list = []
t_list = []
for i in range(A):
  s_list.append(II())
for j in range(B):
  t_list.append(II())
x_list = []
for q in range(Q):
  x_list.append(II())
  
import bisect
for x in x_list:
  # x の左右で最も近い神社と寺をそれぞれ探しておく
  # bisectが0の場合は左はなく、len(x)の場合は
  tidx = bisect.bisect_left(t_list, x)
  if tidx == 0:
    tl = 9*10**11
  else:
    tl = t_list[tidx-1]
  if tidx == len(t_list):
    tr = 9*10**11
  else:
    tr = t_list[tidx]

  sidx = bisect.bisect_left(s_list, x)
  if sidx == 0:
    sl = 9*10**11
  else:
    sl = s_list[sidx-1]
  if sidx == len(s_list):
    sr = 9*10**11
  else:
    sr = s_list[sidx]

  dsl = abs(x-sl)
  dsr = abs(x-sr)
  dtl = abs(x-tl)
  dtr = abs(x-tr)

  print(min(max(dsl, dtl), max(dsr, dtr), dsl+dtr+min(dsl, dtr), dsr+dtl+min(dsr,dtl)))

Submission status: Accepted

Solution code:
x=[]
for i,j in enumerate(map(int,input().split())):
    c=[]
    for l in range(j):
        t=int(input())
        x.append((i,l,t))
        c.append([t])
x.sort(key=lambda x:x[2])
l=[-10**20]*2
for y in x:
    if y[0] != 2: 
        l[y[0]]=y[2]
    else:
        c[y[1]]+=l[:]
l=[10**20]*2
for y in x[::-1]:
    if y[0] != 2: 
        l[y[0]]=y[2]
    else:
        c[y[1]]+=l[:]
print("\n".join(str(min(d[0]-min(d[1],d[2]),max(d[3],d[4])-d[0],
        d[4]-d[1]+min(d[0]-d[1],d[4]-d[0]),
        d[3]-d[2]+min(d[0]-d[2],d[3]-d[0])
        )) for d in c)
        )

Submission status: Accepted

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

Submission status: Accepted

Solution code:
from bisect import bisect_left
from itertools import product

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 xx in x:
    ret = inf

    sr = bisect_left(s, xx)  # xx以上の最小値
    sl = max(0, sr - 1)

    tr = bisect_left(t, xx)
    tl = max(0, tr - 1)

    for ss, tt in product(s[sl:sr + 1], t[tl:tr + 1]):
        ret = min(
            ret,
            abs(xx - ss) + abs(ss - tt),
            abs(xx - tt) + abs(tt - ss)
        )
    print(ret)

Submission status: Accepted

Solution code:
def main():
    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()), i] for i in range(q)]

    y = sorted(x, key=lambda a: a[0])
    d = [0] * q
    i, j = 0, 0
    for p in y:
        place = p[0]
        while s[i] < place:
            i += 1
        while t[j] < place:
            j += 1
        sl, sr = s[i-1], s[i]
        tl, tr = t[j-1], t[j]

        rr = abs(max(sr, tr) - place)
        ll = abs(min(sl, tl) - place)
        if sr < tr:
            rl = abs(sr - place) + abs(sr - tl)
        else:
            rl = abs(tr - place) + abs(tr - sl)
        if sl < tl:
            lr = abs(tl - place) + abs(sr - tl)
        else:
            lr = abs(sl - place) + abs(tr - sl)

        d[p[1]] = min(rr, rl, lr, ll)

    for dd in d:
        print(dd)


main()

Submission status: Accepted

Solution code:
import math
import copy
from operator import mul
from functools import reduce
from collections import defaultdict
from collections import Counter
from collections import deque
# 直積 A={a, b, c}, B={d, e}:のとき，A×B={(a,d),(a,e),(b,d),(b,e),(c,d),(c,e)}: product(A, B)
from itertools import product
# 階乗 P!: permutations(seq), 順列 {}_len(seq) P_n: permutations(seq, n)
from itertools import permutations
# 組み合わせ {}_len(seq) C_n: combinations(seq, n)
from itertools import combinations
# 一次元累積和
from itertools import accumulate
from bisect import bisect_left, bisect_right

# import numpy as np
# from scipy.misc import perm
# from scipy.misc import comb

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

# 四方向: 右, 下, 左, 上
dy = [0, -1, 0, 1]
dx = [1, 0, -1, 0]
 
def i_inpl(): return int(input())
def l_inpl(): return list(map(int, input().split()))
def line_inpl(x): return [i_inpl() for _ in range(x)]

INF = int(1e18)
MOD = int(1e9)+7 # 10^9 + 7

########

def main():
    A, B, Q = l_inpl()
    s = [-INF] + line_inpl(A) + [INF]
    t = [-INF] + line_inpl(B) + [INF]
    x = line_inpl(Q)

    for qi in range(Q):
        b, d = bisect_right(s, x[qi]), bisect_right(t, x[qi])
        res = INF
        for S in (s[b-1], s[b]):
            for T in (t[d-1], t[d]):
                d1, d2 = abs(S-x[qi]) + abs(T-S), abs(T-x[qi]) + abs(S-T)
                res = min(res, d1, d2)
        print(res)

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_right

A , B , Q = map(int,input().split())
INF = 10**20

s = [0] * A
t = [0] * B
x = [0] * Q

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

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

for p in x :
    rightS = bisect_right(s,p)
    rightT = bisect_right(t,p)

    dist = INF

    for ss in [s[rightS - 1], s[rightS]] :
        for tt in [t[rightT - 1], t[rightT]] :
            dist1 = abs(ss - p) + abs(ss - tt)
            dist2 = abs(tt - p) + abs(tt - ss)
            dist = min(dist, dist1, dist2)

    print(dist)

Submission status: Accepted

Solution code:
from bisect import bisect_right

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

    si = bisect_right(s, x)
    ti = bisect_right(t, x)

    ans = INF * 10
    for ss in [s[si-1], s[si]]:
        for tt in [t[ti-1], t[ti]]:
            ans = min(ans,
                      abs(x - ss) + abs(ss - tt),
                      abs(x - tt) + abs(tt - ss))
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right

def func(x, y, z):
    yi = bisect_right(y, x)

    if yi == 0 or yi == len(y):
        ans = 0
        if yi == len(y):
            yi -= 1
        ans += abs(y[yi] - x)
        x = y[yi]

        zi = bisect_right(z, x)
        ans += min(abs(z[zi % len(z)] - x), abs(z[(zi-1) % len(z)] - x))
        return ans
    else:
        ans1 = ans2 = 0
        ans1 += abs(y[yi-1] - x)
        x1 = y[yi-1]
        zi = bisect_right(z, x1)
        ans1 += min(abs(z[zi % len(z)] - x1), abs(z[(zi-1) % len(z)] - x1))

        ans2 += abs(y[yi] - x)
        x2 = y[yi]
        zi = bisect_right(z, x2)
        ans2 += min(abs(z[zi % len(z)] - x2), abs(z[(zi-1) % len(z)] - x2))
        return min(ans1, ans2)


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

    print(min(func(x, s, t), func(x, t, s)))

Submission status: Accepted

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

s = [-float('inf')] + [int(input()) for i in range(A)] + [float('inf')]
t = [-float('inf')] + [int(input()) for i in range(B)] + [float('inf')]

res = []
for i in range(Q):
    x = int(input())
    a = bisect.bisect_left(s, x) - 1
    b = a + 1
    c = bisect.bisect_left(t, x) - 1
    d = c + 1
    ans = float('inf')
    for S in [s[a], s[b]]:
        for T in [t[c], t[d]]:
            ans = min(ans, abs(S - x) + abs(T - S), abs(T - x) + abs(S - T))
    res.append(ans)

print('\n'.join(map(str, res)))

Submission status: Accepted

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

s = [-float('inf')] + [int(input()) for i in range(A)] + [float('inf')]
t = [-float('inf')] + [int(input()) for i in range(B)] + [float('inf')]

res = []
for i in range(Q):
    x = int(input())
    b = bisect.bisect_right(s, x)
    a = b - 1
    d = bisect.bisect_right(t, x)
    c = d - 1
    ans = float('inf')
    for S in [s[a], s[b]]:
        for T in [t[c], t[d]]:
            ans = min(ans, abs(S - x) + abs(T - S), abs(T - x) + abs(S - T))
    res.append(ans)

print('\n'.join(map(str, res)))

Submission status: Accepted

Solution code:
a,b,q = map(int, input().split())
s = [-5*10**10] + [int(input()) for _ in range(a)] + [5*10**10]
t = [-5*10**10] + [int(input()) for _ in range(b)] + [5*10**10]
a += 2
b += 2

def bis(x,lis,num):
    ok = 0
    ng = num
    while ng - ok > 1:
        mid = (ok+ng)//2
        if lis[mid] > x:
            ng = mid
        else:
            ok = mid
    return ok
for _ in range(q):
    x = int(input())
    sl = bis(x,s,a)
    tl = bis(x,t,b)
    sr = sl + 1
    tr = tl + 1
    sl = x-s[sl]
    sr = s[sr]-x
    tl = x-t[tl]
    tr = t[tr]-x
    dis = min(max(sr,tr),max(sl,tl),sr+tl+min(sr,tl),sl+tr+min(sl,tr))
    print(dis)

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]

for _ in range(Q):
    x = int(input())
    s1 = bisect.bisect_left(S, x) -1 #自分の左側のindex
    s2 = s1 + 1 #自分の右側のindex
    t1 = bisect.bisect_left(T, x) -1 #自分の左側のindex
    t2 = t1 + 1 #自分の右側のindex
    res = 10 ** 18
    for s in [S[s1], S[s2]]:
        for t in [T[t1], T[t2]]:
            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:
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:
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())
    b, d = bisect.bisect_left(s, x), bisect.bisect_left(t, x)
    ans = 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)
            ans = min(ans, d1, d2)
    print(ans)