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 numpy as np

a, b, q = list(map(int, input().split(' ')))

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

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

    _s_list_abs = np.abs(s_list - x)
    _t_list_abs = np.abs(t_list - x)

    s_min = np.min(_s_list_abs)
    t_min = np.min(_t_list_abs)

    s_min_dist = s_min
    tmp_x = s_list[np.argmin(_s_list_abs)]
    s_min_dist += np.min(np.abs(t_list - tmp_x))

    t_min_dist = t_min
    tmp_x = t_list[np.argmin(_t_list_abs)]
    t_min_dist += np.min(np.abs(s_list - tmp_x))

    print(np.min([s_min_dist, t_min_dist]))

Submission status: Time Limit Exceeded

Solution code:
a, b, q = [int(i) for i in input().split() ]
s = list([])
t = list([])
z = list([])

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

sd=list([])
td=list([])
if len(s) == 1:
    sd.append([s[0],0, 10**10])
else:
    for j in range(len(s)):
        if j == 0:
            a = 0
            b = s[j] + int((s[j+1] - s[j])/2)
        elif j == len(s) - 1:
            a = s[j] - int((s[j] - s[j-1])/2)
            b = 10**10
        else:
            a = s[j] - int((s[j] - s[j-1])/2)
            b = s[j] + int((s[j+1] - s[j])/2)
        sd.append([s[j],a,b])
if len(t) == 1:
    td.append([t[0],0, 10**10])
else:
    for j in range(len(t)):
        if j == 0:
            a = 0
            b = t[j] + int((t[j+1] - t[j])/2)
        elif j == len(t) - 1:
            a = t[j] - int((t[j] - t[j-1])/2)
            b = 10**10
        else:
            a = t[j] - int((t[j] - t[j-1])/2)
            b = t[j] + int((t[j+1] - t[j])/2)
        td.append([t[j],a,b])

for x in z:
    ans_s = 0
    ans_t = 0
    for ss in sd:
        if ((ss[1] > x) or (ss[2] < x)):
            continue
        else:
            ans_s += abs(x - ss[0])
            y = ss[0]
            for tt in td:
                if ((tt[1] > y) or (tt[2] < y)):
                    continue
                else:
                    ans_s += abs(y - tt[0])
                    break
            break

    for tt in td:
        if ((tt[1] > x) or (tt[2] < x)):
            continue
        else:
            ans_t += abs(x - tt[0])
            y = tt[0]
            for ss in sd:
                if ((ss[1] > y) or (ss[2] < y)):
                    continue
                else:
                    ans_t += abs(y - ss[0])
                    break
            break
    print(min(ans_s, ans_t))

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
import re
from datetime import datetime as dt
if __name__ == '__main__':
    a, b, q = map(int, raw_input().split())
    s = []
    t = []
    x = []
    for i in range(a):
        s.append(input())
    for i in range(b):
        t.append(input())
    for i in range(q):
        x.append(input())

    for i in x:
        te = b - 1
        sh = a- 1
        for j in range(a):
            if i < s[j]:
                sh = j
                break
        for j in range(b):
            if i < t[j]:
                te = j
                break
        if sh == 0:
            sh_array = [sh]
        elif sh == len(s) - 1 and i > s[sh]:
            sh_array = [sh]
        else:
            sh_array = [sh-1, sh]
        if te == 0:
            te_array = [te]
        elif te == len(t) - 1 and i > t[te]:
            te_array = [te]
        else:
            te_array = [te-1, te]
        min = abs(i-s[sh]) + abs(s[sh] - t[te])
        for j in sh_array:
            for k in te_array:
                if min > abs(i-s[j]) + abs(s[j]-t[k]):
                    min = abs(i-s[j]) + abs(s[j]-t[k])
        for j in te_array:
            for k in sh_array:
                if min > abs(i-t[j]) + abs(t[j]-s[k]):
                    min = abs(i-t[j]) + abs(t[j]-s[k])
        print min

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)]
xl = [int(input()) for _ in range(q)]
# print(sl)
# print(tl)
for x in xl:
    si = lower_bound(sl,x)
    ti = lower_bound(tl,x)
    # print(x,si,ti)

    res = 10**15
    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])

    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)
                )
            res = min(res,tmp)
    print(res)

Submission status: Time Limit Exceeded

Solution code:
def check(x, al, bl):
    rcost = None
    for a in al:
        tmp_c = abs(a - x)
        for b in bl:
            t = abs(b - a)
            if rcost is not None:
                rcost = min(rcost, tmp_c + t, abs(b - x) + t)
            else:
                rcost = min(tmp_c + t, abs(b - x) + t)
    print(rcost)


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

sl, tl, xl = [], [], []

for i in range(a):
    sl.append(int(input()))
for i in range(b):
    tl.append(int(input()))
for i in range(q):
    xl.append(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())
a_list = list(map(int, [input() for i in range(a)]))
b_list = list(map(int, [input() for i in range(b)]))
q_list = list(map(int, [input() for i in range(q)]))

for qi in q_list:
  la1 = 10**10
  for i, ai in enumerate(a_list):
    if (abs(qi - ai)) <= la1:
      la1 = abs(qi - ai)
      a_num = i
  lb1 = min([abs(a_list[a_num] - bi) for bi in b_list])

  lb2 = 10**10
  for i, bi in enumerate(b_list):
    if (abs(qi - bi)) <= lb2:
      lb2 = abs(qi - bi)
      b_num = i
  la2 = min([abs(b_list[b_num] - ai) for ai in a_list])

  print(min(la1+lb1, la2+lb2))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import sys

class Avltree:
    def __init__(self,key=None):
        self.key = key
        self.left = None
        self.right = None 
        self.balance = "Even"
    def search(self,key):
        if self.key == None:
            return None
        if self.key > key:
            if self.left == None:
                return None
            else:
                return self.left.search(key)
        if self.key < key:
            if self.right == None:
                return None
            else:
                return self.right.search(key)
        return self # self.key == keyの場合
        
    def search_lower(self,key,key_lower):
        if self.key == None:
            return key_lower
        if self.key > key:
            if self.left == None:
                return key_lower
            else:
                return self.left.search_lower(key,key_lower)
        if self.key < key:
            key_lower = self.key
            if self.right == None:
                return key_lower
            else:
                return self.right.search_lower(key,key_lower)
        #self.key == keyの場合
        if self.left == None:
            return key_lower
        else:
            if key_lower == None:
                return self.left.end_higher(self.left.key)
            else:
                return max(key_lower,self.left.end_higher(self.left.key))
    
    def search_higher(self,key,key_higher):
        if self.key == None:
            return key_higher
        if self.key > key:
            key_higher = self.key
            if self.left == None:
                return key_higher
            else:
                return self.left.search_higher(key,key_higher)
        if self.key < key:
            if self.right == None:
                return key_higher
            else:
                return self.right.search_higher(key,key_higher)
        #self.key == keyの場合
        if self.right == None:
            return key_higher
        else:
            if key_higher == None:
                return self.right.end_lower(self.right.key)
            else:
                return min(key_higher,self.right.end_lower(self.right.key))
        
    
    def end_lower(self,end_lower_key):
        if self.left == None:
            return end_lower_key
        else:
            end_lower_key = self.left.key
            return self.left.end_lower(end_lower_key)
    def end_higher(self,end_higher_key):
        if self.right == None:
            return end_higher_key
        else:
            end_higher_key = self.right.key
            return self.right.end_higher(end_higher_key)
    
            
    def DoubleRightRotation(self):
        tl = self.left
        self.left = tl.right.right
        tl.right.right = self # selfはそのノード
        tlr = tl.right
        tl.right = tlr.left
        tlr.left = tl
        if tlr.balance == "Left":
            tlr.right.balance = "Right"
            tlr.left.balance = "Even"
        elif tlr.balance == "Right":
            tlr.right.balance = "Even"
            tlr.left.balance = "Left"
        elif tlr.balance == "Even":
            tlr.right.balance = "Even"
            tlr.left.balance = "Even"
        tlr.balance = "Even"
        return tlr
    def DoubleLeftRotation(self):
        tr = self.right
        self.right = tr.left.left
        tr.left.left = self
        trl = tr.left
        tr.left = trl.right
        trl.right = tr
        if trl.balance == "Right":
            trl.left.balance = "Left"
            trl.right.balance = "Even"
        elif trl.balance == "Left":
            trl.left.balance = "Even"
            trl.right.balance = "Right"
        elif trl.balance == "Even":
            trl.left.balance = "Even"
            trl.right.balance = "Even"
        trl.balance = "Even"
        return trl
    def SingleLeftRotation(self):
        tr = self.right
        tr.balance = "Even"
        self.balance = "Even"
        self.right = tr.left
        tr.left = self
        return tr
    def SingleRightRotation(self):
        tl = self.left
        tl.balance = "Even"
        self.balance = "Even"
        self.left = tl.right
        tl.right = self
        return tl
    def replace(self,p,v): # 親ノードpの下にある自分(self)をvに置き換える。
        if p.left == self:
            p.left = v
        else :
            p.right = v 
    def insert(self,key): # rootでのみ呼ばれる挿入
        if self.key == None: # rootを含むrotationはしないことにする。
            self.key = key
            return self
        if key < self.key:
            if self.left == None:
                self.left = Avltree(key)
            else:
                self.left.insertx(self,key)
        elif key > self.key:
            if self.right == None:
                self.right = Avltree(key)
            else:
                self.right.insertx(self,key)
        else: # key == self.key:
            pass # do not overwrite
    def insertx(self,p,key): # replaceを呼ぶために一つ上の親を持っているinsert
        if self.key > key:
            if self.left == None:
                self.left = Avltree(key)
            else:
                if not self.left.insertx(self, key): # 左の木が生長しなければ、
                    return False # 成長しない
            if self.balance == "Right":
                self.balance = "Even"
                return False
            elif self.balance == "Even":
                self.balance = "Left"
                return True # 成長した
            elif self.balance == "Left":
                if self.left.balance == "Right":
                    self.replace(p,self.DoubleRightRotation())
                elif self.left.balance == "Left":
                    self.replace(p,self.SingleRightRotation())
                return False # rotationを行うと成長しない
        if self.key < key:
            if self.right == None:
                self.right = Avltree(key)
            else:
                if not self.right.insertx(self, key):
                    return False 
            if self.balance == "Left":
                self.balance = "Even"
                return False
            elif self.balance == "Even":
                self.balance = "Right"
                return True
            elif self.balance == "Right":
                if self.right.balance == "Left": 
                    self.replace(p,self.DoubleLeftRotation())
                elif self.right.balance == "Right":
                    self.replace(p,self.SingleLeftRotation())
                return False
        return False # self.key == keyの時は何もしないので成長もしない 

    def to_s(self):
        return self.key
    def left_s(self):
        if self.left == None:
            return None
        return (self.left).key
    def right_s(self):
        if self.right == None:
            return None
        return (self.right).key
        
input = sys.stdin.readline
a, b, q = map(int,input().split())
treeA, treeB = Avltree(), Avltree()
for i in range(a): treeA.insert(int(input()))
for i in range(b): treeB.insert(int(input()))
for _ in range(q):
    i = int(input())
    # atob
    p1,p2 = 0, 0
    alow = treeA.search_lower(i,10**15)
    ahigh = treeA.search_higher(i,10**15)
    p1 += abs(alow-i)
    p2 += abs(ahigh-i)
    p1 += min(abs(treeB.search_lower(alow,10**15)-alow),abs(treeB.search_higher(alow,10**15)-alow))
    p2 += min(abs(treeB.search_lower(ahigh,10**15)-ahigh),abs(treeB.search_higher(ahigh,10**15)-ahigh))
    ans = min(p1,p2)
    # print(p1,p2)
    # btoa
    p3,p4 = 0, 0
    blow = treeB.search_lower(i,10**15)
    bhigh = treeB.search_higher(i,10**15)
    p3 += abs(blow-i)
    p4 += abs(bhigh-i)
    p3 += min(abs(treeA.search_lower(blow,10**15)-blow),abs(treeA.search_higher(blow,10**15)-blow))
    p4 += min(abs(treeA.search_lower(bhigh,10**15)-bhigh),abs(treeA.search_higher(bhigh,10**15)-bhigh))
    ans = min(p3,p4,ans)
    # print(p3,p4)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
A,B,Q = (int(i) for i 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)]

def len_L(s,x):
    L= 99999999999
    for i in s:
        if i <= x:
            L = x - i
    return L

def len_R(s,x):
    for i in s:
        if i >= x:
            return i - x
    return 99999999999

for i in x:
    mini = min([2*len_L(s,i)+len_R(t,i) , len_L(s,i)+2*len_R(t,i) ,2*len_R(s,i)+len_L(t,i) , len_R(s,i)+2*len_L(t,i) , max([len_L(t,i),len_L(s,i)]) , max([len_R(t,i),len_R(s,i)])])
    print(mini)

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
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(array, point):
    #print ("p",point)
    abs_diff = 10 ** 11
    for place in array:

        diff = place - point
        temp = abs(diff)
        if abs_diff > temp:
            min_diff = diff
            abs_diff = temp
        else:
            break
        
    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:

def check(x, al, bl):
    rcost = None
    for a in al:
        for b in bl:
            if rcost is not None:
                rcost = min(rcost, abs(a - x) + abs(b - a), abs(b - x) + abs(a - b))
            else:
                rcost = min(abs(a - x) + abs(b - a), abs(b - x) + abs(a - b))
    print(rcost)





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

sl, tl, xl = [], [], []

for i in range(a):
    sl.append(int(input()))
for i in range(b):
    tl.append(int(input()))
for i in range(q):
    xl.append(int(input()))

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

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

INF = float('inf')
for _ in range(q):
    x = int(input())
    if x > s[a-1]:
        sl = x - s[a-1]
        sr = INF
    elif x < s[0]:
        sl = INF
        sr = s[0] - x
    else:
        si = bisect.bisect_right(s, x)
        sl = x - s[si-1]
        sr = s[si] - x

    if x > t[b-1]:
        tl = x - t[b-1]
        tr = INF
    elif x < t[0]:
        tl = INF
        tr = t[0] - x
    else:
        ti = bisect.bisect_right(t, x)
        tl = x - t[ti-1]
        tr = t[ti] - x

    ans = min(max(sl, tl), max(sr, tr))

    ans = min(ans, sr*2+tl)
    ans = min(ans, sr+tl*2)
    ans = min(ans, sl*2+tr)
    ans = min(ans, sl+tr*2)

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
A, B, Q = list(map(int, input().split()))
s = []
t = []
s.append(-100000000000)
s.append(100000000000)
t.append(-100000000000)
t.append(100000000000)
for i in range(A):
    s.append(int(input()))
s = sorted(s, reverse=False)
sn = np.array(s)
for i in range(B):
    t.append(int(input()))
t = sorted(t, reverse=False)
tn = np.array(t)
for i in range(Q):
    xi = int(input())

    stot = min(abs(xi - sn[sn.searchsorted(xi)])
               + abs(sn[sn.searchsorted(xi)] - tn[tn.searchsorted(sn[sn.searchsorted(xi)])]),
               abs(xi - sn[sn.searchsorted(xi)])
               + abs(sn[sn.searchsorted(xi)] - tn[tn.searchsorted(sn[sn.searchsorted(xi)]) - 1]),
               abs(xi - sn[sn.searchsorted(xi) - 1])
               + abs(sn[sn.searchsorted(xi) - 1] - tn[tn.searchsorted(sn[sn.searchsorted(xi) - 1])]),
               abs(xi - sn[sn.searchsorted(xi) - 1])
               + abs(sn[sn.searchsorted(xi) - 1] - tn[tn.searchsorted(sn[sn.searchsorted(xi) - 1]) - 1])
               )
    ttos = min(abs(xi - tn[tn.searchsorted(xi)])
               + abs(tn[tn.searchsorted(xi)] - sn[sn.searchsorted(tn[tn.searchsorted(xi)])]),
               abs(xi - tn[tn.searchsorted(xi)])
               + abs(tn[tn.searchsorted(xi)] - sn[sn.searchsorted(tn[tn.searchsorted(xi)]) - 1]),
               abs(xi - tn[tn.searchsorted(xi) - 1])
               + abs(tn[tn.searchsorted(xi) - 1] - sn[sn.searchsorted(tn[tn.searchsorted(xi) - 1])]),
               abs(xi - tn[tn.searchsorted(xi) - 1])
               + abs(tn[tn.searchsorted(xi) - 1] - sn[sn.searchsorted(tn[tn.searchsorted(xi) - 1]) - 1])
               )
    print(min(stot, ttos))

Submission status: Time Limit Exceeded

Solution code:
def get_nearest(point, lst):
    shortest = 1000000000000000
    nearest = float("inf")
    for x in lst:
        dist = abs(x - point)
        if dist < shortest:
            shortest = dist
            nearest = x
    return nearest

def exist_between(a, b, lst):
    for x in lst:
        if a <= x and x <= b:
            return True
    else:
        return False

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 numpy as np

def getNearestValue(list, num):
    idx = np.searchsorted(list, num, side="left")
    if idx > 0 and (idx == len(list) or abs(num - list[idx-1]) < abs(num - list[idx])):
        return list[idx-1]
    else:
        return list[idx]

#    idx = np.abs(np.asarray(list) - num).argmin()
#    return list[idx]

def main():
    A, B, Q = map(int, input().split())  #複数数値入力
    S = [0] * A
    T = [0] * B
    X = [0] * Q
    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 i in range(Q):
        ans = 0

        # 1:神社先
        basyo1 = getNearestValue(S, X[i])   
        dist1 = abs(basyo1 - X[i])
        dist1 += abs(getNearestValue(T, basyo1) -basyo1)

        # 2:寺先
        basyo2 = getNearestValue(T, X[i])
        dist2 = abs(basyo2 - X[i])
        dist2 += abs(getNearestValue(S, basyo2) -basyo2)

        ans += min(dist1, dist2)
        print(ans)


main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

def getValue(list, num):
  idx = np.abs(np.asarray(list) - num).argmin()
  return list[idx]

def resultjudge(lst1, lst2, qq):
  first = 0
  second = 0
  sum_second = 0
  sum_first = 0
  for j in range(len(lst1)):
    if lst1[j] > qq:
      second = lst1[j]
      if j>0:
        first = lst1[j-1]
      break
  if second==0:
    second = lst1[-1]

  for k in range(len(lst2)):
    tera_second = getValue(lst2, second)
    sum_second = abs(second - qq) + abs(second - tera_second)
    result = sum_second
    if first!=0:
      tera_first = getValue(lst2,first)
      sum_first = abs(first - qq) + abs(first - tera_first)
      if sum_first<sum_second:
        result = sum_first
  return result

  
data = input()
data = data.split()
jinjya = []
tera = []
q = []
for _ in range(int(data[0])):
  jinjya.append(int(input()))
for _ in range(int(data[1])):
  tera.append(int(input()))
for _ in range(int(data[2])):
  q.append(int(input()))

jinjya.sort()
tera.sort()

for i in range(len(q)):
  result1 = resultjudge(jinjya, tera, q[i])
  result2 = resultjudge(tera, jinjya, q[i])
  if result1>result2:
    result = result2
  else:
    result = result1
  print(result)

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_right

def getINearests(ss, ts):
    iNearests = [-1] * len(ss)
    for iS, s in enumerate(ss):
        iT = bisect_right(ts, s)
        if iT == len(ts):
            iNearests[iS] = iT-1
        elif iT == 0:
            iNearests[iS] = 0
        else:
            d1 = abs(s - ts[iT-1])
            d2 = abs(s - ts[iT])
            if d1 <= d2:
                iNearests[iS] = iT-1
            else:
                iNearests[iS] = iT
    return iNearests


A, B, Q = map(int, input().split())
ss = [int(input()) for _ in range(A)]
ts = [int(input()) for _ in range(B)]
xs = [int(input()) for _ in range(Q)]

iTNearests = getINearests(ss, ts)
iSNearests = getINearests(ts, ss)

anss = [0] * Q
for iX, x in enumerate(xs):
    ans = float('inf')

    # 初手: 神社
    iS = bisect_right(ss, x)
    if iS > 0:
        cost = abs(x - ss[iS-1])
        cost += abs(ss[iS-1] - ts[iTNearests[iS-1]])
        ans = min(ans, cost)
    if iS < A:
        cost = abs(x - ss[iS])
        cost += abs(ss[iS] - ts[iTNearests[iS]])
        ans = min(ans, cost)

    # 初手: 寺
    iT = bisect_right(ts, x)
    if iT > 0:
        cost = abs(x - ts[iT-1])
        cost += abs(ts[iT-1] - ss[iSNearests[iT-1]])
        ans = min(ans, cost)
    if iT < B:
        cost = abs(x - ts[iT])
        cost += abs(ts[iT] - ss[iSNearests[iT]])
        ans = min(ans, cost)

    anss[iX] = ans

print('\n'.join(map(str, anss)))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

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

s = []
t = []

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

for i in range(Q):
    news = np.array(s)
    newt = np.array(t)
    x = int(input())
    news -= x
    newt -= x
    dis_l_s, dis_r_s, dis_l_t, dis_r_t = (10**11,10**11,10**11,10**11)
    if news[0] < 0: #xが左端でない
        dis_l_s = - np.max(np.where(news<=0, news, -10**11))
    if news[-1] > 0: #xが右端でない
        dis_r_s = np.min(np.where(news>=0, news, 10**11))
    if newt[0] < 0: #xが左端でない
        dis_l_t = - np.max(np.where(newt<=0, newt, -10**11))
    if newt[-1] > 0: #xが右端でない
        dis_r_t = np.min(np.where(newt>=0, newt, 10**11))
    r1 = max(dis_l_s, dis_l_t)
    r2 = max(dis_r_s, dis_r_t)
    r3 = dis_l_s * 2 + dis_r_t
    r4 = dis_l_t * 2 + dis_r_s
    r5 = dis_r_s * 2 + dis_l_t
    r6 = dis_r_t * 2 + dis_l_s

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

Submission status: Time Limit Exceeded

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

for _ in range(Q):
    x = int(input())
    sr = bisect.bisect_right(S, x)
    tr = bisect.bisect_right(T, x)
    tmpS = []
    tmpT = []
    if sr == A:
        tmpS.append(S[A-1])
    elif sr == 0:
        tmpS.append(S[sr])
    else:
        tmpS.append(S[sr])
        tmpS.append(S[sr-1])
    if tr == B:
        tmpT.append(T[B-1])
    elif tr == 0:
        tmpT.append(T[tr])
    else:
        tmpT.append(T[tr])
        tmpT.append(T[tr-1])
    ans = 10**16
    for s in tmpS:
        tmp = abs(x-s)
        tmp1 = 10**16
        for elemT in tmpT:
            tmp1 = min(tmp1, abs(elemT-s))
        ans = min(ans, tmp+tmp1)
    for t in tmpT:
        tmp = abs(x-t)
        tmp1 = 10**16
        for elemS in tmpS:
            tmp1 = min(tmp1, abs(elemS-t))
        ans = min(ans, tmp+tmp1)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
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 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()