Problem:


Score : 400 points

Problem Statement

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

Answer the following Q queries:

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

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

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

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

1 \leq x_i \leq 10^{10}

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

350
1400
301
399

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

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

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

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

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

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

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



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


Sample output:
350
1400
301
399

Submission status: Time Limit Exceeded

Solution code:
a,b,q=(input().split())
a,b,q=int(a),int(b),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)]

import bisect
for k in range(q):

    dist=[float('inf') for i in range(8)]

    sp1=[0 for i in range(2)]
    tp1=[0 for i in range(4)]
#print(sp1,tp1)

    p1=bisect.bisect_left(s,x[k])

    if p1==0:
        sp1[0]=s[0]
        sp1[1]=s[0]
    elif p1==a:
        sp1[0]=s[a-1]
        sp1[1]=s[a-1]
    else:
        sp1[0]=s[p1-1]
        sp1[1]=s[p1]

    for i in range(2):
        p11=bisect.bisect_left(t,sp1[i])

        if p11==0:
            tp1[0+2*i]=t[0]
            tp1[1+2*i]=t[0]
        elif p11==b:
            tp1[0+2*i]=t[b-1]
            tp1[1+2*i]=t[b-1]
        else:
            tp1[0+2*i]=t[p11-1]
            tp1[1+2*i]=t[p11]

    dist[0]=abs(x[k]-sp1[0])+abs(sp1[0]-tp1[0])
    dist[1]=abs(x[k]-sp1[0])+abs(sp1[0]-tp1[1])
    dist[2]=abs(x[k]-sp1[1])+abs(sp1[1]-tp1[2])
    dist[3]=abs(x[k]-sp1[1])+abs(sp1[1]-tp1[3])
                

    sp1=[0 for i in range(2)]
    tp1=[0 for i in range(4)]
#print(sp1,tp1)

    p1=bisect.bisect_left(t,x[k])

    if p1==0:
        sp1[0]=t[0]
        sp1[1]=t[0]
    elif p1==b:
        sp1[0]=t[b-1]
        sp1[1]=t[b-1]
    else:
        sp1[0]=t[p1-1]
        sp1[1]=t[p1]

    for i in range(2):
        p11=bisect.bisect_left(s,sp1[i])

        if p11==0:
            tp1[0+2*i]=s[0]
            tp1[1+2*i]=s[0]
        elif p11==a:
            tp1[0+2*i]=s[a-1]
            tp1[1+2*i]=s[a-1]
        else:
            tp1[0+2*i]=s[p11-1]
            tp1[1+2*i]=s[p11]

    dist[4]=abs(x[k]-sp1[0])+abs(sp1[0]-tp1[0])
    dist[5]=abs(x[k]-sp1[0])+abs(sp1[0]-tp1[1])
    dist[6]=abs(x[k]-sp1[1])+abs(sp1[1]-tp1[2])
    dist[7]=abs(x[k]-sp1[1])+abs(sp1[1]-tp1[3])
    
    ans=min(dist[0],dist[1],dist[2],dist[3],dist[4],dist[5],dist[6],dist[7])

    print(ans)

Submission status: Time Limit Exceeded

Solution code:
A,B,Q = map(int,input().split())
S = [int(input()) for xx in range(A)]
T = [int(input()) for yy in range(B)]
X = [int(input()) for zz in range(Q)]
def sorts(x):
    return sorted([[abs(x-s),s] for s in S])
def sortt(x):
    return sorted([[abs(x-s),s] for s in T])

def min_d(x):
    smallS = sorts(x)[0]
    smallT = sortt(x)[0]
    op1 = smallS[0] + sortt(smallS[1])[0][0]
    op2 = smallT[0] + sorts(smallT[1])[0][0]
    if(A != 1 and B != 1):
        S2 = sorts(x)[1]
        T2 = sortt(x)[1]
        op3 = S2[0] + sortt(S2[1])[0][0]
        op4 = T2[0] + sorts(T2[1])[0][0]
    
        return min(op1,op2,op3,op4)
    else:
        return min(op1,op2)

for _ in X:
        print(min_d(_))

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 = map(int,input().split())
import bisect
L1=[]
L2=[]
for _ in range(A):
    L1.append(int(input()))
for _ in range(B):
    L2.append(int(input()))
for _ in range(q):
    Q = int(input())
    cand = []
    for i in range(2):
        for j in range(2):
            try:
                t =  L1[bisect.bisect_left(L1,Q)-i]
                tmp = abs (t - Q)
                tmp  +=  abs(L2[bisect.bisect_left(L2,t)-j]  - t)
                cand.append(tmp)
            except:
                pass
            try:
                t =  L2[bisect.bisect_left(L2,Q)-i]
                tmp = abs (t - Q)
                tmp  +=  abs(L1[bisect.bisect_left(L1,t)-j]  - t)
                cand.append(tmp)
            except:
                pass
    print(min(cand))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import sys

f_inf = float('inf')


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


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

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

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

class AvlTree:
    """ Avl木を表現するクラス """
    def __init__(self):
        self.avl = [None,None,None,0]

    def node(self,key):
        return [None,key,None,0]

    # search(x) xが存在するならTrueをしないならFalseを返す
    def search(self,key,avl=None):
        if avl == None:
            avl = self.avl
        if key == avl[1]:
            return True
        elif key < avl[1]:
            if avl[0] == None:
                return False
            else:
                return self.search(key,avl[0])
        elif avl[1] < key:
            if avl[2] == None:
                return False
            else:
                return self.search(key,avl[2])

    def search_lower(self,key,key_lower=None,avl=0):
        if avl == 0:
            avl = self.avl
        if avl == None:
            return key_lower
        elif key < avl[1]:
            if avl[0] == None:
                return key_lower
            else:
                return self.search_lower(key,key_lower,avl[0])
        elif avl[1] < key:
            key_lower = avl[1]
            if avl[2] == None:
                return key_lower
            else:
                return self.search_lower(key,key_lower,avl[2])
        #avl[1] == keyの場合
        if avl[0] == None:
            return key_lower
        else:
            if key_lower == None:
                return self.end_higher(avl[0][1],avl[0])
            else:
                return max(key_lower,self.end_higher(avl[0][1],avl[0]))

    def search_higher(self,key,key_higher=None,avl=0):
        if avl == 0:
            avl = self.avl
        if avl == None:
            return key_higher
        if  key < avl[1]:
            key_higher = avl[1]
            if avl[0] == None:
                return key_higher
            else:
                return self.search_higher(key,key_higher,avl[0])
        if avl[1] < key:
            if avl[2] == None:
                return key_higher
            else:
                return self.search_higher(key,key_higher,avl[2])
        #self.key == keyの場合
        if avl[2] == None:
            return key_higher
        else:
            if key_higher == None:
                return self.end_lower(avl[2][1],avl[2])
            else:
                return min(key_higher,self.end_lower(avl[2][1],avl[2]))

    def end_lower(self,end_lower_key,avl=None):
        if avl == None:
            avl = self.avl
        if avl[0] == None:
            return end_lower_key
        else:
            end_lower_key = avl[0][1]
            return self.end_lower(end_lower_key,avl[0])
    def end_higher(self,end_higher_key,avl=None):
        if avl == None:
            avl = self.avl
        if avl[2] == None:
            return end_higher_key
        else:
            end_higher_key = avl[2][1]
            return self.end_higher(end_higher_key,avl[2])

    def DoubleRightRotation(self,avl):
        tl = avl[0]
        avl[0] = tl[2][2]
        tl[2][2] = avl # selfはそのノード
        tlr = tl[2]
        tl[2] = tlr[0]
        tlr[0] = tl
        if tlr[3] == 1:
            tlr[2][3] = 2
            tlr[0][3] = 0
        elif tlr[3] == 2:
            tlr[2][3] = 0
            tlr[0][3] = 1
        elif tlr[3] == 0:
            tlr[2][3] = 0
            tlr[0][3] = 0
        tlr[3] = 0
        return tlr

    def DoubleLeftRotation(self,avl):
        tr = avl[2]
        avl[2] = tr[0][0]
        tr[0][0] = avl
        trl = tr[0]
        tr[0] = trl[2]
        trl[2] = tr
        if trl[3] == 2:
            trl[0][3] = 1
            trl[2][3] = 0
        elif trl.balance == 1:
            trl[0][3] = 0
            trl[2][3] = 2
        elif trl.balance == 0:
            trl[0][3] = 0
            trl[2][3] = 0
        trl[3] = 0
        return trl

    def SingleLeftRotation(self,avl):
        tr = avl[2]
        tr[3] = 0
        avl[3] = 0
        avl[2] = tr[0]
        tr[0] = avl
        return tr

    def SingleRightRotation(self,avl):
        tl = avl[0]
        tl[3] = 0
        avl[3] = 0
        avl[0] = tl[2]
        tl[2] = avl
        return tl

    def replace(self,p,v,avl): # 親ノードpの下にある自分(avl)をvに置き換える。
        if p[0] is avl:
            p[0] = v
        else :
            p[2] = v

    def insert(self,key): # rootでのみ呼ばれる挿入
        if self.avl[1] == None: # rootを含むrotationはしないことにする。
            self.avl[1] = key
            return self.avl
        if key < self.avl[1]:
            if self.avl[0] == None:
                self.avl[0] = self.node(key)
            else:
                self.insertx(self.avl,key,self.avl[0])
        elif self.avl[1] < key:
            if self.avl[2] == None:
                self.avl[2] = self.node(key)
            else:
                self.insertx(self.avl,key,self.avl[2])
        else: # key == self.avl[1]:
            pass # do not overwrite
    def insertx(self,p,key,avl): # replaceを呼ぶために一つ上の親を持っているinsert
        if key < avl[1]:
            if avl[0] == None:
                avl[0] = self.node(key)
            else:
                if not self.insertx(avl,key,avl[0]): # 左の木が生長しなければ、
                    return False # 成長しない
            balance = avl[3]
            if balance == 2:
                avl[3] = 0
                return False
            elif balance == 0:
                avl[3] = 1
                return True # 成長した
            elif balance == 1:
                if avl[0][3] == 2:
                    self.replace(p,self.DoubleRightRotation(avl),avl)
                elif self.left.balance == 1:
                    self.replace(p,self.SingleRightRotation(avl),avl)
                return False # rotationを行うと成長しない
        if avl[1] < key:
            if avl[2] == None:
                avl[2] = self.node(key)
            else:
                if not self.insertx(avl,key,avl[2]):
                    return False
            balance = avl[3]
            if balance == 1:
                avl[3] = 0
                return False
            elif balance == 0:
                avl[3] = 2
                return True
            elif balance == 2:
                if avl[2][3] == 1:
                    self.replace(p,self.DoubleLeftRotation(avl),avl)
                elif avl[2][3] == 2:
                    self.replace(p,self.SingleLeftRotation(avl),avl)
                return False
        return False # avl[1] == keyの時は何もしないので成長もしない

    def debug(self):
        print(self.avl)

def main():
    a, b, q = map(int,input().split())
    treeA, treeB = AvlTree(), AvlTree()
    INF = 10**12
    for _ in range(a): treeA.insert(int(input()))
    for _ in range(b): treeB.insert(int(input()))
    for _ in range(q):
        i = int(input())
        p1,p2 = 0, 0
        alow = treeA.search_lower(i)
        ahigh = treeA.search_higher(i)
        p1 = abs(alow-i) if alow else INF
        p2 = abs(ahigh-i) if ahigh else INF
        if alow:
            add = INF
            if treeB.search_lower(alow):
                add = min(abs(treeB.search_lower(alow)-alow),add)
            if treeB.search_higher(alow):
                add = min(abs(treeB.search_higher(alow)-alow),add)
            p1 += add
        if ahigh:
            add = INF
            if treeB.search_lower(ahigh):
                add = min(abs(treeB.search_lower(ahigh)-ahigh),add)
            if treeB.search_higher(ahigh):
                add = min(abs(treeB.search_higher(ahigh)-ahigh),add)
            p2 += add
        ans = min(p1,p2)
        # btoa
        p3,p4 = 0, 0
        blow = treeB.search_lower(i)
        bhigh = treeB.search_higher(i)
        p3 = abs(blow-i) if blow else INF
        p4 = abs(bhigh-i) if bhigh else INF
        if blow:
            add = INF
            if treeA.search_lower(blow):
                add = min(abs(treeA.search_lower(blow)-blow),add)
            if treeA.search_higher(blow):
                add = min(abs(treeA.search_higher(blow)-blow),add)
            p3 += add
        if bhigh:
            add = INF
            if treeA.search_lower(bhigh):
                add = min(abs(treeA.search_lower(bhigh)-bhigh),add)
            if treeA.search_higher(bhigh):
                add = min(abs(treeA.search_higher(bhigh)-bhigh),add)
            p4 += add
        ans = min(p3,p4,ans)
        print(ans)

if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.readline

class AvlTree:
    """ Avl木を表現するクラス """
    def __init__(self):
        self.avl = [None,None,None,0]

    def node(self,key):
        return [None,key,None,0]

    # search(x) xが存在するならTrueをしないならFalseを返す
    def search(self,key,avl=None):
        if avl == None:
            avl = self.avl
        if key == avl[1]:
            return True
        elif key < avl[1]:
            if avl[0] == None:
                return False
            else:
                return self.search(key,avl[0])
        elif avl[1] < key:
            if avl[2] == None:
                return False
            else:
                return self.search(key,avl[2])

    def search_lower(self,key,key_lower=None,avl=0):
        if avl == 0:
            avl = self.avl
        if avl == None:
            return key_lower
        elif key < avl[1]:
            if avl[0] == None:
                return key_lower
            else:
                return self.search_lower(key,key_lower,avl[0])
        elif avl[1] < key:
            key_lower = avl[1]
            if avl[2] == None:
                return key_lower
            else:
                return self.search_lower(key,key_lower,avl[2])
        #avl[1] == keyの場合
        if avl[0] == None:
            return key_lower
        else:
            if key_lower == None:
                return self.end_higher(avl[0][1],avl[0])
            else:
                return max(key_lower,self.end_higher(avl[0][1],avl[0]))

    def search_higher(self,key,key_higher=None,avl=0):
        if avl == 0:
            avl = self.avl
        if avl == None:
            return key_higher
        if  key < avl[1]:
            key_higher = avl[1]
            if avl[0] == None:
                return key_higher
            else:
                return self.search_higher(key,key_higher,avl[0])
        if avl[1] < key:
            if avl[2] == None:
                return key_higher
            else:
                return self.search_higher(key,key_higher,avl[2])
        #self.key == keyの場合
        if avl[2] == None:
            return key_higher
        else:
            if key_higher == None:
                return self.end_lower(avl[2][1],avl[2])
            else:
                return min(key_higher,self.end_lower(avl[2][1],avl[2]))

    def end_lower(self,end_lower_key,avl=None):
        if avl == None:
            avl = self.avl
        if avl[0] == None:
            return end_lower_key
        else:
            end_lower_key = avl[0][1]
            return self.end_lower(end_lower_key,avl[0])
    def end_higher(self,end_higher_key,avl=None):
        if avl == None:
            avl = self.avl
        if avl[2] == None:
            return end_higher_key
        else:
            end_higher_key = avl[2][1]
            return self.end_higher(end_higher_key,avl[2])

    def DoubleRightRotation(self,avl):
        tl = avl[0]
        avl[0] = tl[2][2]
        tl[2][2] = avl # selfはそのノード
        tlr = tl[2]
        tl[2] = tlr[0]
        tlr[0] = tl
        if tlr[3] == 1:
            tlr[2][3] = 2
            tlr[0][3] = 0
        elif tlr[3] == 2:
            tlr[2][3] = 0
            tlr[0][3] = 1
        elif tlr[3] == 0:
            tlr[2][3] = 0
            tlr[0][3] = 0
        tlr[3] = 0
        return tlr

    def DoubleLeftRotation(self,avl):
        tr = avl[2]
        avl[2] = tr[0][0]
        tr[0][0] = avl
        trl = tr[0]
        tr[0] = trl[2]
        trl[2] = tr
        if trl[3] == 2:
            trl[0][3] = 1
            trl[2][3] = 0
        elif trl.balance == 1:
            trl[0][3] = 0
            trl[2][3] = 2
        elif trl.balance == 0:
            trl[0][3] = 0
            trl[2][3] = 0
        trl[3] = 0
        return trl

    def SingleLeftRotation(self,avl):
        tr = avl[2]
        tr[3] = 0
        avl[3] = 0
        avl[2] = tr[0]
        tr[0] = avl
        return tr

    def SingleRightRotation(self,avl):
        tl = avl[0]
        tl[3] = 0
        avl[3] = 0
        avl[0] = tl[2]
        tl[2] = avl
        return tl

    def replace(self,p,v,avl): # 親ノードpの下にある自分(avl)をvに置き換える。
        if p[0] is avl:
            p[0] = v
        else :
            p[2] = v

    def insert(self,key): # rootでのみ呼ばれる挿入
        if self.avl[1] == None: # rootを含むrotationはしないことにする。
            self.avl[1] = key
            return self.avl
        if key < self.avl[1]:
            if self.avl[0] == None:
                self.avl[0] = self.node(key)
            else:
                self.insertx(self.avl,key,self.avl[0])
        elif self.avl[1] < key:
            if self.avl[2] == None:
                self.avl[2] = self.node(key)
            else:
                self.insertx(self.avl,key,self.avl[2])
        else: # key == self.avl[1]:
            pass # do not overwrite
    def insertx(self,p,key,avl): # replaceを呼ぶために一つ上の親を持っているinsert
        if key < avl[1]:
            if avl[0] == None:
                avl[0] = self.node(key)
            else:
                if not self.insertx(avl,key,avl[0]): # 左の木が生長しなければ、
                    return False # 成長しない
            balance = avl[3]
            if balance == 2:
                avl[3] = 0
                return False
            elif balance == 0:
                avl[3] = 1
                return True # 成長した
            elif balance == 1:
                if avl[0][3] == 2:
                    self.replace(p,self.DoubleRightRotation(avl),avl)
                elif self.left.balance == 1:
                    self.replace(p,self.SingleRightRotation(avl),avl)
                return False # rotationを行うと成長しない
        if avl[1] < key:
            if avl[2] == None:
                avl[2] = self.node(key)
            else:
                if not self.insertx(avl,key,avl[2]):
                    return False
            balance = avl[3]
            if balance == 1:
                avl[3] = 0
                return False
            elif balance == 0:
                avl[3] = 2
                return True
            elif balance == 2:
                if avl[2][3] == 1:
                    self.replace(p,self.DoubleLeftRotation(avl),avl)
                elif avl[2][3] == 2:
                    self.replace(p,self.SingleLeftRotation(avl),avl)
                return False
        return False # avl[1] == keyの時は何もしないので成長もしない

    def debug(self):
        print(self.avl)

a, b, q = map(int,input().split())
treeA, treeB = AvlTree(), AvlTree()
INF = 10**12
for _ in range(a): treeA.insert(int(input()))
for _ in range(b): treeB.insert(int(input()))
for _ in range(q):
    i = int(input())
    p1,p2 = 0, 0
    alow = treeA.search_lower(i)
    ahigh = treeA.search_higher(i)
    p1 = abs(alow-i) if alow else INF
    p2 = abs(ahigh-i) if ahigh else INF
    if alow:
        add = INF
        if treeB.search_lower(alow):
            add = min(abs(treeB.search_lower(alow)-alow),add)
        if treeB.search_higher(alow):
            add = min(abs(treeB.search_higher(alow)-alow),add)
        p1 += add
    if ahigh:
        add = INF
        if treeB.search_lower(ahigh):
            add = min(abs(treeB.search_lower(ahigh)-ahigh),add)
        if treeB.search_higher(ahigh):
            add = min(abs(treeB.search_higher(ahigh)-ahigh),add)
        p2 += add
    ans = min(p1,p2)
    # btoa
    p3,p4 = 0, 0
    blow = treeB.search_lower(i)
    bhigh = treeB.search_higher(i)
    p3 = abs(blow-i) if blow else INF
    p4 = abs(bhigh-i) if bhigh else INF
    if blow:
        add = INF
        if treeA.search_lower(blow):
            add = min(abs(treeA.search_lower(blow)-blow),add)
        if treeA.search_higher(blow):
            add = min(abs(treeA.search_higher(blow)-blow),add)
        p3 += add
    if bhigh:
        add = INF
        if treeA.search_lower(bhigh):
            add = min(abs(treeA.search_lower(bhigh)-bhigh),add)
        if treeA.search_higher(bhigh):
            add = min(abs(treeA.search_higher(bhigh)-bhigh),add)
        p4 += add
    ans = min(p3,p4,ans)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import bisect
A,B,Q = [int(n) for n in input().split()]
# N = int(input())
INF = 10 **18
s = [0]*A
t = [0]*B
s = [-INF] + [int(input()) for n in range(A)] + [INF]
t = [-INF] + [int(input()) for n in range(B)] + [INF]
def binary_search(arry, target):
    result = None
    left = 0
    right = len(arry) - 1

    while left <= right:
        mid = (left + right) // 2
        if arry[mid] == target:
            result = mid
            break
        elif arry[mid] > target:
            right = mid - 1
        else:
            left = mid + 1

    if result == None:
        result = mid
        if(mid+1 < len(arry)):
            result = mid+1 if (abs(arry[mid+1] - target) < abs(arry[mid] - target)) else result
        if(mid-1 >= 0):
            result = mid-1 if (abs(arry[result] - target) > abs(arry[mid-1] - target)) else result
        return result
    else:
        return result+1

for i in range(Q):
    x = int(input())
    mostntera = binary_search(s,x)
    # print(mostntera)
    tera0 = s[mostntera]
    tera1 = s[mostntera-1] if x-tera0<0 else s[mostntera+1]
    # print(tera0,tera1)
    mostnzin = binary_search(t,x)
    zin0 = t[mostnzin]
    zin1 = t[mostnzin-1] if x-zin0<0 else t[mostnzin+1]
    # print(zin0,zin1)
    ans = INF
    for a in [tera0, tera1]:
        for b in [zin0,zin1]:
            d1,d2 = abs(x-a) +abs(a-b), abs(x-b) + abs(a-b)
            ans = min(ans,d1,d2)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import bisect
A,B,Q = [int(n) for n in input().split()]
# N = int(input())
INF = 10 **18
s = [0]*A
t = [0]*B
x = [0]*Q
s = [-INF] + [int(input()) for n in range(A)] + [INF]
t = [-INF] + [int(input()) for n in range(B)] + [INF]
def binary_search(arry, target):
    result = None
    left = 0
    right = len(arry) - 1

    while left <= right:
        mid = (left + right) // 2
        if arry[mid] == target:
            result = mid
            break
        elif arry[mid] > target:
            right = mid - 1
        else:
            left = mid + 1

    if result == None:
        result = mid
        if(mid+1 < len(arry)):
            result = mid+1 if (abs(arry[mid+1] - target) < abs(arry[mid] - target)) else result
        if(mid-1 >= 0):
            result = mid-1 if (abs(arry[result] - target) > abs(arry[mid-1] - target)) else result
        return result
    else:
        return result+1

for q in range(Q):
    x = int(input())
    mostntera = binary_search(s,x)
    # print(mostntera)
    tera0 = s[mostntera]
    tera1 = s[mostntera-1] if x-tera0<0 else s[mostntera+1]
    # print(tera0,tera1)
    mostnzin = binary_search(t,x)
    zin0 = t[mostnzin]
    zin1 = t[mostnzin-1] if x-zin0<0 else t[mostnzin+1]
    # print(zin0,zin1)
    ans = INF
    for a in [tera0, tera1]:
        for b in [zin0,zin1]:
            d1,d2 = abs(x-a) +abs(a-b), abs(x-b) + abs(a-b)
            ans = min(ans,d1,d2)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
import bisect
A,B,Q = [int(n) for n in input().split()]
# N = int(input())
INF = 10 **18
s = [0]*A
t = [0]*B
x = [0]*Q
s = [-INF] + [int(input()) for n in range(A)] + [INF]
t = [-INF] + [int(input()) for n in range(B)] + [INF]
x = [int(input()) for n in range(Q)]
def binary_search(arry, target):
    result = None
    left = 0
    right = len(arry) - 1

    while left <= right:
        mid = (left + right) // 2
        if arry[mid] == target:
            result = mid
            break
        elif arry[mid] > target:
            right = mid - 1
        else:
            left = mid + 1

    if result == None:
        result = mid
        if(mid+1 < len(arry)):
            result = mid+1 if (abs(arry[mid+1] - target) < abs(arry[mid] - target)) else result
        if(mid-1 >= 0):
            result = mid-1 if (abs(arry[result] - target) > abs(arry[mid-1] - target)) else result
        return result
    else:
        return result+1

for q in x:
    mostntera = binary_search(s,q)
    # print(mostntera)
    tera0 = s[mostntera]
    tera1 = s[mostntera-1] if q-tera0<0 else s[mostntera+1]
    # print(tera0,tera1)
    mostnzin = binary_search(t,q)
    zin0 = t[mostnzin]
    zin1 = t[mostnzin-1] if q-zin0<0 else t[mostnzin+1]
    # print(zin0,zin1)
    ans = INF
    for a in [tera0, tera1]:
        for b in [zin0,zin1]:
            d1,d2 = abs(q-a) +abs(a-b), abs(q-b) + abs(a-b)
            ans = min(ans,d1,d2)
    print(ans)