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:
def binary_search_ceiling(list, element):
    i = 0
    j = len(list) - 1
    if element < list[0]:
        return None
    elif element >= list[-1]:
        return len(list) - 1
    while i <= j:
        k = (i + j) // 2
        if list[0] == element:  # k - 1が0にならないので特例
            return 0
        elif list[k - 1] < element <= list[k]:
            return k
        elif list[k] < element < list[k + 1]:
            return k + 1
        elif list[k] < element:
            i = k  # elementがk番とk+1番の間にあるかもしれないのでi = k + 1 ではなくi = k
        else:
            j = k  # 上と同様に考えてj = k

    return None


def main():
    A, B, Q = map(int, input().split())
    INF = 10 ** 11
    s_list = [-2 * INF, -INF] + [int(input()) for i in range(A)] + [INF, 2 * INF]
    t_list = [-2 * INF, -INF] + [int(input()) for i in range(B)] + [INF, 2 * INF]
    x_list = [int(input()) for i in range(Q)]

    for xi in x_list:
        ind_s = binary_search_ceiling(s_list, xi)
        ws = s_list[ind_s - 1]
        es = s_list[ind_s]

        ind_t = binary_search_ceiling(t_list, xi)
        wt = t_list[ind_t - 1]
        et = t_list[ind_t]

        dist = min(
                     xi - min(ws, wt),
                     max(es, et) - xi,
                     xi + es - wt * 2,
                     xi + et - ws * 2,
                     (es * 2) - wt - xi,
                     (et * 2) - ws - xi
                     )

        print(dist)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def binary_search_ceiling(list, element):
    i = 0
    j = len(list) - 1
    if element < list[0]:
        return None
    elif element >= list[-1]:
        return len(list) - 1
    while i <= j:
        k = (i + j) // 2
        if list[0] == element:  # k - 1が0にならないので特例
            return 0
        elif list[k - 1] < element <= list[k]:
            return k
        elif list[k] < element < list[k + 1]:
            return k + 1
        elif list[k] < element:
            i = k  # elementがk番とk+1番の間にあるかもしれないのでi = k + 1 ではなくi = k
        else:
            j = k  # 上と同様に考えてj = k

    return None


def main():
    A, B, Q = map(int, input().split())
    INF = 10 ** 11
    s_list = [-2 * INF, -INF] + [int(input()) for i in range(A)] + [INF, 2 * INF]
    t_list = [-2 * INF, -INF] + [int(input()) for i in range(B)] + [INF, 2 * INF]
    x_list = [int(input()) for i in range(Q)]

    for xi in x_list:
        ind_s = binary_search_ceiling(s_list, xi)
        ws = s_list[ind_s - 1]
        es = s_list[ind_s]

        ind_t = binary_search_ceiling(t_list, xi)
        wt = t_list[ind_t - 1]
        et = t_list[ind_t]

        dist_list = [
                     xi - min(ws, wt),
                     max(es, et) - xi,
                     xi + es - wt * 2,
                     xi + et - ws * 2,
                     (es * 2) - wt - xi,
                     (et * 2) - ws - xi
                     ]

        print(min(dist_list))


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
def binary_search_ceiling(list, element):
    i = 0
    j = len(list) - 1
    if element < list[0]:
        return None
    elif element >= list[-1]:
        return len(list) - 1
    while i <= j:
        k = (i + j) // 2
        if list[0] == element:  # k - 1が0にならないので特例
            return 0
        elif list[k - 1] < element <= list[k]:
            return k
        elif list[k] < element < list[k + 1]:
            return k + 1
        elif list[k] < element:
            i = k  # elementがk番とk+1番の間にあるかもしれないのでi = k + 1 ではなくi = k
        else:
            j = k  # 上と同様に考えてj = k

    return None


def main():
    A, B, Q = map(int, input().split())
    INF = 10 ** 11
    s_list = [-2 * INF, -INF] + [int(input()) for i in range(A)] + [INF, 2 * INF]
    t_list = [-2 * INF, -INF] + [int(input()) for i in range(B)] + [INF, 2 * INF]
    x_list = [int(input()) for i in range(Q)]

    for xi in x_list:
        dist_list = [INF for i in range(8)]

        ind_s = binary_search_ceiling(s_list, xi)
        ws = s_list[ind_s - 1]
        dist_list[0] = dist_list[1] = abs(ws - xi)
        es = s_list[ind_s]
        dist_list[2] = dist_list[3] = abs(es - xi)

        ind_t = binary_search_ceiling(t_list, xi)
        wt = t_list[ind_t - 1]
        dist_list[4] = dist_list[5] = abs(wt - xi)
        et = t_list[ind_t]
        dist_list[6] = dist_list[7] = abs(et - xi)

        ws_ind_t = binary_search_ceiling(t_list, ws)
        wswt = t_list[ws_ind_t - 1]
        dist_list[0] += abs(wswt - ws)
        wset = t_list[ws_ind_t]
        dist_list[1] += abs(wset - ws)

        es_ind_t = binary_search_ceiling(t_list, es)
        eswt = t_list[es_ind_t - 1]
        dist_list[2] += abs(eswt - es)
        eset = t_list[es_ind_t]
        dist_list[3] += abs(eset - es)

        wt_ind_s = binary_search_ceiling(s_list, wt)
        wtws = s_list[wt_ind_s - 1]
        dist_list[4] += abs(wtws - wt)
        wtes = s_list[wt_ind_s]
        dist_list[5] += abs(wtes - wt)

        et_ind_s = binary_search_ceiling(s_list, et)
        etws = s_list[et_ind_s - 1]
        dist_list[6] += abs(etws - et)
        etes = s_list[et_ind_s]
        dist_list[7] += abs(etes - et)

        print(min(dist_list))


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
sn, tn, qn = map(int, input().split())

sa = []
ta = []
qa = []
for i in range(sn):
    sa.append(int(input()))
for i in range(tn):
    ta.append(int(input()))
for i in range(qn):
    qa.append(int(input()))


def find_nearest(q, al, s, e):
    while True:
        if e - s < 2:
            if al[s] == q:
                return [al[s], al[s]]
            if al[e] == q:
                return [al[e], al[e]]
            return [al[s], al[e]]
        idx = (e - s) // 2 + s
        if al[idx] == q:
            return [al[idx], al[idx]]
        if al[idx] > q:
            e = idx
        else:
            s = idx

def move_cost(q, al, bl):
    a1, a2 = find_nearest(q, al, 0, len(al) - 1)
    b1, b2 = find_nearest(q, bl, 0, len(bl) - 1)

    def calc(x1, x2, x3):
        y1 = min(x1, x2)
        y2 = max(x1, x2)
        if x3 >= y1 and x3 <= y2:
            return abs(x1 - x2)
        return abs(x1 - x2) + abs(x2 - x3)
    return min(
        calc(q, a1, b1),
        calc(q, a1, b2),
        calc(q, a2, b1),
        calc(q, a2, b2),
        calc(q, b1, a1),
        calc(q, b1, a2),
        calc(q, b2, a1),
        calc(q, b2, a2),
    )

for q in qa:
    print(move_cost(q, sa, ta))

Submission status: Time Limit Exceeded

Solution code:
sn, tn, qn = map(int, input().split())

sa = []
ta = []
qa = []
for i in range(sn):
    sa.append(int(input()))
for i in range(tn):
    ta.append(int(input()))
for i in range(qn):
    qa.append(int(input()))


def find_nearest(q, al, s, e):
    if e - s < 2:
        if al[s] == q:
            return [al[s], al[s]]
        if al[e] == q:
            return [al[e], al[e]]
        return [al[s], al[e]]
    idx = (e - s) // 2 + s
    if al[idx] == q:
        return [al[idx], al[idx]]
    if al[idx] > q:
        return find_nearest(q, al, s, idx)
    return find_nearest(q, al, idx, e)

def move_cost(q, al, bl):
    a1, a2 = find_nearest(q, al, 0, len(al) - 1)
    b1, b2 = find_nearest(q, bl, 0, len(bl) - 1)

    def calc(x1, x2, x3):
        y1 = min(x1, x2)
        y2 = max(x1, x2)
        if x3 >= y1 and x3 <= y2:
            return abs(x1 - x2)
        return abs(x1 - x2) + abs(x2 - x3)
    return min(
        calc(q, a1, b1),
        calc(q, a1, b2),
        calc(q, a2, b1),
        calc(q, a2, b2),
        calc(q, b1, a1),
        calc(q, b1, a2),
        calc(q, b2, a1),
        calc(q, b2, a2),
    )

for q in qa:
    print(move_cost(q, sa, ta))

Submission status: Time Limit Exceeded

Solution code:
sn, tn, qn = map(int, input().split())

sa = []
ta = []
qa = []
for i in range(sn):
    sa.append(int(input()))
for i in range(tn):
    ta.append(int(input()))
for i in range(qn):
    qa.append(int(input()))


def move_cost(q, al, bl):
    md = abs(q - al[0])
    mx = al[0]
    for a in al:
        d = abs(q - a)
        if d < md:
            md = d
            mx = a
    x1 = min(q, mx)
    x2 = max(q, mx)

    md2 = abs(mx - bl[0])
    mx2 = bl[0]
    for b in bl:
        if b >= x1 and b <= x2:
            return abs(q - mx)
        d = abs(mx - b)
        if d < md2:
            md2 = d
            mx2 = b
    return abs(q - mx) + abs(mx2 - mx)

for q in qa:
    a1 = move_cost(q, sa, ta)
    a2 = move_cost(q, ta, sa)
    print(min(a1, a2))

Submission status: Time Limit Exceeded

Solution code:
import bisect
inf = 10**18
A,B,Q = map(int,input().split(' '))
ss = [-inf] + sorted([int(input()) for i in range(1,A+1)]) + [inf]
ts = [-inf] + sorted([int(input()) for i in range(A+1,A+B+1)]) + [inf]

def f0(A,x):
  i = bisect.bisect_left(A, x)
  return i, i-1
def f1(A,B,x):
  a = f0(A,x)
  bs = [f0(B,A[i]) for i in a]
  return min([abs(A[i]-x) + abs(A[i]-B[j]) 
              for ix, i in enumerate(a) 
              for j in bs[ix]]) 

for i in range(A+B+1,A+B+Q+1):
  x = int(input())
  print(min(f1(ss,ts,x),f1(ts,ss,x)))

Submission status: Time Limit Exceeded

Solution code:
import bisect

A,B,Q = map(int,input().split(' '))
ss = sorted([int(input()) for i in range(1,A+1)])
ts = sorted([int(input()) for i in range(A+1,A+B+1)])
xs = [int(input()) for i in range(A+B+1,A+B+Q+1)]

def f0(A,x):
  i = bisect.bisect_left(A, x)
  return [x for x in [i, i-1] if 0<=x<len(A)]
def f1(A,B,x):
  a = f0(A,x)
  bs = [f0(B,A[i]) for i in a]
  return min([abs(A[i]-x) + abs(A[i]-B[j]) 
              for ix, i in enumerate(a) 
              for j in bs[ix]])
def f2(x):
  return min(f1(ss,ts,x),f1(ts,ss,x))
for x in xs:
  print(f2(x))

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_right
INF = float('inf')

a, b, q = map(int, input().split(' '))
s, t, x = [], [], []
for i in range(a):
  s.append(int(input()))
for i in range(b):
  t.append(int(input()))
for i in range(q):
  x.append(int(input()))
  
def func(lis, val):
  li = [-INF] + lis + [INF]
  j = bisect_right(li, val)
  return li[j-1], li[j]
 
for i in range(q):
  sl, sh = func(s, x[i])
  tl, th = func(t, x[i])
  a1 = abs(sl - x[i]) + abs(tl - sl)
  a2 = abs(sl - x[i]) + abs(th - sl)
  b1 = abs(sh - x[i]) + abs(tl - sh)
  b2 = abs(sh - x[i]) + abs(th - sh)
  c1 = abs(tl - x[i]) + abs(sl - tl)
  c2 = abs(tl - x[i]) + abs(sh - tl)
  d1 = abs(th - x[i]) + abs(sl - th)
  d2 = abs(th - x[i]) + abs(sh - th)
  j = min(a1, a2, b1, b2, c1, c2, d1, d2)
  print(j)

Submission status: Time Limit Exceeded

Solution code:
a, b, q = map(int, input().split(' '))
s, t, x = [], [], []
for i in range(a):
  s.append(int(input()))
for i in range(b):
  t.append(int(input()))
for i in range(q):
  x.append(int(input()))
  
def func(lis, val):
  l, h = 0, 0
  if val < lis[0]:
    l, h = -10**10, lis[0]
  elif val >= lis[-1]:
    l, h = lis[-1], -10**10
  else:
    l = next(filter(lambda w: w < val, reversed(lis)))
    h = next(filter(lambda w: w >= val, lis))
  return l, h
 
for i in range(q):
  sl, sh = func(s, x[i])
  tl_sl, th_sl = func(t, sl)
  tl_sh, th_sh = func(t, sh)
  tl, th = func(t, x[i])
  sl_tl, sh_tl = func(s, tl)
  sl_th, sh_th = func(s, th)
  a1 = abs(sl - x[i]) + abs(tl_sl - sl)
  a2 = abs(sl - x[i]) + abs(th_sl - sl)
  b1 = abs(sh - x[i]) + abs(tl_sh - sh)
  b2 = abs(sh - x[i]) + abs(th_sh - sh)
  c1 = abs(tl - x[i]) + abs(sl_tl - tl)
  c2 = abs(tl - x[i]) + abs(sh_tl - tl)
  d1 = abs(th - x[i]) + abs(sl_th - th)
  d2 = abs(th - x[i]) + abs(sh_th - th)
  j = min(a1, a2, b1, b2, c1, c2, d1, d2)
  print(j)

Submission status: Time Limit Exceeded

Solution code:
a, b, q = map(int, input().split(' '))
s, t, x = [], [], []
for i in range(a):
  s.append(int(input()))
for i in range(b):
  t.append(int(input()))
for i in range(q):
  x.append(int(input()))
  
def func(lis, val):
  l, h = 0, 0
  if val < lis[0]:
    l, h = -10**10, lis[0]
  elif val >= lis[-1]:
    l, h = lis[-1], -10**10
  else:
    l = list(filter(lambda w: w < val, lis))[-1]
    h = list(filter(lambda w: w > val, lis))[0]
  return l, h
 
for i in range(q):
  sl, sh = func(s, x[i])
  tl_sl, th_sl = func(t, sl)
  tl_sh, th_sh = func(t, sh)
  tl, th = func(t, x[i])
  sl_tl, sh_tl = func(s, tl)
  sl_th, sh_th = func(s, th)
  a1 = abs(sl - x[i]) + abs(tl_sl - sl)
  a2 = abs(sl - x[i]) + abs(th_sl - sl)
  b1 = abs(sh - x[i]) + abs(tl_sh - sh)
  b2 = abs(sh - x[i]) + abs(th_sh - sh)
  c1 = abs(tl - x[i]) + abs(sl_tl - tl)
  c2 = abs(tl - x[i]) + abs(sh_tl - tl)
  d1 = abs(th - x[i]) + abs(sl_th - th)
  d2 = abs(th - x[i]) + abs(sh_th - th)
  j = min(a1, a2, b1, b2, c1, c2, d1, d2)
  print(j)

Submission status: Time Limit Exceeded

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

shrine = list()
temple = list()

for i in range(A):
    shrine.append(int(input()))

for j in range(B):
    temple.append(int(input()))
    
for k in range(Q):
    start = int(input())
    min_root = 100000000000000
    
    for i in range(A):
        interim_root = abs(start - shrine[i])
        for j in range(B):
            total_root = interim_root + abs(shrine[i]-temple[j])
            if total_root < min_root:
                min_root = total_root
                
    for j in range(B):
        interim_root = abs(start - temple[j])
        for i in range(A):
            total_root = interim_root + abs(temple[j] - shrine[i])
            if total_root < min_root:
                min_root = total_root
    print(min_root)

Submission status: Time Limit Exceeded

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

shrine = list()
temple = list()
flag = 0

for i in range(A):
    shrine.append(int(input()))

for j in range(B):
    temple.append(int(input()))
    
for k in range(Q):
    start = int(input())
    min_root = 100000000000000
    
    for i in range(A):
        interim_root = abs(start - shrine[i])
        #print(interim_root)
        for j in range(B):
            total_root = interim_root + abs(shrine[i]-temple[j])
            #print("shrine_s",total_root)
            if total_root < min_root or flag == 0:
                min_root = total_root
                flag = 1
                
    for j in range(B):
        interim_root = abs(start - temple[j])
        #print(interim_root)
        for i in range(A):
            total_root = interim_root + abs(temple[j] - shrine[i])
            #print(temple[j]-shrine[i])
            #print("tem_s",total_root)
            if total_root < min_root:
                min_root = total_root
    print(min_root)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

A,B,Q = map(int,input().split())
sa = [int(input()) for i in range(A)]
tb = [int(input()) for i in range(B)]
xq = [int(input()) for i in range(Q)]

for x in xq:
    ans = 0
    near_s = sa[np.argmin([abs(s-x) for s in sa])]
    near_t = tb[np.argmin([abs(near_s-t) for t in tb])]
    ans += abs(near_s-x)+abs(near_t-near_s)
    
    ans2 = 0
    near_t_2 = tb[np.argmin([abs(t-x) for t in tb])]
    near_s_2 = sa[np.argmin([abs(near_t_2-s) for s in sa])]
    ans2 += abs(near_t_2-x) + abs(near_s_2 -near_t_2)
    print(min(ans,ans2))

Submission status: Time Limit Exceeded

Solution code:
a,b,q = map(int,input().split())
s = []
t = []
for i in range(a):
    k = int(input())
    s.append(k)
for i in range(b):
    k = int(input())
    t.append(k)


import bisect
import itertools
#sは配列,xは知りたい値
inf = 10**15
s = [-inf]+s+[inf]
t = [-inf]+t+[inf]
#最初と最後にinfをつけておく。

for i in range(q):
    x = int(input())
    asa = bisect.bisect_left(s,x)-1
    bs = bisect.bisect_left(t,x)-1
    s1,s2 = s[asa],s[asa+1]
    t1,t2 = t[bs],t[bs+1]
    ans = min(x-min(s1,t1),max(s2,t2)-x,
    s2-t1+min(s2-x,x-t1),
    t2-s1+min(t2-x,x-s1))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = list(map(int,input().split()))
s = []
t = []
x = []
for i in range(N[0]):
  s.append(int(input()))
for j in range(N[1]):
  t.append(int(input()))
for k in range(N[2]):
  x.append(int(input()))
for l in range(N[2]):
  w = []
  z = []
  q = []
  for m in range(N[0]):
    for n in range(N[1]):
      w.append(min(abs(x[l]-s[m]),abs(x[l]-t[n]))+abs(s[m]-t[n]))
    z.append(min(w))
  print(min(z))

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)]
for i in range(q):
    W = []
    Z = []
    ans = float("inf")
    x = int(input())
    for S in s:
        for T in t:
            W.append(min(abs(x - S), abs(x - T)) + abs(S - T))
        Z.append(min(W))
    print(min(Z))

Submission status: Time Limit Exceeded

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

def bi(arr, l, r, val):
    if r-l<=1:
        return l
    m = (l+r)//2
    if val < arr[m]:
        return bi(arr, l, m, val)
    else:
        return bi(arr, m, r, val)

import itertools
for _ in range(Q):
    pos = int(input())
    s_near_id = bi(s, 0, len(s), pos)
    t_near_id = bi(t, 0, len(t), pos)
    print(min( min(abs(pos-s_pos)+abs(s_pos-t_pos), abs(pos-t_pos)+abs(t_pos-s_pos)) for s_pos, t_pos in itertools.product(s[s_near_id:s_near_id+2],t[t_near_id:t_near_id+2]) ))

Submission status: Time Limit Exceeded

Solution code:

def get_near(tera_num, tera_data, start_point):
    tera_pre, tera_after = float('inf'), 0
    for i in range(tera_num):
        if tera_data[i] >= start_point:
            tera_after = tera_data[i]
            break
        tera_pre = tera_data[i]
    return tera_pre, tera_after

def calc_data(start_point, point_a, point_b, min_point):
    a = abs(start_point - point_a) + abs(point_a - point_b)
    b = abs(start_point - point_b) + abs(point_b - point_a)
    min_point = min(a, b, min_point)
    return min_point

def calc_ans(start_point, tera_pre, tera_after, jinja_pre, jinja_after):
    min_point = float('inf')
    min_point = calc_data(start_point, tera_pre, jinja_pre, min_point)
    min_point = calc_data(start_point, tera_pre, jinja_after, min_point)
    min_point = calc_data(start_point, tera_after, jinja_pre, min_point)
    min_point = calc_data(start_point, tera_after, jinja_after, min_point)
    return min_point


def start(tera_num, jinja_num, q_num, tera_data, jinja_data, q_data):
    for i in range(q_num):
        start_point = q_data[i]
        tera_pre, tera_after = get_near(tera_num, tera_data, start_point)
        jinja_pre, jinja_after = get_near(jinja_num, jinja_data, start_point)
        ans = calc_ans(start_point, tera_pre, tera_after, jinja_pre, jinja_after)
        print(ans)

def main():
    tera_num, jinja_num, q_num = list(map(int, input().split()))
    tera_data = [int(input()) for i in range(tera_num)]
    jinja_data = [int(input()) for i in range(jinja_num)]
    q_data = [int(input()) for i in range(q_num)]

    tera_data.sort()
    jinja_data.sort()

    start(tera_num, jinja_num, q_num, tera_data, jinja_data, q_data)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
ls = list(int(input()) for i in range(A))
lt = list(int(input()) for i in range(B))
lx = list(int(input()) for i in range(Q))

def go(x, list, N):
  clist = []
  for i in range(N):
    clist.append(abs(list[i] - x))
  return min(clist)

for x in lx:
  l = []
  for i in range(A):
    if x - ls[i] < 0:
      break
  if i:
    l.append(abs(ls[i-1]-x) + go(ls[i-1], lt, B))
  if i < A:
    l.append(abs(ls[i]-x) + go(ls[i], lt, B))
  for i in range(B):
    if x - lt[i] < 0:
      break
  if i:
    l.append(abs(x-lt[i-1]) + go(lt[i-1], ls, A))
  if i < B:
    l.append(abs(lt[i]-x) + go(lt[i], ls, A))
  print(min(l))

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
ls = list(int(input()) for i in range(A))
lt = list(int(input()) for i in range(B))
lx = list(int(input()) for i in range(Q))

def go(x, list, N):
  clist = list.copy()
  for i in range(N):
    clist[i] = abs(clist[i] - x)
  return min(clist)

for x in lx:
  l = []
  for i in range(A):
    if x - ls[i] < 0:
      break
  if i:
    l.append(abs(ls[i-1]-x) + go(ls[i-1], lt, B))
  if i < A:
    l.append(abs(ls[i]-x) + go(ls[i], lt, B))
  for i in range(B):
    if x - lt[i] < 0:
      break
  if i:
    l.append(abs(x-lt[i-1]) + go(lt[i-1], ls, A))
  if i < B:
    l.append(abs(lt[i]-x) + go(lt[i], ls, A))
  print(min(l))

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left

INF = float("inf")


def main():
    A, B, Q = map(int, input().split())
    S = [-INF] + [int(input()) for _ in range(A)] + [INF]
    T = [-INF] + [int(input()) for _ in range(B)] + [INF]
    for i in range(Q):
        x = int(input())
        l1 = bisect_left(S, x)
        l2 = bisect_left(T, x)
        tmp = INF
        for s in (S[l1-1], S[l1]):
            for t in (T[l2-1], T[l2]):
                tmp = min(tmp, abs(s-t) + abs(x-s))
                tmp = min(tmp, abs(s-t) + abs(x-t))
        print(tmp)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
inf = 10 ** 11

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

for i in range(Q):
    j = 1
    while S[j] < X[i]:
        j += 1

    s_low = S[j-1] - X[i]
    s_high = S[j] - X[i]

    j = 1
    while T[j] < X[i]:
        j += 1

    t_low = T[j-1] - X[i]
    t_high = T[j] - X[i]

    l_1 = max(abs(s_low), abs(t_low))
    l_2 = max(s_high, t_high)
    l_3 = 2 * min(abs(t_low), s_high) + max(abs(t_low), s_high)
    l_4 = 2 * min(abs(s_low), t_high) + max(abs(s_low), t_high)

    l = min(l_1, l_2, l_3, l_4)

    print(l)

Submission status: Time Limit Exceeded

Solution code:
def binsearch(left=-1, right=float("inf"), evaluate=lambda: True):
    while left + 1 < right:
        mid = (left + right) // 2
        if evaluate(mid):
            right = mid
        else:
            left = mid
    return left


def binsearch_arr(target, arr):
    return binsearch(evaluate=lambda x: target <= arr[x], left=-1, right=len(arr))


def main():
    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())
        l1 = binsearch_arr(x, S)
        l2 = binsearch_arr(x, T)
        tmp = float("inf")
        if l1 >= 0 and l2 >= 0:
            tmp = min(tmp, x - min(S[l1], T[l2]))
        if l1+1 < len(S) and l2 >= 0:
            tmp = min(tmp, S[l1+1] - T[l2] + min(S[l1+1]-x, x-T[l2]))
        if l1 >= 0 and l2+1 < len(T):
            tmp = min(tmp, T[l2+1] - S[l1] + min(T[l2+1]-x, x-S[l1]))
        if l1+1 < len(S) and l2+1 < len(T):
            tmp = min(tmp, max(S[l1+1], T[l2+1]) - x)
        print(tmp)


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
inf = 10 ** 11

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

for i in range(Q):

    s_low = max([s - X[i] for s in S if s - X[i] < 0])
    s_high = min([s - X[i] for s in S if s - X[i] > 0])
    t_low = max([t - X[i] for t in T if t - X[i] < 0])
    t_high = min([t - X[i] for t in T if t - X[i] > 0])

    l_1 = max(abs(s_low), abs(t_low))
    l_2 = max(s_high, t_high)
    l_3 = 2 * min(abs(t_low), s_high) + max(abs(t_low), s_high)
    l_4 = 2 * min(abs(s_low), t_high) + max(abs(s_low), t_high)

    l = min(l_1, l_2, l_3, l_4)

    print(l)

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import bisect

a, b, q = [int(x) for x in 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_que = deque(s)
s_que.appendleft(-10 ** 12)
s_que.append(10 ** 12)

t_que = deque(t)
t_que.appendleft(-10 ** 12)
t_que.append(10 ** 12)

for i in range(q):
    x = int(input())
    k = bisect.bisect_left(s_que, x)
    sb = s_que[k]
    sa = s_que[k-1]
    j = bisect.bisect_left(t_que, x)
    tb = t_que[j]
    ta = t_que[j-1]

    y = []
    for h in [sa, sb]:
        for g in [ta, tb]:
            y.append(abs(x-h) + abs(h-g))
    for h in [ta, tb]:
        for g in [sa, sb]:
            y.append(abs(x-h) + abs(h-g))

    print(min(y))

Submission status: Time Limit Exceeded

Solution code:
from collections import deque
import bisect

a, b, q = [int(x) for x in 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_que = deque(s)
s_que.appendleft(-10 ** 12)
s_que.append(10 ** 12)

t_que = deque(t)
t_que.appendleft(-10 ** 12)
t_que.append(10 ** 12)

for i in x:
    k = bisect.bisect_left(s_que, i)
    sb = s_que[k]
    sa = s_que[k-1]
    j = bisect.bisect_left(t_que, i)
    tb = t_que[j]
    ta = t_que[j-1]

    y = []
    for h in [sa, sb]:
        for g in [ta, tb]:
            y.append(abs(i-h) + abs(h-g))
    for h in [ta, tb]:
        for g in [sa, sb]:
            y.append(abs(i-h) + abs(h-g))

    print(min(y))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import bisect
INF = 10**15
def solve(a, b, q, s, t, x):
    for xi in x:
        sl = s[bisect.bisect_left(s, xi+1)-1]
        tl = t[bisect.bisect_left(t, xi+1)-1]
        sr = s[bisect.bisect_right(s, xi-1)]
        tr = t[bisect.bisect_right(t, xi-1)]
        ans = min([
            max(sr-xi, tr-xi),
            max(xi-sl, xi-tl),
            (sr-xi+sr-tl),
            (xi-tl+sr-tl),
            (tr-xi+tr-sl),
            (xi-sl+tr-sl)
        ])
        print(ans)

a, b, q = map(int, input().split())
s = np.asarray([int(input()) for i in range(a)] + [-INF, INF], dtype=int)
t = np.asarray([int(input()) for i in range(b)] + [-INF, INF], dtype=int)
x = np.asarray([int(input()) for i in range(q)], dtype=int)
s.sort()
t.sort()
solve(a,b,q,s,t,x)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
INF = 10**15
def f(s, x):
    n = len(s)
    lb = 0
    ub = n - 1
    prev = -1
    while True:
        cur = (lb+ub) // 2
        if s[cur] > x:
            ub = cur
        else:
            lb = cur
        if prev == cur:
            break
        prev = cur
    return cur-1 if (s[cur] > x) else cur

def g(s, x):
    n = len(s)
    lb = 0
    ub = n - 1
    prev = -1
    while True:
        cur = (lb+ub) // 2
        if s[cur] > x:
            ub = cur
        else:
            lb = cur
        if prev == cur:
            break
        prev = cur
    return cur+1 if (s[cur] < x) else cur

def solve(a, b, q, s, t, x):
    for xi in x:
        sl = s[f(s, xi)]
        tl = t[f(t, xi)]
        sr = s[g(s, xi)]
        tr = t[g(t, xi)]
        ans = min([
            max(sr-xi, tr-xi),
            max(xi-sl, xi-tl),
            (sr-xi+sr-tl),
            (xi-tl+sr-tl),
            (tr-xi+tr-sl),
            (xi-sl+tr-sl)
        ])
        print(ans)

a, b, q = map(int, input().split())
s = np.asarray([int(input()) for i in range(a)] + [-INF, INF], dtype=int)
t = np.asarray([int(input()) for i in range(b)] + [-INF, INF], dtype=int)
x = np.asarray([int(input()) for i in range(q)], dtype=int)
s.sort()
t.sort()
solve(a,b,q,s,t,x)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np


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


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

mp = 0
jinja = []
tera = []
start = []


for i in range(int(a)):
    j = int(input())
    jinja.append(j)
for i in range(int(b)):
    j = int(input())
    tera.append(j)
for i in range(int(qqq)):
    j = int(input())
    start.append(j)


for q in start:
    jinja_left = None
    jinja_right = None
    tera_left = None
    tera_right = None
    for j in jinja:
        if q > j:
            jinja_left = j
        elif jinja_right is None:
            jinja_right = j

    for t in tera:
        if q > t:
            tera_left = t
        elif tera_right is None:
            tera_right = t

    distance_list = []

    if jinja_left is not None:
        distance_list.append(get_nearest_value(tera, jinja_left) + abs(jinja_left - q))
    if jinja_right is not None:
        distance_list.append(get_nearest_value(tera, jinja_right) + abs(jinja_right - q))
    if tera_left is not None:
        distance_list.append(get_nearest_value(jinja, tera_left) + abs(tera_left - q))
    if tera_right is not None:
        distance_list.append(get_nearest_value(jinja, tera_right) + abs(tera_right - q))

    print(sorted(distance_list)[0])