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
A, B, Q = map(int, input().split())
s = [-10**11] + [int(input()) for i in range(A)] + [10**11]
t = [-10**11] + [int(input()) for i in range(B)] + [10**11]

#self_jisso
def nibutans(x, l, r):
	if r - l <= 1:
		return r
	nibu = (r + l) // 2
	return nibutans(x, nibu, r) if x > s[nibu] else nibutans(x, l, nibu)

def nibutant(x, l, r):
	if r - l <= 1:
		return r
	nibu = (r + l) // 2
	return nibutant(x, nibu, r) if x > t[nibu] else nibutant(x, l, nibu)

for i in range(Q):
	x = int(input())
	sr, tr = nibutans(x, 0, A + 1), nibutant(x, 0, B + 1)
	ans = 10**17
	for S in [s[sr - 1], s[sr]]:
		for T in [t[tr - 1], t[tr]]:
			d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
#			print(str(ans) + ' ' + str(d1) + ' ' + str(d2))
			ans = min(ans, d1, d2)
	print(ans)

Submission status: Time Limit Exceeded

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

def nibutans(x, l, r):
	if r - l <= 1:
		return max(r, l)
	nibu = (r + l) // 2
	return nibutans(x, nibu, r) if x > s[nibu] else nibutans(x, l, nibu)

def nibutant(x, l, r):
	if r - l <= 1:
		return max(r, l)
	nibu = (r + l) // 2
	return nibutant(x, nibu, r) if x > t[nibu] else nibutant(x, l, nibu)

for i in range(Q):
	x = int(input())
	sr, tr = nibutans(x, 0, A + 1), nibutant(x, 0, B + 1)
	ans = 10**17
	for S in [s[sr - 1], s[sr]]:
		for T in [t[tr - 1], t[tr]]:
			d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
#			print(str(ans) + ' ' + str(d1) + ' ' + str(d2))
			ans = min(ans, d1, d2)
	print(ans)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
import sys


def check(x, al, bl):
    rcost = np.inf
    for a in al:
        tmp_c = abs(a - x)
        for b in bl:
            t = abs(b - a)
            rcost = min(rcost, tmp_c + t, abs(b - x) + t)

    print(int(rcost))


n = [int(each) for each in sys.stdin.readline().split()]
a, b, q = n[0], n[1], n[2]

sl = np.zeros(a)
tl = np.zeros(b)
xl = np.zeros(q)

for i in range(a):
    sl[i] = int(sys.stdin.readline())
for i in range(b):
    tl[i] = int(sys.stdin.readline())
for i in range(q):
    xl[i] = int(sys.stdin.readline())

result = []
for x in xl:
    check(x, sl, tl)

Submission status: Time Limit Exceeded

Solution code:
from bisect import bisect_left
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()))
X = []
for _ in range(q):
  X.append(int(input()))

INF = 10 ** 11
def dfs(direction, tors, pos, count):
  if tors == 1:
    L = T
  elif tors == -1:
    L = S
  i = bisect_left(L, pos)
  if i == len(L):
    if direction == 1:
      return INF
    elif direction == -1:
      res = abs(L[i-1]-pos)
      next_pos = L[i-1]
  elif L[i] == pos:
    res = 0
    next_pos = pos
  else:
    if direction == 1:
      res = abs(L[i]-pos)
      next_pos = L[i]
    elif direction == -1:
      if i == 0:
        return INF

      res = abs(L[i-1]-pos)
      next_pos = L[i-1]

  if count == 1:
    return res

  res0 = res + dfs(direction, tors*(-1), next_pos, count-1)
  res1 = res + dfs(direction*(-1), tors*(-1), next_pos, count-1)

  return min(res0, res1)

for x in X:
  res0 = dfs(1, 1, x, 2)
  res1 = dfs(-1, 1, x, 2)
  res2 = dfs(1, -1, x, 2)
  res3 = dfs(-1, -1, x, 2)

  print(min(res0, res1, res2, res3))

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import bisect,math
import multiprocessing
A,B,Q=map(int,raw_input().split())
s=[0]*A
t=[0]*B
for i in range(A):
    s[i]=input()
for i in range(B):
    t[i]=input()
buf=[]
def f(x):
    sl=bisect.bisect_left(s,x)-1
    sr=sl+1
    tl=bisect.bisect_left(t,x)-1
    tr=tl+1
    ans=float("inf")
    if sl!=-1 and tl!=-1:
        A=max(s[sl],t[tl])
        B=min(s[sl],t[tl])
        L=abs(x-A)+abs(A-B)
        ans=min(ans,L)
    if sl!=-1 and tr!=len(t):
        L=abs(x-s[sl])*2 + abs(t[tr]-x)        
        ans=min(ans,L)
        ans=min(ans,abs(x-s[sl])+abs(t[tr]-x)*2)
    if tl!=-1 and sr!=len(s):
        ans=min(ans,abs(x-t[tl])*2+abs(s[sr]-x))
        ans=min(ans,abs(x-t[tl])+abs(s[sr]-x)*2)
    if tr!=len(t) and sr!=len(s):
        A=min(s[sr],t[tr])
        B=max(s[sr],t[tr])
        L=abs(A-x)+abs(B-A)
        ans=min(ans,L)
    return str(ans)

I=[0]*Q
for i in xrange(Q):
    I[i]=input()
r=map(f,I)
print("\n".join(r))

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import bisect,math
import multiprocessing
A,B,Q=map(int,raw_input().split())
s=[0]*A
t=[0]*B
for i in range(A):
    s[i]=input()
for i in range(B):
    t[i]=input()
buf=[]
def f(x):
    sl=bisect.bisect_left(s,x)-1
    sr=bisect.bisect_left(s,x)
    tl=bisect.bisect_left(t,x)-1
    tr=bisect.bisect_left(t,x)
    ans=float("inf")
    if sl!=-1 and tl!=-1:
        A=max(s[sl],t[tl])
        B=min(s[sl],t[tl])
        L=abs(x-A)+abs(A-B)
        ans=min(ans,L)
    if sl!=-1 and tr!=len(t):
        L=abs(x-s[sl])*2 + abs(t[tr]-x)        
        ans=min(ans,L)
        ans=min(ans,abs(x-s[sl])+abs(t[tr]-x)*2)
    if tl!=-1 and sr!=len(s):
        ans=min(ans,abs(x-t[tl])*2+abs(s[sr]-x))
        ans=min(ans,abs(x-t[tl])+abs(s[sr]-x)*2)
    if tr!=len(t) and sr!=len(s):
        A=min(s[sr],t[tr])
        B=max(s[sr],t[tr])
        L=abs(A-x)+abs(B-A)
        ans=min(ans,L)
    return str(ans)

I=[0]*Q
for i in xrange(Q):
    I[i]=input()
r=map(f,I)
print("\n".join(r))

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import bisect,math
import multiprocessing
A,B,Q=map(int,raw_input().split())
s=[]
t=[]
for a in range(A):
    s.append(input())
for a in range(B):
    t.append(input())
buf=[]    
def f(x):
    sl=bisect.bisect_left(s,x)-1
    sr=bisect.bisect_left(s,x)
    tl=bisect.bisect_left(t,x)-1
    tr=bisect.bisect_left(t,x)
    ans=float("inf")
    if sl!=-1 and tl!=-1:
        A=max(s[sl],t[tl])
        B=min(s[sl],t[tl])
        L=abs(x-A)+abs(A-B)
        ans=min(ans,L)
    if sl!=-1 and tr!=len(t):
        L=abs(x-s[sl])*2 + abs(t[tr]-x)        
        ans=min(ans,L)
        ans=min(ans,abs(x-s[sl])+abs(t[tr]-x)*2)
    if tl!=-1 and sr!=len(s):
        ans=min(ans,abs(x-t[tl])*2+abs(s[sr]-x))
        ans=min(ans,abs(x-t[tl])+abs(s[sr]-x)*2)
    if tr!=len(t) and sr!=len(s):
        A=min(s[sr],t[tr])
        B=max(s[sr],t[tr])
        L=abs(A-x)+abs(B-A)
        ans=min(ans,L)
    return str(ans)

I=[0]*Q
for i in xrange(Q):
    I[i]=input()
r=map(f,I)
print("\n".join(r))

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import bisect,math
A,B,Q=map(int,raw_input().split())
s=[]
t=[]
for a in range(A):
    s.append(input())
for a in range(B):
    t.append(input())
buf=[]    
for _ in xrange(Q):
    x=input()
    sl=bisect.bisect_left(s,x)-1
    sr=bisect.bisect_left(s,x)
    tl=bisect.bisect_left(t,x)-1
    tr=bisect.bisect_left(t,x)
    ans=float("inf")
    if sl!=-1 and tl!=-1:
        A=max(s[sl],t[tl])
        B=min(s[sl],t[tl])
        L=abs(x-A)+abs(A-B)
        ans=min(ans,L)
    if sl!=-1 and tr!=len(t):
        L=abs(x-s[sl])*2 + abs(t[tr]-x)        
        ans=min(ans,L)
        ans=min(ans,abs(x-s[sl])+abs(t[tr]-x)*2)
    if tl!=-1 and sr!=len(s):
        ans=min(ans,abs(x-t[tl])*2+abs(s[sr]-x))
        ans=min(ans,abs(x-t[tl])+abs(s[sr]-x)*2)
    if tr!=len(t) and sr!=len(s):
        A=min(s[sr],t[tr])
        B=max(s[sr],t[tr])
        L=abs(A-x)+abs(B-A)
        ans=min(ans,L)
    buf.append(str(ans))
print "\n".join(buf)

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import bisect,math
A,B,Q=map(int,raw_input().split())
s=[]
t=[]
for a in range(A):
    s.append(input())
for a in range(B):
    t.append(input())
for _ in xrange(Q):
    x=input()
    sl=bisect.bisect_left(s,x)-1
    sr=bisect.bisect_left(s,x)
    tl=bisect.bisect_left(t,x)-1
    tr=bisect.bisect_left(t,x)
    ans=float("inf")
    if sl!=-1 and tl!=-1:
        A=max(s[sl],t[tl])
        B=min(s[sl],t[tl])
        L=abs(x-A)+abs(A-B)
        ans=min(ans,L)
    if sl!=-1 and tr!=len(t):
        L=abs(x-s[sl])*2 + abs(t[tr]-x)        
        ans=min(ans,L)
        ans=min(ans,abs(x-s[sl])+abs(t[tr]-x)*2)
    if tl!=-1 and sr!=len(s):
        ans=min(ans,abs(x-t[tl])*2+abs(s[sr]-x))
        ans=min(ans,abs(x-t[tl])+abs(s[sr]-x)*2)
    if tr!=len(t) and sr!=len(s):
        A=min(s[sr],t[tr])
        B=max(s[sr],t[tr])
        L=abs(A-x)+abs(B-A)
        ans=min(ans,L)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
import bisect

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

ss.sort()
ts.sort()
for x in xs:
    i = bisect.bisect_left(ss, x)
    s1 = ss[i - 1] if 0 < i else -(10 ** 20)
    s2 = ss[i] if i < A else 10 ** 20
    i = bisect.bisect_left(ts, x)
    t1 = ts[i - 1] if 0 < i else -(10 ** 20)
    t2 = ts[i] if i < B else 10 ** 20

    # s1 < x < s2
    # t1 < x < t2
    print(min(
        x - min(s1, t1),  # s1, t1
        2 * (x - s1) + (t2 - x),  # s1, t2
        2 * (t2 - x) + (x - s1),  # t2, s1
        2 * (s2 - x) + (x - t1),  # s2, t1
        2 * (x - t1) + (s2 - x),  # t1, s2
        max(s2, t2) - x,  # s2, t2
    ))

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import bisect,math
A,B,Q=map(int,raw_input().split())
s=[]
t=[]
for a in range(A):
    s.append(input())
for a in range(B):
    t.append(input())
for _ in range(Q):
    x=input()
    sl=bisect.bisect_left(s,x)-1
    sr=bisect.bisect_left(s,x)
    tl=bisect.bisect_left(t,x)-1
    tr=bisect.bisect_left(t,x)
    ans=float("inf")
    if sl!=-1 and tl!=-1:
        A=max(s[sl],t[tl])
        B=min(s[sl],t[tl])
        L=abs(x-A)+abs(A-B)
        ans=min(ans,L)
    if sl!=-1 and tr!=len(t):
        L=abs(x-s[sl])*2 + abs(t[tr]-x)        
        ans=min(ans,L)
        ans=min(ans,abs(x-s[sl])+abs(t[tr]-x)*2)
    if tl!=-1 and sr!=len(s):
        ans=min(ans,abs(x-t[tl])*2+abs(s[sr]-x))
        ans=min(ans,abs(x-t[tl])+abs(s[sr]-x)*2)
    if tr!=len(t) and sr!=len(s):
        A=min(s[sr],t[tr])
        B=max(s[sr],t[tr])
        L=abs(A-x)+abs(B-A)
        ans=min(ans,L)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import bisect,math
A,B,Q=map(int,raw_input().split())
s=[]
t=[]
for a in range(A):
    s.append(input())
for a in range(B):
    t.append(input())
for _ in range(Q):
    x=input()
    sl=bisect.bisect_left(s,x)-1
    sr=bisect.bisect_left(s,x)
    tl=bisect.bisect_left(t,x)-1
    tr=bisect.bisect_left(t,x)
    ans=1<<50
    if sl!=-1 and tl!=-1:
        A=max(s[sl],t[tl])
        B=min(s[sl],t[tl])
        L=abs(x-A)+abs(A-B)
        ans=min(ans,L)
    if sl!=-1 and tr!=len(t):
        L=abs(x-s[sl])*2 + abs(t[tr]-x)
        ans=min(ans,L)
        ans=min(ans,abs(x-s[sl])+abs(t[tr]-x)*2)
    if tl!=-1 and sr!=len(s):
        ans=min(ans,abs(x-t[tl])*2+abs(s[sr]-x))
        ans=min(ans,abs(x-t[tl])+abs(s[sr]-x)*2)
    if tr!=len(t) and sr!=len(s):
        A=min(s[sr],t[tr])
        B=max(s[sr],t[tr])
        L=abs(A-x)+abs(B-A)
        ans=min(ans,L)
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
#coding:utf-8
import bisect,math
A,B,Q=map(int,raw_input().split())
s=[]
t=[]
for a in range(A):
    s.append(input())
for a in range(B):
    t.append(input())
for _ in range(Q):
    x=input()
    sl=bisect.bisect_left(s,x)-1
    sr=bisect.bisect_left(s,x)
    tl=bisect.bisect_left(t,x)-1
    tr=bisect.bisect_left(t,x)
    ans=1<<114514
    if sl!=-1 and tl!=-1:
        A=max(s[sl],t[tl])
        B=min(s[sl],t[tl])
        L=abs(x-A)+abs(A-B)
        ans=min(ans,L)
    if sl!=-1 and tr!=len(t):
        L=abs(x-s[sl])*2 + abs(t[tr]-x)
        ans=min(ans,L)
        ans=min(ans,abs(x-s[sl])+abs(t[tr]-x)*2)
    if tl!=-1 and sr!=len(s):
        ans=min(ans,abs(x-t[tl])*2+abs(s[sr]-x))
        ans=min(ans,abs(x-t[tl])+abs(s[sr]-x)*2)
    if tr!=len(t) and sr!=len(s):
        A=min(s[sr],t[tr])
        B=max(s[sr],t[tr])
        L=abs(A-x)+abs(B-A)
        ans=min(ans,L)
    print(ans)

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)]
IMF=10**12

for i in range(Q):
    if s[-1]<x[i]:
        rs=IMF
        ls=x[i]-s[-1]
    elif s[0]>x[i]:
        rs=s[0]-x[i]
        ls=IMF
    else:
        for j in range(A):
            if s[j]==x[i]:
                rs=0
                ls=0
                break
            elif s[j]>x[i]:
                rs=s[j]-x[i]
                ls=x[i]-s[j-1]
                break

    if t[-1]<x[i]:
        rt=IMF
        lt=x[i]-t[-1]
    elif t[0]>x[i]:
        rt=t[0]-x[i]
        lt=IMF
    else:
        for j in range(B):
            if t[j]==x[i]:
                rt=0
                lt=0
                break
            elif t[j]>x[i]:
                rt=t[j]-x[i]
                lt=x[i]-t[j-1]
                break


    R=max(rs, rt)
    L=max(ls, lt)
    SRs=rs+lt+min(rs, lt)
    SRt=rt+ls+min(rt, ls)

    print(min(R, L, SRs, SRt))

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

def Min(u):
    return 10**12 if len(u)==0 else min(u)

for i in range(Q):
    rs=[j-x[i] for j in s if j>=x[i]]
    rt=[j-x[i] for j in t if j>=x[i]]
    ls=[x[i]-j for j in s if j<=x[i]]
    lt=[x[i]-j for j in t if j<=x[i]]
    Minrs=Min(rs)
    Minrt=Min(rt)
    Minls=Min(ls)
    Minlt=Min(lt)

    R=max(Minrs, Minrt)
    L=max(Minls, Minlt)
    SRs=Minrs+Minlt+min(Minrs, Minlt)
    SRt=Minrt+Minls+min(Minrt, Minls)

    print(min(R, L, SRs, SRt))

Submission status: Time Limit Exceeded

Solution code:
import bisect
A,B,C =map(int,input().split())
s =[-10**11] + [int(input())for _ in range(A)] +[10**11]
t =[-10**11] + [int(input())for _ in range(B)] +[10**11]

for _ in range(C):
    x =int(input())
    ns = bisect.bisect_left(s,x)
    nt = bisect.bisect_left(t,x)
    sx =[s[ns-1],s[ns]]
    tx =[t[nt-1],t[nt]]
    lis =[sx,tx]
    ans = 10**11
    for i in range(8):
        p =i%2
        q =(i//2)%2
        r =i//4
        foo =abs(x-lis[p][q])+abs(lis[p][q]-lis[p-1][r])
        if foo < ans:
            ans = foo
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# from sys import stdin #入力の高速化(0.2秒ぐらい早くなる)
A, B, Q = list(map(int, input().split()))
# もし神社(寺)が1つしかなかった場合に両端に仮想の神社を建築して処理の一貫性を保つ。かりにこれが選ばれても最大のコストなので最終的に最適になることはない。
INF = 10 ** 18

# S = [-INF] + list(map(int, (stdin.readline() for _ in [0] * A))) + [INF]
# T = [-INF] + list(map(int, [stdin.readline() for _ in [0] * B])) + [INF]
S = [-INF] + [int(input()) for _ in range(A)]+[INF]
T = [-INF] + [int(input()) for _ in range(B)]+[INF]

from bisect import bisect_right
# from bisect import bisect_left as bisect_right #これでも通ったりする。
from itertools import product

for q in range(Q):  # 各問に答える
    x = int(input())  # 位置の指定
    s_idx, t_idx = bisect_right(S, x), bisect_right(T, x)
    ans = INF
    # 左右の神社と寺のの組み合わせ
    for s, t in product(S[s_idx - 1:s_idx + 1], T[t_idx - 1:t_idx + 1]):
        t_root = abs(t - x) + abs(s - t)  # 寺から最初に回るルート
        s_root = abs(s - x) + abs(s - t)
        ans = min(ans, t_root, s_root)
    # 最小をとって終わり
    print(ans)

'''
bisect_right

ソートされた順序を保ったまま x を a に挿入できる点を探し当てます。リストの中から検索する部分集合を指定するには、パラメータの lo と hi を使います。デフォルトでは、リスト全体が使われます。x がすでに a に含まれている場合、挿入点は既存のどのエントリーよりも後(右)になります。戻り値は、list.insert() の第一引数として使うのに適しています。a はすでにソートされているものとします。


In[3]: A
Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In[4]: bisect.bisect_right(A, 2.5)
Out[4]: 3

In[5]: bisect.bisect_right(A, 3)
Out[5]: 4
'''

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

def Min(u):
    return 10**12 if len(u)==0 else min(u)

for i in range(Q):
    rs=[j-x[i] for j in s if j>=x[i]]
    rt=[j-x[i] for j in t if j>=x[i]]
    ls=[x[i]-j for j in s if j<=x[i]]
    lt=[x[i]-j for j in t if j<=x[i]]

    R=max(Min(rs),Min(rt))
    L=max(Min(ls),Min(lt))
    MRs=Min(rs)+Min(lt)+min(Min(rs), Min(lt))
    MRt=Min(rt)+Min(ls)+min(Min(rt), Min(ls))

    print(min(R, L, MRs, MRt))

Submission status: Time Limit Exceeded

Solution code:

A,B,Q = (int(i) for i in 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 math
s_t = [0] * A #min dis form s to t
for i in range(A):
    max_ = B - 1
    min_ = 0
    k = int(max_ / 2)
    while(abs(max_ - min_)>1):
        if abs(t[k + 1] - s[i]) >  abs(t[k] - s[i]):
            max_ = k
            k =  int((k+min_) / 2)
        else:
            min_ = k
            k = int((k+max_)/2)
    k = max_
    if abs(t[max_] - s[i]) >  abs(t[min_] - s[i]):
        k = min_
    s_t[i] = abs(t[k] - s[i])

t_s = [0] * B #min dis form t to s
for i in range(B):
    max_ = A - 1
    min_ = 0
    k = int(max_ / 2)
    while(abs(max_ - min_)>1):
        if abs(s[k + 1] - t[i]) >  abs(s[k] - t[i]):
            max_ = k
            k =  int((k+min_) / 2)
        else:
            min_ = k
            k = int((k+max_)/2)
    k = max_
    if abs(s[max_] - t[i]) >  abs(s[min_] - t[i]):
        k = min_
    t_s[i] = abs(s[k] - t[i])


for i in range(Q):
    dis = []
    #first s
    max_ = A - 1
    min_ = 0
    k = int(max_ / 2)
    while(abs(max_ - min_)>1):
        if abs(s[k + 1] - x[i]) >  abs(s[k] - x[i]):
            max_ = k
            k =  int((k+min_) / 2)
        else:
            min_ = k
            k = int((k+max_)/2)
    k = max_
    if abs(s[max_] - x[i]) >  abs(s[min_] - x[i]):
        k = min_

    dis.append(abs(s[k] - x[i]) + s_t[k])
    if k > 0:
        dis.append(abs(s[k-1] - x[i]) + s_t[k-1])
    if k+1<A:
        dis.append(abs(s[k+1] - x[i]) + s_t[k+1])

    #first t
    max_ = B - 1
    min_ = 0
    k = int(max_ / 2)
    while(abs(max_ - min_)>1):
        if abs(t[k + 1] - x[i]) >  abs(t[k] - x[i]):
            max_ = k
            k =  int((k+min_) / 2)
        else:
            min_ = k
            k = int((k+max_)/2)
    k = max_
    if abs(t[max_] - x[i]) >  abs(t[min_] - x[i]):
        k = min_

    dis.append(abs(t[k] - x[i]) + t_s[k])
    if k > 0:
        dis.append(abs(t[k-1] - x[i]) + t_s[k-1])
    if k+1<B:
        dis.append(abs(t[k+1] - x[i]) + t_s[k+1])

    print(sorted(dis)[0])

Submission status: Time Limit Exceeded

Solution code:
def find(x, p):
	l, r = 0, len(p) - 1
	while l <= r:
		m = (l + r) // 2
		if p[m] < x:
			l = m + 1
		else:
			r = m - 1
	if l == len(p):
		l -= 1
	if r == -1:
		r += 1
	return r, l

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()))
for i in range(q):
	x = int(input())
	ls, rs = find(x, s)
	lt, rt = find(x, t)
	ans = min([
		abs(x - s[ls]) + abs(s[ls] - t[lt]),
		abs(x - s[ls]) + abs(s[ls] - t[rt]),
		abs(x - s[rs]) + abs(s[rs] - t[lt]),
		abs(x - s[rs]) + abs(s[rs] - t[rt]),
		abs(x - t[lt]) + abs(t[lt] - s[ls]),
		abs(x - t[lt]) + abs(t[lt] - s[rs]),
		abs(x - t[rt]) + abs(t[rt] - s[ls]),
		abs(x - t[rt]) + abs(t[rt] - s[rs])])
	print(ans)

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 q in range(Q):
    X=int(input())
    x_t=[X-b for b in t]
    a=[abs(i) for i in x_t]
    l1=min(a)
    if -l1 in x_t:
        l1=-l1
    x_s=[X-b for b in s]
    b=[abs(i) for i in x_s]
    l2=min(b)
    if -l2 in x_s:
        l2=-l2
    print(min(abs(l1)+min([abs(X-l1-b) for b in s]),abs(l2)+min([abs(X-l2-b) for b in t])))

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 q in range(Q):
    X=int(input())
    x_t=[X-b for b in t]
    l1=min([abs(i) for i in x_t])
    if -l1 in x_t:
        l1=-l1
    x_s=[X-b for b in s]
    l2=min([abs(i) for i in x_s])
    if -l2 in x_s:
        l2=-l2
    print(min(abs(l1)+min([abs(X-l1-b) for b in s]),abs(l2)+min([abs(X-l2-b) for b in t])))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
def getNearestValue(list, num):
    """
    概要: リストからある値に最も近い値を返却する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return list[idx]

def lazy():
    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)]#出発
    jin1=0
    tera1=0
    jin2=0
    tera2=0
    #print(s,t,x)
    for i in x:
        jin1=getNearestValue(s,i)
        tera1=getNearestValue(t,jin1)
        ans1=abs(jin1-i)+abs(tera1-jin1)

        tera2=getNearestValue(t,i)
        jin2=getNearestValue(s,tera2)
        ans2=abs(tera2-i)+abs(tera2-jin2)

        print(min(ans1,ans2))
    exit()
print(lazy())

Submission status: Time Limit Exceeded

Solution code:
import bisect
import numpy as np
INF=10**18
A,B,Q=map(int,input().split())
s=[int(input()) for i in range(A)]
t=[int(input()) for i in range(B)]
s=[-INF]+s+[INF]
t=[-INF]+t+[INF]
s=np.array(s)
t=np.array(t)
for q in range(Q):
    X=int(input())
    t1=bisect.bisect_right(t,X)
    s1=bisect.bisect_right(s,X)
    res=INF
    for T in [t[t1],t[t1-1]]:
        for S in [s[s1],s[s1-1]]:
            ans1=abs(X-T)+abs(S-T)
            ans2=abs(X-S)+abs(S-T)
            res=min(res,ans1,ans2)
    print(res)

Submission status: Time Limit Exceeded

Solution code:
import bisect
import numpy as np
INF=10**18
A,B,Q=map(int,input().split())
s=[int(input()) for i in range(A)]
t=[int(input()) for i in range(B)]
s=[-INF]+s+[INF]
t=[-INF]+t+[INF]
s=np.array(s)
t=np.array(t)
for q in range(Q):
    X=int(input())
    t1=bisect.bisect_right(t,X)
    l1=X-t[t1]
    if (t[t1]-X)>(X-t[t1-1]):
        l1=X-t[t1-1]
    s1=bisect.bisect_right(s,X)
    l2=X-s[s1]
    if (s[s1]-X)>(X-s[s1-1]):
        l2=X-s[s1-1]
    l3=bisect.bisect_right(s,X-l1)
    l4=bisect.bisect_right(t,X-l2)
    print(min(abs(l1)+min(s[l3]-X+l1,X-l1-s[l3-1]),abs(l2)+min(t[l4]-X+l2,X-l2-t[l4-1])))

Submission status: Time Limit Exceeded

Solution code:
import bisect
import numpy as np
INF=10**18
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)]
s=[-INF]+s+[INF]
t=[-INF]+t+[INF]
s=np.array(s)
t=np.array(t)
x=np.array(x)
for X in x:
    t1=bisect.bisect_right(t,X)
    l1=X-t[t1]
    if (t[t1]-X)>(X-t[t1-1]):
        l1=X-t[t1-1]
    s1=bisect.bisect_right(s,X)
    l2=X-s[s1]
    if (s[s1]-X)>(X-s[s1-1]):
        l2=X-s[s1-1]
    l3=bisect.bisect_right(s,X-l1)
    l4=bisect.bisect_right(t,X-l2)
    print(min(abs(l1)+min(s[l3]-X+l1,X-l1-s[l3-1]),abs(l2)+min(t[l4]-X+l2,X-l2-t[l4-1])))

Submission status: Time Limit Exceeded

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

import numpy as np

ss = np.array(ss)
ts = np.array(ts)

INF = 10e16

def near(l, v):
    diff = l - v
    absd = np.abs(diff)
    idx = absd.argmin()
    if diff[idx] > 0:
        if idx == 0:
            return INF, absd[idx]
        else:
            return absd[idx-1], absd[idx]
    else:
        if idx+1 == len(l):
            return absd[idx], INF
        else:
            return absd[idx], absd[idx+1]

for x in xs:
    sl, sh = near(ss, x)
    tl, th = near(ts, x)

    p1 = max(sl, tl)
    p2 = max(sh, th)
    p3 = 2*sl + th if sl < th else sl + 2*th
    p4 = 2*tl + sh if tl < sh else tl + 2*sh

    print(min(p1, p2, p3, p4))

Submission status: Time Limit Exceeded

Solution code:
A,B,Q=map(int,input().split())
inf=1e50
s=[int(input()) for _ in range(A)]
s=[-inf]+s+[inf]
t=[int(input()) for _ in range(B)]
t=[-inf]+t+[inf]

from bisect import bisect

for _ in range(Q):
    x=int(input())
    i=bisect(s,x)
    j=bisect(t,x)
    
    sL=x-s[i-1]
    sR=s[i]-x
    
    tL=x-t[j-1]
    tR=t[j]-x
    print(min(max(sR,tR),max(sL,tL),sR+tL+min(sR,tL),sL+tR+min(sL,tR)))

Submission status: Time Limit Exceeded

Solution code:
A,B,Q=map(int,input().split())
inf=1e50
s=[-inf]
for _ in range(A):
    s.append(int(input()))
s.append(inf)

t=[-inf]
for _ in range(B):
    t.append(int(input()))
t.append(inf)
from bisect import bisect

for _ in range(Q):
    x=int(input())
    i=bisect(s,x)
    j=bisect(t,x)
    
    sL=x-s[i-1]
    sR=s[i]-x
    
    tL=x-t[j-1]
    tR=t[j]-x
    print(min(max(sR,tR),max(sL,tL),sR+tL+min(sR,tL),sL+tR+min(sL,tR)))

Submission status: Time Limit Exceeded

Solution code:
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()))
from bisect import bisect
infty=1e50
for _ in range(Q):
    x=int(input())
    i=bisect(s,x)
    j=bisect(t,x)
    if 0<i<A:
        sL=x-s[i-1]
        sR=s[i]-x
    elif i==0:
        sL=infty
        sR=s[i]-x
    else:
        sL=x-s[-1]
        sR=infty
    
    if 0<j<B:
        tL=x-t[j-1]
        tR=t[j]-x
    elif j==0:
        tL=infty
        tR=t[j]-x
    else:
        tL=x-t[-1]
        tR=infty
    print(min(max(sR,tR),max(sL,tL),sR+tL+min(sR,tL),sL+tR+min(sL,tR)))

Submission status: Time Limit Exceeded

Solution code:
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()))
from bisect import bisect
infty=1e50
for _ in range(Q):
    x=int(input())
    i=bisect(s,x)
    j=bisect(t,x)
    if 0<i<A:
        sL=s[i-1]
        sR=s[i]
    elif i==0:
        sL=-infty
        sR=s[i]
    else:
        sL=s[-1]
        sR=infty
    
    if 0<j<B:
        tL=t[j-1]
        tR=t[j]
    elif j==0:
        tL=-infty
        tR=t[j]
    else:
        tL=t[-1]
        tR=infty
    sL=abs(sL-x)
    sR=abs(sR-x)
    tL=abs(tL-x)
    tR=abs(tR-x)

    print(min(max(sR,tR),max(sL,tL),sR+tL+min(sR,tL),sL+tR+min(sL,tR)))

Submission status: Time Limit Exceeded

Solution code:
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())
import bisect
for i in range(q):
  x=int(input())
  ids=bisect.bisect_left(s,x)
  idt=bisect.bisect_left(t,x)
  mi=14857363987569617
  if ids < a:
    if idt < b:
      mi=min(mi,min([abs(s[ids]-x)+abs(s[ids]-t[idt]),
                    abs(t[idt]-x)+abs(t[idt]-s[ids])]))
    if idt > 0:
      mi=min(mi,min([abs(s[ids]-x)+abs(s[ids]-t[idt-1]),
                    abs(t[idt-1]-x)+abs(t[idt-1]-s[ids])]))
  if ids > 0:
    if idt < b:
      mi=min(mi,min([abs(s[ids-1]-x)+abs(s[ids-1]-t[idt]),
                    abs(t[idt]-x)+abs(t[idt]-s[ids-1])]))
    if idt > 0:
      mi=min(mi,min([abs(s[ids-1]-x)+abs(s[ids-1]-t[idt-1]),
                    abs(t[idt-1]-x)+abs(t[idt-1]-s[ids-1])]))
  print(mi)

Submission status: Time Limit Exceeded

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

def lower_bound(al, key):
    """
    一般に左側が満たしておらず、右側は満たしている判定基準(境目は一つ)ならlower_boundになる
    (条件を満たすもののうち、最小のインデックスを返す)
    単調にさえなっていれば、左右が逆になっていても検索には使える(ng/okも一緒に逆にする必要がある)
    """
    def isOk(a):
        # alの中でkey以上のアイテムのうち最小のインデックスを返す
        # upper_boundにする時にはa>key
        return a>=key

    ng = -1
    ok = len(al)

    while abs(ok-ng)>1:
        mid = (ok+ng)//2

        if isOk(al[mid]):
            ok = mid
        else:
            ng = mid

    return ok

INF = 10**18
a,b,q = map(int, input().split())
sl = [-INF] + [int(input()) for _ in range(a)] + [INF]
tl = [-INF] + [int(input()) for _ in range(b)] + [INF]
# print(sl)
# print(tl)
for _ in range(q):
    x = int(input())
    si = lower_bound(sl,x)
    ti = lower_bound(tl,x)
    # print(x,si,ti)
    res = INF
    for s in [sl[si-1], sl[si]]:
        for t in [tl[ti-1], tl[ti]]:
            res = min(
                res,
                abs(s-x)+abs(t-s),
                abs(t-x)+abs(s-t)
            )
    print(res)