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:
A, B, Q = map(int, input().split())
S, T =[None] * (A+1), [None] * (B+1)
S[0], T[0] = -10**20, -10**20
for i in range(A):
    S[i+1] = int(input())
for i in range(B):
    T[i+1] = int(input())
S.append(10**20)
T.append(10**20)

def Bsearch(x, L, lenL):
    low, high = 0, lenL
    while high-low > 1:
        mid = (low+high)//2
        if L[mid] > x:
            high = mid
        else: low = mid
    return [x-L[low], L[low+1]-x]

printAns = ""
lenS, lenT = len(S), len(T)
for _ in range(Q):
    x = int(input())
    sLength0, sLength1 = Bsearch(x, S, lenS)
    tLength0, tLength1 = Bsearch(x, T, lenT)
    Ans = [max(sLength0, tLength0), max(sLength1, tLength1), sLength0 + tLength1 + min(sLength0, tLength1), sLength1 + tLength0 + min(sLength1, tLength0)]
    printAns += str(min(Ans)) + "\n"
print(printAns)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
a, b, q = map(int, input().split())
s = np.array([input() for i in range(a)],dtype="int64")
t = np.array([input() for i in range(b)],dtype="int64")
x = np.array([input() for i in range(q)],dtype="int64")

for i, now_x in enumerate(x):
  s_diff = s-now_x
  s_fst_min_l = min(np.abs(s_diff))
  t_s_diff = t-s[np.argmin(np.abs(s_diff))]
  s_fst_min_l += min(np.abs(t_s_diff))
  
  t_diff = t-now_x
  t_fst_min_l = min(np.abs(t_diff))
  s_t_diff = s-t[np.argmin(np.abs(t_diff))]
  t_fst_min_l += min(np.abs(s_t_diff))
  
  print(s_fst_min_l if s_fst_min_l<t_fst_min_l else t_fst_min_l)

Submission status: Time Limit Exceeded

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

for _ in range(Q):
    x = int(input())
    a = bisect.bisect_left(S, x)
    b = bisect.bisect_left(T, x)
    print(min(x - min(S[a-1], T[b-1]), max(S[a], T[b]) - x, x+T[b]-2*S[a-1], x+S[a]-2*T[b-1], 2*T[b]-x-S[a-1], 2*S[a]-x-T[b-1]))

Submission status: Time Limit Exceeded

Solution code:
import bisect

A, B, Q = map(int, input().split())
s = []
for i in range(A):
    s.append(int(input()))
t = []
for i in range(B):
    t.append(int(input()))
for i in range(Q):
    x = int(input())
    j = bisect.bisect(s, x)
    ans = 2 * 10 ** 10
    if j > 0:
        k = bisect.bisect(t, s[j - 1])
        if k > 0:
            ans = min(ans,abs(x-s[j-1])+abs(s[j-1]-t[k-1]))
        if k < B:
            ans = min(ans, abs(x-s[j-1])+abs(s[j-1]-t[k]))
    if j < A:
        k = bisect.bisect(t, s[j])
        if k > 0:
            ans = min(ans, abs(x-s[j])+abs(s[j]-t[k-1]))
        if k < B:
            ans = min(ans, abs(x-s[j])+abs(s[j]-t[k]))
    j = bisect.bisect(t, x)
    if j > 0:
        k = bisect.bisect(s, t[j - 1])
        if k > 0:
            ans = min(ans,abs(x-t[j-1])+abs(t[j-1]-s[k-1]))
        if k < A:
            ans = min(ans, abs(x-t[j-1])+abs(t[j-1]-s[k]))
    if j < B:
        k = bisect.bisect(s, t[j])
        if k > 0:
            ans = min(ans, abs(x-t[j])+abs(t[j]-s[k-1]))
        if k < A:
            ans = min(ans, abs(x-t[j])+abs(t[j]-s[k]))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
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)]

for x in X:
  l = []
  for s in S:
    m = abs(x-s)
    for t in T:
      n = abs(s-t)
      l.append(m + n)
  for t in T:
    m = abs(x-t)
    for s in S:
      n = abs(s-t)
      l.append(m + n)
  print(min(l))

Submission status: Time Limit Exceeded

Solution code:
a, b, q = [int(_) for _ in input().split()]
s = []
t = []
x = []
xa = []

for i in range(a):
    s.append(int(input()))
for i in range(b):
    t.append(int(input()))

for i in range(a):
    x.append([s[i], min([abs(t0 - s[i]) for t0 in t])])
for i in range(b):
    x.append([t[i], min([abs(s0 - t[i]) for s0 in s])])

for i in range(q):
    xq = int(input())
    xa.append(min([abs(x0[0] - xq) + x0[1] for x0 in x]))

for i in xa:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
import bisect

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

s_diff = [0]*A
t_diff = [0]*B
for i in range(A):
    ind = bisect.bisect_left(t, s[i])
    if ind == 0:
        sm = float("inf")
    else:
        sm = s[i] - t[ind-1]
    if ind == B:
        bi = float("inf")
    else:
        bi = t[ind] - s[i]
    s_diff[i] = min(sm, bi)
for i in range(B):
    ind = bisect.bisect_left(s, t[i])
    if ind == 0:
        sm = float("inf")
    else:
        sm = t[i] - s[ind-1]
    if ind == A:
        bi = float("inf")
    else:
        bi = s[ind] - t[i]
    t_diff[i] = min(sm, bi)

for i in range(Q):
    x = int(input())
    ind = bisect.bisect_left(t, x)
    if ind == 0:
        sm = float("inf")
    else:
        sm = x - t[ind-1] + t_diff[ind-1]
    if ind == B:
        bi = float("inf")
    else:
        bi = t[ind] - x + t_diff[ind]
    ans = min(sm, bi)
    ind = bisect.bisect_left(s, x)
    if ind == 0:
        sm = float("inf")
    else:
        sm = x - s[ind-1] + s_diff[ind-1]
    if ind == A:
        bi = float("inf")
    else:
        bi = s[ind] - x + s_diff[ind]
    ans = min(ans, sm, bi)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import copy

S, T, Q = map(int, input().split(' '))

s = []
t = []

for i in range(S):
    s.append(int(input()))
for i in range(T):
    t.append(int(input()))

for i in range(Q):
    news = copy.deepcopy(s)
    newt = copy.deepcopy(t)
    x = int(input())
    news.append(x)
    newt.append(x)
    news = sorted(news)
    newt = sorted(newt)
    dis_l_s, dis_r_s, dis_l_t, dis_r_t = (10**11,10**11,10**11,10**11)
    s_near = 0
    t_near = 0
    if news.index(x)-1 >=0:
        dis_l_s = x - news[news.index(x)-1]
    if news.index(x)+1 <=len(news)-1:
        dis_r_s = - x + news[news.index(x)+1]
    if newt.index(x)-1 >=0:
        dis_l_t = x - newt[newt.index(x)-1]
    if newt.index(x) + 1 <= len(newt) - 1:
        dis_r_t = - x + newt[newt.index(x)+1]

    r1 = max(dis_l_s, dis_l_t)
    r2 = max(dis_r_s, dis_r_t)
    r3 = dis_l_s * 2 + dis_r_t
    r4 = dis_l_t * 2 + dis_r_s
    r5 = dis_r_s * 2 + dis_l_t
    r6 = dis_r_t * 2 + dis_l_s

    r = [r1,r2,r3,r4,r5,r6]
    print(min(r))

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
S, T =[None] * (A+1), [None] * (B+1)
S[0], T[0] = -10**20, -10**20
for i in range(A):
    S[i+1] = int(input())
for i in range(B):
    T[i+1] = int(input())
S.append(10**20)
T.append(10**20)

def Bsearch(x, L):
    low, high = 0, len(L)
    while high-low > 1:
        mid = (low+high)//2
        if L[mid] > x:
            high = mid
        else: low = mid
    return low

def Length(x, i, L):
    return [x - L[i], L[i+1] - x]

printAns = ""

for _ in range(Q):
    x = int(input())
    sLength0, sLength1 = Length(x, Bsearch(x, S), S)
    tLength0, tLength1 = Length(x, Bsearch(x, T), T)
    Ans = min(max(sLength0, tLength0), max(sLength1, tLength1))
    Ans = min(Ans, min(sLength0 + tLength1 + min(sLength0, tLength1), sLength1 + tLength0 + min(sLength1, tLength0)))
    printAns += str(Ans) + "\n"
print(printAns)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np


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

S = np.array([int(input()) for _ in range(A)])
T = np.array([int(input()) for _ in range(B)])

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

for x in X:
    R = []
    try:
        SSX0x = S[S > x][0] - x
    except:
        pass
    try:
        TTx0x = T[T > x][0] - x
    except:
        pass
    try:
        xSSx1 = x - S[S < x][-1]
    except:
        pass
    try:
        xTTx1 = x - T[T < x][-1]
    except:
        pass
    # +方向に神社・寺
    try:
        R.append(max(SSX0x, TTx0x))
    except:
        pass
    # -方向に神社・寺
    try:
        R.append(max(xSSx1, xTTx1))
    except:
        pass
    # +方向に神社、-方向に寺
    try:
        R.append(SSX0x * 2 + xTTx1)
    except:
        pass
    # -方向に神社、+方向に寺
    try:
        R.append(xSSx1 * 2 + TTx0x)
    except:
        pass
    # +方向に寺、-方向に神社
    try:
        R.append(TTx0x * 2 + xSSx1)
    except:
        pass
    # -方向に寺、+方向に神社
    try:
        R.append(xTTx1 * 2 + SSX0x)
    except:
        pass
    print(min(R))
    try:
        del SSX0x
    except:
        pass
    try:
        del TTx0x
    except:
        pass
    try:
        del xSSx1
    except:
        pass
    try:
        del xTTx1
    except:
        pass

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
S, T =[None] * (A+1), [None] * (B+1)
S[0], T[0] = 0, 0
for i in range(A):
    S[i+1] = int(input())
for i in range(B):
    T[i+1] = int(input())
S.append(10**20)
T.append(10**20)

def Bsearch(x, L):
    low, high = 0, len(L)
    while high-low > 1:
        mid = (low+high)//2
        if L[mid] > x:
            high = mid
        else: low = mid
    return low

def Length(x, i, L):
    if i == 0: return [10**30, L[1] - x]
    else: return [x - L[i], L[i+1] - x]

for _ in range(Q):
    x = int(input())
    sLength, tLength = Length(x, Bsearch(x, S), S), Length(x, Bsearch(x, T), T)
    Ans = min(max(sLength[0], tLength[0]), max(sLength[1], tLength[1]))
    Ans = min(Ans, min(sLength[0] + tLength[1] + min(sLength[0], tLength[1]), sLength[1] + tLength[0] + min(sLength[1], tLength[0])))
    print(Ans)

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
shrine = []
temple = []
for i in range(A):
    shrine.append(int(input()))
for i in range(B):
    temple.append(int(input()))

for i in range(Q):
    pos = int(input())
    sh = [[shrine[i], abs(pos - shrine[i])] for i in range(A)]
    tem = [[temple[i], abs(pos - temple[i])] for i in range(B)]
    sh.sort(key = lambda x: x[1])
    tem.sort(key = lambda x: x[1])
    l1 = sh[0][1]
    npos = sh[0][0]
    ntem = [abs(npos - temple[i]) for i in range(B)]
    ntem.sort()
    l1 += ntem[0]

    l2 = tem[0][1]
    npos = tem[0][0]
    nsh = [abs(npos - shrine[i]) for i in range(A)]
    nsh.sort()
    l2 += nsh[0]
    print(min([l1, l2]))

Submission status: Time Limit Exceeded

Solution code:
import bisect
a,b,q = map(int,input().split())
x = [int(input()) for i in range(a)]
y = [int(input()) for i in range(b)]
x.sort()
y.sort()
xx = [0]*a
yy = [0]*b
n = 0
for i in range(a):
    while n < b-1 and abs(x[i]-y[n]) > abs(x[i]-y[n+1]):
        n+=1
    xx[i] = abs(x[i]-y[n])
n = 0
for i in range(b):
    while n < a-1 and abs(y[i]-x[n]) > abs(y[i]-x[n+1]):
        n+=1

    yy[i] = abs(y[i]-x[n])

for i in range(q):
    z = int(input())
    ans = 1<<61
    n = bisect.bisect_left(x, z)
    if n<a:
        tmp = abs(x[n]-z)+xx[n]
        ans = min(ans,tmp)
    if n>0:
        tmp = abs(x[n-1]-z)+xx[n-1]
        ans = min(ans,tmp)

    n = bisect.bisect_left(y, z)
    if n<b:
        tmp = abs(y[n]-z)+yy[n]
        ans = min(ans,tmp)
    if n>0:
        tmp = abs(y[n-1]-z)+yy[n-1]
        ans = min(ans,tmp)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
A, B, Q = map(int, input().split())
inp = np.array([int(input()) for _ in range(A +B + Q)])

adisps , bdisps, qdisps = inp[:A], inp[A:A+B], inp[A+B:]

def nearest(now, disps):
    idx = np.argmin(np.abs(disps - now))
    nearest_point = disps[idx]
    cost = np.abs(now - nearest_point)
    return nearest_point, cost

for qdisp in qdisps:

    #A→B
    pos_a1, cost_a1 = nearest(qdisp, adisps)
    pos_b1, cost_b1 = nearest(pos_a1, bdisps)
    cost1 = cost_a1 + cost_b1

    #B→A
    pos_b2, cost_b2 = nearest(qdisp, bdisps)
    pos_a2, cost_a2 = nearest(pos_b2, adisps)
    cost2 = cost_a2 + cost_b2

    ans = min(cost1, cost2)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def solve(a, b, q, al, bl, ql):
    for i in ql:
        qstep(al, bl, i)

def qstep(al, bl, q):
    asmall = None
    abig = None
    bsmall = None
    bbig = None
        
    for e in al:
        if e <= q:
            asmall = e
        else:
            abig = e
            break
        
    for e in bl:
        if e <= q:
            bsmall = e
        else:
            bbig = e
            break

    answer = 2 * (10 ** 10)
    
    # small , small
    if( asmall is not None) and (bsmall is not None):
        t = min(asmall,bsmall)
        v = q - t
        if v < answer:
            answer = v

    # big , big
    if( abig is not None) and (bbig is not None):
        t = max(abig,bbig)
        v = t - q
        if v < answer:
            answer = v

    # small , big
    if( asmall is not None) and (bbig is not None):
        v = (bbig - asmall) + min(bbig - q, q - asmall)
        if v < answer:
            answer = v

    # big , big
    if( abig is not None) and (bsmall is not None):
        v = (abig - bsmall) + min(abig - q, q - bsmall)
        if v < answer:
            answer = v

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

al = []
for i in range(a):
    al.append(int(input()))
bl = []
for i in range(b):
    bl.append(int(input()))
ql = []
for i in range(q):
    ql.append(int(input()))

solve(a, b, q, sorted(al), sorted(bl), ql)

Submission status: Time Limit Exceeded

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


import sys
import math


# 1整数
# n = int(input())

def tikai(ll: [], target: int):
    n = len(ll)
    min = 0
    max = n
    while max - min != 1:
        mid = int((min + max) / 2)
        if (ll[mid] > target):
            max = mid
        else:
            min = mid
    return min


def walk(list: [], start: int):
    target = tikai(list, start)
    if target == 0:
        return abs(start - list[0])
    if target == len(list) - 1:
        return abs(start - list[-1])
    return min(abs(start - list[target]), abs(start - list[target + 1]))


# 空白区切り整数
a, b, q = list(map(int, input().split()))

jinja = [0] * a
tera = [0] * b

question = [0] * q


for i in range(a):
    jinja[i] = int(input())
for i in range(b):
    tera[i] = int(input())
for i in range(q):
    ret = 99999999999999999999

    target = int(input())
    ##神社から先に向かう
    ji = tikai(jinja, target)
    #print('ji=' + str(ji))
    ##左の神社
    move = 0
    move += abs(target - jinja[ji])
    move += walk(tera,jinja[ji])
    ret = min(ret,move)
    #print('1-'+str(move))
    ##右の神社
    move=0
    if ji < len(jinja)-1:
        move += abs(target - jinja[ji+1])
        move += walk(tera, jinja[ji+1])
        #print('2-'+str(move))
        ret = min(ret, move)

    ##寺から先に向かう
    te = tikai(tera, target)
    #print('te='+str(te))
    ##左の寺
    move = 0
    move += abs(target - tera[te])
    move += walk(jinja, tera[te])
    ret = min(ret, move)
    #print('3-'+str(move))
    ##右の神社
    move = 0
    if te < len(tera) - 1:
        move += abs(target - tera[te + 1])
        move += walk(jinja, tera[te + 1])
        ret = min(ret, move)
        #print('4-'+str(move))

    print(ret)

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
s = [0 for _ in range(A)]
t = [0 for _ in range(B)]
x = [0 for _ in range(Q)]
for a in range(A):
  s[a] = int(input())
for b in range(B):
  t[b] = int(input())
for q in range(Q):
  x[q] = int(input())
INF = float('inf')

ns = [INF for _ in range(A)]
nt = [INF for _ in range(B)]
for a in range(A):
  for b in range(B):
    ns[a] = min(ns[a], abs(s[a]-t[b]))
    nt[b] = min(nt[b], abs(t[b]-s[a]))

for q in range(Q):
  S = min(map(lambda X, Y:abs(X-x[q])+Y, s, ns))
  T = min(map(lambda X, Y:abs(X-x[q])+Y, t, nt))
  print(min(S, T))

Submission status: Time Limit Exceeded

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

s_list = [int(input()) for _ in range(A)]
t_list = [int(input()) for _ in range(B)]
x_list = [int(input()) for _ in range(Q)]

# print("s : ",s_list)
# print("t : ",t_list)
# print("x : ",x_list)

s_nearest_t = []
t_nearest_s = []

for s in s_list:
    t_dis = [abs(s-t) for t in t_list]
    s_nearest_t.append(np.min(t_dis))
for t in t_list:
    s_dis = [abs(s-t) for s in s_list]
    t_nearest_s.append(np.min(s_dis))


def get_ans(s_list, t_list, x):
    s_res = [abs(s-x) for s in s_list]
    t_res = [abs(t-x) for t in t_list]
    s_nearest = np.min(s_res)
    t_nearest = np.min(t_res)
    
    s_nearest_idx = s_res.index(s_nearest)
    t_nearest_idx = t_res.index(t_nearest)
    
    if s_nearest_t[s_nearest_idx] + s_nearest < t_nearest_s[t_nearest_idx] + t_nearest:
        ans = s_nearest_t[s_nearest_idx] + s_nearest
    else:
        ans = t_nearest_s[t_nearest_idx] + t_nearest
    
#     nearest = min(np.min(s_res), np.min(t_res))
    
#     ans = nearest
    
#     if np.min(s_res) < np.min(t_res):
#         x = s_list[np.argmin(s_res)]
#         t_res_ = [abs(t-x) for t in t_list]
#         ans += np.min(t_res_)
#     else:
#         x = t_list[np.argmin(t_res)]
#         s_res_ = [abs(s-x) for s in s_list]
#         ans += np.min(s_res_)
    return ans
        
for x in x_list:
    print(get_ans(s_list, t_list, x))

Submission status: Time Limit Exceeded

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

result = [0]*Q
c = 0
for k in x:
    cand = list()
    for sk in s:
        for tk in t:
            if abs(sk-k) < abs(tk-k):
                cand.append(abs(sk-k)+abs(sk-tk))
            else:
                cand.append(abs(tk - k) + abs(sk - tk))
    result[c] = min(cand)
    c += 1

for i in result:
    print(i)

Submission status: Time Limit Exceeded

Solution code:
import bisect

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

Z=[-10**10]
T=[-10**10]

for i in range(A):
    s=int(input())
    Z.append(s)
Z.append(10**11)
for i in range(B):
    t=int(input())
    T.append(t)
T.append(10**11)
    
for i in range(Q):
    x=int(input())
    a=max(Z[bisect.bisect_left(Z,x)],T[bisect.bisect_left(T,x)])-x
    b=x-min(Z[bisect.bisect_left(Z,x)-1],T[bisect.bisect_left(T,x)-1])
    c=Z[bisect.bisect_left(Z,x)]-T[bisect.bisect_left(T,x)-1]+(x-T[bisect.bisect_left(T,x)-1])
    d=Z[bisect.bisect_left(Z,x)]-T[bisect.bisect_left(T,x)-1]+(Z[bisect.bisect_left(Z,x)]-x)
    e=T[bisect.bisect_left(T,x)]-Z[bisect.bisect_left(Z,x)-1]+(x-Z[bisect.bisect_left(Z,x)-1])
    f=T[bisect.bisect_left(T,x)]-Z[bisect.bisect_left(Z,x)-1]+(T[bisect.bisect_left(T,x)]-x)
    print(min(a,b,c,d,e,f))

Submission status: Time Limit Exceeded

Solution code:
import bisect

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

Z=[-100000000000000000]
T=[-100000000000000000]

for i in range(A):
    s=int(input())
    Z.append(s)
Z.append(100000000000000000)
for i in range(B):
    t=int(input())
    T.append(t)
T.append(100000000000000000)
    
for i in range(Q):
    x=int(input())
    a=max(Z[bisect.bisect_left(Z,x)],T[bisect.bisect_left(T,x)])-x
    b=x-min(Z[bisect.bisect_left(Z,x)-1],T[bisect.bisect_left(T,x)-1])
    c=Z[bisect.bisect_left(Z,x)]-T[bisect.bisect_left(T,x)-1]+(x-T[bisect.bisect_left(T,x)-1])
    d=Z[bisect.bisect_left(Z,x)]-T[bisect.bisect_left(T,x)-1]+(Z[bisect.bisect_left(Z,x)]-x)
    e=T[bisect.bisect_left(T,x)]-Z[bisect.bisect_left(Z,x)-1]+(x-Z[bisect.bisect_left(Z,x)-1])
    f=T[bisect.bisect_left(T,x)]-Z[bisect.bisect_left(Z,x)-1]+(T[bisect.bisect_left(T,x)]-x)
    print(min(a,b,c,d,e,f))

Submission status: Time Limit Exceeded

Solution code:
import bisect
a,b,q = map(int,input().split())
x = [int(input()) for i in range(a)]
y = [int(input()) for i in range(b)]
x.sort()
y.sort()
xx = [0]*a
yy = [0]*b
for i in range(a):
    n = bisect.bisect_left(y,x[i])
    o = 1<<61
    p = 1<<61
    try:
        o = abs(y[n]-x[i])
    except:
        pass
    try:
        p = abs(y[n-1]-x[i])
    except:
        pass
    xx[i] = min(o,p)

for i in range(b):
    n = bisect.bisect_left(x,y[i])
    o = 1<<61
    p = 1<<61
    try:
        o = abs(x[n]-y[i])
    except:
        pass
    try:
        p = abs(x[n-1]-y[i])
    except:
        pass
    yy[i] = min(o,p)

for i in range(q):
    z = int(input())
    ans = 1<<61
    n = bisect.bisect_left(x, z)
    if n<a:
        tmp = abs(x[n]-z)+xx[n]
        ans = min(ans,tmp)
    if n>0:
        tmp = abs(x[n-1]-z)+xx[n-1]
        ans = min(ans,tmp)

    n = bisect.bisect_left(y, z)
    if n<b:
        tmp = abs(y[n]-z)+yy[n]
        ans = min(ans,tmp)
    if n>0:
        tmp = abs(y[n-1]-z)+yy[n-1]
        ans = min(ans,tmp)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
shrine = []
temple = []
for i in range(A):
    shrine.append(int(input()))
for i in range(B):
    temple.append(int(input()))

for i in range(Q):
    pos = int(input())
    sh = list(map(lambda x: abs(pos - shrine[x]), range(A)))
    tem = list(map(lambda x: abs(pos - temple[x]), range(B)))
    #print(sh, tem)
    l1 = min(sh)
    npos = shrine[sh.index(l1)]
    ntem =  list(map(lambda x: abs(npos - temple[x]), range(B)))
    l1 += min(ntem)

    l2 = min(tem)
    npos = temple[tem.index(l2)]
    nsh =  list(map(lambda x: abs(npos - shrine[x]), range(A)))
    l2 += min(nsh)
    print(min([l1, l2]))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np


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

S = np.array([int(input()) for _ in range(A)])
T = np.array([int(input()) for _ in range(B)])

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

for x in X:
    R = []
    # +方向に神社・寺
    try:
        R.append(max(S[S > x][0] - x, T[T > x][0] - x))
    except:
        pass
    # -方向に神社・寺
    try:
        R.append(max(x - S[S < x][-1], x - T[T < x][-1]))
    except:
        pass
    # +方向に神社、-方向に寺
    try:
        R.append((S[S > x][0] - x) * 2 + (x - T[T < x][-1]))
    except:
        pass
    # -方向に神社、+方向に寺
    try:
        R.append((x - S[S < x][-1]) * 2 + (T[T > x][0] - x))
    except:
        pass
    # +方向に寺、-方向に神社
    try:
        R.append((T[T > x][0] - x) * 2 + (x - S[S < x][-1]))
    except:
        pass
    # -方向に寺、+方向に神社
    try:
        R.append((x - T[T < x][-1]) * 2 + (S[S > x][0] - x))
    except:
        pass
    print(min(R))

Submission status: Accepted

Solution code:
import bisect
import math

a, b, q = map(int, input().split())
s = [-math.inf]
t = [-math.inf]
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()))
s.append(math.inf)
t.append(math.inf)

for i in x:
    ws = abs(s[bisect.bisect(s, i) - 1] - i)
    if ws != math.inf:
        ws += min(abs(t[bisect.bisect(t, s[bisect.bisect(s, i) - 1])-1] - s[bisect.bisect(s, i) - 1]), \
                  abs(t[bisect.bisect(t, s[bisect.bisect(s, i) - 1])] - s[bisect.bisect(s, i) - 1]))
    else:
        ws = math.inf
    
    es = abs(s[bisect.bisect(s, i)] - i)
    if es != math.inf:
        es += min(abs(t[bisect.bisect(t, s[bisect.bisect(s, i)]) -1] - s[bisect.bisect(s, i)]), \
                  abs(t[bisect.bisect(t, s[bisect.bisect(s, i)])] - s[bisect.bisect(s, i)]))
    else:
        es = math.inf
    
    wt = abs(t[bisect.bisect(t, i) - 1] - i)
    if wt != math.inf:
        wt += min(abs(s[bisect.bisect(s, t[bisect.bisect(t, i) - 1])-1] - t[bisect.bisect(t, i) - 1]), \
                  abs(s[bisect.bisect(s, t[bisect.bisect(t, i) - 1])] - t[bisect.bisect(t, i) - 1]))
    else:
        wt = math.inf
    
    et = abs(t[bisect.bisect(t, i)] - i)
    if et != math.inf:
        et += min(abs(s[bisect.bisect(s, t[bisect.bisect(t, i)])-1] - t[bisect.bisect(t, i)]), \
                  abs(s[bisect.bisect(s, t[bisect.bisect(t, i)])] - t[bisect.bisect(t, i)]))
    else:
        et = math.inf
        
    print(min(ws, es, wt, et))

Submission status: Accepted

Solution code:
from bisect import bisect_right
A, B, Q = map(int, input().split())
INF = float('inf')
S = [-INF] + list(int(input()) for _ in range(A)) + [INF]
T = [-INF] + list(int(input()) for _ in range(B)) + [INF]
for _ in range(Q):
    x = int(input())
    i = bisect_right(S,x)
    j = bisect_right(T,x)
    d = INF
    for s in [S[i-1], S[i]]:
        for t in [T[j-1], T[j]]:
            d1 = abs(s-x) + abs(s-t)
            d2 = abs(t-x) + abs(s-t)
            d = min(d, d1, d2)
    print(d)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left

sys.setrecursionlimit(10 ** 7)
f_inf = float('inf')
mod = 10 ** 9 + 7


def neighborhood(L, now):
    tmp = bisect_left(L, now)
    if tmp == 0:
        return [tmp, None]
    elif tmp == len(L):
        return [tmp - 1, None]
    else:
        return [tmp - 1, tmp]


def dist_calc(now, p1, p2):
    if p1 is None or p2 is None:
        return f_inf
    res1 = abs(now - p1) + abs(p1 - p2)
    res2 = abs(now - p2) + abs(p1 - p2)
    return min(res1, res2)


def resolve():
    a, b, q = map(int, input().split())
    S = list(int(input()) for _ in range(a))
    T = list(int(input()) for _ in range(b))
    query = list(int(input()) for _ in range(q))

    for x in query:
        dist1 = f_inf
        s1, s2 = neighborhood(S, x)
        for s in [s1, s2]:
            if s is not None:
                t1, t2 = neighborhood(T, S[s])
                for t in [t1, t2]:
                    if t is not None:
                        dist1 = min(dist1, dist_calc(x, S[s], T[t]))

        dist2 = f_inf
        t1, t2 = neighborhood(T, x)
        for t in [t1, t2]:
            if t is not None:
                s1, s2 = neighborhood(S, T[t])
                for s in [s1, s2]:
                    if s is not None:
                        dist2 = min(dist2, dist_calc(x, S[s], T[t]))

        res = min(dist1, dist2)
        print(res)


if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
from bisect import bisect_right


def main():
    a, b, q = map(int, input().split())
    s = [int(input()) for _ in range(a)]
    t = [int(input()) for _ in range(b)]
    neighbour_temple = [[] for _ in range(a)]
    for i in range(a):
        idx = bisect_right(t, s[i])
        if idx == b:
            neighbour_temple[i].append(t[-1])
        else:
            if idx > 0:
                neighbour_temple[i].append(t[idx - 1])
            neighbour_temple[i].append(t[idx])
    for _ in range(q):
        begin = int(input())
        idx = bisect_right(s, begin)
        visit_s = []
        if idx == a:
            visit_s.append(a - 1)
        else:
            if idx > 0:
                visit_s.append(idx - 1)
            visit_s.append(idx)
        ans = float("inf")
        for v_s in visit_s:
            for v_t in neighbour_temple[v_s]:
                min_point = min(s[v_s], v_t)
                large_point = max(s[v_s], v_t)
                if min_point <= begin <= large_point:
                    ans = min(ans, large_point - min_point + min(begin - min_point, large_point - begin))
                elif begin <= min_point <= large_point:
                    ans = min(ans, abs(large_point - begin))
                else:
                    ans = min(ans, abs(min_point - begin))
        print(ans)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
def main():
    import bisect

    a, b, q = map(int, input().split())
    INF = float('inf')
    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 i in x:
        si = bisect.bisect_left(s, i)
        ti = bisect.bisect_left(t, i)
        sl, sr = i-s[si-1], s[si]-i
        tl, tr = i-t[ti-1], t[ti]-i
        print(min(max(sl,tl), sl+tr+min(sl,tr), sr+tl+min(sr,tl), max(sr,tr)))

main()

Submission status: Accepted

Solution code:
import bisect

a, b, q = map(int, input().split())
INF = float('inf')
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 i in x:
    si = bisect.bisect_left(s, i)
    ti = bisect.bisect_left(t, i)
    sl, sr = i-s[si-1], s[si]-i
    tl, tr = i-t[ti-1], t[ti]-i
    print(min(max(sl,tl), sl+tr+min(sl,tr), sr+tl+min(sr,tl), max(sr,tr)))