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 copy
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()))
for i in range(q):
    c_s = []
    c_t = []
    dist_s_t = []
    s2 = copy.deepcopy(s)
    t2 = copy.deepcopy(t)
    s3 = copy.deepcopy(s)
    t3 = copy.deepcopy(t)
    s4 = copy.deepcopy(s)
    t4 = copy.deepcopy(t)
    s2.append(x[i])
    s2.sort()
    idx_s = s2.index(x[i])
    t2.append(x[i])
    t2.sort()
    idx_t = t2.index(x[i])
    if idx_s == 0:
        c_s.append(s2[1])
    if idx_s == a:
        c_s.append(s2[a-1])
    if 0 < idx_s < a:
        c_s.append(s2[idx_s-1])
        c_s.append(s2[idx_s+1])
    if idx_t == 0:
        c_t.append(t2[1])
    if idx_t == b:
        c_t.append(t2[b-1])
    if 0 < idx_t < b:
        c_t.append(t2[idx_t-1])
        c_t.append(t2[idx_t+1])
    if len(c_s) == 2:
        t3.append(c_s[0])
        t3.sort()
        idx_s0_t = t3.index(c_s[0])
        if idx_s0_t == 0:
             d_s_t = abs(c_s[0] - t3[1])
             d_x_s = abs(x[i] - c_s[0])
             dist_s_t.append(d_s_t + d_x_s)
        if idx_s0_t == b:
             d_s_t = abs(c_s[0] - t3[b-1])
             d_x_s = abs(x[i] - c_s[0])
             dist_s_t.append(d_s_t + d_x_s)
        if 0 < idx_s0_t < b:
             d_s_t1 = abs(c_s[0] - t3[idx_s0_t -1])
             d_s_t2 = abs(c_s[0] - t3[idx_s0_t +1])
             d_x_s = abs(x[i] - c_s[0])
             dist_s_t.append(d_s_t1 + d_x_s)
             dist_s_t.append(d_s_t2 + d_x_s)
        t4.append(c_s[1])
        t4.sort()
        idx_s0_t = t4.index(c_s[1])
        if idx_s0_t == 0:
             d_s_t = abs(c_s[1] - t4[1])
             d_x_s = abs(x[i] - c_s[1])
             dist_s_t.append(d_s_t + d_x_s)
        if idx_s0_t == b:
             d_s_t = abs(c_s[1] - t4[b-1])
             d_x_s = abs(x[i] - c_s[1])
             dist_s_t.append(d_s_t + d_x_s)
        if 0 < idx_s0_t < b:
             d_s_t1 = abs(c_s[1] - t4[idx_s0_t -1])
             d_s_t2 = abs(c_s[1] - t4[idx_s0_t +1])
             d_x_s = abs(x[i] - c_s[1])
             dist_s_t.append(d_s_t1 + d_x_s)
             dist_s_t.append(d_s_t2 + d_x_s)
    elif len(c_s) == 1:
        t3.append(c_s[0])
        t3.sort()
        idx_s0_t = t3.index(c_s[0])
        if idx_s0_t == 0:
             d_s_t = abs(c_s[0] - t3[1])
             d_x_s = abs(x[i] - c_s[0])
             dist_s_t.append(d_s_t + d_x_s)
        if idx_s0_t == b:
             d_s_t = abs(c_s[0] - t3[b-1])
             d_x_s = abs(x[i] - c_s[0])
             dist_s_t.append(d_s_t + d_x_s)
        if 0 < idx_s0_t < b:
             d_s_t1 = abs(c_s[0] - t3[idx_s0_t -1])
             d_s_t2 = abs(c_s[0] - t3[idx_s0_t +1])
             d_x_s = abs(x[i] - c_s[0])
             dist_s_t.append(d_s_t1 + d_x_s)
             dist_s_t.append(d_s_t2 + d_x_s)
    if len(c_t) == 2:
        s3.append(c_t[0])
        s3.sort()
        idx_s_t = s3.index(c_t[0])
        if idx_s_t == 0:
             d_s_t = abs(c_t[0] - s3[1])
             d_x_t = abs(x[i] - c_t[0])
             dist_s_t.append(d_s_t + d_x_t)
        if idx_s_t == a:
             d_s_t = abs(c_t[0] - s3[a-1])
             d_x_t = abs(x[i] - c_t[0])
             dist_s_t.append(d_s_t + d_x_t)
        if 0 < idx_s_t < a:
             d_s_t1 = abs(c_t[0] - s3[idx_s_t -1])
             d_s_t2 = abs(c_t[0] - s3[idx_s_t +1])
             d_x_t = abs(x[i] - c_t[0])
             dist_s_t.append(d_s_t1 + d_x_t)
             dist_s_t.append(d_s_t2 + d_x_t)
        s4.append(c_t[1])
        s4.sort()
        idx_s_t = s4.index(c_t[1])
        if idx_s_t == 0:
             d_s_t = abs(c_t[1] - s4[1])
             d_x_t = abs(x[i] - c_t[1])
             dist_s_t.append(d_s_t + d_x_t)
        if idx_s_t == a:
             d_s_t = abs(c_t[1] - s4[a-1])
             d_x_t = abs(x[i] - c_t[1])
             dist_s_t.append(d_s_t + d_x_t)
        if 0 < idx_s_t < a:
             d_s_t1 = abs(c_t[1] - s4[idx_s_t -1])
             d_s_t2 = abs(c_t[1] - s4[idx_s_t +1])
             d_x_t = abs(x[i] - c_t[1])
             dist_s_t.append(d_s_t1 + d_x_t)
             dist_s_t.append(d_s_t2 + d_x_t)
    elif len(c_t) == 1:
        s3.append(c_t[0])
        s3.sort()
        idx_s_t = s3.index(c_t[0])
        if idx_s_t == 0:
             d_s_t = abs(c_t[0] - s3[1])
             d_x_t = abs(x[i] - c_t[0])
             dist_s_t.append(d_s_t + d_x_t)
        if idx_s_t == a:
             d_s_t = abs(c_t[0] - s3[a-1])
             d_x_t = abs(x[i] - c_t[0])
             dist_s_t.append(d_s_t + d_x_t)
        if 0 < idx_s_t < a:
             d_s_t1 = abs(c_t[0] - s3[idx_s_t -1])
             d_s_t2 = abs(c_t[0] - s3[idx_s_t +1])
             d_x_t = abs(x[i] - c_t[0])
             dist_s_t.append(d_s_t1 + d_x_t)
             dist_s_t.append(d_s_t2 + d_x_t)
    print(min(dist_s_t))

Submission status: Time Limit Exceeded

Solution code:
A,B,Q = map(int,input().split())
INF = 10**18
s=[-INF]
t=[-INF]
for _ in range(A):
    s.append(int(input()))
for _ in range(B):
    t.append(int(input()))
# s.sort()
# t.sort()
s.append(INF)
t.append(INF)
def binSearch(value,upper,lower,array):
    ng = upper
    ok = lower
    while ng>ok+1:
        mid=(ok+ng)//2
        if(array[mid]<value):
            ok=mid
        else:
            ng=mid
    return(ok)

def solve(x):
    I = binSearch(x,A,-1,s)
    J = binSearch(x,B,-1,t)
    candidates=[]
    candidates.append(abs(x-s[I])+abs(s[I]-t[J]))
    candidates.append(abs(x-t[J])+abs(t[J]-s[I]))
    candidates.append(abs(x-s[I+1])+abs(s[I+1]-t[J]))
    candidates.append(abs(x-t[J])+abs(s[I+1]-t[J]))
    candidates.append(abs(x-s[I])+abs(s[I]-t[J+1]))
    candidates.append(abs(x-t[J+1])+abs(s[I]-t[J+1]))
    candidates.append(abs(x-s[I+1])+abs(s[I+1]-t[J+1]))
    candidates.append(abs(x-t[J+1])+abs(s[I+1]-t[J+1]))
    return(min(candidates))

for _ in range(Q):
    X = int(input())
    print(solve(X))

Submission status: Time Limit Exceeded

Solution code:
A,B,Q = map(int,input().split())
s=[]
t=[]
for _ in range(A):
    s.append(int(input()))
for _ in range(B):
    t.append(int(input()))
s.sort()
t.sort()
def binSearch(value,upper,lower,array):
    ng = upper
    ok = lower
    while ng>ok+1:
        mid=(ok+ng)//2
        if(array[mid]<=value):
            ok=mid
        else:
            ng=mid
    return(ok)

def solve(x):
    I = binSearch(x,A,-1,s)
    J = binSearch(x,B,-1,t)
    candidates=[]
    candidates.append(abs(x-s[I])+abs(s[I]-t[J]))
    candidates.append(abs(x-t[J])+abs(t[J]-s[I]))
    if I+1<A:
        candidates.append(abs(x-s[I+1])+abs(s[I+1]-t[J]))
        candidates.append(abs(x-t[J])+abs(s[I+1]-t[J]))
    if J+1<B:
        candidates.append(abs(x-s[I])+abs(s[I]-t[J+1]))
        candidates.append(abs(x-t[J+1])+abs(s[I]-t[J+1]))
    if J+1<B and I+1<A:
        candidates.append(abs(x-s[I+1])+abs(s[I+1]-t[J+1]))
        candidates.append(abs(x-t[J+1])+abs(s[I+1]-t[J+1]))
    return(min(candidates))

for _ in range(Q):
    X = int(input())
    print(solve(X))

Submission status: Time Limit Exceeded

Solution code:
# Lazy Faith
A, B, Q = map(int, input().split())
s = [int(input().strip()) for _ in range(A)]
t = [int(input().strip()) for _ in range(B)]
x = [int(input().strip()) for _ in range(Q)]


def mydis(xi):
	# s first
	D = []
	for a in range(A):
		dis = abs(xi - s[a])
		for b in range(B):
			D.append(dis + abs(s[a] - t[b]))
	min_dis_s = min(D)

	# t first
	D = []
	for b in range(B):
		dis = abs(xi - t[b])
		for a in range(A):
			D.append(dis + abs(t[b] - s[a]))
	min_dis_t = min(D)

	min_dis = min(min_dis_s, min_dis_t)
	return min_dis

for q in range(Q):
	dis = mydis(x[q])
	print(dis)

Submission status: Time Limit Exceeded

Solution code:
def calc(a_list, b_list, x):
    inf = 10**11
    aa = [a - x for a in a_list]
    bb = [b - x for b in b_list]
    if len([b for b in bb if b>=0])*len([a for a in aa if a>=0]) >0:
        p_1 = max([b for b in bb if b>=0][0], [a for a in aa if a>=0][0])
    else:
        p_1 = inf
    if len([b for b in bb if b<=0])*len([a for a in aa if a<=0]) >0:
        p_2 = max(abs(max([b for b in bb if b<=0])), abs(max([a for a in aa if a<=0])))
    else:
        p_2 = inf
    if len([b for b in bb if b<=0])*len([a for a in aa if a>=0]) >0:
        b_tmp = max([b for b in bb if b<=0])
        a_tmp = min([a for a in aa if a>=0])
        p_3 = a_tmp - b_tmp + min(abs(a_tmp), abs(b_tmp))
    else:
        p_3 = inf
    if len([b for b in bb if b>=0])*len([a for a in aa if a<=0]) >0:
        b_tmp = min([b for b in bb if b>=0])
        a_tmp = max([a for a in aa if a<=0])
        p_4 = b_tmp - a_tmp + min(abs(a_tmp), abs(b_tmp))
    else:
        p_4 = inf
    return min(p_1, p_2, p_3, p_4)
a,b,q = map(int, input().split())
a_list = []
b_list = []
q_list = []
for i in range(a):
    a_list.append(int(input()))
for j in range(b):
    b_list.append(int(input()))
for k in range(q):
    q = int(input())
    ans = calc(a_list, b_list, q)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
def calc(a_list, b_list, x):
    inf = 10**11
    aa = [a - x for a in a_list]
    bb = [b - x for b in b_list]
    if len([b for b in bb if b>=0])*len([a for a in aa if a>=0]) >0:
        p_1 = max([b for b in bb if b>=0][0], [a for a in aa if a>=0][0])
    else:
        p_1 = inf
    if len([b for b in bb if b<=0])*len([a for a in aa if a<=0]) >0:
        p_2 = max(abs(max([b for b in bb if b<=0])), abs(max([a for a in aa if a<=0])))
    else:
        p_2 = inf
    if len([b for b in bb if b<=0])*len([a for a in aa if a>=0]) >0:
        b_tmp = max([b for b in bb if b<=0])
        a_tmp = min([a for a in aa if a>=0])
        p_3 = a_tmp - b_tmp + min(abs(a_tmp), abs(b_tmp))
    else:
        p_3 = inf
    if len([b for b in bb if b>=0])*len([a for a in aa if a<=0]) >0:
        b_tmp = min([b for b in bb if b>=0])
        a_tmp = max([a for a in aa if a<=0])
        p_4 = b_tmp - a_tmp + min(abs(a_tmp), abs(b_tmp))
    else:
        p_4 = inf
    return min(p_1, p_2, p_3, p_4)

a,b,q = map(int, input().split())
a_list = []
b_list = []
q_list = []
for i in range(a):
    a_list.append(int(input()))
for j in range(b):
    b_list.append(int(input()))
a_list = sorted(a_list)
b_list = sorted(b_list)
for k in range(q):
    q = int(input())
    ans = calc(a_list, b_list, q)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# coding: utf-8
# Your code here!

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 i in x : 
    min_s = abs(i -s[0])
    j_count = 0
    j_k_count = 0
    min_t = abs(i -t[0])
#    min_t_s = abs(i -s[0])
    k_count = 0
    k_j_count = 0
#Sから攻める
    for j in s : 
        if abs(i-j) <= min_s : 
            min_s = abs(i-j)
            j_count = j
            
    min_s_t = abs(j_count -t[0])
            
    for k in t : 
        if abs(j_count-k) <= min_s_t : 
            min_s_t = abs(j_count-k)
            j_k_count = k
    min0 = abs(i-j_count)+abs(j_count-j_k_count)

# ---------------------------------------------

    for m in t : 
        if abs(i-m) <= min_t : 
            min_t = abs(i-m)
            m_count = m
            
    min_t_s = abs(m_count -s[0])
            
    for n in s : 
        if abs(m_count-n) <= min_t_s : 
            min_t_s = abs(m_count-n)
            m_n_count = n
    min1 = abs(i-m_count)+abs(m_count-m_n_count)

#小さい方採用

    print(min(min0, min1))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
MAX_LEN = 10 ** 10 * 2

def get_nearest_location(target_list,start_x,go_west):
    if go_west:
        tgts = target_list[target_list <= start_x]
        if len(tgts) != 0:
            tgt = np.max(tgts)
            return start_x - tgt, tgt
    else:
        tgts = target_list[target_list >= start_x]
        if len(tgts) != 0:
            tgt = np.min(tgts)
            return tgt - start_x, tgt
    return MAX_LEN,0

def get_least_dist(target_list,start_x):
    t_w_list = target_list[target_list <= start_x]
    t_e_list = target_list[target_list >= start_x]
    dist_w = start_x - np.max(t_w_list) if len(t_w_list) != 0 else MAX_LEN
    dist_e = np.min(t_e_list) - start_x if len(t_e_list) != 0 else MAX_LEN
    return min(dist_w,dist_e)

def find_least_movement(s,t,start_x):
    min_dist = MAX_LEN
    for targets in [[s,t],[t,s]]:
        for go_west in [True,False]:
            d1,x1 = get_nearest_location(targets[0],start_x,go_west)
            d2 = get_least_dist(targets[1],x1)
            min_dist = min(d1 + d2,min_dist)
    return min_dist

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

s = np.array(s)
t = np.array(t)
for sx in q:
    print(find_least_movement(s,t,sx))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
MAX_LEN = 10 ** 10 * 2

def get_nearest_location(target_list,start_x,go_west):
    if go_west:
        tgts = target_list[target_list < start_x]
        if len(tgts) != 0:
            tgt = np.max(tgts)
            return start_x - tgt, tgt
    else:
        tgts = target_list[target_list > start_x]
        if len(tgts) != 0:
            tgt = np.min(tgts)
            return tgt - start_x, tgt
    return MAX_LEN,0

def get_least_dist(target_list,start_x):
    t_w_list = target_list[target_list < start_x]
    t_e_list = target_list[target_list > start_x]
    dist_w = start_x - np.max(t_w_list) if len(t_w_list) != 0 else MAX_LEN
    dist_e = np.min(t_e_list) - start_x if len(t_e_list) != 0 else MAX_LEN
    return min(dist_w,dist_e)

def find_least_movement(s,t,start_x):
    min_dist = MAX_LEN
    for targets in [[s,t],[t,s]]:
        for go_west in [True,False]:
            d1,x1 = get_nearest_location(targets[0],start_x,go_west)
            d2 = get_least_dist(targets[1],x1)
            min_dist = min(d1 + d2,min_dist)
    return min_dist

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

s = np.array(s)
t = np.array(t)
for sx in q:
    print(find_least_movement(s,t,sx))

Submission status: Time Limit Exceeded

Solution code:
import bisect
a, b, q = map(int, input().split())
inf = float('inf')
S = [- inf] + [int(input()) for i in range(a)] + [inf]
T = [- inf] + [int(input()) for i in range(b)] + [inf]

for i in range(q):
    x = int(input())
    s_idx = bisect.bisect_left(S, x)
    s1, s2 = S[s_idx - 1], S[s_idx]
    
    t_idx = bisect.bisect_left(T, x)
    t1, t2 = T[t_idx - 1], T[t_idx]
    
    ans = inf
    for i in s1, s2, t1, t2:
        for j in s1, s2, t1, t2:
            if i != j:
                tmp = abs(x - i) + abs(i - j)
                ans = min(ans, tmp)
                
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-


def main():
    from bisect import bisect_right

    a, b, q = map(int, input().split())
    s = [-float('inf')] + [int(input()) for _ in range(a)] + [float('inf')]
    t = [-float('inf')] + [int(input()) for _ in range(b)] + [float('inf')]

    # See:
    # https://img.atcoder.jp/abc119/editorial.pdf
    for _ in range(q):
        x = int(input())
        s_right = bisect_right(s, x)
        s_left = s_right - 1
        t_right = bisect_right(t, x)
        t_left = t_right - 1
        ans = float('inf')

        for si in [s[s_left], s[s_right]]:
            for ti in [t[t_left], t[t_right]]:
                ans = min(ans, abs(si - x) + abs(si - ti), abs(ti - x) + abs(si - ti))

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def bisearch(li,target):
    l=0
    r=len(li)-1
    while(l<=r):        
        m=int((l+r)/2)
        if(m==len(li)-1):
            return target-li[m][0]+li[m][1]
        if(li[m][0]<target and target<li[m+1][0]):
            return min(target-li[m][0]+li[m][1],li[m+1][0]-target+li[m+1][1])
        if(m==0 and target<li[0][0]):
            return li[0][0]-target+li[0][1]
        if(target<li[m][0]):
            r = m-1
        else:
            l = m+1

inf = 10**15
A,B,Q = [int(x) for x in input().split()]
s = [0]*(A+1)
t = [0]*(B+1)
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())
s[-1] = inf
t[-1] = inf

li = []
a = b = 0
while(a<A or b<B):
    if(s[a]<t[b]):
        li.append([s[a],min(abs(t[b]-s[a]),abs(t[b-1]-s[a]))])
        a+=1
    else:
        li.append([t[b],min(abs(t[b]-s[a]),abs(t[b]-s[a-1]))])
        b+=1

for i in x:
    print(bisearch(li,i))

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 n in range(Q)]
for x_i in x:
  min_val = 10 ** 10
  min_s = 0
  for s_i in s:
    if abs(x_i-s_i) < min_val:
      min_val = abs(x_i-s_i)
      min_s = s_i
  min_1 = (min([abs(min_s-t_i) for t_i in t]) + min_val)
  min_val = 10 ** 10
  min_s = 0
  for s_i in t:
    if abs(x_i-s_i) < min_val:
      min_val = abs(x_i-s_i)
      min_s = s_i
  min_2 = (min([abs(min_s-t_i) for t_i in s]) + min_val)
  print (min(min_1, min_2))

Submission status: Time Limit Exceeded

Solution code:
import bisect
w=20000000001
a,b,q=map(int,input().split())
s=[int(input()) for i in range(a)]
t=[int(input()) for i in range(b)]
#bisect.bisect_left

for i in range(q):
    x=int(input())
    ans=w
    tmp=x
    ls=bisect.bisect_left(s,tmp)
    lt=bisect.bisect_left(t,tmp)
    if (s[ls-1]<=tmp and t[lt-1]<=tmp): ans=min(ans,tmp-min(s[ls-1],t[lt-1]))
    if (s[ls-1]<=tmp and lt<b and t[lt]>=tmp): ans=min(ans,(tmp-s[ls-1])+(t[lt]-s[ls-1]),(t[lt]-tmp)+(t[lt]-s[ls-1]))
    if (ls<a and s[ls]>=tmp and t[lt-1]<=tmp): ans=min(ans,(tmp-t[lt-1])+(s[ls]-t[lt-1]),(s[ls]-tmp)+(s[ls]-t[lt-1]))
    if (ls<a and lt<b and s[ls]>=tmp and t[lt]>=tmp): ans=min(ans,max(s[ls],t[lt])-tmp)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
INF = 10**20
s = [-INF]
for i in range(A):
    s.append(int(input()))
s.append(INF)
t = [-INF]
for i in range(B):
    t.append(int(input()))
t.append(INF)

x = [int(input()) for i in range(Q)]

# x[i]の東にある神社・寺のうち１番近いのと２番めに近いものEastShrine EastTemple
# x[i]の西にある神社・寺のうち１番近いのと２番めに近いものをみてWest~~
# EastShrine,EastTemple
# EastShrine,WastTemple
# WestShrine,EastTemple
# WestShrine,WestTemple

# x[i]-s[i]の符号が変わるタイミングで近い２点を求める
# print(s)
# print(t)

for x_i in x:
    for i in range(len(s)):
        if s[i] < x_i:
            pass
        elif s[i] == x_i:
            """
            if i == 0:
                WestShrine = s[i]
                EastShrine = s[i + 1]
            elif i == len(s) - 1:
                WestShrine = s[i-1]
                EastShrine = s[i]
            """
            if abs(s[i - 1] - x_i) > abs(s[i + 1] - x_i):
                EastShrine = s[i + 1]
                WestShrine = s[i]
            else:
                EastShrine = s[i]
                WestShrine = s[i - 1]
        else:
            WestShrine = s[i - 1]
            EastShrine = s[i]
            #print(WestShrine, EastShrine)
            break

    for i in range(len(t)):
        if t[i] < x_i:
            pass
        elif t[i] == x_i:
            """
            if i == 0:
                WestTemple = t[i]
                EastTemple = t[i + 1]
            elif i == len(t) - 1:
                WestTemple = t[i-1]
                EastTemple = t[i]
            """
            if abs(t[i - 1] - x_i) > abs(t[i + 1] - x_i):
                EastTemple = t[i + 1]
                WestTemple = t[i]
            else:
                EastTemple = t[i]
                WestTemple = t[i - 1]
        else:
            WestTemple = t[i - 1]
            EastTemple = t[i]
            #print(WestTemple, EastTemple)
            break

    #print("WS:", WestShrine, "ES:", EastShrine)
    #print("WT:", WestTemple, "ET:", EastTemple)

    ans1 = abs(max([EastShrine, EastTemple]) - x_i)
    ans2 = abs(min([WestShrine, WestTemple]) - x_i)

    smaller = min(abs(x_i - EastShrine), abs(x_i - WestTemple))
    larger = max(abs(x_i - EastShrine), abs(x_i - WestTemple))
    #print("S:", smaller, "L:", larger)
    ans3 = smaller * 2 + larger

    smaller = min(abs(x_i - WestShrine), abs(x_i - EastTemple))
    larger = max(abs(x_i - WestShrine), abs(x_i - EastTemple))
    ans4 = smaller * 2 + larger

    #print(WestShrine, EastShrine)
    #print(WestTemple, EastTemple)
    #print(ans1, ans2, ans3, ans4)
    print(min([ans1, ans2, ans3, ans4]))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
INF=10**18

A,B,Q = list(map(int, input().split()))
s = np.asarray([-INF] + [int(input()) for _ in range(A)] + [INF])
t = np.asarray([-INF] + [int(input()) for _ in range(B)] + [INF])
x = [int(input()) for _ in range(Q)]

#r1 = np.asarray([*s[1:-1],*t[1:-1]])
r1 = np.concatenate([s[1:-1],t[1:-1]])
r2 = np.asarray([])
r3 = np.asarray([])
for tmp in s[1:-1]:
    r2 = np.append(r2,min(abs(tmp - np.max(t[tmp>t])),abs(np.min(t[tmp<t]) - tmp)))
for tmp in t[1:-1]:
    r2 = np.append(r2,min(abs(tmp - np.max(s[tmp>s])),abs(np.min(s[tmp<s]) - tmp)))

r1 = np.concatenate([[-INF],r1,[INF]])
r2 = np.concatenate([[-INF],r2,[INF]])

for tmp in x:
    left = np.max(r1[tmp>r1])
    #print(r2[r1==left])
    left = abs(left - tmp) + r2[r1==left]
    right = np.min(r1[tmp<r1])
    right = abs(right - tmp) + r2[r1==right]
    r3 = np.append(r3,min(left,right))

for tmp in r3:print(int(tmp))

Submission status: Time Limit Exceeded

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

jinjya = []
otera = []

for i in range(a):
    jinjya.append(int(input()))
for i in range(b):
    otera.append(int(input()))
def find(arr,tar,start,end):
    if start >= end:
        return start
    bar = (start+end)//2
    if arr[bar]<tar:
        return find(arr,tar,bar+1,end)
    elif arr[bar]>tar:
        return find(arr,tar,start,bar-1)
    else:
        return bar
for i in range(q):
    jinjyaEast = 0
    jinjyaWest = 0
    oteraEast = 0
    oteraWest = 0
    pos = int(input())
    idx = find(jinjya,pos,0,len(jinjya)-1)
    if(jinjya[idx] < pos):
        jinjyaWest = jinjya[idx]
        if idx<len(jinjya)-1:
            jinjyaEast = jinjya[idx+1]
    else:
        jinjyaEast = jinjya[idx]
        if idx>0:
            jinjyaWest = jinjya[idx-1]
    idx = find(otera,pos,0,len(otera)-1)
    if(otera[idx] < pos):
        oteraWest = otera[idx]
        if idx<len(otera)-1:
            oteraEast = otera[idx+1]
    else:
        oteraEast = otera[idx]
        if idx>0:
            oteraWest = otera[idx-1]
    res = []
    j = []
    o = []
    if jinjyaWest != 0:
        j.append(jinjyaWest)
    if jinjyaEast != 0:
        j.append(jinjyaEast)
    if oteraWest != 0:
        o.append(oteraWest)
    if oteraEast != 0:
        o.append(oteraEast)
    for a in j:
        for b in o:
            res.append(min(abs(pos-a)+abs(b-a),abs(pos-b)+abs(a-b)))
    print(min(res))

Submission status: Time Limit Exceeded

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

    return None


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

    len_s = A + 1
    len_t = B + 1

    for i in range(Q):
        xi = int(input())
        ind_s = binary_search_ceiling(s_list, len_s, xi)
        ws = s_list[ind_s - 1]
        es = s_list[ind_s]

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

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

        print(min(dist_list))


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

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

    return None


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

    len_s = A + 1
    len_t = B + 1

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

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

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

        print(min(dist_list))


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
sl = [int(input()) for _ in range(A)]
tl = [int(input()) for _ in range(B)]
ql = [int(input()) for _ in range(Q)]

def find(sl, tl, min_list):
  for s in sl:
    d = 0
    d += abs(q-s)
    d += min(list(map(lambda x: abs(x-s), tl)))
    min_list.append(d)
    
  return min_list
  
for q in ql:
  min_list = []
  min_list = find(sl, tl, min_list)
  min_list = find(tl, sl, min_list)
  print(min(min_list))

Submission status: Time Limit Exceeded

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

    return None


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

    len_s_list = A + 4
    len_t_list = B + 4
    for xi in x_list:
        ind_s = binary_search_ceiling(s_list, len_s_list, xi)
        ws = s_list[ind_s - 1]
        es = s_list[ind_s]

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

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

        print(min(dist_list))


if __name__ == "__main__":
    main()