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 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())
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
x = [int(input()) for i in range(q)]
lens, lent = len(s), len(t)
treeA, treeB = Avltree(), Avltree()
for i in s: treeA.insert(i) # 木を作る
for i in t: treeB.insert(i)
for i in x:
    # 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 = 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 = 10**10
  for i, bi in enumerate(b_list):
    if (abs(a_list[a_num] - bi)) <= lb1:
      lb1 = abs(a_list[a_num] - bi)
  lb2 = 10**10
  for i, bi in enumerate(b_list):
    if (abs(qi - bi)) <= lb2:
      lb2 = abs(qi - bi)
      b_num = i
  la2 = 10**10
  for i, ai in enumerate(a_list):
    if (abs(b_list[b_num] - ai)) <= la2:
      la2 = abs(b_list[b_num] - ai)
  print(min(la1+lb1, la2+lb2))

Submission status: Time Limit Exceeded

Solution code:
def get_nearest(x, al):
    costs = [abs(a - x) for a in al]
    min_cost = min(costs)

    return min_cost, [al[i] for i, x in enumerate(costs) if x == min_cost]


def get_cost(x, al, bl):
    a_cost, a_positions = get_nearest(x, al)
    for ap in a_positions:
        b_cost, b_positions = get_nearest(ap, bl)

    return a_cost + b_cost


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:
    print(min(get_cost(x, sl, tl), get_cost(x, tl, sl)))

    # 最初に寺

    # 最初に神社

Submission status: Time Limit Exceeded

Solution code:
import bisect

A, B, Q = map(int, input().split())

INF = 1<<60

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

bisect.insort_left(s, -INF)
bisect.insort_left(s, INF)
bisect.insort_left(t, -INF)
bisect.insort_left(t, INF)

def cost(sl, sr, tl, tr):
    tmp = INF
    tmp = min(tmp, sl * 2 + tr)
    tmp = min(tmp, tl * 2 + sr)
    tmp = min(tmp, sr * 2 + tl)
    tmp = min(tmp, tr * 2 + sl)
    tmp = min(tmp, max(sl, tl))
    tmp = min(tmp, max(sr, tr))
    return tmp

# print(s)
# print(t)

for _ in range(Q):
    x = int(input())
    # print(x)
    sl = x - s[bisect.bisect_left(s, x) - 1]
    sr = s[bisect.bisect_left(s, x)] - x
    tl = x - t[bisect.bisect_left(t, x) - 1]
    tr = t[bisect.bisect_left(t, x)] - x
    print(cost(sl, sr, tl, tr))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np


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


A, B, Q = map(int, input().split())
s = [int(input()) for _ in range(A)]
t = [int(input()) for _ in range(B)]
x = [int(input()) for _ in range(Q)]
for query in x:
    shrine = findShrineAndTemple(s, query)
    temple = findShrineAndTemple(t, query)
    planA = abs(query - shrine) + abs(findShrineAndTemple(t, shrine) - shrine)
    planB = abs(query - temple) + abs(findShrineAndTemple(s, temple) - temple)
    print(min(planA, planB))

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
        #print ("d",diff)
        if abs_diff > abs(diff):
            min_diff = diff
            abs_diff = abs(diff)
        
    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:
a,b,q = map(int,input().split())
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
x = [int(input()) for i in range(q)]
ans = []
for x_ in x:
    s_ = []
    t_ = []
    for i in range(len(s)):
        s_.append(s[i]-x_)
    for i in range(len(t)):
        t_.append(t[i]-x_)
    s_l=-float('inf')
    s_r=float('inf')
    t_l=-float('inf')
    t_r=float('inf')
    for k in s_:
        if k<0:
            s_l=k
        else:
            s_r=k
            break
    for k in t_:
        if k<0:
            t_l=k
        else:
            t_r=k
            break
    ans.append(min(max(abs(s_l),abs(t_l)),abs(s_l)*2+t_r,t_r*2+abs(s_l),max(s_r,t_r),s_r*2+abs(t_l),abs(t_l)*2+s_r))
for ans_ in ans:
    print(ans_)

Submission status: Time Limit Exceeded

Solution code:
import bisect

A, B, Q = map(int, input().split())
s = []
sd = {}
for i in range(A):
    x = int(input())
    s.append(x)
    sd[i] = x
t = []
td = {}
for i in range(B):
    x = int(input())
    t.append(x)
    td[i] = x
for i in range(Q):
    x = int(input())
    j = bisect.bisect(s, x)
    ans = 2 * 10 ** 10
    if j > 0:
        k = bisect.bisect(t, sd[j - 1])
        if k > 0:
            ans = min(ans,abs(x-sd[j-1])+abs(sd[j-1]-td[k-1]))
        if k < B:
            ans = min(ans, abs(x-sd[j-1])+abs(sd[j-1]-td[k]))
    if j < A:
        k = bisect.bisect(t, sd[j])
        if k > 0:
            ans = min(ans, abs(x-sd[j])+abs(sd[j]-td[k-1]))
        if k < B:
            ans = min(ans, abs(x-sd[j])+abs(sd[j]-td[k]))
    j = bisect.bisect(t, x)
    if j > 0:
        k = bisect.bisect(s, td[j - 1])
        if k > 0:
            ans = min(ans,abs(x-td[j-1])+abs(td[j-1]-sd[k-1]))
        if k < A:
            ans = min(ans, abs(x-td[j-1])+abs(td[j-1]-sd[k]))
    if j < B:
        k = bisect.bisect(s, td[j])
        if k > 0:
            ans = min(ans, abs(x-td[j])+abs(td[j]-sd[k-1]))
        if k < A:
            ans = min(ans, abs(x-td[j])+abs(td[j]-sd[k]))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np

# リストからある値に最も近い値を返却する関数
def getNearestValue(list, num):
    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

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

ST=[]
for i in range(a):
    k=int(input())
    ST.append([k,0,0])
for i in range(b):
    k=int(input())
    ST.append([k,1,0])

ST.sort()
for i in range(a+b):
    ty=ST[i][1]
    le=i-1
    ri=i+1
    moyori=np.inf
    while le>=0 and ST[le][1]==ty :
        le-=1
    if le>=0:
        moyori=min(moyori,abs(ST[i][0]-ST[le][0]))
    while ri<=a+b-1 and ST[ri][1]==ty :
        ri+=1
    if ri<=a+b-1:
        moyori=min(moyori,abs(ST[i][0]-ST[ri][0]))
    ST[i][2]=moyori

for i in range(q):
    k=int(input())
    ST.append([k,2,0,i])

ST.sort()

ANS=[]
for i in range(a+b+q):
    if ST[i][1]==2 :
        moyori=np.inf
        for typ in range(2):
            le=i-1
            ri=i+1
            
            while le>=0 and (ST[le][1]==typ or ST[le][1]==2) :
                le-=1
            if le>=0:
                moyori=min(moyori,abs(ST[i][0]-ST[le][0])+ST[le][2])
                #print("L")
                #print(moyori)
            while ri<=a+b+q-1 and (ST[ri][1]==typ or ST[ri][1]==2):
                ri+=1
            if ri<=a+b+q-1 :
                moyori=min(moyori,abs(ST[i][0]-ST[ri][0])+ST[ri][2])
                #print("R")
                #print(moyori)
        ST[i][2]=moyori
        ANS.append([ST[i][3],moyori])

ANS.sort()

#print(ST)

for i in range(q):
    print(ANS[i][1])

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left, bisect_right
a, b, q = map(int, input().split())
s = [int(input()) for _ in range(a)]
t = [int(input()) for _ in range(b)]
q = [int(input()) for _ in range(q)]
for qi in q:
    qans = 10**18
    ai = bisect_left(s, qi)
    bi = bisect_left(t, qi)
    ac = []
    bc = []
    for i in range(3):
        if (0 <= ai + i < a):
            ac.append(ai + i);
        if (0 <= ai - i < a):
            ac.append(ai - i);
    for i in range(3):
        if (0 <= bi + i < b):
            bc.append(bi + i);
        if (0 <= bi - i < b):
            bc.append(bi - i);
    for i in ac:
        for j in bc:
            aa = s[i];
            bb = t[j];
            if (max(aa, bb) <= qi):
                qans = min(qans, qi - min(aa, bb))
            elif (qi <= min(aa, bb)):
                qans = min(qans, max(aa, bb) - qi)
            else:
                qans = min(qans, min(abs(aa - qi), abs(bb - qi)) * 2 + max(abs(aa - qi), abs(bb - qi)))
    print(qans)

Submission status: Time Limit Exceeded

Solution code:
def main():
  A, B, Q = map(int, input().split())
  S = [int(input()) for i in range(A)]
  T = [int(input()) for i in range(B)]
  X = [int(input()) for i in range(Q)]

  for x in X:
    l = [abs(x-s)+abs(s-t) for s in S for t in T]
    m = [abs(x-t)+abs(t-s) for s in S for t in T]
    print(min(min(l),min(m)))

main()

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import bisect

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

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

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

Submission status: Time Limit Exceeded

Solution code:
(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)]


def find_left_and_right(st, pos):
    for i, s_i in enumerate(st):
        if s_i - pos > 0:
            return (i-1, i)
    return (len(st) - 1, -1)


def find_optimum(ss, ts, pos):
    (sl_index, sr_index) = find_left_and_right(ss, pos)
    (tl_index, tr_index) = find_left_and_right(ts, pos)

    penalty = 9999999999999
    s_left = s[sl_index] if 0 <= sl_index else penalty
    s_right = s[sr_index] if 0 <= sr_index else penalty
    t_left = t[tl_index] if 0 <= tl_index else penalty
    t_right = t[tr_index] if 0 <= tr_index else penalty

    dist0 = abs(s_left - pos) + min(abs(t_left - s_left), abs(t_right - s_left))
    dist1 = abs(s_right - pos) + min(abs(t_left - s_right), abs(t_right - s_right))
    dist2 = abs(t_left - pos) + min(abs(s_left - t_left), abs(s_right - t_left))
    dist3 = abs(t_right - pos) + min(abs(s_left - t_right), abs(s_right - t_right))
    return min([dist0, dist1, dist2, dist3])


for x_i in x:
    print(find_optimum(s, t, x_i))

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

for x in X:
  l = [abs(x-s)+abs(s-t) for s in S for t in T]
  m = [abs(x-t)+abs(t-s) for s in S for t in T]
  print(min(min(l),min(m)))

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
S = [0] * A
T = [0] * B
for i in range(A):
  S[i] = int(input())
for i in range(B):
  T[i] = int(input())
def lr_find(x, Y):
  if x < Y[0]:
    return [0, Y[0]]
  if x >= Y[-1]:
    return [Y[-1], 0]
  l, r = 0, len(Y) - 1
  while r - l > 1:
    m = (l + r) // 2
    if x < Y[m]:
      r = m
    else:
      l = m
  return [Y[l], Y[r]]
for q in range(Q):
  x = int(input())
  D = [lr_find(x, S), lr_find(x, T)]
  ans = 10 ** 12
  for i in range(8):
    s = D[0][i % 2]
    t = D[1][(i // 2) % 2]
    if s and t:
      dist = abs(s - t) + abs(x - [s, t][(i // 4) % 2])
      ans = min(dist, ans)
  print(ans)

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):
  first = 0
  second = 0
  sum_second = 0
  sum_first = 0
  for j in range(len(lst1)):
    if lst1[j] > q[i]:
      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 - q[i]) + abs(second - tera_second)
    result = sum_second
    if first!=0:
      tera_first = getValue(lst2,first)
      sum_first = abs(first - q[i]) + 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)
  result2 = resultjudge(tera, jinjya)
  if result1>result2:
    result = result2
  else:
    result = result1
  print(result)

Submission status: Time Limit Exceeded

Solution code:
# def out_end(nums):
#     result = 0
#     for each in nums:
#         result = result * 10 + each
#     exit()
#
#
# n = [int(each) for each in input().split()]
# n, m = n[0], n[1]
#
# a = [int(each) for each in input().split()]
# a.sort(reverse=True)
#
# costs = [
#     (1, 2), (2, 5), (3, 5), (4, 4), (5, 5), (6, 6), (7, 3), (8, 7), (9, 6)
# ]
#
# use_nums = []
# for each in a:
#     use_nums.append(costs[each + 1])
#
# nums = []
# remaining = n
#
# while remaining > 0:
#     for use_num in use_nums:
#         if remaining - use_num[1] > 0:
#             remaining -= use_num[1]
#             nums.append(use_num[0])
#         if remaining - use_num[1] == 0:
#             nums.append(use_num[0])
#             out_end(nums)
#         # else:
#         #     # 下の桁から順に数を検索
#         #
#         #     checked = [False for each in use_nums]
#         #     for keta in nums.reverse():
#         #         if

def get_nearest(x, al):
    cost = None
    positions = []
    for a in al:
        if cost is None:
            cost = abs(a - x)
            positions = [a]
        elif cost > abs(a - x):
            cost = abs(a - x)
            positions = [a]
        elif cost == abs(a - x):
            positions.append(a)
        else:
            pass
    return cost, positions


def get_cost(x, al, bl):
    a_cost, a_positions = get_nearest(x, al)

    # print('a_cost', a_cost)
    # print('a_positions', a_positions)
    for ap in a_positions:
        b_cost, b_positions = get_nearest(ap, bl)

    return a_cost + b_cost


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

# print('sl', sl)
# print('tl', tl)
# print('xl', xl)

result = []
for x in xl:
    print(min(get_cost(x, sl, tl), get_cost(x, tl, sl)))

    # 最初に寺

    # 最初に神社

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
S, T =[None] * (A+1), [None] * (B+1)
S[0], T[0] = -10**20, -10**20
for i in range(A):
    S[i+1] = int(input())
for i in range(B):
    T[i+1] = int(input())
S.append(10**20)
T.append(10**20)

def Bsearch(x, L, lenL):
    low, high = 0, lenL
    while high-low > 1:
        mid = (low+high)//2
        if L[mid] > x:
            high = mid
        else: low = mid
    return [x-L[low], L[low+1]-x]

lenS, lenT = len(S), len(T)
for _ in range(Q):
    x = int(input())
    sLength0, sLength1 = Bsearch(x, S, lenS)
    tLength0, tLength1 = Bsearch(x, T, lenT)
    Ans = [max(sLength0, tLength0), max(sLength1, tLength1), sLength0 + tLength1 + min(sLength0, tLength1), sLength1 + tLength0 + min(sLength1, tLength0)]
    print(min(Ans))

Submission status: Time Limit Exceeded

Solution code:
import bisect
from itertools import permutations
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)
    c = []
    if sr == A:
        c.append([S[A-1], 0])
    elif sr == 0:
        c.append([S[sr], 0])
    else:
        c.append([S[sr], 0])
        c.append([S[sr-1], 0])
    if tr == B:
        c.append([T[B-1], 1])
    elif tr == 0:
        c.append([T[tr], 1])
    else:
        c.append([T[tr], 1])
        c.append([T[tr-1], 1])
    ans = 10**16
    for elem in permutations(c):
        tmp = 0
        flag = [False, False]
        now_pos = x
        flag_calc = True
        for pos, kind in elem:
            if flag[kind]:
                flag_calc = False
                break
            tmp += abs(pos-now_pos)
            now_pos = pos
            flag[kind] = True
            if flag[0] and flag[1]:
                break
        if flag_calc:
            ans = min(ans, tmp)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
a, b, q = [int(i) for i in input().split()]
ss = [int(input()) for i in range(a)]
ts = [int(input()) for i in range(b)]
xs = [int(input()) for i in range(q)]
# print(ss)
# print(ts)
# print(xs)
for x in xs:
    ans1 = 10e11
    min_len, which = 10e11, None
    tmp_x = x
    for i in ss:
        if i - x > 0 and min_len > i - x:
            min_len = i - x
            which = 's'
            tmp_x = i
    for i in ts:
        if i - x > 0  and min_len > i - x:
            min_len = i - x
            which = 't'
            tmp_x = i

    # print(min_len, which)
    if which == 's':
        tmp_ts = [abs(t - tmp_x) for t in ts]
        ans1 = min_len + min(tmp_ts)
    elif which == 't':
        tmp_ss = [abs(s - tmp_x) for s in ss]
        ans1 = min_len + min(tmp_ss)
    # print(ans1)

    ans2 = 10e11
    min_len, which = 10e11, None
    tmp_x = x
    for i in ss:
        if x - i > 0 and min_len > x - i:
            min_len = x - i
            which = 's'
            tmp_x = i
    for i in ts:
        if x - i > 0  and min_len > x - i:
            min_len = x - i
            which = 't'
            tmp_x = i

    # print(min_len, which)
    if which == 's':
        tmp_ts = [abs(t - tmp_x) for t in ts]
        ans2 = min_len + min(tmp_ts)
    elif which == 't':
        tmp_ss = [abs(s - tmp_x) for s in ss]
        ans2 = min_len + min(tmp_ss)
    # print(ans2)
    print(min(ans1, ans2))

Submission status: Time Limit Exceeded

Solution code:
import bisect
from itertools import permutations
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)
    none_flag = [False, False]
    c = []
    d = []
    if sr == A:
        sr = None
        sl = A-1
        none_flag[0] = True
        c.append([S[sl], 0])
        d.append(S[sl])
    elif sr == 0:
        sl = None
        none_flag[0] = True
        c.append([S[sr], 0])
        d.append(S[sr])
    else:
        sl = sr-1
        c.append([S[sr], 0])
        c.append([S[sl], 0])
        d.append(S[sl])
        d.append(S[sr])
    if tr == B:
        tr = None
        none_flag[1] = True
        tl = B-1
        c.append([T[tl], 1])
        d.append(T[tl])
    elif tr == 0:
        tl = None
        none_flag[1] = True
        c.append([T[tr], 1])
        d.append(T[tr])
    else:
        tl = tr-1
        c.append([T[tr], 1])
        c.append([T[tl], 1])
        d.append(T[tr])
        d.append(T[tl])
    c.sort()
    ans = 10**16
    for elem in permutations(c):
        tmp = 0
        flag = [False, False]
        now_pos = x
        flag_calc = True
        for pos, kind in elem:
            if flag[kind]:
                flag_calc = False
                break
            tmp += abs(pos-now_pos)
            now_pos = pos
            flag[kind] = True
            if flag[0] and flag[1]:
                break
        if flag_calc:
            ans = min(ans, tmp)
    print(ans)