Problem:


Score : 400 points

Problem Statement

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

Answer the following Q queries:

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

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

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

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

1 \leq x_i \leq 10^{10}

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

350
1400
301
399

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

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

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

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

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

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

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



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


Sample output:
350
1400
301
399

Submission status: Time Limit Exceeded

Solution code:
import sys
import bisect
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)]
s = sorted(s)
t = sorted(t)

for _ in range(Q):
    x = int(input())
    idx1 = bisect.bisect_right(s, x)
    idx2 = bisect.bisect_right(t, x)
    ans = float('inf')
    if idx1 > 0:
        left_s = s[idx1-1]
    else:
        left_s = float('inf')
    if idx2 > 0:
        left_t = t[idx2-1]
    else:
        left_t = float('inf')
    if idx1 < A:
        right_s = s[idx1]
    else:
        right_s = float('inf')
    if idx2 < B:
        right_t = t[idx2]
    else:
        right_t = float('inf')

    #print(left_s, right_s)
    #print(left_t, right_t)
    if left_s <= x <= right_t:
        tmp = right_t-left_s + min(x-left_s, right_t-x)
        ans = min(ans, tmp)
    if left_t <= x <= right_s:
        tmp = right_s-left_t + min(x-left_t, right_s-x)
        ans = min(ans, tmp)
    ans = min(ans, max(abs(x-left_s), abs(x-left_t)))
    ans = min(ans, max(abs(right_s-x), abs(right_t-x)))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect
a, b, q = map(int, input().split())
s, t = [0]*(a+2), [0]*(b+2)
for i in range(a):
    s[i+1] = int(input())
for i in range(b):
    t[i+1] = int(input())

s[0] = -float("inf")
s[-1] = float("inf")
t[0] = -float("inf")
t[-1] = float("inf")
#print(s)
#print(t)
for _ in range(q):
    start = int(input())
    x = bisect.bisect_right(s, start)
    y = bisect.bisect_right(t, start)
    ans = float("inf")
    for i in [s[x], s[x-1]]:
        for j in [t[y], t[y-1]]:
            res = min(abs(i-start) + abs(j-i), abs(j-start) + abs(i-j))
            ans = min(ans, res)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
"""
D - Lazy Faith
"""


def solve():
    # データ読込
    A, B, Q = map(int, input().split())
    si = [-float('inf')] + [int(input()) for i in range(A)] + [float('inf')]
    ti = [-float('inf')] + [int(input()) for i in range(B)] + [float('inf')]
    xi = [int(input()) for i in range(Q)]
    # 問題計算
    for x in xi:
        left_t = 0
        right_t = 0
        for i, t in enumerate(ti):
            if x <= t:
                left_t = ti[i - 1]
                right_t = ti[i]
                break
        left_s = 0
        right_s = 0
        for i, s in enumerate(si):
            if x <= s:
                left_s = si[i - 1]
                right_s = si[i]
                break
        # left_t = max([t for t in ti if t <= x])
        # right_t = min([t for t in ti if t >= x])
        # left_s = max([s for s in si if s <= x])
        # right_s = min([s for s in si if s >= x])
        print(min(abs(x - min(left_t, left_s)),
                  abs(x - max(right_t, right_s)),
                  abs(x - right_t) + abs(right_t - left_s),
                  abs(x - left_t) + abs(left_t - right_s),
                  abs(x - right_s) + abs(right_s - left_t),
                  abs(x - left_s) + abs(left_s - right_t)))


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
"""
D - Lazy Faith
"""


def solve():
    # データ読込
    A, B, Q = map(int, input().split())
    si = [-float('inf')] + [int(input()) for i in range(A)] + [float('inf')]
    ti = [-float('inf')] + [int(input()) for i in range(B)] + [float('inf')]
    xi = [int(input()) for i in range(Q)]
    # 問題計算
    for x in xi:
        left_t = max([t for t in ti if t <= x])
        right_t = min([t for t in ti if t >= x])
        left_s = max([s for s in si if s <= x])
        right_s = min([s for s in si if s >= x])
        print(min(abs(x - min(left_t, left_s)),
                  abs(x - max(right_t, right_s)),
                  abs(x - right_t) + abs(right_t - left_s),
                  abs(x - left_t) + abs(left_t - right_s),
                  abs(x - right_s) + abs(right_s - left_t),
                  abs(x - left_s) + abs(left_s - right_t)))


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

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

def binary_search(array, x):
    t = len(array)
    l, r = -1, t
    while l + 1 < r:
        m = (l+r)//2
        if array[m] >= x:
            r = m
        else:
            l = m
    return l , r if r < t else -1

def calc(y, z, x):
    tmp = abs(y-x)
    x = y
    tmp += abs(z-x)
    return tmp

INF = 10 ** 30
for _ in range(Q):
    x = int(input())
    l_s,r_s = binary_search(S, x)
    l_t,r_t = binary_search(T, x)
    ans = INF
    if l_s > -1:
        if l_t > -1:
            s, t = S[l_s], T[l_t]
            if abs(s-x) < abs(t-x):
                y, z = s, t
            else:
                y, z = t, s
            ans = min(ans, calc(y, z, x))
        if r_t > -1:
            s, t = S[l_s], T[r_t]
            if abs(s-x) < abs(t-x):
                y, z = s, t
            else:
                y, z = t, s
            ans = min(ans, calc(y, z, x))
    if r_s > -1:
        if l_t > -1:
            s, t = S[r_s], T[l_t]
            if abs(s-x) < abs(t-x):
                y, z = s, t
            else:
                y, z = t, s
            ans = min(ans, calc(y, z, x))
        if r_t > -1:
            s, t = S[r_s], T[r_t]
            if abs(s-x) < abs(t-x):
                y, z = s, t
            else:
                y, z = t, s
            ans = min(ans, calc(y, z, x))

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect

A, B, Q = map(int, input().split())
Shrine = [int(input()) for _ in range(A)]
Temple = [int(input()) for _ in range(B)]

Shrine = [-100000000000] + Shrine + [100000000000]
Temple = [-100000000000] + Temple + [100000000000]

for i in range(Q):
    x = int(input())
    nums = bisect.bisect_left(Shrine, x)
    tems = bisect.bisect_left(Temple, x)
    ans1 = max(abs(Shrine[nums]-x), abs(Temple[tems]-x))
    ans2 = max(abs(x - Shrine[nums-1]), abs(x - Temple[tems-1]))
    ans3 = abs(Shrine[nums]-x) * 2 + abs(x - Temple[tems-1])
    ans4 = abs(Temple[tems]-x) * 2 + abs(x - Shrine[nums-1])
    ans5 = abs(x - Shrine[nums-1]) * 2 + abs(Temple[tems]-x)
    ans6 = abs(x - Temple[tems-1]) * 2 + abs(Shrine[nums]-x)

    print(min(ans1, ans2, ans3, ans4, ans5, ans6))

Submission status: Time Limit Exceeded

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())
  i = bisect.bisect_right(s,x)
  j = bisect.bisect_right(t,x)
  print(min(max(s[i],t[j])-x,x-min(s[i-1],t[j-1]),min(s[i]-x,x-t[j-1])+s[i]-t[j-1],min(t[j]-x,x-s[i-1])+t[j]-s[i-1]))

Submission status: Time Limit Exceeded

Solution code:
import sys
from bisect import bisect_left
def input(): return sys.stdin.readline().strip()

def main():
    A, B, Q = map(int, input().split())
    S = [-10**100]
    T = [-10**100]
    for _ in range(A): S.append(int(input()))
    for _ in range(B): T.append(int(input()))
    S.append(10**100)
    T.append(10**100)

    for _ in range(Q):
        x = int(input())
        idx1 = bisect_left(S, x)
        idx2 = bisect_left(T, x)
        ans = 10 ** 100
        cand1 = (x - S[idx1 - 1]) + abs(S[idx1 - 1] - T[idx2 - 1])
        ans = min(ans, cand1)
        cand2 = (x - S[idx1 - 1]) + abs(S[idx1 - 1] - T[idx2])
        ans = min(ans, cand2)
        cand3 = (S[idx1] - x) + abs(S[idx1] - T[idx2 - 1])
        ans = min(ans, cand3)
        cand4 = (S[idx1] - x) + abs(S[idx1] - T[idx2])
        ans = min(ans, cand4)
        cand5 = (x - T[idx2 - 1]) + abs(T[idx2 - 1] - S[idx1 - 1])
        ans = min(ans, cand5)
        cand6 = (x - T[idx2 - 1]) + abs(T[idx2 - 1] - S[idx1])
        ans = min(ans, cand6)
        cand7 = (T[idx2] - x) + abs(T[idx2] - S[idx1 - 1])
        ans = min(ans, cand7)
        cand8 = (T[idx2] - x) + abs(T[idx2] - S[idx1])
        ans = min(ans, cand8)
        print(ans)



if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import bisect

A,B,Q = map(int,(input().split()))
s = [[0]*3 for _ in range(A)]
t = [[0]*3 for _ in range(B)]
x = [[0]*3 for _ in range(Q)]
slen = []
tlen = []
road = []
for i in range(A):
    s[i][0] = int(input())
    slen.append(s[i][0])
    s[i][1] = "s"
    road.append(s[i])
for i in range(B):
    t[i][0] = int(input())
    tlen.append(t[i][0])
    t[i][1] = "t"
    road.append(t[i])
for i in range(Q):
    x[i][0] = int(input())
road.sort()

for i in range(len(s)):
    index = bisect.bisect_left(tlen,s[i][0])
    if index < B:
        s[i][2] = min(abs(s[i][0]-tlen[index-1]),abs(tlen[index]-s[i][0]))
    else:
        s[i][2] = abs(s[i][0]-tlen[index-1])
for i in range(len(t)):
    index = bisect.bisect_left(slen,t[i][0])
    if index < A:
        t[i][2] = min(abs(t[i][0]-slen[index-1]),abs(slen[index]-t[i][0]))
    else:
        t[i][2] = abs(t[i][0]-slen[index-1])

for i in range(Q):
    index = bisect.bisect_left(road,x[i])
    if index < A+B:
        print(min(abs(x[i][0]-road[index-1][0])+road[index-1][2],abs(x[i][0]-road[index][0])+road[index][2]))
    else:
        print(abs(x[i][0]-road[index-1][0])+road[index-1][2])

Submission status: Time Limit Exceeded

Solution code:
def upper(arr, x):
    # xよりも大きい最小のindexを返す
    if arr[0] > x:
        return 0
    high, low = len(arr), 0
    while high - low > 1:
        mid = (high + low) // 2
        if arr[mid] > x:
            high = mid
        else:
            low = mid
    return high


def lower(arr, x):
    # xよりも小さい最大のindexを返す
    if arr[-1] < x:
        return len(arr) - 1
    high, low = len(arr) - 1, -1
    while high - low > 1:
        mid = (high + low) // 2
        if arr[mid] < x:
            low = mid
        else:
            high = mid
    return low


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())
    shr_u, shr_l = upper(s, x), lower(s, x)
    tmp_u, tmp_l = upper(t, x), lower(t, x)
    ans = float('inf')
    if shr_u != A and tmp_u != B:
        ans = min(ans, max(s[shr_u] - x, t[tmp_u] - x))
    if shr_l != -1 and tmp_l != -1:
        ans = min(ans, max(x - s[shr_l], x - t[tmp_l]))
    if shr_l != -1 and tmp_u != B:
        cost = t[tmp_u] - s[shr_l] + min(x - s[shr_l], t[tmp_u] - x)
        ans = min(ans, cost)
    if shr_u != A and tmp_l != -1:
        cost = s[shr_u] - t[tmp_l] + min(s[shr_u] - x, x - t[tmp_l])
        ans = min(ans, cost)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

a, b, q = map(int, input().split())
sh = []
te = []


def getNearestValue(list, num):
    """
    概要: リストからある値に最も近い値を返却する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return list[idx]


def checkshrine(x):
    x_near_sh = getNearestValue(sh, x)
    xsash = np.abs(x_near_sh - x)
    sh_near_te = getNearestValue(te, x_near_sh)
    return xsash + np.abs(sh_near_te - x_near_sh)


def checktemple(x):
    x_near_te = getNearestValue(te, x)
    xsate = np.abs(x_near_te - x)
    te_near_sh = getNearestValue(sh, x_near_te)
    return xsate + np.abs(te_near_sh - x_near_te)


sh = [int(input()) for _ in range(a)]
te = [int(input()) for _ in range(b)]

for i in range(q):
    x = int(input())
    checkshrinevalue = checkshrine(x)
    checktemplevalue = checktemple(x)
    if (checkshrinevalue > checktemplevalue):
        print(checktemplevalue)
    else:
        print(checkshrinevalue)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

a, b, q = map(int, input().split())
sh = []
te = []


def getNearestValue(list, num):
    """
    概要: リストからある値に最も近い値を返却する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return list[idx]


def checkshrine(x):
    x_near_sh = getNearestValue(sh, x)
    xsash = np.abs(x_near_sh - x)
    sh_near_te = getNearestValue(te, x_near_sh)
    return xsash + np.abs(sh_near_te - x_near_sh)


def checktemple(x):
    x_near_te = getNearestValue(te, x)
    xsate = np.abs(x_near_te - x)
    te_near_sh = getNearestValue(sh, x_near_te)
    return xsate + np.abs(te_near_sh - x_near_te)


for i in range(a):
    sh.append(int(input()))

for i in range(b):
    te.append(int(input()))

for i in range(q):
    x = int(input())
    checkshrinevalue = checkshrine(x)
    checktemplevalue = checktemple(x)
    if (checkshrinevalue > checktemplevalue):
        print(checktemplevalue)
    else:
        print(checkshrinevalue)

Submission status: Time Limit Exceeded

Solution code:
def main():
  import bisect
  A, B, Q = map(int, input().split())
  s = list()
  t = list()
  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())
    sw = bisect.bisect_right(s, x)-1 #xより西で一番近い(同じ場所でもいい)神社の番号
    se = sw + 1 #xより東で一番近い神社の番号
    tw = bisect.bisect_right(t, x)-1
    te = tw + 1
    l1 = max(x-s[sw], x-t[tw])
    l2 = max(s[se]-x, t[te]-x)
    l3 = s[se]-x + s[se]-t[tw]
    l4 = t[te]-x + t[te]-s[sw]
    l5 = x-s[sw] + t[te]-s[sw]
    l6 = x-t[tw] + s[se]-t[tw]
    print(min(l1, l2, l3, l4, l5, l6))
main()

Submission status: Time Limit Exceeded

Solution code:
import bisect
A, B, Q = map(int, input().split())
s = list()
t = list()
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())
  sw = bisect.bisect_right(s, x)-1 #xより西で一番近い(同じ場所でもいい)神社の番号
  se = sw + 1 #xより東で一番近い神社の番号
  tw = bisect.bisect_right(t, x)-1
  te = tw + 1
  l1 = max(x-s[sw], x-t[tw])
  l2 = max(s[se]-x, t[te]-x)
  l3 = s[se]-x + s[se]-t[tw]
  l4 = t[te]-x + t[te]-s[sw]
  l5 = x-s[sw] + t[te]-s[sw]
  l6 = x-t[tw] + s[se]-t[tw]
  print(min(l1, l2, l3, l4, l5, l6))

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left
from itertools import product

a, b, q = [int(i) for i in input().split()]

s_list = [int(input()) for _ in range(a)]
t_list = [int(input()) for _ in range(b)]

n_list = [a, b]
s_t_list = [s_list, t_list]

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

    temp_s_t_list = [[10 ** 11] * 2, [10 ** 11] * 2]
    for i in range(2):
        xi = bisect_left(s_t_list[i], x)

        if xi < n_list[i]:
            temp_s_t_list[i][0] = s_t_list[i][xi] - x
        if xi > 0:
            temp_s_t_list[i][1] = s_t_list[i][xi - 1] - x
    
    temp_list = []
    for s_x, t_x in list(product(temp_s_t_list[0], temp_s_t_list[1])):
        temp_s_x = s_x
        s_x = abs(s_x)
        temp_t_x = t_x
        t_x = abs(t_x)
        if temp_s_x // s_x == temp_t_x // t_x:
            temp_list.append(max(s_x, t_x))
        else:
            temp_list.append(s_x + t_x + min(s_x, t_x))
    print(min(temp_list))

Submission status: Time Limit Exceeded

Solution code:
import bisect
a,b,q=map(int,input().split())
S=[];T=[]
for _ in range(a):
    s=int(input())
    S.append(s)
for _ in range(b):
    t=int(input())
    T.append(t)
S.append(10**12)
T.append(10**12)

for _ in range(q):
    x=int(input())
    idx_s=bisect.bisect_left(S,x)
    idx_t=bisect.bisect_left(T,x)
    se=S[idx_s]
    sw=S[idx_s-1]
    te=T[idx_t]
    tw=T[idx_t-1]

    m1=abs(x-se)+abs(se-te)
    m2=abs(x-se)+abs(se-tw)
    m3=abs(x-sw)+abs(sw-te)
    m4=abs(x-sw)+abs(sw-tw)
    m5=abs(x-te)+abs(te-se)
    m6=abs(x-te)+abs(te-sw)
    m7=abs(x-tw)+abs(tw-se)
    m8=abs(x-tw)+abs(tw-sw)
    print(min(m1,m2,m3,m4,m5,m6,m7,m8))

Submission status: Time Limit Exceeded

Solution code:
import bisect
a,b,q=map(int,input().split())
S=[10**12];T=[10**12]
for _ in range(a):
    s=int(input())
    S.append(s)
for _ in range(b):
    t=int(input())
    T.append(t)
S.sort()
T.sort()

for _ in range(q):
    x=int(input())
    idx_s=bisect.bisect_left(S,x)
    idx_t=bisect.bisect_left(T,x)
    se=S[idx_s]
    sw=S[idx_s-1]
    te=T[idx_t]
    tw=T[idx_t-1]

    m1=abs(x-se)+abs(se-te)
    m2=abs(x-se)+abs(se-tw)
    m3=abs(x-sw)+abs(sw-te)
    m4=abs(x-sw)+abs(sw-tw)
    m5=abs(x-te)+abs(te-se)
    m6=abs(x-te)+abs(te-sw)
    m7=abs(x-tw)+abs(tw-se)
    m8=abs(x-tw)+abs(tw-sw)
    print(min(m1,m2,m3,m4,m5,m6,m7,m8))

Submission status: Time Limit Exceeded

Solution code:
import bisect
a,b,q=map(int,input().split())
S=[10**20];T=[10**20]
for _ in range(a):
    s=int(input())
    S.append(s)
for _ in range(b):
    t=int(input())
    T.append(t)
S.sort()
T.sort()

for _ in range(q):
    x=int(input())
    se=S[bisect.bisect_left(S,x)]
    sw=S[bisect.bisect_left(S,x)-1]
    te=T[bisect.bisect_left(T,x)]
    tw=T[bisect.bisect_left(T,x)-1]

    m1=abs(x-se)+abs(se-te)
    m2=abs(x-se)+abs(se-tw)
    m3=abs(x-sw)+abs(sw-te)
    m4=abs(x-sw)+abs(sw-tw)
    m5=abs(x-te)+abs(te-se)
    m6=abs(x-te)+abs(te-sw)
    m7=abs(x-tw)+abs(tw-se)
    m8=abs(x-tw)+abs(tw-sw)
    print(min(m1,m2,m3,m4,m5,m6,m7,m8))

Submission status: Time Limit Exceeded

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

T = [int(input()) for _ in range(B)]

X = [int(input()) for _ in range(Q)]

from bisect import bisect_left

for _ in range(Q):
    ans = 10**12
    x = X[_]
    idxs = bisect_left(S,x)
    idxt = bisect_left(T,x)

    if idxs < A and idxt < B:
        ans = min(ans, max(S[idxs],T[idxt])-x)
    if 0 <= idxs-1 and 0 <= idxt-1:
        ans = min(ans, x-min(S[idxs-1],T[idxt-1]))
    if idxs < A and 0 <= idxt-1:
        ans = min(ans, S[idxs]-T[idxt-1] + min(S[idxs]-x, x-T[idxt-1]))
    if idxt < B and 0 <= idxs-1:
        ans = min(ans, T[idxt]-S[idxs-1] + min(T[idxt]-x, x-S[idxs-1]))

    print(ans)

Submission status: Time Limit Exceeded

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

T = [int(input()) for _ in range(B)]

from bisect import bisect_left

for _ in range(Q):
    ans = 10**12
    x = int(input())
    idxs = bisect_left(S,x)
    idxt = bisect_left(T,x)

    if idxs < A and idxt < B:
        ans = min(ans, max(S[idxs],T[idxt])-x)
    if 0 <= idxs-1 and 0 <= idxt-1:
        ans = min(ans, x-min(S[idxs-1],T[idxt-1]))
    if idxs < A and 0 <= idxt-1:
        ans = min(ans, S[idxs]-T[idxt-1] + min(S[idxs]-x, x-T[idxt-1]))
    if idxt < B and 0 <= idxs-1:
        ans = min(ans, T[idxt]-S[idxs-1] + min(T[idxt]-x, x-S[idxs-1]))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect

a, b, q = map(int, input().split())
s = sorted([int(input()) for _ in range(a)])
t = sorted([int(input()) for _ in range(b)])

for _ in range(q):
    x = int(input())
    s_i = bisect.bisect_left(s, x)
    t_i = bisect.bisect_left(t, x)

    s0, s1, t0, t1 = None, None, None, None
    ans = 10 ** 11
    if s_i > 0:
        s0 = x - s[s_i-1]
    if s_i < a:
        s1 = s[s_i] - x
    if t_i > 0:
        t0 = x - t[t_i-1]
    if t_i < b:
        t1 = t[t_i] - x

    if s0 is not None and t0 is not None:
        ans = min(ans, max(s0, t0))
    if s1 is not None and t1 is not None:
        ans = min(ans, max(s1, t1))
    if s0 is not None and t1 is not None:
        ans = min(ans, s0*2 + t1, t1*2 + s0)
    if s1 is not None and t0 is not None:
        ans = min(ans, s1*2 + t0, t0*2 + s1)

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import math

A, B, Q = list(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)]

def binary_search(target, data):
    # def _binary_search(target, data, left, right):
    #     # print(left, right)
    #     is_found = right - left <= 1
    #     if is_found:
    #         diff_left = abs(target - data[left])
    #         diff_right = abs(target - data[right])
    #         if diff_left < diff_right: return left
    #         else : return right

    #     center = int((right - left) / 2)
    #     base = data[center]

    #     if target <= base:
    #         new_left = left
    #         new_right = center
    #     else:
    #         new_left = center
    #         new_right = right

    #     found = _binary_search(target, data, new_left, new_right)

    #     return found

    left = 0
    right = len(data) - 1
    # found = _binary_search(target, data, left, right)
    found = None
    while True:
        is_found = right - left <= 1
        if is_found:
            diff_left = abs(target - data[left])
            diff_right = abs(target - data[right])
            if diff_left < diff_right:
                found = left
                break
            else :
                found = right
                break

        center = int((right - left) / 2)
        base = data[center]

        if target < base:
            left = left
            right = center
        else:
            left = center
            right = right

    return data[found]


for xi in x:
    x_to_s = binary_search(xi, s)
    s_to_t = binary_search(x_to_s, t)
    x_s_t = abs(xi - x_to_s) + abs(x_to_s - s_to_t)

    x_to_t = binary_search(xi, t)
    t_to_s = binary_search(x_to_t, s)
    x_t_s = abs(xi - x_to_t) + abs(x_to_t - t_to_s)

    answer = min(x_s_t, x_t_s)

    print(answer)

Submission status: Time Limit Exceeded

Solution code:
import math

A, B, Q = list(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)]

def binary_search(target, data):
    # def _binary_search(target, data, left, right):
    #     # print(left, right)
    #     is_found = right - left <= 1
    #     if is_found:
    #         diff_left = abs(target - data[left])
    #         diff_right = abs(target - data[right])
    #         if diff_left < diff_right: return left
    #         else : return right

    #     center = int((right - left) / 2)
    #     base = data[center]

    #     if target <= base:
    #         new_left = left
    #         new_right = center
    #     else:
    #         new_left = center
    #         new_right = right

    #     found = _binary_search(target, data, new_left, new_right)

    #     return found

    left = 0
    right = len(data) - 1
    # found = _binary_search(target, data, left, right)
    found = None
    while True:
        is_found = right - left <= 1
        if is_found:
            diff_left = abs(target - data[left])
            diff_right = abs(target - data[right])
            if diff_left < diff_right:
                found = left
                break
            else :
                found = right
                break

        center = int((right - left) / 2)
        base = data[center]

        if target <= base:
            left = left
            right = center
        else:
            left = center
            right = right

    return data[found]


for xi in x:
    x_to_s = binary_search(xi, s)
    s_to_t = binary_search(x_to_s, t)
    x_s_t = abs(xi - x_to_s) + abs(x_to_s - s_to_t)

    x_to_t = binary_search(xi, t)
    t_to_s = binary_search(x_to_t, s)
    x_t_s = abs(xi - x_to_t) + abs(x_to_t - t_to_s)

    answer = min(x_s_t, x_t_s)

    print(answer)

Submission status: Time Limit Exceeded

Solution code:
def main():
  inf = 10 ** 20
  a,b,q = map(int, input().split())
  s = [None] * (a + 3)
  s[0:2] = [-inf,-inf]
  s[-1] = inf
  t = [None] * (b + 3)
  t[0:2] = [-inf,-inf]
  t[-1] = inf
  for i in range(a):
      s[i+2] = int(input())
  for i in range(b):
      t[i+2] = int(input())

  from bisect import bisect_right


  for _ in range(q):
    ans = inf
    x = int(input())
    sr = bisect_right(s, x)
    tr = bisect_right(t, x)    
    for si in (sr, sr-1):
      for ti in (tr, tr-1):
        ans = min(ans, abs(x-s[si]) + abs(s[si]-t[ti]), abs(x-t[ti]) + abs(s[si]-t[ti]))
    print(ans)
  
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
def main():
  inf = float("INF")
  a,b,q = map(int, input().split())
  s = [None] * (a + 3)
  s[0:2] = [-inf,-inf]
  s[-1] = inf
  t = [None] * (b + 3)
  t[0:2] = [-inf,-inf]
  t[-1] = inf
  for i in range(a):
      s[i+2] = int(input())
  for i in range(b):
      t[i+2] = int(input())

  from bisect import bisect_right

  dp0 = [None] * (a+3)
  dp1 = [None] * (b+3)

  for _ in range(q):
    ans = inf
    x = int(input())
    sr = bisect_right(s, x)
    tr = bisect_right(t, x)    
    for si in (sr, sr-1):
      for ti in (tr, tr-1):
        ans = min(ans, abs(x-s[si]) + abs(s[si]-t[ti]), abs(x-t[ti]) + abs(s[si]-t[ti]))
    print(ans)
  
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
def main():
  inf = float("INF")
  a,b,q = map(int, input().split())
  s = [None] * (a + 3)
  s[0:2] = [-inf,-inf]
  s[-1] = inf
  t = [None] * (b + 3)
  t[0:2] = [-inf,-inf]
  t[-1] = inf
  for i in range(a):
      s[i+2] = int(input())
  for i in range(b):
      t[i+2] = int(input())

  from bisect import bisect_left

  dp0 = [None] * (a+3)
  dp1 = [None] * (b+3)

  def f(s,t,x,ss,i):
    if i == 0 and dp0[ss] != None: return abs(x - s[ss]) + dp0[ss]
    elif i == 1 and dp1[ss] != None: return abs(x - s[ss]) + dp1[ss]
    tr = bisect_left(t, s[ss])
    tl = tr - 1
    if i == 0: dp0[ss] = min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))
    if i == 1: dp1[ss] = min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))
    return abs(x - s[ss]) + min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))


  for _ in range(q):
    ans = inf
    x = int(input())
    sr = bisect_left(s, x)
    ans = min(ans, f(s,t,x,sr,0))
    ans = min(ans, f(s,t,x,sr - 1,0))
    tr = bisect_left(t, x)
    ans = min(ans, f(t,s,x,tr,1))
    ans = min(ans, f(t,s,x,tr - 1,1))
    print(ans)
  
if __name__ == "__main__":
  main()

Submission status: Time Limit Exceeded

Solution code:
inf = float("INF")
a,b,q = map(int, input().split())
s = [None] * (a + 3)
s[0:2] = [-inf,-inf]
s[-1] = inf
t = [None] * (b + 3)
t[0:2] = [-inf,-inf]
t[-1] = inf
for i in range(a):
	s[i+2] = int(input())
for i in range(b):
	t[i+2] = int(input())

from bisect import bisect_left

dp0 = [None] * (a+3)
dp1 = [None] * (b+3)

def f(s,t,x,ss,i):
  if i == 0 and dp0[ss] != None: return abs(x - s[ss]) + dp0[ss]
  elif i == 1 and dp1[ss] != None: return abs(x - s[ss]) + dp1[ss]
  tr = bisect_left(t, s[ss])
  tl = tr - 1
  if i == 0: dp0[ss] = min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))
  if i == 1: dp1[ss] = min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))
  return abs(x - s[ss]) + min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))


for _ in range(q):
  ans = inf
  x = int(input())
  sr = bisect_left(s, x)
  ans = min(ans, f(s,t,x,sr,0))
  ans = min(ans, f(s,t,x,sr - 1,0))
  tr = bisect_left(t, x)
  ans = min(ans, f(t,s,x,tr,1))
  ans = min(ans, f(t,s,x,tr - 1,1))
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
inf = float("INF")
a,b,q = map(int, input().split())
s = [None] * (a + 3)
s[0:2] = [-inf,-inf]
s[-1] = inf
t = [None] * (b + 3)
t[0:2] = [-inf,-inf]
t[-1] = inf
for i in range(a):
	s[i+2] = int(input())
for i in range(b):
	t[i+2] = int(input())

from bisect import bisect_left
from collections import defaultdict

dp = defaultdict(lambda: None)

def f(s,t,x,ss,i):
  if dp[(ss,i)] != None: return abs(x - s[ss]) + dp[(ss,i)]
  tr = bisect_left(t, s[ss])
  tl = tr - 1
  dp[(ss,i)] = min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))
  return abs(x - s[ss]) + dp[(ss,i)]


for _ in range(q):
  ans = inf
  x = int(input())
  sr = bisect_left(s, x)
  ans = min(ans, f(s,t,x,sr,0))
  ans = min(ans, f(s,t,x,sr - 1,0))
  tr = bisect_left(t, x)
  ans = min(ans, f(t,s,x,tr,1))
  ans = min(ans, f(t,s,x,tr - 1,1))
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
inf = float("INF")
a,b,q = map(int, input().split())
s = [-inf, -inf]+[int(input()) for _ in range(a)]+[inf]
t = [-inf, -inf]+[int(input()) for _ in range(b)]+[inf]

from bisect import bisect_left
from collections import defaultdict

dp = defaultdict(lambda: None)

def f(s,t,x,ss,i):
  if dp[(ss,i)] != None: return abs(x - s[ss]) + dp[(ss,i)]
  tr = bisect_left(t, s[ss])
  tl = tr - 1
  dp[(ss,i)] = min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))
  return abs(x - s[ss]) + dp[(ss,i)]


for _ in range(q):
  ans = inf
  x = int(input())
  sr = bisect_left(s, x)
  ans = min(ans, f(s,t,x,sr,0))
  ans = min(ans, f(s,t,x,sr - 1,0))
  tr = bisect_left(t, x)
  ans = min(ans, f(t,s,x,tr,1))
  ans = min(ans, f(t,s,x,tr - 1,1))
  print(ans)