Problem:


Score : 400 points

Problem Statement

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

Answer the following Q queries:

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

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

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

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

1 \leq x_i \leq 10^{10}

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

350
1400
301
399

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

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

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

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

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

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

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



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


Sample output:
350
1400
301
399

Submission status: Time Limit Exceeded

Solution code:
import sys

A, B, Q = map(int, input().split())
S = [int(sys.stdin.readline()) for _ in range(A)]
T = [int(sys.stdin.readline()) for _ in range(B)]
X = [int(sys.stdin.readline()) 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
    for _ in range(100):
        if query>arr[t]:
            low = t
        else:
            high = t
        t = (low+high)//2
        if low>=high-1:
            break
    return arr[low], arr[high]

def find(query):
    s1, s2 = binary_search(query, S)
    t1, t2 = binary_search(query, T)
    return s1, s2, t1, t2

def main():
    for x in X:
        s1, s2, t1, t2 = find(x)
        cands = [
            abs(t1-x) + abs(s2-t1),
            abs(s1-x) + abs(t2-s1),
            abs(s2-x) + abs(t1-s2),
            abs(t2-x) + abs(s1-t2),
            abs(t1-x) + abs(s1-t1),
            abs(s1-x) + abs(t1-s1),
            abs(s2-x) + abs(t2-s2),
            abs(t2-x) + abs(s2-t2)
        ]
        print(min(cands))
    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)]
NS = []
for s in S:
    for i in range(1, B):
        if s <= T[i]:
            if T[i] - s <= abs(T[i - 1] - s):
                NS.append(i)
            else:
                NS.append(i - 1)
            break
    else:
        NS.append(B - 1)
NT = []
for t in T:
    for i in range(1, A):
        if t <= S[i]:
            if S[i] - t <= abs(S[i - 1] - t):
                NT.append(i)
            else:
                NT.append(i - 1)
            break
    else:
        NT.append(A - 1)
ALL = sorted([("S", s, n) for s, n in zip(S, NS)] + [("T", t, n) for t, n in zip(T, NT)], key=lambda l: l[1])
for x in X:
    for i in range(1, A + B):
        if x <= ALL[i][1]:
            R = []
            if ALL[i][0] == "S":
                R.append(ALL[i][1] - x + abs(ALL[i][1] - T[NS[ALL[i][2]]]))
            else:
                R.append(ALL[i][1] - x + abs(ALL[i][1] - S[NT[ALL[i][2]]]))
            if ALL[i - 1][0] == "S":
                R.append(abs(ALL[i - 1][1] - x) + abs(ALL[i - 1][1] - T[NS[ALL[i - 1][2]]]))
            else:
                R.append(abs(ALL[i - 1][1] - x) + abs(ALL[i - 1][1] - S[NT[ALL[i - 1][2]]]))
            print(min(R))
            break
    else:
        if ALL[-1][0] == "S":
            print(abs(ALL[-1][1] - x) + abs(ALL[-1][1] - T[NS[ALL[-1][2]]]))
        else:
            print(abs(ALL[-1][1] - x) + abs(ALL[-1][1] - S[NT[ALL[-1][2]]]))

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 min_idx(arr, x):
  ar = [d - x for d in arr]
  abs_arr = list(map(abs, ar))
  idx = [i for i, x in enumerate(abs_arr) if x == min(abs_arr)]
  return(idx)

  
for q in range(len(x)):
  xx = x[q]
  ss = [d - xx for d in s]
  tt = [d - xx for d in t]
  
  cost_s = 0
  # pattern1 sから
  cost_s = min(map(abs, ss))
  idx = min_idx(s, xx)

  for i in idx:
    cost_s += min([abs(d-s[i]) for ii, d in enumerate(t)])

  cost_t = 0
  # pattern2 tから
  cost_t = min(map(abs, tt))
  idx = min_idx(t, xx)
  
  for i in idx:
    cost_t += min([abs(d-t[i]) for ii, d in enumerate(s)])

  if cost_s < cost_t:
    print(cost_s)
  else:
    print(cost_t)

Submission status: Time Limit Exceeded

Solution code:
a,b,q=(input().split())
a=int(a)
b=int(b)
q=int(q)
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 k in range(q):
    mins=float('inf')
    ptmins=0
    for i in range(a):
        if abs(s[i]-x[k]) < mins:
            ptmins=s[i]
            mins=abs(s[i]-x[k])

    ansa=float('inf')
    for i in range(b):
        if abs(t[i]-ptmins) < ansa:
            ansa=abs(t[i]-ptmins)
    anssa=mins+ansa

    mint=float('inf')
    ptmint=0
    for i in range(b):
        if abs(t[i]-x[k]) < mint:
            ptmint=t[i]
            mint=abs(t[i]-x[k])
   
    ansb=float('inf')    
    for i in range(a):
        if abs(s[i]-ptmint) < ansb:
            ansb=abs(s[i]-ptmint)
    anssb=mint+ansb
    
    print(min(anssa,anssb))

Submission status: Time Limit Exceeded

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

def distance(s,t,xi):
  s_ = s-xi
  if len(s_[s_<=0])!=0:
    s_m = s_[s_<=0].max()
  else:
    s_m =-np.inf
  if len(s_[s_>=0]) !=0:
    s_p = s_[s_>=0].min()
  else:
    s_p = np.inf
    
  t_ = t-xi
  if len(t_[t_<=0])!=0:
    t_m = t_[t_<=0].max()
  else:
    t_m = -np.inf
  if len(t_[t_>=0]) !=0:
    t_p = t_[t_>=0].min()
  else:
    t_p = np.inf
  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(distance(s,t,i))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

hint = list(map(int, input().split()))
s = [int(input()) for i in range(sum(hint))]
# print(s)

a = np.asarray(s[:hint[0]])
b = np.asarray(s[hint[0]:-hint[2]])
sum = 0
for t in s[-hint[2]:]:
    a_dis = np.argmin(np.abs(a - t))
    b_dis = np.argmin(np.abs(b - t))
    a_d = np.abs(a[a_dis] - t)
    b_d = np.abs(b[b_dis] - t)
    cand1 = b_d + np.min(np.abs(a[np.max([a_dis-1,0]):a_dis+1] - b[b_dis]))
    cand2 = a_d + np.min(np.abs(b[np.max([b_dis-1,0]):b_dis+1] - a[a_dis]))
    print(np.min([cand1, cand2]))

Submission status: Time Limit Exceeded

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

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

def near(lis, po, dict):
    if po in dict.keys():
        return dict[po]
    dif = list(map(lambda x: abs(x-po), lis))
    ind = dif.index(min(dif))
    res=lis[ind]-po
    dict[po] = res
    return res

def nearnext(lis, start, end, now, n):
    for point in lis:
        if(start <= point and point <= end):
            return 0
    return near(lis, now, n)

dicta = {}
dictb = {}

for i in q:
    start=int(i)
    neara=near(a, start, dicta)
    #print(a, start)
    #print(neara)
    if(neara < 0):
        #print(nearnext(b, start+neara, start, start+neara))
        neara=abs(neara)+abs(nearnext(b, start+neara, start, start+neara, dictb))
    else:
        #print(nearnext(b, start, start+neara, start+neara))
        neara+=abs(nearnext(b, start, start+neara, start+neara, dictb))
    #print(neara)

    nearb=near(b, start, dictb)
    if(nearb < 0):
        nearb=abs(nearb)+abs(nearnext(a, start+nearb, start, start+nearb, dicta))
    else:
        nearb+=abs(nearnext(a, start, start+nearb, start+nearb, dicta))

    #print(neara, nearb)
    if(neara < nearb):
        print(neara)
    else:
        print(nearb)

Submission status: Time Limit Exceeded

Solution code:
A,B,Q=list(map(int,input().split()))
s=[0]*(A+2)
t=[0]*(B+2)
X=[0]*Q
s[0] = -float('inf')
s[A+1] = float('inf')
t[0] = -float('inf')
t[B+1] = float('inf')
for i in range(1,A+1):
    s[i] = int(input())
for i in range(1,B+1):
    t[i] = int(input())
for i in range(Q):
    X[i] = int(input())

import bisect


def dec(x,s,t):
    s_ = s-x
    t_ = t-x
    as_ = abs(s_)
    at_ = abs(t_)
    if (s_>0 and t_<0) or (s_<0 and t_>0):
        return as_ + at_ + min(as_, at_)
    else:
        return max(as_,at_)


for x in X:
    s_i = bisect.bisect_left(s,x)
    t_i = bisect.bisect_left(t,x)
    s_l = s[s_i-1]
    s_r = s[s_i]
    t_l = t[t_i-1]
    t_r = t[t_i]
    ans = dec(x,s_l,t_l)
    ans_ = dec(x,s_l,t_r)
    if ans > ans_:
        ans = ans_
    ans_ = dec(x,s_r,t_l)
    if ans > ans_:
        ans = ans_
    ans_ = dec(x,s_r,t_r)
    if ans > ans_:
        ans = ans_
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def nibuntansaku(l,x):
    n = len(l)
    def hantei(med):
        if med == -1:
            return False
        elif med == n:
            return True
        elif l[med] > x:
            return True
        else:
            return False
    left = -1
    right =n
    while right-left >1:
        med = (left+right)//2
        if right == med or left == med:
            break
        if hantei(med):
            right = med
        else:
            left = med
    ret =[0,0]
    if left == -1:
        ret[0] = 10**11
        ret[1] = l[right] -x
    elif right == n:
        ret[0] = x -l[left]
        ret[1] = 10**11
    else:
        ret[0] = x - l[left]
        ret[1] = l[right] -x
    return ret


A,B,Q =[int(i)for i in input().split()]
S =[int(input())for _ in range(A)]
T =[int(input())for _ in range(B)]

for _ in range(Q):
    x = int(input())
    slef,sri = nibuntansaku(S,x)
    tlef,tri = nibuntansaku(T,x)
    lmax,lmin = max(slef,tlef),min(slef,tlef)
    rmax,rmin = max(sri,tri),min(sri,tri)
    ans = min(lmax,rmax,2*lmin+rmin,2*rmin+lmin)
    print(ans)

Submission status: Time Limit Exceeded

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


def solve():
    # データ読込
    A, B, Q = map(int, input().split())
    shrines = [int(input()) for i in range(A)]
    temple = [int(input()) for i in range(B)]
    question = [int(input()) for i in range(Q)]
    # 問題計算
    for q in question:
        t_list = []
        # 寺から神社に行くときの計算
        t_s = 0
        abs_temple = [abs(q - t) for t in temple]
        target = abs_temple.index(min(abs_temple))
        t_temple = temple[target]
        t_s += abs(q - t_temple)
        abs_shrines = [abs(t_temple - s) for s in shrines]
        t_s += min(abs_shrines)
        t_list.append(t_s)
        if abs_temple.count(min(abs_temple)) > 1:
            # 同じ距離の寺が二つあるときの考慮
            t_s2 = 0
            t_temple = temple[target + 1]
            t_s2 += abs(q - t_temple)
            abs_shrines = [abs(t_temple - s) for s in shrines]
            t_s2 += min(abs_shrines)
            t_list.append(t_s2)
        # 神社から寺に行くときの計算
        s_t = 0
        abs_shrines = [abs(q - s) for s in shrines]
        target = abs_shrines.index(min(abs_shrines))
        t_shrines = shrines[target]
        s_t += abs(q - t_shrines)
        abs_temple = [abs(t_shrines - t) for t in temple]
        s_t += min(abs_temple)
        t_list.append(s_t)
        if abs_shrines.count(min(abs_shrines)) > 1:
            # 同じ距離の寺が二つあるときの考慮
            s_t2 = 0
            t_shrines = shrines[target + 1]
            s_t2 += abs(q - t_shrines)
            abs_temple = [abs(t_shrines - t) for t in temple]
            s_t2 += min(abs_temple)
            t_list.append(s_t2)
        # 出力
        print(min(t_list))


if __name__ == '__main__':
    solve()

Submission status: Time Limit Exceeded

Solution code:
A,B,Q=map(int,input().split())
s=[]
t=[]
for i in range(A):
  s.append(int(input()))
for i in range(B):
  t.append(int(input()))
for i in range(Q):
  x=int(input())
  s1=s[:]
  s1.append(x)
  s1.sort()
  j=s1.index(x)
  if j==0:
    kouhoA=[s[j]]
  elif j==A:
    kouhoA=[s[j-1]]
  else:
    kouhoA=[s[j],s[j-1]]
  t1=t[:]
  t1.append(x)
  t1.sort()
  k=t1.index(x)
  if k==0:
    kouhoB=[t[k]]
  elif k==B:
    kouhoB=[t[k-1]]
  else:
    kouhoB=[t[k],t[k-1]]
  if len(kouhoA)==1:
    
    if len(kouhoB)==1:
      a=abs(kouhoA[0]-kouhoB[0])
      ans=min([abs(x-kouhoA[0])+a,abs(x-kouhoB[0])+a])
    else:
      a=abs(kouhoA[0]-kouhoB[0])
      b=abs(kouhoA[0]-kouhoB[1])
      ans=min([abs(x-kouhoA[0])+a,abs(x-kouhoB[0])+a,abs(x-kouhoA[0])+b,abs(x-kouhoB[1])+b])
  else:
    if len(kouhoB)==1:
      a=abs(kouhoA[0]-kouhoB[0])
      c=abs(kouhoB[0]-kouhoA[1])
      ans=min([abs(x-kouhoA[0])+a,abs(x-kouhoB[0])+a,abs(x-kouhoA[1])+c,abs(x-kouhoB[0])+c])
    else:
      a=abs(kouhoA[0]-kouhoB[0])
      d=abs(kouhoA[1]-kouhoB[1])
      ans=min([abs(x-kouhoA[0])+a,abs(x-kouhoB[0])+a,abs(x-kouhoA[1])+d,abs(x-kouhoB[1])+d,abs(x-kouhoA[1])+abs(kouhoA[1]-kouhoB[0]),abs(x-kouhoB[0])+abs(kouhoB[0]-kouhoA[1]),abs(x-kouhoA[0])+abs(kouhoA[0]-kouhoB[1]),abs(x-kouhoB[1])+abs(kouhoB[1]-kouhoA[0])])
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
a,b,q=map(int,input().split(' '))
s=[]
t=[]
for i in range(a):
    s.append(int(input()))
for i in range(b):
    t.append(int(input()))
s.sort()
t.sort()
for i in range(q):
    x=int(input())
    n=x
    start=0
    end=a-1
    count=0
    mid=start+(end-start)//2
    while start<end:
        if s[mid]==x:
            break
        elif s[mid]>x:
            end=mid
            mid=start+(end-start)//2
        else:
            start=mid+1
            mid=start+(end-start)//2
    if s[mid]==x:
        count=0
    elif s[mid]>x:
        if mid>0:
            count+=min(s[mid]-x,x-s[mid-1])
            if s[mid]-x>x-s[mid-1]:
                x=s[mid-1]
            else:
                x=s[mid]
        else:
            count+=s[mid]-x
            x=s[mid]
    else:
        if mid<a-1:
            count+=min(x-s[mid],s[mid+1]-x)
            if x-s[mid]>s[mid+1]-x:
                x=s[mid+1]
            else:
                x=s[mid]
        else:
            count+=x-s[mid]
            x=s[mid]
    #print(count,x)
    start=0
    end=b-1
    mid=start+(end-start)//2
    while start<end:
        if t[mid]==x:
            break
        elif t[mid]>x:
            end=mid
            mid=start+(end-start)//2
        else:
            start=mid+1
            mid=start+(end-start)//2
   # print(mid)
    if t[mid]==x:
        pass
    elif t[mid]>x :
        if mid>0:
            count+=min(t[mid]-x,x-t[mid-1])
        else:
            count+=t[mid]-x
    else:
        if mid<b-1:
            count+=min(x-t[mid],t[mid+1]-x)
        else:
            count+=x-t[mid]
    start=0
    end=b-1
    count1=0
    x=n
    mid=start+(end-start)//2
    while start<end:
        if t[mid]==x:
            break
        elif t[mid]>x:
            end=mid
            mid=start+(end-start)//2
        else:
            start=mid+1
            mid=start+(end-start)//2
    if t[mid]==x:
        count1=0
    elif t[mid]>x:
        if mid>0:
            count1+=min(t[mid]-x,x-t[mid-1])
            if t[mid]-x>x-t[mid-1]:
                x=t[mid-1]
            else:
                x=t[mid]
        else:
            count1+=t[mid]-x
            x=t[mid]
    else:
        if mid<b-1:
            count1+=min(x-t[mid],t[mid+1]-x)
            if x-t[mid]>t[mid+1]-x:
                x=t[mid+1]
            else:
                x=t[mid]
        else:
            count1+=x-t[mid]
            x=t[mid]
    #print(count1,x)
    start=0
    end=a-1
    mid=start+(end-start)//2
    while start<end:
        if s[mid]==x:
            break
        elif s[mid]>x:
            end=mid
            mid=start+(end-start)//2
        else:
            start=mid+1
            mid=start+(end-start)//2
    if s[mid]==x:
        pass
    elif s[mid]>x :
        if mid>0:
            count1+=min(s[mid]-x,x-s[mid-1])
        else:
            count1+=s[mid]-x

    else:
        if mid<a-1:
            count1+=min(x-s[mid],s[mid+1]-x)
        else:
            count1+=x-s[mid]
    print(min(count,count1))

Submission status: Time Limit Exceeded

Solution code:
def calc(locate, start_point):
    if start_point <= min(locate):
        if locate[0] >= locate[shrine_no]: 
            print(locate[0] - start_point)
        else:
            print(locate[shrine_no] - start_point)
            
    elif start_point >= max(locate):
        if locate[shrine_no -1] >= locate[-1]:
            print(start_point - locate[-1])
        else:
            print(start_point - locate[shrine_no - 1])
            
    else:
        s_diff = start_point - locate[0]
        t_diff = start_point - locate[shrine_no]
        for i in range(1, shrine_no):
            if abs(s_diff) > abs(start_point - locate[i]):
                s_diff = start_point - locate[i]
                
        for i in range(shrine_no+1, shrine_no + temple_no):
            if abs(t_diff) > abs(start_point - locate[i]):
                t_diff = start_point - locate[i]
                
        if s_diff * t_diff < 0:
            s_diff_list = []
            t_diff_list = []
            
            for i in range(shrine_no):
                s_diff_list.append(start_point - locate[i])
            sort_s_diff = sorted(s_diff_list)
                
            for i in range(shrine_no, shrine_no + temple_no):
                t_diff_list.append(start_point - locate[i])
            sort_t_diff = sorted(t_diff_list)

            dist = []
            for i in range(len(s_diff_list)):
                for j in range(len(t_diff_list)):
                    dist.append(abs(s_diff_list[i]-t_diff_list[j]) + min(abs(s_diff_list[i]), abs(t_diff_list[j])))
            print(min(dist))
            
        elif s_diff * t_diff > 0:
            print(max(abs(s_diff), abs(t_diff)))
        else:
            print(abs(s_diff+t_diff))

shrine_no, temple_no, q = map(int, input().split())
locate = []
start = []

for i in range(shrine_no+temple_no+q):
    tmp = int(input())
    if i < shrine_no+temple_no:
        locate.append(tmp)
    else:
        start.append(tmp)

for i in range(len(start)):
    calc(locate, start[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)]

StoT_W = [10000000010]*A
t = 0
for i in range(A):
    if S[i]<T[0]:
        continue
    while(((t+1)<B)and(T[t+1] < S[i])):
        t += 1
    StoT_W[i] = S[i] - T[t]

StoT_E = [10000000010]*A
t = B-1
for i in range(A-1,-1,-1):
    if T[B-1]<S[i]:
        continue
    while((-1<(t-1))and(S[i] < T[t-1])):
        t-=1
    StoT_E[i] = T[t] - S[i]

StoT = [10000000010]*A
for i in range(A):
    StoT[i] = min(StoT_W[i],StoT_E[i])

TtoS_W = [10000000010]*B
s = 0
for i in range(B):
    if T[i]<S[0]:
        continue
    while(((s+1)<A)and(S[s+1] < T[i])):
        s += 1
    TtoS_W[i] = T[i] - S[s]
    
TtoS_E = [10000000010]*B
s = 0
for i in range(B):
    while(S[s]<T[i]):
        s+=1
        if s==A:
            break
    else:
        TtoS_E[i] = S[s] - T[i]
        continue
    break

TtoS = [10000000010]*B
for i in range(B):
    TtoS[i] = min(TtoS_W[i],TtoS_E[i])

for x in X:
    ans = 30000000000
    for i in range(A):
        ans = min(ans,abs(S[i]-x)+StoT[i])
    for i in range(B):
        ans = min(ans,abs(T[i]-x)+TtoS[i])
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np


def check(x, al, bl):
    # al2 = np.sort(np.abs(al - x))
    rcost = np.inf
    for a in al:
        tmp_c = np.abs(a - x)
        for b in bl:
            t = np.abs(b - a)
            rcost = min(rcost, tmp_c + t, np.abs(b - x) + t)

    print(int(rcost))


n = [int(each) for each in input().split()]
a, b, q = n[0], n[1], n[2]

sl = np.zeros(a)
tl = np.zeros(b)
xl = np.zeros(q)

for i in range(a):
    sl[i] = int(input())
for i in range(b):
    tl[i] = int(input())
for i in range(q):
    xl[i] = int(input())

result = []
for x in xl:
    check(x, sl, tl)

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
jin = [int(input()) for i in range(A)]
tera = [int(input()) for i in range(B)]
x = [int(input()) for i in range(Q)]

def near_jinja(x):
    l = list(map(lambda y: abs(y-x), jin))
    near_place = l.index(min(l))
    near_dist = l[near_place]
    return near_place
  
def dist_jinja(x):
    l = list(map(lambda y: abs(y-x), jin))
    near_place = l.index(min(l))
    near_dist = l[near_place]
    return near_dist
  
def near_tera(x):
    l = list(map(lambda y: abs(y-x), tera))
    near_place = l.index(min(l))
    near_dist = l[near_place]
    return near_place

def dist_tera(x):
    l = list(map(lambda y: abs(y-x), tera))
    near_place = l.index(min(l))
    near_dist = l[near_place]
    return near_dist

for i in range(Q):
    pattern1 = dist_tera(jin[near_jinja(x[i])]) + dist_jinja(x[i])
    pattern2 = dist_jinja(tera[near_tera(x[i])]) + dist_tera(x[i])
    if pattern1 < pattern2:
        print(pattern1)
    else:
        print(pattern2)

Submission status: Time Limit Exceeded

Solution code:
def split_x(L, x):
    L_i = list(i if x > l else next(iter([])) for i, l in enumerate(L))
    if L_i == []:
        L_L = []
        L_R = L
    else:
        L_L = L[:L_i[-1]+1]
        L_R = L[ L_i[-1]+1:]
    return L_L, L_R

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

H = {}
Y = X.copy()

Y.sort()

for y in Y:
    res = []
    S_L, S_R = split_x(S, y)
    T_L, T_R = split_x(T, y)
    # R方向に神社・寺
    try:
        res.append(max(S_R[0], T_R[0]) - y)
    except:
        pass
    # L方向に神社・寺
    try:
        res.append(y - min(S_L[-1], T_L[-1]))
    except:
        pass
    # R方向に神社、L方向に寺
    try:
        res.append((S_R[0] - y) * 2 + (y - T_L[-1]))
    except:
        pass
    # L方向に神社、R方向に寺
    try:
        res.append((y - S_L[-1]) * 2 + (T_R[0] - y))
    except:
        pass
    # R方向に寺、L方向に神社
    try:
        res.append((T_R[0] - y) * 2 + (y - S_L[-1]))
    except:
        pass
    # L方向に寺、R方向に神社
    try:
        res.append((y - T_L[-1]) * 2 + (S_R[0] - y))
    except:
        pass
    H[y] = min(res)
    S = S_L[-1:] + S_R
    T = T_L[-1:] + T_R

for x in X:
    print(H[x])

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import math

#def get_nearest(point, lst):
#    idx = np.abs(np.asarray(lst) - point).argmin()
#    return lst[idx]

def get_nearest(point, lst):
    idx = np.searchsorted(lst, point, side="left")
    if idx > 0 and (idx == len(lst) or \
            math.fabs(point - lst[idx-1]) < math.fabs(point - lst[idx])):
        return lst[idx-1]
    else:
        return lst[idx]

A, B, Q = [int(x) for x in input().split(" ")]
a = []
b = []
for i in range(A):
    a.append(int(input()))
for i in range(B):
    b.append(int(input()))

for i in range(Q):
    q = int(input())
    nearest_a = get_nearest(q, a)
    nearest_b = get_nearest(q, b)
#   print(q, nearest_a, nearest_b)
    
    if abs(nearest_a - q) < abs(nearest_b - q):
        nearer, farer = nearest_a, nearest_b
        nearer_list, farer_list = a, b
    else:
        nearer, farer = nearest_b, nearest_a
        nearer_list, farer_list = b, a

    nearer_first  = abs(q - nearer)
    nearer_first += abs(nearer - get_nearest(nearer, farer_list))

    farer_first  = abs(q - farer)
    farer_first += abs(farer - get_nearest(farer, nearer_list))

    answer = min(nearer_first, farer_first)

    print(answer)

Submission status: Time Limit Exceeded

Solution code:
import sys

A, B, Q = map(int, input().split())
S = [int(sys.stdin.readline()) for _ in range(A)]
T = [int(sys.stdin.readline()) for _ in range(B)]
X = [int(sys.stdin.readline()) 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 find(query):
    s1, s2 = binary_search(query, S)
    t1, t2 = binary_search(query, T)
    return s1, s2, t1, t2

def main():
    for x in X:
        s1, s2, t1, t2 = find(x)
        cands = [
            abs(t1-x) + abs(s2-t1),
            abs(s1-x) + abs(t2-s1),
            abs(s2-x) + abs(t1-s2),
            abs(t2-x) + abs(s1-t2),
            abs(t1-x) + abs(s1-t1),
            abs(s1-x) + abs(t1-s1),
            abs(s2-x) + abs(t2-s2),
            abs(t2-x) + abs(s2-t2)
        ]
        print(min(cands))
    return

main()

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = list(map(int, raw_input().split()))

jinja = list()
for a in xrange(A): jinja.append(long(raw_input()))
tera = list()
for b in xrange(B): tera.append(long(raw_input()))

max_val = 10000000000000000.0

for q in xrange(Q):
    question = long(raw_input())
    if jinja[0] >= question:
        min_jinja = max_val
        max_jinja = jinja[0] - question
    elif jinja[-1] <= question:
        min_jinja = question - jinja[-1]
        max_jinja = max_val
    else:
        for a in xrange(A-1):
            if jinja[a] <= question and jinja[a+1] >= question:
                min_jinja = question - jinja[a]
                max_jinja = jinja[a+1] - question
    if tera[0] >= question:
        min_tera = max_val
        max_tera = tera[0] - question
    elif tera[-1] <= question:
        min_tera = question - tera[-1]
        max_tera = max_val
    else:
        for b in xrange(B-1):
            if tera[b] <= question and tera[b+1] >= question:
                min_tera = question - tera[b]
                max_tera =  tera[b+1] - question

    if max_tera == max_val and max_jinja == max_val:
        if min_jinja >= min_tera: print min_jinja
        else: print min_tera
    elif min_tera == max_val and min_jinja == max_val:
        if max_jinja >= max_tera: print max_jinja
        else: print max_tera
    elif min_jinja > min_tera and max_tera < max_jinja:
        if min_jinja >= max_jinja: print max_jinja
        else: print min_jinja
    elif min_tera < min_jinja and min_jinja < max_tera:
        if min_tera >= max_tera: print max_tera
        else: print min_tera
    elif min_tera <= min_jinja:
        dist = [min_jinja, min_tera*2 + max_jinja, min_tera + max_jinja*2, max_tera]
        dist.sort()
        print dist[0]
    elif min_jinja <= min_tera:
        dist = [min_tera, min_jinja*2 + max_tera, min_jinja + max_tera*2, max_jinja]
        dist.sort()
        print dist[0]

Submission status: Time Limit Exceeded

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from heapq import heappush, heappop
import math
import bisect
import random
def LI(): return list(map(int, input().split()))
def I(): return int(input())
def LS(): return input().split()
def S(): return list(input())
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
mod = 1000000007

#A

#B

#C
"""
n,a,b,c = LI()
l = IR(n)
f = [True for i in range(3)]
ans = 0
for i in range(n):
    for d in range(3):
        if abs(l[i]-[a,b,c][d]) <= 10 and f[d]:
            ans += abs(l[i]-[a,b,c][d])
            f[d] = False
            l[i] = -float("inf")
k = False
for i in f:
    if i:
        k = True
        break
if not k:
    print(ans)
    quit()
"""
#D
a,b,q = LI()
s = IR(a)
t = IR(b)
for i in range(q):
    x = I()
    c = bisect.bisect_left(s,x)
    ans = float("inf")
    if c == a:
        k = abs(x-s[-1])
        y = s[-1]
        d = bisect.bisect_left(t,y)
        if d == b:
            k += abs(y-t[-1])
        else:
            if abs(y-t[d-1]) < abs(y-t[d]):
                k += abs(y-t[d-1])
            else:
                k += abs(y-t[d])
        ans = min(k,ans)
    else:
        k = abs(x-s[c-1])
        y = s[c-1]
        d = bisect.bisect_left(t,y)
        if d == b:
            k += abs(y-t[-1])
        else:
            if abs(y-t[d-1]) < abs(y-t[d]):
                k += abs(y-t[d-1])
            else:
                k += abs(y-t[d])
        ans = min(k,ans)
        k = abs(x-s[c])
        y = s[c]
        d = bisect.bisect_left(t,y)
        if d == b:
            k += abs(y-t[-1])
        else:
            if abs(y-t[d-1]) < abs(y-t[d]):
                k += abs(y-t[d-1])
            else:
                k += abs(y-t[d])
        ans = min(k,ans)
    c = bisect.bisect_left(t,x)
    if c == b:
        k = abs(x-t[-1])
        y = t[-1]
        d = bisect.bisect_left(s,y)
        if d == a:
            k += abs(y-s[-1])
        else:
            if abs(y-s[d-1]) < abs(y-s[d]):
                k += abs(y-s[d-1])
            else:
                k += abs(y-s[d])
        ans = min(k,ans)
    else:
        k = abs(x-t[c-1])
        y = t[c-1]
        d = bisect.bisect_left(s,y)
        if d == a:
            k += abs(y-s[-1])
        else:
            if abs(y-s[d-1]) < abs(y-s[d]):
                k += abs(y-s[d-1])
            else:
                k += abs(y-s[d])
        ans = min(k,ans)
        k = abs(x-t[c])
        y = t[c]
        d = bisect.bisect_left(s,y)
        if d == a:
            k += abs(y-s[-1])
        else:
            if abs(y-s[d-1]) < abs(y-s[d]):
                k += abs(y-s[d-1])
            else:
                k += abs(y-s[d])
        ans = min(k,ans)
    print(ans)
#E

#F

#G

#H

#I

#J

#K

#L

#M

#N

#O

#P

#Q

#R

#S

#T