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:
# -*- coding: utf-8 -*-

def lower_bound(al, key):
    """
    一般に左側が満たしておらず、右側は満たしている判定基準(境目は一つ)ならlower_boundになる
    (条件を満たすもののうち、最小のインデックスを返す)
    単調にさえなっていれば、左右が逆になっていても検索には使える(ng/okも一緒に逆にする必要がある)
    """
    def isOk(a):
        # alの中でkey以上のアイテムのうち最小のインデックスを返す
        # upper_boundにする時にはa>key
        return a>=key

    ng = -1
    ok = len(al)

    while abs(ok-ng)>1:
        mid = (ok+ng)//2

        if isOk(al[mid]):
            ok = mid
        else:
            ng = mid

    return ok


a,b,q = map(int, input().split())
sl = [int(input()) for _ in range(a)]
tl = [int(input()) for _ in range(b)]
# print(sl)
# print(tl)
for _ in range(q):
    x = int(input())
    si = lower_bound(sl,x)
    ti = lower_bound(tl,x)
    # print(x,si,ti)

    ssl = []
    if si==a:
        ssl.append(sl[-1])
    elif si==-1:
        ssl.append(sl[0])
    else:
        ssl.append(sl[si])
        if si>0:
            ssl.append(sl[si-1])
    ttl = []
    if ti==b:
        ttl.append(tl[-1])
    elif ti==-1:
        ttl.append(tl[0])
    else:
        ttl.append(tl[ti])
        if ti>0:
            ttl.append(tl[ti-1])

    res = -1
    for s in ssl:
        for t in ttl:
            if s>=x and t>=x:
                tmp = max(s-x, t-x)
            elif s<x and t<x:
                tmp = max(x-s, x-t)
            elif s>=x>=t:
                tmp = min(
                    2*(s-x)+(x-t),
                    (s-x)+2*(x-t)
                )
            else:
                tmp = min(
                    2*(x-s)+(t-x),
                    (x-s)+2*(t-x)
                )
            if res<0:
                res = tmp
            else:
                res = min(res,tmp)
    print(res)

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = [int(i) for i in input().split()]
sList = [int(input()) for _ in range(A)]
tList = [int(input()) for _ in range(B)]
xList = [int(input()) for _ in range(Q)]

def getDist(distance, someList):
    for i, some in enumerate(someList):
        if some > distance:
            return [someList[max(i-1, 0)], some]
    return [some, some]

for x in xList:
    sDists = getDist(x, sList)
    tDists = getDist(x, tList)
    ans = float("inf")
    for s in sDists:
        for t in tDists:
            ans = min(ans, min(abs(x - s), abs(x - t)) + abs(s - t))
    print(ans)

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 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: Time Limit Exceeded

Solution code:
import bisect

f_inf = float('inf')


def cal(syurui, d, index):
    if d == 'e':
        return syurui[index]
    elif d == 'w':
        return syurui[index - 1]


A, B, Q = map(int, input().split())
s = [int(input()) for i in range(A)]
s.sort()
t = [int(input()) for i in range(B)]
t.sort()
ｓ.insert(0, -f_inf)
t.insert(0, -f_inf)
ｓ.append(f_inf)
t.append(f_inf)

for i in range(Q):
    x = int(input())
    s_index = bisect.bisect_left(s, x)
    t_index = bisect.bisect_left(t, x)
    print(min(max(abs(x-s[s_index]), abs(x-t[t_index])), max(abs(x-s[s_index-1]), abs(x-t[t_index-1])), 2*abs(x-s[s_index-1])+abs(x-t[t_index]), 2*abs(x-s[s_index])+abs(x-t[t_index-1]), abs(x-s[s_index-1])+2*abs(x-t[t_index]), abs(x-s[s_index])+2*abs(x-t[t_index-1])))

Submission status: Time Limit Exceeded

Solution code:
import bisect

f_inf = float('inf')


def cal(syurui, d, index):
    if d == 'e':
        return syurui[index]
    elif d == 'w':
        return syurui[index - 1]


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

for i in range(Q):
    x = int(input())
    s_index = bisect.bisect_left(s, x)
    t_index = bisect.bisect_left(t, x)
    if s_index == len(s) and t_index == len(t):
        print(max(abs(x-s[s_index-1]), abs(x-t[t_index-1])))
    elif s_index == len(s):
        ｓ.insert(0, -f_inf)
        t.insert(0, -f_inf)
        print(min(max(abs(x-s[s_index]), abs(x-t[t_index])),
                  2*abs(x-s[s_index])+abs(x-t[t_index+1]), abs(x-s[s_index])+2*abs(x-t[t_index+1])))
    elif t_index == len(t):
        ｓ.insert(0, -f_inf)
        t.insert(0, -f_inf)
        print(min(max(abs(x-s[s_index]), abs(x-t[t_index])), 2*abs(x-s[s_index+1])+abs(x-t[t_index]),
                  abs(x-s[s_index+1])+2*abs(x-t[t_index])))
    else:
        ｓ.insert(0, -f_inf)
        t.insert(0, -f_inf)
        print(min(max(abs(x-s[s_index]), abs(x-t[t_index])), max(
            abs(x-s[s_index+1]), abs(x-t[t_index+1])), 2*abs(x-s[s_index+1])+abs(x-t[t_index]), 2*abs(x-s[s_index])+abs(x-t[t_index+1]), abs(x-s[s_index+1])+2*abs(x-t[t_index]), abs(x-s[s_index])+2*abs(x-t[t_index+1])))

Submission status: Time Limit Exceeded

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

for i in range(q):
    x = int(input())
    xs = bisect.bisect(s,x)
    xt = bisect.bisect(t,x)
    S = [s[xs-1],s[xs]]
    T = [t[xt-1],t[xt]]
    
    ans = float('inf')
    for j in range(2):
        for k in range(2):
            ans = min(ans, abs(S[j]-x) + abs(S[j]-T[k]))
            ans = min(ans, abs(T[j]-x) + abs(T[j]-S[k]))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
a,b,q=[int(it) for it in input().split()]
dummy=10**20
s=[-dummy] + [int(input()) for it in range(a)] + [dummy]
t=[-dummy] + [int(input()) for it in range(b)] + [dummy]
x=[int(input()) for it in range(q)]

def find_left(l, p):
    a,b=0,len(l)-1
    while True:
        c=(a+b)//2
        if p <= l[c]:
            b = c-1
        elif l[c+1] <= p:
            a = c+1
        else:
            return c
def find_right(l, p):
    a,b=0,len(l)-1
    while True:
        c=(a+b)//2
        if p <= l[c-1]:
            b = c-1
        elif l[c] <= p:
            a = c+1
        else:
            return c
for xi in x:
    s_w = s[find_left(s, xi)]
    s_e = s[find_right(s, xi)]
    t_w = t[find_left(t, xi)]
    t_e = t[find_right(t, xi)]

    d = min(
        abs(xi - s_w) + abs(s_w - t_w),
        abs(xi - s_e) + abs(s_e - t_w),
        abs(xi - s_w) + abs(s_w - t_e),
        abs(xi - s_e) + abs(s_e - t_e),
        abs(xi - t_w) + abs(t_w - s_w),
        abs(xi - t_e) + abs(t_e - s_w),
        abs(xi - t_w) + abs(t_w - s_e),
        abs(xi - t_e) + abs(t_e - s_e)
    )
    print(d)

Submission status: Time Limit Exceeded

Solution code:
a,b,q=[int(it) for it in input().split()]
dummy=10**20
s=[-dummy] + [int(input()) for it in range(a)] + [dummy]
t=[-dummy] + [int(input()) for it in range(b)] + [dummy]
x=[int(input()) for it in range(q)]

for xi in x:
    s_w = [it for it in s if it < xi][-1]
    s_e = [it for it in s if it > xi][0]
    t_w = [it for it in t if it < xi][-1]
    t_e = [it for it in t if it > xi][0]

    d = min(
        abs(xi - s_w) + abs(s_w - t_w),
        abs(xi - s_e) + abs(s_e - t_w),
        abs(xi - s_w) + abs(s_w - t_e),
        abs(xi - s_e) + abs(s_e - t_e),
        abs(xi - t_w) + abs(t_w - s_w),
        abs(xi - t_e) + abs(t_e - s_w),
        abs(xi - t_w) + abs(t_w - s_e),
        abs(xi - t_e) + abs(t_e - s_e)
    )
    print(d)

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)]
INF = 10**12

def binary_search(query, arr):
    arr = [-INF] + arr + [INF]
    low = 0
    high = len(arr)
    while high-low>1:
        mid = (low+high)//2
        if query>arr[mid]:
            low = mid
        else:
            high = mid
    return arr[low], arr[high]

def main():
    for x in X:
        s1, s2 = binary_search(x, S)
        t1, t2 = binary_search(x, T)
        ans = [ abs(t-s)+min(abs(t-x), abs(s-x)) \
            for t in [t1, t2] for s in [s1, s2] ]
        print(min(ans))
    return

main()

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)]
INF = 10**12

def binary_search(query, arr):
    arr = [-INF] + arr + [INF]
    low = 0
    high = len(arr)
    while high-low>1:
        mid = (low+high)//2
        if query>arr[mid]:
            low = mid
        else:
            high = mid
    return arr[low], arr[high]

def main():
    for x in X:
        s1, s2 = binary_search(x, S)
        t1, t2 = binary_search(x, T)
        ans = INF
        ans = [ min(ans, abs(t-s)+min(abs(t-x), abs(s-x)))\
            for t in [t1, t2] for s in [s1, s2] ]
        print(min(ans))
    return

main()

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)]
INF = 10**12

def binary_search(query, arr):
    arr = [-INF] + arr + [INF]
    low = 0
    high = len(arr)
    while high-low>1:
        mid = (low+high)//2
        if query>arr[mid]:
            low = mid
        else:
            high = mid
    return arr[low], arr[high]

def main():
    for x in X:
        s1, s2 = binary_search(x, S)
        t1, t2 = binary_search(x, T)
        ans = INF
        for s in [s1, s2]:
            for t in [t1, t2]:
                ans = min(ans, abs(t-s)+min(abs(t-x), abs(s-x)))
        print(ans)
    return

main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
A, B, Q = map(int, input().split())
s = np.array([-10**10 - 1, -10**10] + [int(input()) for _ in range(A)] + [2*10**10])
t = np.array([-10**10 - 1, -10**10] + [int(input()) for _ in range(B)] + [2*10**10])
x = [int(input()) for _ in range(Q)]


def func(c, d, z):
    i = np.searchsorted(c, z)
    j1 = np.searchsorted(d, c[i - 1])
    j2 = np.searchsorted(d, c[i])
    return min(z - d[j1 - 1], z - c[i - 1] * 2 + d[j1], d[j2] - z, c[i] * 2 - z - d[j2 - 1])


for z in x:
    print(min(func(s, t, z), func(t, s, z)))

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()))
x = []
for i in range(Q):
    x.append(int(input()))

for i in range(Q):
    sx, tx, sy, ty = [], [], [], []
    for j in s:
        sx.append(abs(j - x[i]))
    for j in t:
        tx.append(abs(j - x[i]))
    sxi = sx.index(min(sx))
    txi = tx.index(min(tx))
    for j in t:
        ty.append(abs(j - s[sxi]))
    for j in s:
        sy.append(abs(j - t[txi]))
    a = min(sx) + min(ty)
    b = min(tx) + min(sy)
    if a < b:
        print(str(a))
    else:
        print(str(b))

Submission status: Time Limit Exceeded

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

for i in range(Q):
    sx, tx, sy, ty = [], [], [], []
    for j in s:
        sx.append(abs(j - x[i]))
    for j in t:
        tx.append(abs(j - x[i]))
    sxi = sx.index(min(sx))
    txi = tx.index(min(tx))
    for j in t:
        ty.append(abs(j - s[sxi]))
    for j in s:
        sy.append(abs(j - t[txi]))
    a = min(sx) + min(ty)
    b = min(tx) + min(sy)
    if a < b:
        print(str(a))
    else:
        print(str(b))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
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)]
s=np.array(s)
t=np.array(t)
x=np.array(x)
for X in x:
    l1=min(abs(X-t))
    if -l1 in X-t:
        l1=-l1
    l2=min(abs(X-s))
    if -l2 in X-s:
        l2=-l2
    print(min(abs(l1)+min(abs(X-l1-s)),abs(l2)+min(abs(X-l2-t))))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
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)]
s=np.array(s)
t=np.array(t)
x=np.array(x)
for X in x:
    l1=min(abs(X-t))
    if -l1 in X-t:
        l1=-l1
    l2=min(abs(X-s))
    if -l2 in X-s:
        l2=-l2
    print(min(min(abs(X-t))+min(abs(X-l1-s)),min(abs(X-s))+min(abs(X-l2-t))))

Submission status: Time Limit Exceeded

Solution code:
def nibun(x,s,N):
    l=0
    r=N-1
    while r!=l+1:
        c=(l+r)//2
        if s[c]>x:
            r=c
        elif s[c]<x:
            l=c
        else:
            return c
    if (s[r]-x)>(x-s[l]):
        return l
    return r
import numpy as np
A,B,Q=map(int,input().split())
s=[0 for i in range(A)]
t=[0 for i in range(B)]
x=[0 for i in range(Q)]
s=np.array(s)
t=np.array(t)
x=np.array(x)
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())

for X in x:
    l1=abs(X-t[nibun(X,t,B)])
    if -l1 in X-t:
        l1=-l1
    l2=abs(X-s[nibun(X,s,A)])
    if -l2 in X-s:
        l2=-l2
    print(min(abs(l1)+abs(X-l1-s[nibun(X-l1,s,A)]),abs(l2)+abs(X-l2-t[nibun(X-l2,t,B)])))

Submission status: Time Limit Exceeded

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

for i in range(Q):
    sx, tx, sy, ty = [], [], [], []
    for j in range(A):
        sx.append(abs(s[j] - x[i]))
    for j in range(B):
        tx.append(abs(t[j] - x[i]))
    sxi = sx.index(min(sx))
    txi = tx.index(min(tx))
    for j in range(B):
        ty.append(abs(t[j] - s[sxi]))
    for j in range(A):
        sy.append(abs(s[j] - t[txi]))
    a = min(sx) + min(ty)
    b = min(tx) + min(sy)
    if a < b:
        print(str(a))
    else:
        print(str(b))

Submission status: Time Limit Exceeded

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


def searchindex(p, z):
    for i, d in enumerate(p):
        if d > z:
            return i - 1


def func(c, d, z):
    i = searchindex(c, z)
    j1 = searchindex(d, c[i])
    j2 = searchindex(d, c[i + 1])
    return min(z - d[j1], z - c[i] * 2 + d[j1 + 1], d[j2 + 1] - z, c[i + 1] * 2 - z - d[j2])


for z in x:
    print(min(func(s, t, z), func(t, s, z)))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
A,B,Q=map(int,input().split())
s=[0 for i in range(A)]
t=[0 for i in range(B)]
x=[0 for i in range(Q)]
s=np.array(s)
t=np.array(t)
x=np.array(x)
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())
for X in x:
    l1=min(abs(X-t))
    if -l1 in X-t:
        l1=-l1
    l2=min(abs(X-s))
    if -l2 in X-s:
        l2=-l2
    print(min(min(abs(X-t))+min(abs(X-l1-s)),min(abs(X-s))+min(abs(X-l2-t))))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-

def main():
  N_a, N_b, N_q = map(int, input().strip().split(' '))
  As = list(map(int, [input().strip() for _ in range(N_a)]))
  Bs = list(map(int, [input().strip() for _ in range(N_b)]))
  Qs = list(map(int, [input().strip() for _ in range(N_q)]))

  for q in Qs:
    min_a_l = -(2*(10**10)+1)
    min_b_l = -(2*(10**10)+1)
    min_a_r = 2*(10**10)+1
    min_b_r = 2*(10**10)+1
    i = 0
    for a in As:
      da = a - q
      if da < 0:
        i += 1
      elif da > 0:
        min_a_r = da
        if i-1>=0:
          min_a_l = As[i-1] - q
        break
    if i == len(As):
      min_a_l = As[-1] - q


    i = 0
    for b in Bs:
      db = b - q
      if db < 0:
        i += 1
      elif db > 0:
        min_b_r = db
        if i-1>=0:
          min_b_l = Bs[i-1] - q
        break
    if i == len(Bs):
      min_b_l = Bs[-1] - q

    score = min([
      min_a_r if min_a_r > min_b_r else min_b_r,
      abs(min_a_l) if min_a_l < min_b_l else abs(min_b_l),
      2*min_a_r + abs(min_b_l) if min_a_r < abs(min_b_l) else min_a_r + 2*abs(min_b_l),
      2*abs(min_a_l) + abs(min_b_r) if abs(min_a_l) < abs(min_b_r) else abs(min_a_l) + 2*abs(min_b_r)])
    print(score)

  pass

if __name__=='__main__':
  main()

Submission status: Time Limit Exceeded

Solution code:
def check(startA, startB, S, T, a, b):
  pat1 = float("inf")
  if startA >= 0:
    pat1 = x - S[startA]
    if startB >= 0 and S[startA] > T[startB]:
      if startB != b - 1:
        pat1 += min(S[startA] - T[startB], T[startB + 1] - S[startA])
      else:
        pat1 += S[startA] - T[startB]
    elif startB == -1 and S[startA] < T[0]:
      pat1 += T[0] - S[startA]
  pat2 = float("inf")
  if startA != a - 1:
    pat2 = S[startA + 1] - x
    if startB != b - 1 and S[startA + 1] < T[startB + 1]:
      if startB != -1:
        pat2 += min(T[startB + 1] - S[startA + 1], S[startA + 1] - T[startB])
      else:
        pat2 += T[startB + 1] - S[startA + 1]
    elif startB == b - 1 and S[startA + 1] > T[b - 1]:
      pat2 +=  S[startA + 1] - T[b - 1]
  return min(pat1, pat2)
  
a, b, q = map(int, input().split())
S = [int(input()) for _ in range(a)]
T = [int(input()) for _ in range(b)]
X = [int(input()) for _ in range(q)]

for x in X:
  startA = -1
  for i in range(a):
    if x - S[i] > 0:
      startA = i
  startB = -1
  for i in range(b):
    if x - T[i] > 0:
      startB = i
  
  print(min(check(startA, startB, S, T, a, b), check(startB, startA, T, S, b, a)))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import numpy as np
INF = 10 ** 12

A, B, Q = list(map(int, input().split()))
S, T, X = [-INF], [-INF], []
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(INF)
T.append(INF)
S = np.array(S)
T = np.array(T)

for x in X:
    ans = INF
    sr = np.searchsorted(S, x)
    tr = np.searchsorted(T, x)
    for s in S[sr-1: sr+1]:
        for t in T[tr-1: tr+1]:
            ans = min(ans, abs(s-x) + abs(s-t), abs(t-x) + abs(s-t))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
INF = 10**18
A = 0
B = 0
A, B, Q = [int(s) for s in input().split()]

s = [-INF] + [int(input()) for _ in range(A)] + [INF]
t = [-INF] + [int(input()) for _ in range(B)] + [INF]


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


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

    sr = bisect_right(s, q)

    tr = bisect_right(t, q)

    res = INF
    for _s in s[sr-1:sr+1]:
        for _t in t[tr-1:tr+1]:
            res = min(res, abs(q-_s) + abs(_t-_s), abs(q-_t)+abs(_t-_s))

    print(res)

Submission status: Time Limit Exceeded

Solution code:
import bisect
a,b,q = map(int,input().split())
s = [int(input()) for _ in range(a)]
t = [int(input()) for _ in range(b)]

for i in range(q):
    x = int(input())
    xs = bisect.bisect(s,x)
    xt = bisect.bisect(t,x)
   
    ds = []
    if 0 < xs < a:
        ds.append([s[xs-1],abs(x-s[xs-1])])
        ds.append([s[xs],abs(x-s[xs])])
    elif xs == a:
        ds.append([s[xs-1],abs(x-s[xs-1])])
    else:
        ds.append([s[xs],abs(x-s[xs])])
    
    dt = []
    if 0 < xt < b:
        dt.append([t[xt-1],abs(x-t[xt-1])])
        dt.append([t[xt],abs(x-t[xt])])
    elif xt == b:
        dt.append([t[xt-1],abs(x-t[xt-1])])
    else:
        dt.append([t[xt],abs(x-t[xt])])

    ans = []
    for j in range(len(ds)):
        for k in range(len(dt)):
            ans.append(ds[j][1] + abs(dt[k][0]-ds[j][0]))
            
    for j in range(len(dt)):
        for k in range(len(ds)):
            ans.append(dt[j][1] + abs(ds[k][0]-dt[j][0]))
    print(min(ans))

Submission status: Time Limit Exceeded

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

(A,B,Q) = map(int,input().split())
inf = 10**12
s = np.empty(A+2,dtype=np.int64)
t = np.empty(B+2,dtype=np.int64)
s[0] = -inf
t[0] = -inf
s[A+1] = inf
t[B+1] = inf

for i in range(A):
    s[i+1] = np.int64(input())
for i in range(B):
    t[i+1] = np.int64(input())

for i in range(Q):
    x = np.int64(input())
    p = bisect.bisect_left(s,x)
    q = bisect.bisect_left(t,x)
    ans = min(max(s[p]-x,t[q]-x),
              max(x-s[p-1],x-t[q-1]),
                  (s[p]-x)*2 + (x-t[q-1]),
                  (s[p]-x) + (x-t[q-1])*2,
                  (t[q]-x)*2 + (x-s[p-1]),
                  (t[q]-x) + (x-s[p-1])*2)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import bisect

(A,B,Q) = map(int,input().split())
inf = 10**12
s = np.empty(A+2,dtype=np.int64)
t = np.empty(B+2,dtype=np.int64)
s[0] = -inf
t[0] = -inf
s[A+1] = inf
t[B+1] = inf

for i in range(A):
    s[i+1] = int(input())
for i in range(B):
    t[i+1] = int(input())

for _ in range(Q):
    x = int(input())
    p = bisect.bisect_left(s,x)
    q = bisect.bisect_left(t,x)
    spx = s[p] - x
    tqx = t[q] - x
    xtq1 = x - t[q-1]
    xsp1 = x - s[p-1]
    ans = min(max(spx, tqx),
              max(xsp1, xtq1),
                  spx*2 + xtq1,
                  spx + xtq1*2,
                  tqx*2 + xsp1,
                  t[q]-x + xsp1*2)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
A,B,Q=map(int,input().split())
S=[-int(1e10)]+[int(input()) for _ in range(A)]+[int(2e10)]
T=[-int(1e10)]+[int(input()) for _ in range(B)]+[int(2e10)]
for _ in range(Q):
    x=int(input())
    seq=False
    teq=False
    su=A+1
    sl=0
    while su-sl>1:
        t=(su+sl)//2
        if S[t]==x:
            seq=True
            break
        if S[t]>x: su=t
        else: sl=t
    tu=B+1
    tl=0
    while tu-tl>1:
        t=(tu+tl)//2
        if T[t]==x:
            teq=True
            break
        if T[t]>x: tu=t
        else: tl=t
    
    if seq and teq:
        print(0)
    elif seq:
        print(min(x-T[tl],T[tu]-x))
    elif teq:
        print(min(x-S[sl],S[su]-x))
    else:
        SU=S[su]-x
        TU=T[tu]-x
        SL=x-S[sl]
        TL=x-T[tl]
        print(min([max(SU,TU), max(SL,TL), SU*2+TL, TL*2+SU, TU*2+SL, SL*2+TU]))

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import bisect
import copy
A,B,Q = map(int,input().split())
S = []
T = []
X = []
for a in range(A):
    S.append(int(input()))
for b in range(B):
    T.append(int(input()))
for q in range(Q):
    X.append(int(input()))

#print (S,T,X)

def find_nearest(arr, point):
    #print (point)
    array = copy.deepcopy(arr)
    #print ("p",point)
    array.insert(0,-1*(10**12))
    array.append(10**12)
    abs_diff = 10 ** 12
    left_idx = bisect.bisect_left(array,point)
    target = [left_idx]
    if left_idx < len(array)-1:
        target.append(left_idx+1) 
    #print (array,target)
    for t in target:    
        diff = array[t-1] - point
        temp = abs(diff)
        if abs_diff > temp:
            min_diff = diff
            abs_diff = temp
            
        
    return min_diff

def calc(first, second,point):
    score = 0
    md = find_nearest(first,point)
    #print("m",md)
    score += abs(md)
    point += md
    md = find_nearest(second,point)
    score += abs(md)
    #print ("m",md)
    #print (score)
    return score

for x in X:
    print (min(calc(S,T,x),calc(T,S,x)))
    #break

Submission status: Time Limit Exceeded

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

s.sort()
t.sort()

def near(x, buildings):
    left, right = 0, len(buildings) - 1

    while right - left > 1:
        center = (left + right) // 2
        value = buildings[center]
        if x < value:
            right = center
        elif x > value:
            left = center
        else:
            return center
    return left if abs(x - buildings[left]) < abs(x - buildings[right]) else right


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

    si = near(x, s)
    spos = [si, si + 1] if s[si] < x else [si, si - 1]
    ti = near(x, t)
    tpos = [ti, ti + 1] if t[ti] < x else [ti, ti - 1]

    result = float("inf")
    for sindex in spos:
        for tindex in tpos:
            v1 = abs(x - s[sindex]) + abs(s[sindex] - t[tindex])
            v2 = abs(x - t[tindex]) + abs(t[tindex] - s[sindex])
            result = min(
                float("inf") if math.isnan(v1) else v1,
                float("inf") if math.isnan(v2) else v2,
                result
            )

    print(result)

Submission status: Time Limit Exceeded

Solution code:
data = input().split()  
an = int(data[0])
bn = int(data[1])
qn = int(data[2])

a = [-10000000000000]
for i in range(an):
    a.append(int(input()))
a.append(10000000000000)
b = [-10000000000000]
for i in range(bn):
    b.append(int(input()))
b.append(10000000000000)
q = []
for i in range(qn):
    q.append(int(input()))
#print(a, b, q)

def near(lis, po):
    dif = list(map(lambda x: abs(x-po), lis))
    #print(dif)
    ind = dif.index(min(dif))
    res=lis[ind]-po
    #print(ind , res)
    if(res < 0):
        return lis[ind], lis[ind+1]
    else:
        return lis[ind-1], lis[ind]

for s in q:
    start = int(s)
    al =near(a, start)
    bl =near(b, start)
    r = []
    for ae in al:
        for be in bl:
            tmp=abs(start-ae)+abs(ae-be)
            r.append(tmp)
    for be in bl:
        for ae in al:
            tmp=abs(start-be)+abs(ae-be)
            r.append(tmp)
    print(min(r))

Submission status: Time Limit Exceeded

Solution code:
a,b,q = map(int,input().split())
A = [int(input()) for i in range(a)]
B = [int(input()) for i in range(b)]
Q = [int(input()) for i in range(q)]
P = [[a,abs(a-b)] for a in A for b in B] + [[b,abs(a-b)] for a in A for b in B]
for x in Q:
  print(min([abs(x - p[0]) + p[1] for p in P]))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
# -*- coding:utf-8 -*-

def main():
  N_a, N_b, N_q = map(int, input().strip().split(' '))
  As = list(map(int, [input().strip() for _ in range(N_a)]))
  Bs = list(map(int, [input().strip() for _ in range(N_b)]))
  Qs = list(map(int, [input().strip() for _ in range(N_q)]))

  for q in Qs:
    min_a_l = -(2*(10**10)+1)
    min_b_l = -(2*(10**10)+1)
    min_a_r = 2*(10**10)+1
    min_b_r = 2*(10**10)+1
    for a in As:
      da = a - q
      if 0 <= da < min_a_r:
          min_a_r = da
          break
      if 0 > da >= min_a_l:
          min_a_l = da

    for b in Bs:
      db = b - q
      if 0<= db < min_b_r:
          min_b_r = db
          break
      if 0 > db >= min_b_l:
          min_b_l = db
    score = min([
      min_a_r if min_a_r > min_b_r else min_b_r,
      abs(min_a_l) if min_a_l < min_b_l else abs(min_b_l),
      2*min_a_r + abs(min_b_l) if min_a_r < abs(min_b_l) else min_a_r + 2*abs(min_b_l),
      2*abs(min_a_l) + abs(min_b_r) if abs(min_a_l) < abs(min_b_r) else abs(min_a_l) + 2*abs(min_b_r)])
    print(score)

  pass

if __name__=='__main__':
  main()

Submission status: Time Limit Exceeded

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

def distance(s,t,xi):
  s_ = s-xi
  s_m = s_[s_<=0].max()
  s_p = s_[s_>=0].min()
  t_ = t-xi
  t_m = t_[t_<=0].max()
  t_p = t_[t_>=0].min()
  
  return min(abs(min(s_m,t_m)),abs(t_p-s_m)+min(abs(t_p),abs(s_m))\
         ,abs(max(t_p,s_p)),abs(s_p-t_m)+min(abs(s_p),abs(s_p)))
 
for i in x:
  print(int(distance(s,t,i)))

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)]
INF = 10**12

def binary_search(query, arr):
    arr = [-INF] + arr + [INF]
    low = 0
    high = len(arr)
    t = (low+high)//2
    while low<high-1:
        if query>arr[t]:
            low = t
        else:
            high = t
        t = (low+high)//2
    return arr[low], arr[high]

def main():
    for x in X:
        s1, s2 = binary_search(x, S)
        t1, t2 = binary_search(x, T)
        ans = INF
        for s in [s1, s2]:
            for t in [t1, t2]:
                d1 = abs(t-x) + abs(s-t)
                d2 = abs(s-x) + abs(t-s)
                ans = min(ans, d1, d2)
        print(ans)
    return

main()