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:
from collections import defaultdict, Counter
from itertools import product, groupby, count, permutations, combinations
from math import pi, sqrt
from collections import deque
from bisect import bisect, bisect_left, bisect_right
from string import ascii_lowercase
from functools import lru_cache
import sys
sys.setrecursionlimit(10000)
INF = float("inf")
YES, Yes, yes, NO, No, no = "YES", "Yes", "yes", "NO", "No", "no"
dy4, dx4 = [0, 1, 0, -1], [1, 0, -1, 0]
dy8, dx8 = [0, -1, 0, 1, 1, -1, -1, 1], [1, 0, -1, 0, 1, 1, -1, -1]


def inside(y, x, H, W):
    return 0 <= y < H and 0 <= x < W


def ceil(a, b):
    return (a + b - 1) // b


# aとbの最大公約数
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)


# aとbの最小公倍数
def lcm(a, b):
    g = gcd(a, b)
    return a / g * b


class BisectWrapper:
    try:
        from typing import List
    except:
        List = list
    from bisect import bisect, bisect_left, bisect_right

    def __init__(self):
        pass

    # aにxが存在するか
    @staticmethod
    def exist(a: List, x: int):
        i = bisect_left(a, x)
        if i != len(a) and a[i] == x:
            return True
        return False

    # xのindex(なければ-1)
    @staticmethod
    def index(a: List, x: int):
        i = bisect_left(a, x)
        if i != len(a) and a[i] == x:
            return i
        return -1

    # y < xのようなyの中でもっとも右のindex
    @staticmethod
    def index_lt(a: List, x: int):
        i = bisect_left(a, x)
        if i:
            return i - 1
        return -1

    # y < xのようなyの個数
    @staticmethod
    def num_lt(a: List, x: int):
        return bisect_left(a, x)

    # y <= xのようなyの中でもっとも右のindex
    @staticmethod
    def index_lte(a: List, x: int):
        i = bisect_right(a, x)
        if i:
            return i - 1
        return -1

    # y < xのようなyの個数
    @staticmethod
    def num_lte(a: List, x: int):
        return bisect_right(a, x)

    # y > xのようなyの中でもっとも左のindex
    @staticmethod
    def index_gt(a: List, x: int):
        i = bisect_right(a, x)
        if i != len(a):
            return i
        return -1

    # y > xのようなyの個数
    @staticmethod
    def num_gt(a: List, x: int):
        return len(a) - bisect_right(a, x)

    # y >= xのようなyの中でもっとも左のindex
    @staticmethod
    def index_gte(a: List, x: int):
        i = bisect_left(a, x)
        if i != len(a):
            return i
        return -1

    # y >= xのようなyの個数
    @staticmethod
    def num_gte(a: List, x: int):
        return len(a) - bisect_left(a, x)


def near(A, x):
    l = BisectWrapper.index_lte(A, x)
    r = BisectWrapper.index_gte(A, x)
    if l == -1:
        return abs(x - A[r])
    if r == -1:
        return abs(x - A[l])
    return min(abs(x - A[r]), abs(x - A[l]))


def main():
    A, B, Q = map(int, input().split())
    S = list(sorted([int(input()) for _ in range(A)]))
    T = list(sorted([int(input()) for _ in range(B)]))

    for _ in range(Q):
        x = int(input())

        ans = INF
        s_l = BisectWrapper.index_lte(S, x)
        if s_l != -1:
            s = S[s_l]
            ans = min(ans, abs(x - s) + near(T, s))

        s_r = BisectWrapper.index_gte(S, x)
        if s_r != -1:
            s = S[s_r]
            ans = min(ans, abs(x - s) + near(T, s))

        t_l = BisectWrapper.index_lte(T, x)
        if t_l != -1:
            t = T[t_l]
            ans = min(ans, abs(x - t) + near(S, t))

        t_r = BisectWrapper.index_gte(T, x)
        if t_r != -1:
            t = T[t_r]
            ans = min(ans, abs(x - t) + near(S, t))

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
from itertools import product
from bisect import bisect_left, bisect_right


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

    # gen = TLE(A, B, Q, ss, ts, xs)
    gen = f(A, B, Q, ss, ts, xs)
    print(*gen, sep="\n")


def TLE(A, B, Q, ss, ts, xs):
    for x in xs:
        ans = float("inf")
        for s in ss:
            for t in ts:
                if s <= x <= t or t <= x <= s:
                    ds, dt = abs(x-s), abs(x-t)
                    tmp = min(ds, dt) + abs(s-t)
                elif x <= s <= t or x <= t <= s:
                    tmp = max(s, t)-x
                elif x >= s >= t or x >= t >= s:
                    tmp = x-min(s, t)
                ans = min(ans, tmp)

        yield ans


def f_ans(s, t, x):
    if s <= x <= t or t <= x <= s:
        ds, dt = abs(x-s), abs(x-t)
        tmp = min(ds, dt) + abs(s-t)
    elif x <= s <= t or x <= t <= s:
        tmp = max(s, t)-x
    elif x >= s >= t or x >= t >= s:
        tmp = x-min(s, t)
    return tmp


def f(A, B, Q, ss, ts, xs):
    for x in xs:
        t_left = bisect_left(ts, x)
        t_right = bisect_right(ts, x)
        s_left = bisect_left(ss, x)
        s_right = bisect_right(ss, x)

        t_idx = [t_right + a for a in [-1, 0, 1]]
        t_idx += [t_left + a for a in [-1, 0, 1]]
        s_idx = [s_right + a for a in [-1, 0, 1]]
        s_idx += [s_left + a for a in [-1, 0, 1]]

        ans = float("inf")
        for si, ti in product(set(s_idx), set(t_idx)):
            if 0 <= si < A and 0 <= ti < B:
                tmp = f_ans(ss[si], ts[ti], x)
                ans = min(ans, tmp)
        yield ans


if __name__ == "__main__":
    main()

Submission status: Time Limit Exceeded

Solution code:
import bisect
A, B, Q = map(int,input().split())
S = [-float("inf")] + sorted([int(input()) for k in range(A)]) + [float("inf")]
T = [-float("inf")] + sorted([int(input()) for k in range(B)]) + [float("inf")]
X = [int(input()) for k in range(Q)]

for x in X:
    p = bisect.bisect_left(S,x)
    q = bisect.bisect_left(T,x)
    t1 = max(abs(S[p]-x),abs(T[q]-x))
    t2 = max(abs(S[p-1]-x),abs(T[q-1]-x))
    t3 = abs(S[p-1]-x)+abs(S[p-1]-T[q])
    t4 = abs(T[q-1]-x)+abs(S[p]-T[q-1])    
    t5 = abs(S[p]-x)+abs(S[p]-T[q-1])    
    t6 = abs(T[q]-x)+abs(S[p-1]-T[q])
    print(min(t1,t2,t3,t4,t5,t6))

Submission status: Time Limit Exceeded

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

# end of world
EOW = 10 ** 10

# boundary info
tbounds = [(T[i+1] + T[i]) // 2 for i in range(B-1)]
sbounds = [(S[i+1] + S[i]) // 2 for i in range(A-1)]

# add pivot
tbounds.insert(0, 0)
tbounds.append(EOW)
sbounds.insert(0, 0)
sbounds.append(EOW)

# temple to shrine
ttos = []
cur = 0
for i in range(B):
    while True:
        if T[i] <= sbounds[cur]:
            break
        cur += 1
    ttos.append(cur-1)

# shrine to temple
stot = []
cur = 0
for i in range(A):
    while True:
        if S[i] <= tbounds[cur]:
            break
        cur += 1
    stot.append(cur-1)

for x in X:
    snear = 0
    while True:
        if x <= sbounds[snear]:
            break
        snear += 1
    tnears_range = range(max(0, stot[snear-1]), min(stot[snear-1] + 4, B))
    best = abs(S[snear-1]-x) + abs(T[stot[snear-1]]-S[snear-1])
    for j in tnears_range:
        dist = abs(T[j]-x) + abs(S[ttos[j]]-T[j])
        if dist < best:
            best = dist
    # svisit = 0
    # tnear = 0
    # best = EOW * 2
    # # search
    # for i in range(A):
    #     tnear = stot[i]
    #     dist = abs(S[i]-x) + abs(T[tnear]-S[i])
    #     if best > dist:
    #         best = dist
    #     else:
    #         break
    # for i in range(max(0, tnear-3), min(tnear+3, B)):
    #     snear = ttos[i]
    #     dist = abs(T[i]-x) + abs(S[snear]-T[i])
    #     if best > dist:
    #         best = dist
    print(best)
    # print(min(min(abs(S[i]-x) + abs(T[nt]-S[i]) for (i, nt) in enumerate(stot)), min(abs(T[i]-x) + abs(S[ns]-T[i]) for (i, ns) in enumerate(ttos))))

Submission status: Time Limit Exceeded

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

# end of world
EOW = 10 ** 10

# boundary info
tbounds = [(T[i+1] + T[i]) // 2 for i in range(B-1)]
sbounds = [(S[i+1] + S[i]) // 2 for i in range(A-1)]

# add pivot
tbounds.insert(0, 0)
tbounds.append(EOW)
sbounds.insert(0, 0)
sbounds.append(EOW)

# temple to shrine
ttos = []
cur = 0
for i in range(B):
    while True:
        if T[i] <= sbounds[cur]:
            break
        cur += 1
    ttos.append(cur-1)

# shrine to temple
stot = []
cur = 0
for i in range(A):
    while True:
        if S[i] <= tbounds[cur]:
            break
        cur += 1
    stot.append(cur-1)

for x in X:
    print(min(min(abs(S[i]-x) + abs(T[nt]-S[i]) for (i, nt) in enumerate(stot)), min(abs(T[i]-x) + abs(S[ns]-T[i]) for (i, ns) in enumerate(ttos))))

Submission status: Time Limit Exceeded

Solution code:
a,b,q=map(int,input().split())
S,T=[],[]
for i in range(a):
  S.append(int(input()))
for i in range(b):
  T.append(int(input()))
def f(list,n):
  if n<list[0]:
    return [-float("inf"),list[0]]
  elif list[-1]<n:
    return [list[-1],float("inf")]
  else:
    flag,count=0,0
    l=len(list)
    i=(l-1)//2
    while flag==0:
      if list[i]<n<list[i+1]:
        flag=1
        return [list[i],list[i+1]]
      elif n<list[i]:
        i//=2
        count+=1
      else:
        i+=(l-1)//(2**(count+1))
        count+=1
def g(SS,TT,x):
  a,b,c,d=x-SS[0],SS[1]-x,x-TT[0],TT[1]-x
  dis1=max(a,c)
  dis2=min(2*a+d,2*d+a)
  dis3=max(b,d)
  dis4=min(2*b+c,2*c+b)
  return min([dis1,dis2,dis3,dis4])
        
for i in range(q):
  x=int(input())
  print(g(f(S,x),f(T,x),x))

Submission status: Time Limit Exceeded

Solution code:
a, b, q = map(int, input().split())
INF = 10**11+2
s = []
t = []

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


def nearest_s(y):
  dist_s = INF
  ret = []
  for i in s:
    if abs(y-i) < dist_s:
      nearestS = i
      dist_s = abs(y-i)
    elif abs(y-i) == dist_s:
      ret.append(nearestS)
      nearestS = i
      dist_s = abs(y-i)
  ret.append(nearestS)
  ret.append(dist_s)
  return ret

def nearest_t(y):
  dist_t = INF
  ret = []
  for i in t:
    if abs(y-i) < dist_t:
      nearestT = i
      dist_t = abs(y-i)
    elif abs(y-i) == dist_t:
      ret.append(nearestT)
      nearestT = i
      dist_t = abs(y-i)
  ret.append(nearestT)
  ret.append(dist_t)
  return ret

for i in range(q):
  x = int(input())
  
  # s → t
  s_t = INF
  for j in range(len(nearest_s(x))-1):
    if (nearest_s(x)[-1] + nearest_t(nearest_s(x)[j])[-1]) < s_t:
      s_t = nearest_s(x)[-1] + nearest_t(nearest_s(x)[j])[-1]
      
  # t → s
  t_s = INF
  for j in range(len(nearest_t(x))-1):
    if (nearest_t(x)[-1] + nearest_s(nearest_t(x)[j])[-1]) < t_s:
      t_s = nearest_t(x)[-1] + nearest_s(nearest_t(x)[j])[-1]
      
  print(min(t_s,s_t))

Submission status: Time Limit Exceeded

Solution code:
INF = 10 ** 11
A,B,Q = map(int, input().split())
s_list = [int(input()) for i in range(A)]
t_list = [int(input()) for i in range(B)]
q_list = [int(input()) for i in range(Q)]

#print("---------------")

def go_left(cur, _list):
    dist = INF
    next_pos = -1
    for j in range(len(_list)):
        if _list[j] > cur:
            break
        else:
            dist = abs(cur - _list[j])
            next_pos = _list[j]
    return dist, next_pos 

def go_right(cur, _list):
    dist = INF
    next_pos = -1
    for j in range(len(_list)):
        if _list[j] >= cur:
            dist = abs(cur - _list[j])
            next_pos = _list[j]
            break
    return dist, next_pos 


for i in range(Q):
    start = q_list[i]

    #Go left s 
    dist1, next_pos = go_left(start, s_list)
    #Go left s => left t
    dist_tmp, next_pos_tmp = go_left(next_pos, t_list)
    #Go left s => rihgt t
    dist_tmp2, next_pos_tmp = go_right(next_pos, t_list)
    dist1 += min(dist_tmp, dist_tmp2)

    #Go left t
    dist2, next_pos = go_left(start, t_list)
    #Go left t => left s
    dist_tmp, next_pos_tmp = go_left(next_pos, s_list)
    #Go left t => rihgt s
    dist_tmp2, next_pos_tmp = go_left(next_pos, s_list)
    dist2 += min(dist_tmp, dist_tmp2)

    #Go right s 
    dist3, next_pos = go_right(start, s_list)
    #Go right s => left t
    dist_tmp, next_pos_tmp = go_left(next_pos, t_list)
    #Go right s => rihgt t
    dist_tmp2, next_pos_tmp = go_right(next_pos, t_list)
    dist3 += min(dist_tmp, dist_tmp2)

    #Go right t 
    dist4, next_pos = go_right(start, t_list)
    #Go right t => left s
    dist_tmp, next_pos_tmp = go_left(next_pos, s_list)
    #Go right t => rihgt s
    dist_tmp2, next_pos_tmp = go_right(next_pos, s_list)
    dist4 += min(dist_tmp, dist_tmp2)
    print(min(dist1, dist2, dist3, dist4))

Submission status: Time Limit Exceeded

Solution code:
A,B,Q = [ int(it) for it in input().split() ]
si = [ int(input()) for i in range(A) ]
ti = [ int(input()) for i in range(B) ]
xi = [ int(input()) for i in range(Q) ]

si.sort()
ti.sort()



def find(v,li):
  le = len(li)-1
  dx = 1
  for i in range(100000):
    if (2*dx<=le):
      dx*=2
    else:
      break
  x=dx

  if (v < li[0]):
    return -1
  if (v > li[le]):
    return le

  for i in range(100000):
    #print ("x:",x,"dx:",dx)
    if ( x >= le ):
      x-=dx
      dx//=2
    elif ( li[x+1] < v ):
      x+=dx
      dx//=2
    elif ( v < li[x]  ):
      x-=dx
      dx//=2
    else:
      return x

sl = len(si)
tl = len(ti)

for x in xi:
  wh = 1e+20
  s = find(x,si)
  t = find(x,ti)
  
  if ( s>=0 and t>=0):
    wh = min ( wh, abs(x - si[s])+abs(si[s]-ti[t]) )

    
  if ( s<sl-1 and t>=0 ):
    wh = min ( wh, abs(x - si[s+1])+abs(si[s+1]-ti[t]) )
  if ( s>=0 and t<tl-1):
    wh = min ( wh, abs(x - si[s])+abs(si[s]-ti[t+1]) )
  if ( s<sl-1 and t<tl-1):
    wh = min ( wh, abs(x - si[s+1])+abs(si[s+1]-ti[t+1]) )
  if ( t>=0 and s>=0):
    wh = min ( wh, abs(x - ti[t])+abs(ti[t]-si[s]) )
    #p\rint ("w" , wh)
  if ( t<tl-1 and s>=0 ):
    wh = min ( wh, abs(x - ti[t+1])+abs(ti[t+1]-si[s]) )
  if ( t>=0 and s<sl-1):
    wh = min ( wh, abs(x - ti[t])+abs(ti[t]-si[s+1]) )
  if ( t<tl-1 and s<sl-1):
    wh = min ( wh, abs(x - ti[t+1])+abs(ti[t+1]-si[s+1]) )
  print ( wh )

Submission status: Time Limit Exceeded

Solution code:
A,B,Q = [ int(it) for it in input().split() ]
si = [ int(input()) for i in range(A) ]
ti = [ int(input()) for i in range(B) ]
xi = [ int(input()) for i in range(Q) ]

si.sort()
ti.sort()



def find(v,li):
  le = len(li)-1
  dx = 1
  for i in range(100000):
    if (2*dx<=le):
      dx*=2
    else:
      break
  x=dx

  if (v < li[0]):
    return -1
  if (v > li[le]):
    return le

  for i in range(100000):
    #print ("x:",x,"dx:",dx)
    if ( x >= le ):
      x-=dx
      dx//=2
    elif ( li[x+1] < v ):
      x+=dx
      dx//=2
    elif ( v < li[x]  ):
      x-=dx
      dx//=2
    else:
      return x

sl = len(si)
tl = len(ti)

for x in xi:
  wh = 1000000000000000000000000000000000
  s = find(x,si)
  t = find(x,ti)
  
  if ( s>=0 and t>=0):
    wh = min ( wh, abs(x - si[s])+abs(si[s]-ti[t]) )

    
  if ( s<sl-1 and t>=0 ):
    wh = min ( wh, abs(x - si[s+1])+abs(si[s+1]-ti[t]) )
  if ( s>=0 and t<tl-1):
    wh = min ( wh, abs(x - si[s])+abs(si[s]-ti[t+1]) )
  if ( s<sl-1 and t<tl-1):
    wh = min ( wh, abs(x - si[s+1])+abs(si[s+1]-ti[t+1]) )
  if ( t>=0 and s>=0):
    wh = min ( wh, abs(x - ti[t])+abs(ti[t]-si[s]) )
    #p\rint ("w" , wh)
  if ( t<tl-1 and s>=0 ):
    wh = min ( wh, abs(x - ti[t+1])+abs(ti[t+1]-si[s]) )
  if ( t>=0 and s<sl-1):
    wh = min ( wh, abs(x - ti[t])+abs(ti[t]-si[s+1]) )
  if ( t<tl-1 and s<sl-1):
    wh = min ( wh, abs(x - ti[t+1])+abs(ti[t+1]-si[s+1]) )
  print ( wh )

Submission status: Time Limit Exceeded

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

s_s = [int(input()) for _ in range(a)]
t_s = [int(input()) for _ in range(b)]
x_s = [int(input()) for _ in range(q)]

for x in x_s:
  mind = 2*(10**10)
  for s in s_s:
    for t in t_s:
      if x > t and x > s:
        mind = min(mind, x - min(t, s))
        continue
      if x < t and x < s:
        mind = min(mind, max(t, s) - x)
        continue
      mind = min(mind, abs(t-s) + min(abs(x-s), abs(x-t)))
  print(mind)

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
  n = len(ls)
  lb = -1
  rb = n

  while rb-lb > 1:
    mid = (lb+rb)//2

    if ls[mid] >= x:
      rb = mid
    else:
      lb = mid

  return rb

for x in xs:
    sind = binarysearch(ss,x)-1
    tind = binarysearch(ts,x)-1

    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    print(min(max(x-s0,x-t0),min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x)),min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x)),max(s1-x, t1-x)))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
  n = len(ls)
  lb = -1
  rb = n

  while rb-lb > 1:
    mid = lb+(rb-lb)//2

    if ls[mid] > x:
      rb = mid
    else:
      lb = mid

  return rb

for x in xs:
    sind = binarysearch(ss,x)-1
    tind = binarysearch(ts,x)-1

    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    print(min(max(x-s0,x-t0),min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x)),min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x)),max(s1-x, t1-x)))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
  n = len(ls)
  lb = -1
  rb = n

  while rb-lb > 1:
    mid = lb+(rb-lb)//2

    if ls[mid] > x:
      rb = mid
    else:
      lb = mid

  return rb

for x in xs:
    sind = binarysearch(ss,x)-1
    tind = binarysearch(ts,x)-1

    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
  n = len(ls)
  lb = 0
  rb = n

  while rb-lb > 0:
    mid = (lb+rb)//2

    if ls[mid] < x:
      lb = mid+1
    else:
      rb = mid

  return lb

for x in xs:
    sind = binarysearch(ss,x)-1
    tind = binarysearch(ts,x)-1

    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
  n = len(ls)
  lb = -1
  rb = n-1

  while rb-lb > 1:
    mid = (lb+rb)//2

    if ls[mid] == x:
      return mid

    if ls[mid] < x:
      lb = mid
    else:
      rb = mid

  if x <= ls[rb]:
    return rb
  else:
    return rb+1

for x in xs:
    sind = binarysearch(ss,x)
    tind = binarysearch(ts,x)

    s0,s1,t0,t1 = ss[sind-1],ss[sind],ts[tind-1],ts[tind]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
  n = len(ls)
  lb = -1
  rb = n-1

  while rb-lb > 1:
    mid = (lb+rb)//2

    if ls[mid] < x:
      lb = mid
    else:
      rb = mid

  if x <= ls[rb]:
    return rb
  else:
    return rb+1

for x in xs:
    sind = binarysearch(ss,x)
    tind = binarysearch(ts,x)

    s0,s1,t0,t1 = ss[sind-1],ss[sind],ts[tind-1],ts[tind]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
  n = len(ls)
  lb = 0
  rb = n+1

  while rb-lb > 1:
    mid = (lb+rb)//2

    if ls[mid] > x:
      rb = mid
    else:
      lb = mid

  return min(lb,n-1)

for x in xs:
    sind = binarysearch(ss,x)
    tind = binarysearch(ts,x)
    
    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
  n = len(ls)
  lb = 0
  rb = n+1

  while rb-lb > 1:
    mid = (lb+rb)//2

    if ls[mid] > x:
      rb = mid
    else:
      lb = mid

  return lb

for x in xs:
    sind = binarysearch(ss,x)
    tind = binarysearch(ts,x)
    
    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
  n = len(ls)
  lb = 0
  rb = n+1

  while rb-lb > 1:
    mid = (lb+rb)//2

    if ls[mid] <= x:
      lb = mid
    else:
      rb = mid

  return lb

for x in xs:
    sind = binarysearch(ss,x)
    tind = binarysearch(ts,x)
    
    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
    n = len(ls)
    width = n//2
    pos = n//2
    flg = n%2==1
    while True:
        prvW = width

        if width == 1:
          width = 1
        else:
          width = (width+flg)//2
        flg = prvW%2==1

        if ls[pos] <= x <= ls[pos+1]:
            index = pos
            break    
        elif x < ls[pos]:
            pos -= width
        elif ls[pos+1] < x:
            pos += width
        pos = min(n-1,pos)
        pos = max(pos,0)
    return index

for x in xs:
    sind = binarysearch(ss,x)
    tind = binarysearch(ts,x)
    
    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
    n = len(ls)
    width = n//2
    pos = n//2
    while True:
        width = (width+1)//2
        if ls[pos] <= x <= ls[pos+1]:
            index = pos
            break    
        elif x < ls[pos]:
            pos -= width
        elif ls[pos+1] < x:
            pos += width
        pos = min(n-1,pos)
        pos = max(pos,0)
    return index

for x in xs:
    sind = binarysearch(ss,x)
    tind = binarysearch(ts,x)
    
    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
# xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
    n = len(ls)
    width = n//2
    pos = n//2
    while True:
        width = (width+1)//2
        if ls[pos] < x < ls[pos+1]:
            index = pos
            break    
        elif x < ls[pos]:
            pos -= width
        elif ls[pos+1] < x:
            pos += width
        pos = min(n-1,pos)
        pos = max(pos,0)
    return index

# for x in xs:
for i in range(Q):
    x = int(input())
    sind = binarysearch(ss,x)
    tind = binarysearch(ts,x)
    
    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Time Limit Exceeded

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

ss = [-10**10]+[int(input()) for _ in range(A)]+[2*10**10]
ts = [-10**10]+[int(input()) for _ in range(B)]+[2*10**10]
xs = [int(input()) for _ in range(Q)]

def binarysearch(ls,x):
    n = len(ls)
    width = n//2
    pos = n//2
    while True:
        width = (width+1)//2
        if ls[pos] < x < ls[pos+1]:
            index = pos
            break    
        elif x < ls[pos]:
            pos -= width
        elif ls[pos+1] < x:
            pos += width
        pos = min(n-1,pos)
        pos = max(pos,0)
    return index

for x in xs:
    sind = binarysearch(ss,x)
    tind = binarysearch(ts,x)
    
    s0,s1,t0,t1 = ss[sind],ss[sind+1],ts[tind],ts[tind+1]
    d1,d2,d3,d4 = 10**10,10**10,10**10,10**10

    d1 = max(x-s0,x-t0)
    d2 = min((t1-x)*2+(x-s0),(x-s0)*2+(t1-x))
    d3 = min((s1-x)*2+(x-t0),(x-t0)*2+(s1-x))
    d4 = max(s1-x, t1-x)
    print(min(d1,d2,d3,d4))

Submission status: Time Limit Exceeded

Solution code:
import bisect

A, B, Q = map(int, input().split())
s = [0]*(A+4)
t = [0]*(B+4)

for i in range(2, A+2):
    s[i] = int(input())

for i in range(2, B+2):
    t[i] = int(input())

s[0], s[1], s[-2], s[-1] = -10**11-1, -10**11, 10**11, 10**11+1
t[0], t[1], t[-2], t[-1] = -10**11-1, -10**11, 10**11, 10**11+1


for i in range(Q):
    x = int(input())
    sh_left = bisect.bisect(s, x) - 1
    sh_right = sh_left + 1
    ans = 10**12
    for i in range(2):
        loc_sh = s[[sh_left, sh_right][i]]
        dis = abs(x-loc_sh)
        te_left = bisect.bisect(t, loc_sh) - 1
        te_right = te_left + 1
        loc_te_l = t[te_left]
        loc_te_r = t[te_right]
        tmp = min(dis+abs(loc_sh-loc_te_l), dis+abs(loc_sh-loc_te_r))
        ans = min(ans, tmp)
    te_left = bisect.bisect(t, x) - 1
    te_right = te_left + 1
    for i in range(2):
        loc_te = t[[te_left, te_right][i]]
        dis = abs(x-loc_te)
        sh_left = bisect.bisect(s, loc_te) - 1
        sh_right = sh_left + 1
        loc_sh_l = s[sh_left]
        loc_sh_r = s[sh_right]
        tmp = min(dis+abs(loc_te-loc_sh_l), dis+abs(loc_te-loc_sh_r))
        ans = min(ans, tmp)
    print(ans)