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

# tmp_s=10000000001
# arg_s=0
# tmp_t=10000000001
# arg_t=0
# lis_s=[]
# lis_t=[]
# lis_tmp_s_0=[]
# lis_tmp_s_1=[]
# lis_tmp_t_0=[]
# lis_tmp_t_1=[]
# for i in range(q):
#     min_1=10000000001
#     min_2=10000000001
#     for j in range(a):
#         lis_s.append(abs(x[i]-s[j]))
#     aa=lis_s.index(min(lis_s))
#     lis_s.pop(lis_s.index(min(lis_s)))
#     ii=lis_s.index(min(lis_s))
#     for k in range(b):
#         lis_tmp_s_0.append(abs(s[aa]-t[k]))
#     lis_tmp_s_0.sort()
#     for k in range(b):
#         lis_tmp_s_1.append(abs(lis_s[ii]-t[k]))
#     min_1=min(lis_s[0]+lis_tmp_s_0[0],lis_s[1]+lis_tmp_s_1[0])

#     for j in range(b):
#         lis_t.append(abs(x[i]-t[j]))
#     lis_t.sort()
#     aa=lis_t.index(min(lis_t))
#     lis_t.pop(lis_t.index(min(lis_t)))
#     ii=lis_t.index(min(lis_t))
#     for k in range(a):
#         lis_tmp_t_0.append(abs(lis_t[aa]-s[k]))
#     lis_tmp_t_0.sort()
#     for k in range(a):
#         lis_tmp_t_1.append(abs(lis_t[ii]-s[k]))
#     min_2=min(lis_t[0]+lis_tmp_t_0[0],lis_t[1]+lis_tmp_t_1[0])
#     print(min(min_1,min_2))

import bisect
a,b,q=map(int,input().split())
s=[]
t=[]
x=[]
s.append(-float("inf"))
t.append(-float("inf"))
for i in range(a):
    s.append(int(input()))
for i in range(b):
    t.append(int(input()))
s.append(float("inf"))
t.append(float("inf"))
s.sort()
t.sort()
for i in range(q):
    x=int(input())
    ans=float("inf")
    tmp_s_1=bisect.bisect_left(s,x)-1
    tmp_s_2=tmp_s_1+1
    ans=min(abs(x-s[tmp_s_1])+abs(s[tmp_s_1]-t[bisect.bisect_left(t,s[tmp_s_1])-1]), abs(x-s[tmp_s_1])+abs(s[tmp_s_1]-t[bisect.bisect_left(t,s[tmp_s_1])]), abs(x-s[tmp_s_2])+abs(s[tmp_s_2]-t[bisect.bisect_left(t,s[tmp_s_2])-1]), abs(x-s[tmp_s_2])+abs(s[tmp_s_2]-t[bisect.bisect_left(t,s[tmp_s_2])]))
    tmp_t_1=bisect.bisect_left(t,x)-1
    tmp_t_2=tmp_t_1+1
    ans=min(ans, abs(x-t[tmp_t_1])+abs(t[tmp_t_1]-s[bisect.bisect_left(s,t[tmp_t_1])-1]), abs(x-t[tmp_t_1])+abs(t[tmp_t_1]-s[bisect.bisect_left(s,t[tmp_t_1])]), abs(x-t[tmp_t_2])+abs(t[tmp_t_2]-s[bisect.bisect_left(s,t[tmp_t_2])-1]), abs(x-t[tmp_t_2])+abs(t[tmp_t_2]-s[bisect.bisect_left(s,t[tmp_t_2])]))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect
A, B, Q = map(int, input().split())
S = [int(input()) for i in range(A)]
S = [-(10**11+1)] + S + [10**11+1]
T = [int(input()) for i in range(B)]
T = [-(10**11+1)] + T + [10**11+1]
X = [int(input()) for i in range(Q)]

for x in X:
    s_left = bisect.bisect_right(S, x)
    s_right = s_left - 1
    t_left = bisect.bisect_right(T, x)
    t_right = t_left - 1
    s1, s2 = S[s_left], S[s_right]
    t1, t2 = T[t_left], T[t_right]
    dis1 = abs(s1-x)+abs(s1-t1)
    dis2 = abs(s1-x)+abs(s1-t2)
    dis3 = abs(s2-x)+abs(s2-t1)
    dis4 = abs(s2-x)+abs(s2-t2)
    dis5 = abs(t1 - x) + abs(t1 - s1)
    dis6 = abs(t1 - x) + abs(t1 - s2)
    dis7 = abs(t2 - x) + abs(t2 - s1)
    dis8 = abs(t2 - x) + abs(t2 - s2)
    print(min(dis1, dis2, dis3, dis4, dis5, dis6, dis7, dis8))

Submission status: Time Limit Exceeded

Solution code:
A, B, Q = map(int, input().split())
s = []
t = []
x = []
for _ in range(A):
    s.append(int(input()))
for _ in range(B):
    t.append(int(input()))
for _ in range(Q):
    x.append(int(input()))
    
import sys
INT_MAX = sys.maxsize
s.insert(0, -1 * INT_MAX)
s.append(INT_MAX)
t.insert(0, -1 * INT_MAX)
t.append(INT_MAX)

for xi in x:
    #print(xi)
    si = 0
    for si, v in enumerate(s):
        if v > xi:
            break
    ti = 0
    for ti, v in enumerate(t):
        if v > xi:
            break
    #print(si, ti)
    sa = s[si]
    ta = t[ti]
    sb = s[si-1]
    tb = t[ti-1]
    #print(sa, sb,ta,tb)
    ans = min([
        abs(xi-sa)+abs(sa-ta),
        abs(xi-sa)+abs(sa-tb),
        abs(xi-sb)+abs(sb-ta),
        abs(xi-sb)+abs(sb-tb),
        abs(xi-ta)+abs(ta-sa),
        abs(xi-ta)+abs(ta-sb),
        abs(xi-tb)+abs(tb-sa),
        abs(xi-tb)+abs(tb-sb)
    ])
    print(ans)

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]

def f(S,T):
    res = INF
    s = bisect.bisect_left(S,x)
    for i in range(2):
    	for j in range(2):
            t = bisect.bisect_left(T,S[s-i])
            ans= abs(x-S[s-i])+abs(S[s-i]-T[t-j])
            if ans < res:
                res = ans
    return res

for i in range(q):
    x = int(input())
    print(min(f(S,T),f(T,S)))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys


def getNearestIndexOf(query: int, s: "List[int]"):
    findTarget = s
    while len(findTarget) != 1:
        if len(findTarget) == 2:
            if abs(findTarget[0] - query) < abs(findTarget[1] - query):
                findTarget = [findTarget[0]]
            else:
                findTarget = [findTarget[1]]
            continue
        middle = int(len(findTarget)/2)
        if findTarget[middle] > query:
            findTarget = findTarget[0:middle + 1]
        else:
            findTarget = findTarget[middle:]
    #print(f"▫️{query} from {s} -> {findTarget[0]}")
    return findTarget[0]


def getCostByOrder(begin: int, s: "List[int]", t: "List[int]"):
    nc = 0
    nx = getNearestIndexOf(begin, t)
    nc += abs(nx-begin)
    nx2 = getNearestIndexOf(nx, s)
    nc += abs(nx2 - nx)
    return nc


def solve(A: int, B: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):
    for query in x:
        # 最初に神社に行く場合
        print(min(getCostByOrder(query, t, s), getCostByOrder(query, s, t)))
    return


# Generated by 1.1.3 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    s = [int(next(tokens)) for _ in range(A)]  # type: "List[int]"
    t = [int(next(tokens)) for _ in range(B)]  # type: "List[int]"
    x = [int(next(tokens)) for _ in range(Q)]  # type: "List[int]"
    solve(A, B, Q, s, t, x)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import bisect
A, B, Q = map(int,input().split())
 
S = [-10**18] + [int(input()) for _ in [0]*A] + [10**18]
T = [-10**18] + [int(input()) for _ in [0]*B] + [10**18]

for _ in range(Q):
    x = int(input())
    ans = 10**18
    for i in range(2):
        if i == 0:
            a = S
            b = T
        elif i== 1:
            a = T
            b = S
 
        idx_x = bisect.bisect_left(a,x)
        for j in range(2):
            ax = a[idx_x-j]
            idx_a = bisect.bisect_left(b,ax)
            for k in range(2):
                bx = b[idx_a-k]
                ans = min(ans, abs(ax-x)+abs(bx-ax))
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect
A, B, Q = map(int,input().split())

S = [-10**18] + sorted([int(input()) for _ in [0]*A]) + [10**18]
T = [-10**18] + sorted([int(input()) for _ in [0]*B]) + [10**18]





for _ in range(Q):
    x = int(input())
    ans = 10**18
    for i in range(2):
        if i == 0:
            a = S
            b = T
        elif i== 1:
            a = T
            b = S

        idx_x = bisect.bisect_left(a,x)
        for j in range(2):
            ax = a[idx_x-j]
            idx_a = bisect.bisect_left(b,ax)
            for k in range(2):
                bx = b[idx_a-k]
                ans = min(ans, abs(ax-x)+abs(bx-ax))
    print(ans)

Submission status: Time Limit Exceeded

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

s.sort()
t.sort()

def bifind(r,z):
    low = 0
    high = len(r)-1
    y = (low + high)//2
    if z < r[0]:
        return [r[0],r[0]]
    elif z > r[-1]:
        return [r[-1],r[-1]]
    while True:
        if r[y] <= z:
            low = y
            y = (y+high)//2
        else:
            high = y
            y = (low + y)//2
        if r[y] < z < r[y+1]:
            break
    return [r[y],r[y+1]]

for i in range(0,q):
    ls = bifind(s,x[i])
    lt = bifind(t,x[i])
    ans = list()
    for j in range(0,2):
        for k in range(0,2):
            ans.append(abs(ls[j]-x[i])+abs(lt[k]-ls[j]))
            ans.append(abs(lt[k]-x[i])+abs(lt[k]-ls[j]))
    print(min(ans))

Submission status: Time Limit Exceeded

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

s.sort()
t.sort()

def bifind(r,z):
    y = len(r)//2
    halftime = 2
    if z < r[0]:
        return [r[0],r[0]]
    elif z > r[-1]:
        return [r[-1],r[-1]]
    while True:
        if r[y] <= z:
            y += len(r)//(2**halftime)+1
        else:
            y -= len(r)//(2**halftime)+1
        halftime += 1
        if y+1  >= len(r):
            y = len(r)-2
        if y  < 0:
            y = 0
        if r[y] < z < r[y+1]:
            break
    return [r[y],r[y+1]]

for i in range(0,q):
    ls = bifind(s,x[i])
    lt = bifind(t,x[i])
    ans = list()
    for j in range(0,2):
        for k in range(0,2):
            ans.append(abs(ls[j]-x[i])+abs(lt[k]-ls[j]))
            ans.append(abs(lt[k]-x[i])+abs(lt[k]-ls[j]))
    print(min(ans))

Submission status: Time Limit Exceeded

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

s.sort()
t.sort()

def bifind(r,z):
    y = len(r)//2
    halftime = 2
    if z < r[0]:
        return [10**11,r[0]]
    elif z > r[-1]:
        return [r[-1],10**11]
    while True:
        if r[y] <= z:
            y += len(r)//(2**halftime)+1
        else:
            y -= len(r)//(2**halftime)+1
        halftime += 1
        if y+1  >= len(r):
            y = len(r)-2
        if y  < 0:
            y = 0
        if r[y] < z < r[y+1]:
            break
    return [r[y],r[y+1]]

for i in range(0,q):
    ls = bifind(s,x[i])
    lt = bifind(t,x[i])
    ans = 10**11
    for j in range(0,2):
        for k in range(0,2):
            ans = min(ans,abs(ls[j]-x[i])+abs(lt[k]-ls[j]))
            ans = min(ans,abs(lt[k]-x[i])+abs(lt[k]-ls[j]))
    print(ans)

Submission status: Time Limit Exceeded

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

for xx in x:
  
  low = 0
  high = len(s)-1
  mid = (low+high)//2
  while low<=high:
    tmp = [i-xx for i in s[mid:mid+2]]
    if tmp[0] <= 0 and 0 <= tmp[1]:
      s_l = abs(tmp[0])
      s_r = abs(tmp[1])
      break
    elif tmp[0] > 0:
      high = mid
      mid = (low+high)//2
    else:
      low = mid
      mid = (low+high)//2
      
  low = 0
  high = len(t)-1
  mid = (low+high)//2
  while low<=high:
    tmp = [i-xx for i in t[mid:mid+2]]
    if tmp[0] <= 0 and 0 <= tmp[1]:
      t_l = abs(tmp[0])
      t_r = abs(tmp[1])
      break
    elif tmp[0] > 0:
      high = mid
      mid = (low+high)//2
    else:
      low = mid
      mid = (low+high)//2
  
  #print(s_l,s_r,t_l,t_r)
  
  #l = max(s_l,t_l)
  #r = max(s_r,t_r)
  if s_l <= t_l:
    l = t_l
    lr = s_l*2 + t_r
  else:
    l = s_l
    lr = t_l*2 + s_r
  if s_r <= t_r:
    r = t_r
    rl = s_r*2 + t_l
  else:
    r = s_r
    rl = t_r*2 + s_l
 
  ans = min(l,r,lr,rl)
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
def search(x,r):
  low = 0
  high = len(r)-1
  mid = (low+high)//2
  while low<=high:
    tmp = [i-x for i in r[mid:mid+2]]
    if tmp[0] <= 0 and 0 <= tmp[1]:
      return(abs(tmp[0]),abs(tmp[1]))
    elif tmp[0] > 0:
      high = mid
      mid = (low+high)//2
    else:
      low = mid
      mid = (low+high)//2
      
a, b, q = [int(i) for i in input().split()]
s = [-float('inf')] + [int(input()) for _ in range(a)] + [float('inf')]
t = [-float('inf')] + [int(input()) for _ in range(b)] + [float('inf')]
x = [int(input()) for _ in range(q)]

for xx in x:
  
  s_l,s_r=search(xx,s)
  t_l,t_r=search(xx,t)
  
  #print(s_l,s_r,t_l,t_r)
  
  #l = max(s_l,t_l)
  #r = max(s_r,t_r)
  if s_l <= t_l:
    l = t_l
    lr = s_l*2 + t_r
  else:
    l = s_l
    lr = t_l*2 + s_r
  if s_r <= t_r:
    r = t_r
    rl = s_r*2 + t_l
  else:
    r = s_r
    rl = t_r*2 + s_l
 
  ans = min(l,r,lr,rl)
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
def search(x,r):
  low = 0
  high = len(r)-1
  mid = (low+high)//2
  while low<=high:
    rr = r[mid]-x
    ll = r[mid+1]-x
    if rr*ll<=0:
      return(abs(rr),abs(ll))
    elif r[mid]-x > 0:
      high = mid
      mid = (low+high)//2
    else:
      low = mid
      mid = (low+high)//2
      

a, b, q = [int(i) for i in input().split()]
s = []
for i in range(a):
	s.append(int(input()))
s = [-float('inf')] + s + [float('inf')]
t = []
for i in range(b):
	t.append(int(input()))
t = [-float('inf')] + t + [float('inf')]
x = []
for i in range(q):
	x.append(int(input()))

for xx in x:
  
  s_l,s_r=search(xx,s)
  t_l,t_r=search(xx,t)
  
  #print(s_l,s_r,t_l,t_r)
  
  #l = max(s_l,t_l)
  #r = max(s_r,t_r)
  if s_l <= t_l:
    l = t_l
    lr = s_l*2 + t_r
  else:
    l = s_l
    lr = t_l*2 + s_r
  if s_r <= t_r:
    r = t_r
    rl = s_r*2 + t_l
  else:
    r = s_r
    rl = t_r*2 + s_l
 
  ans = min(l,r,lr,rl)
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
def search(x,r):
  low = 0
  high = len(r)-1
  mid = (low+high)//2
  while low<=high:
    rr = r[mid]-x
    ll = r[mid+1]-x
    if rr*ll<=0:
      return(abs(rr),abs(ll))
    elif r[mid]-x > 0:
      high = mid
      mid = (low+high)//2
    else:
      low = mid
      mid = (low+high)//2
      

a, b, q = [int(i) for i in input().split()]
s = []
for i in range(a):
	s.append(int(input()))
t = []
for i in range(b):
	t.append(int(input()))
x = []
for i in range(q):
	x.append(int(input()))

for xx in x:

  s_l = float('inf')
  s_r = float('inf')
  if s[-1] - xx <= 0:
    s_l = abs(s[-1] - xx)
  elif s[0] - xx >= 0:
    s_r = abs(s[0] - xx)
  else:
  	s_l,s_r=search(xx,s)
  
  t_l = float('inf')
  t_r = float('inf')
  if t[-1] - xx <= 0:
    t_l = abs(t[-1] - xx)
  elif t[0] - xx >= 0:
    t_r = abs(t[0] - xx)
  else:
  	t_l,t_r=search(xx,t)
  
  #print(s_l,s_r,t_l,t_r)
  
  #l = max(s_l,t_l)
  #r = max(s_r,t_r)
  if s_l <= t_l:
    l = t_l
    lr = s_l*2 + t_r
  else:
    l = s_l
    lr = t_l*2 + s_r
  if s_r <= t_r:
    r = t_r
    rl = s_r*2 + t_l
  else:
    r = s_r
    rl = t_r*2 + s_l
 
  ans = min(l,r,lr,rl)
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
def search(x,r):
  low = 0
  high = len(r)-1
  mid = (low+high)//2
  while low<=high:
    if (r[mid]-x)*(r[mid+1]-x)<=0:
      #print(abs(r[mid]-x),abs(r[mid+1]-x))
      return(abs(r[mid]-x),abs(r[mid+1]-x))
    elif r[mid]-x > 0:
      high = mid
      mid = (low+high)//2
    else:
      low = mid
      mid = (low+high)//2
      

a, b, q = [int(i) for i in input().split()]
s = []
for i in range(a):
	s.append(int(input()))
t = []
for i in range(b):
	t.append(int(input()))
x = []
for i in range(q):
	x.append(int(input()))

for xx in x:

  s_l = float('inf')
  s_r = float('inf')
  if s[-1] - xx <= 0:
    s_l = abs(s[-1] - xx)
  elif s[0] - xx >= 0:
    s_r = abs(s[0] - xx)
  else:
  	s_l,s_r=search(xx,s)
  
  t_l = float('inf')
  t_r = float('inf')
  if t[-1] - xx <= 0:
    t_l = abs(t[-1] - xx)
  elif t[0] - xx >= 0:
    t_r = abs(t[0] - xx)
  else:
  	t_l,t_r=search(xx,t)
  
  #print(s_l,s_r,t_l,t_r)
  
  l = max(s_l,t_l)
  r = max(s_r,t_r)
  lr_st = s_l*2 + t_r
  lr_ts = t_l*2 + s_r
  rl_st = t_l + s_r*2
  rl_ts = s_l + t_r*2
 
  ans = min(l,r,lr_st,lr_ts,rl_st,rl_ts)
  print(ans)

Submission status: Time Limit Exceeded

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

for xx in x:
  s_l = float('inf')
  s_r = float('inf')
  for ss in s:
    tmp = ss-xx
    if tmp <= 0:
      if abs(tmp) < s_l:
        s_l = abs(tmp)
    else:
      s_r = tmp
      break

  t_l = float('inf')
  t_r = float('inf')      
  for tt in t:
    tmp = tt-xx
    if tmp <= 0:
      if abs(tmp) < t_l:
        t_l = abs(tmp)
    else:
      t_r = tmp
      break
  
  l = max(s_l,t_l)
  r = max(s_r,t_r)
  lr_st = s_l*2 + t_r
  lr_ts = t_l*2 + s_r
  rl_st = t_l + s_r*2
  rl_ts = s_l + t_r*2
  ans = min(l,r,lr_st,lr_ts,rl_st,rl_ts)
  print(ans)

Submission status: Time Limit Exceeded

Solution code:
read = input
# read = Read(False, """
# 1 1 3
# 1
# 10000000000
# 2
# 9999999999
# 5000000000
# """).read
A,B,Q = list(map(int, read().split(' ')))
arrA = list(map(int, [read() for i in range(A)]))
arrB = list(map(int, [read() for i in range(B)]))
arrQ = list(map(int, [read() for i in range(Q)]))
arrA.sort()
arrB.sort()
import bisect
def cs(x, arr):
    al = bisect.bisect_left(arr, x)
    return list(map(lambda i: arr[i], filter(lambda i:i>=0 and i< len(arr), range(al-1, al + 2))))
def same_s(da,db):
    da = da / abs(da)
    db = db / abs(db)
    return da*db>0
    
def t(q,a,b):
    da = q - a
    db = q - b
    if(min(abs(da), abs(db)) == 0):
        return max(abs(da), abs(db))
    if same_s(da, db):
        return max(abs(da), abs(db))
    else :
        return 2*min(abs(da), abs(db)) + max(abs(da), abs(db))
for q in arrQ:
    optA = cs(q, arrA)
    optB = cs(q, arrB)
    ret = 10 ** 11
    for a in optA:
        for b in optB:
            ret = min(ret, t(q, a,b))
    print(ret)

Submission status: Time Limit Exceeded

Solution code:
import bisect
INF = float("inf")

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

for i in range(Q):
    q = int(input())
    b,d = bisect.bisect_right(s,q),bisect.bisect_right(t,q)
    ans = INF
    for S in [s[b-1],s[b]]:
        for T in [t[d-1],t[d]]:
            d1,d2 = abs(S-q)+abs(T-S),abs(T-q)+abs(S-T)
            ans = min(ans,d1,d2)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
INF = float("inf")
import bisect

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

for i in range(Q):
    q = int(input())
    b,d = bisect.bisect_right(s,q),bisect.bisect_right(t,q)
    ans = INF
    for S in [s[b-1],s[b]]:
        for T in [t[d-1],t[d]]:
            d1,d2 = abs(S-q)+abs(T-S),abs(T-q)+abs(S-T)
            ans = min(ans,d1,d2)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import itertools
import math
from collections import deque
from collections import defaultdict
from itertools import permutations
import heapq
import bisect
from scipy.sparse.csgraph import floyd_warshall as wf
INF = float("inf")

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

for i in range(Q):
    q = int(input())
    b,d = bisect.bisect_right(s,q),bisect.bisect_right(t,q)
    ans = INF
    for S in [s[b-1],s[b]]:
        for T in [t[d-1],t[d]]:
            d1,d2 = abs(S-q)+abs(T-S),abs(T-q)+abs(S-T)
            ans = min(ans,d1,d2)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# -*- coding: utf-8 -*-
"""
D - Lazy Faith
https://atcoder.jp/contests/abc119/tasks/abc119_d

"""
import sys
from bisect import bisect_left, bisect_right

def solve(x):
    i = bisect_right(shrines, x)
    ds = x - shrines[i-1]
    j = bisect_right(temples, x)
    dt = x - temples[j-1]
    ans1 = max(ds, dt)

    i = bisect_left(shrines, x)
    ds = shrines[i] - x
    j = bisect_left(temples, x)
    dt = temples[j] - x
    ans2 = max(ds, dt)

    i = bisect_left(shrines, x)
    ds = shrines[i] - x
    j = bisect_right(temples, x)
    dt = x - temples[j-1]
    ans3 = min(ds, dt) * 2 + max(ds, dt)

    i = bisect_right(shrines, x)
    ds = x - shrines[i-1]
    j = bisect_left(temples, x)
    dt = temples[j] - x
    ans4 = min(ds, dt) * 2 + max(ds, dt)

    return min(ans1, ans2, ans3, ans4)


shrines = None
temples = None

def main(args):
    global shrines, temples
    A, B, Q = map(int, input().split())
    shrines = sorted([int(input()) for _ in range(A)] + [float('-inf'), float('inf')])
    temples = sorted([int(input()) for _ in range(B)] + [float('-inf'), float('inf')])
    for _ in range(Q):
        x = int(input())
        ans = solve(x)
        print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Time Limit Exceeded

Solution code:
def get_most_near_value(a, L):
    result = L[0]
    for l in L:
        if abs(a - l) < abs(a - result):
            result =  l
    return result

def calc_min_AB_distance(x, S, T):
    a = get_most_near_value(x, S)
    b = get_most_near_value(a, T)
    return abs(x - a) + abs(a - b)

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 x in X:
    print(min(calc_min_AB_distance(x, S, T), calc_min_AB_distance(x, T, S)))

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3
import sys


def solve(n: int, m: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):

    def check_pos(target, a, x):
        ret = {}
        a_x = a + x
        a_x.sort()
        idx = 0
        while idx < len(a_x) and a_x[idx] < target[0]:
            dis = target[0] - a_x[idx]
            ret[a_x[idx]] = [dis, [target[0], dis]] # [pos, dis]
            idx += 1
        for i in range(len(target) - 1):
            while idx < len(a_x) and target[i] <= a_x[idx] <= target[i + 1]:
                pos = a_x[idx]
                l = a_x[idx] - target[i]
                r = target[i + 1] - a_x[idx]
                ret[pos] = [
                    min(l, r),
                    [target[i],     l],
                    [target[i + 1], r]
                ]
                idx += 1
        while idx < len(a_x):
            dis = a_x[idx] - target[-1]
            ret[a_x[idx]] = [dis, [target[-1], dis]] # [pos, dis]
            idx += 1
        return ret

    nearest_s = check_pos(s, t, x)
    nearest_t = check_pos(t, s, x)

    for q in x:
        ret = min(
                min([(pos_dis[1] + nearest_t[pos_dis[0]][0]) for pos_dis in nearest_s[q][1:]]),
                min([(pos_dis[1] + nearest_s[pos_dis[0]][0]) for pos_dis in nearest_t[q][1:]]))
        print(ret)
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    s = [ int(next(tokens)) for _ in range(A) ]  # type: "List[int]"
    t = [ int(next(tokens)) for _ in range(B) ]  # type: "List[int]"
    x = [ int(next(tokens)) for _ in range(Q) ]  # type: "List[int]"
    solve(A, B, Q, s, t, x)

if __name__ == '__main__':
    main()

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()))
L1 = [-10**20] + L1 + [10**20]
L2 = [-10**20] + L2 + [10**20]
for _ in range(q):
    Q = int(input())
    cand = []
    for i in range(2):
        for j in range(2):
                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)
                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)
    print(min(cand))

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

for i in range(Q):
  leftS=int(-3e10)
  leftT=int(-3e10)
  rightS=int(3e10)
  rightT=int(3e10)
  x=int(input())
  for j in range(A):
    if S[j] < x and S[j] > leftS :
      leftS=S[j]
    if S[j] > x and S[j] < rightS :
      rightS=S[j]
  for j in range(B):
    if T[j] < x and T[j] > leftT :
      leftT=T[j]
    if T[j] > x and T[j] < rightT :
      rightT=T[j]
  d1=max(rightS,rightT)-x
  d2=x-min(leftS, leftT)
  d3=(x-leftS)+(rightT-leftS)
  d4=(x-leftT)+(rightS-leftT)
  d5=(rightS-x)+(rightS-leftT)
  d6=(rightT-x)+(rightT-leftS)
  print(min(d1,d2,d3,d4,d5,d6))

Submission status: Time Limit Exceeded

Solution code:
import bisect

A, B, Q = map(int,input().split())
s = [0 for _ in range(A+2)]
t = [0 for _ in range(B+2)]
s[0] = -(10**18)
s[-1] = 10**18
t[0] = -(10**18)
t[-1] = 10**18
for i in range(A):
    s[i+1] = int(input())
for i in range(B):
    t[i+1] = int(input())

def solve(s,t,x):
    ans = 10**18
    for i in range(2):
        a, b = (s, t) if i==0 else (t, s)
        posX1 = bisect.bisect_left(a,x)
        for j in range(2):
            ax = a[posX1 -j]
            posX2 = bisect.bisect_left(b,ax)
            for k in range(2):
                bx = b[posX2-k]
                ans = min(ans, abs(x-ax)+abs(bx-ax))
    return ans

for _ in range(Q):
    x = int(input())
    print(solve(s,t,x))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import bisect

A, B, Q = map(int,input().split())
s = [0 for _ in range(A+2)]
t = [0 for _ in range(B+2)]
s[0] = -np.inf
s[-1] = np.inf
t[0] = -np.inf
t[-1] = np.inf
for i in range(A):
    s[i+1] = int(input())
for i in range(B):
    t[i+1] = int(input())

def solve(s,t,x):
    ans = np.inf
    for i in range(2):
        a, b = (s, t) if i==0 else (t, s)
        posX1 = bisect.bisect_left(a,x)
        for j in range(2):
            ax = a[posX1 -j]
            posX2 = bisect.bisect_left(b,ax)
            for k in range(2):
                bx = b[posX2-k]
                ans = min(ans, abs(x-ax)+abs(bx-ax))
    return ans

for _ in range(Q):
    x = int(input())
    print(solve(s,t,x))