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: Accepted

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

import sys, re
from collections import deque, defaultdict, Counter
from math import sqrt, hypot, factorial, pi, sin, cos, radians, log10
if sys.version_info.minor >= 5: from math import gcd
else: from fractions import gcd 
from heapq import heappop, heappush, heapify, heappushpop
from bisect import bisect_left, bisect_right
from itertools import permutations, combinations, product, accumulate
from operator import itemgetter, mul, xor
from copy import copy, deepcopy
from functools import reduce, partial
from fractions import Fraction
from string import ascii_lowercase, ascii_uppercase, digits
from datetime import date

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def round(x): return int((x*2+1) // 2)
def fermat(x, y, MOD): return x * pow(y, MOD-2, MOD) % MOD
def lcm(x, y): return (x * y) // gcd(x, y)
def lcm_list(nums): return reduce(lcm, nums, 1)
def gcd_list(nums): return reduce(gcd, nums, nums[0])
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

A,B,Q=MAP()

S=[0]*(A+2)
for i in range(A):
    S[i+1]=INT()
T=[0]*(B+2)
for i in range(B):
    T[i+1]=INT()
S[-1]=T[-1]=INF

# Si番目の神社から左に一番近い寺
L1=[INF]*(A+2)
# Si番目の神社から右に一番近い寺
R1=[INF]*(A+2)
for i in range(1, A+1):
    idx=bisect_right(T, S[i])-1
    if idx!=0:
        L1[i]=S[i]-T[idx]
    idx=bisect_left(T, S[i])
    if idx!=INF:
        R1[i]=T[idx]-S[i]
# Ti番目の寺から左に一番近い神社
L2=[INF]*(B+2)
# Ti番目の寺から右に一番近い神社
R2=[INF]*(B+2)
for i in range(1, B+1):
    idx=bisect_right(S, T[i])-1
    if idx!=0:
        L2[i]=T[i]-S[idx]
    idx=bisect_left(S, T[i])
    if idx!=INF:
        R2[i]=S[idx]-T[i]

for i in range(Q):
    dist1=dist2=dist3=dist4=INF
    x=INT()
    idx=bisect_right(S, x)-1
    if idx!=0:
        dist1=x-S[idx]
        dist1+=min(L1[idx], R1[idx])
    idx=bisect_left(S, x)
    if idx!=INF:
        dist2=S[idx]-x
        dist2+=min(L1[idx], R1[idx])
    idx=bisect_right(T, x)-1
    if idx!=0:
        dist3=x-T[idx]
        dist3+=min(L2[idx], R2[idx])
    idx=bisect_left(T, x)
    if idx!=INF:
        dist4=T[idx]-x
        dist4+=min(L2[idx], R2[idx])
    print(min(dist1, dist2, dist3, dist4))

Submission status: Accepted

Solution code:
import bisect
import sys
A, B, Q = map(int, input().split())
INF = 10 ** 13
s = [-INF] + [int(input()) for i in range(A)] + [INF]
t = [-INF] + [int(input()) for i in range(B)] + [INF]
xs = [int(sys.stdin.readline()) for i in range(Q)]
for x in xs:
    b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
    res = INF
    for S in [s[b - 1], s[b]]:
        for T in [t[d - 1], t[d]]:
            d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
            res = min(res, d1, d2)
    print(res)

Submission status: Accepted

Solution code:
import bisect

def nearlr(l, x):
    n = bisect.bisect(l, x)
    return n-1, n

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:
    s_1, s_2 = nearlr(s, _x)
    t_1, t_2 = nearlr(t, _x)
    s_cand = []
    t_cand = []
    if s_1 < 0:
        s_cand = [s[s_2] - _x]
    elif s_2 >= len(s):
        s_cand = [s[s_1] - _x]
    else:
        s_cand = [s[s_1] - _x, s[s_2] - _x]
    if t_1 < 0:
        t_cand = [t[t_2] - _x]
    elif t_2 >= len(t):
        t_cand = [t[t_1] - _x]
    else:
        t_cand = [t[t_1] - _x, t[t_2] - _x]
    ans = float('inf')
    for _s in s_cand:
        for _t in t_cand:
            if _t * _s < 0:
                ans = min(ans, abs(_s) * 2 + abs(_t), abs(_s) + abs(_t) * 2)
            else:
                ans = min(ans, max(abs(_s), abs(_t)))
    print(ans)

Submission status: Accepted

Solution code:
import bisect

def nearlr(l, x):
    n = bisect.bisect(l, x)
    return n-1, n

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

for _x in x:
    s_1, s_2 = nearlr(s, _x)
    t_1, t_2 = nearlr(t, _x)
    s_cand = []
    t_cand = []
    if s_1 < 0:
        s_cand = [s[s_2] - _x]
    elif s_2 >= len(s):
        s_cand = [s[s_1] - _x]
    else:
        s_cand = [s[s_1] - _x, s[s_2] - _x]
    if t_1 < 0:
        t_cand = [t[t_2] - _x]
    elif t_2 >= len(t):
        t_cand = [t[t_1] - _x]
    else:
        t_cand = [t[t_1] - _x, t[t_2] - _x]
    ans = float('inf')
    for _s in s_cand:
        for _t in t_cand:
            if _t * _s < 0:
                ans = min(ans, abs(_s) * 2 + abs(_t), abs(_s) + abs(_t) * 2)
            else:
                ans = min(ans, max(abs(_s), abs(_t)))
    print(ans)

Submission status: Accepted

Solution code:
import bisect
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.insert(0, -(10**11))
s.append(10**11)
t.insert(0, -(10**11))
t.append(10**11)

for xi in x:
  sb = bisect.bisect(s, xi)
  tb = bisect.bisect(t, xi)
  
  print(min((abs(s[sb]-xi)+abs(t[tb]-s[sb])), 
              (abs(s[sb]-xi)+abs(t[tb-1]-s[sb])),
              (abs(s[sb-1]-xi)+abs(t[tb]-s[sb-1])),
              (abs(s[sb-1]-xi)+abs(t[tb-1]-s[sb-1])),
              (abs(t[tb]-xi)+abs(s[sb]-t[tb])),
              (abs(t[tb]-xi)+abs(s[sb-1]-t[tb])),
              (abs(t[tb-1]-xi)+abs(s[sb]-t[tb-1])),
              (abs(t[tb-1]-xi)+abs(s[sb-1]-t[tb-1]))))

Submission status: Accepted

Solution code:
import bisect
a,b,q = (int(i) for i in input().split())
s = [int(input()) for s in range(a)]
t = [int(input()) for p in range(b)]
inf = 10**15
s = [-inf]+s+[inf]
t = [-inf]+t+[inf]
def distan(x,s,t):
  return(min(abs(x-s)+abs(s-t),abs(x-t)+abs(t-s)))

for i in range(q):
  x = int(input())
  sl = bisect.bisect_left(s,x)
  sr = bisect.bisect_right(s,x)
  if sl == sr:sl -= 1
  tl = bisect.bisect_left(t,x)
  tr = bisect.bisect_right(t,x)
  if tl == tr:tl -= 1
    
  sl = s[sl]
  sr = s[sr]
  tl = t[tl]
  tr = t[tr]
  ans = inf
  #1 x-sl-tl,x-tl-sl...
  print(min(distan(x,sl,tl),distan(x,sr,tl),distan(x,sl,tr),distan(x,sr,tr)))

Submission status: Accepted

Solution code:
import bisect

A,B,Q=map(int,input().split())
inf = 10 ** 18
S = [-inf] + [int(input()) for _ in range(A)] + [inf]
T = [-inf] + [int(input()) for _ in range(B)] + [inf]

for q in range(Q):
    x = int(input())
    s_h = bisect.bisect(S,x)
    s_l = s_h - 1
    t_h = bisect.bisect(T,x)
    t_l = t_h - 1

    ans = inf
    for s in [S[s_l],S[s_h]]:
        for t in [T[t_l],T[t_h]]:
            d1 = abs(s-x)+abs(t-s)
            d2 = abs(t-x)+abs(s-t)
            ans = min(ans,d1,d2)
    
    print(ans)

Submission status: Accepted

Solution code:
def main():
    a, b, q = map(int, input().rstrip("\n").split(" "))

    jinja_list = []

    for i in range(a):
        jinja_list.append(int(input().rstrip("\n")))

    temple_list = []
    for i in range(b):
        temple_list.append(int(input().rstrip("\n")))

    from bisect import bisect

    for i in range(q):
        pos = int(input().rstrip("\n"))

        jinja_index = bisect(jinja_list, pos)
        jinja_left = jinja_list[jinja_index - 1:jinja_index]
        jinja_right = jinja_list[jinja_index:jinja_index + 1]

        temple_index = bisect(temple_list, pos)
        temple_left = temple_list[temple_index - 1:temple_index]
        temple_right = temple_list[temple_index:temple_index + 1]

        distances = []
        #distances.append((pos, jinja_left, jinja_right, temple_left, temple_right))
        if jinja_left and temple_left:
            distances.append(pos - min(jinja_left[0], temple_left[0]))
            #distances.append("jinja_left and temple_left")
        if jinja_right and temple_right:
            distances.append(max(jinja_right[0], temple_right[0]) - pos)
            #distances.append("jinja_right and temple_right")
        if jinja_left and temple_right:
            left_right = abs(pos - jinja_left[0]) + abs(temple_right[0] - jinja_left[0])
            right_left = abs(pos - temple_right[0]) + abs(jinja_left[0] - temple_right[0])
            distances.append(left_right)
            distances.append(right_left)
            #distances.append("jinja_left and temple_right")
        if jinja_right and temple_left:
            left_right = abs(pos - temple_left[0]) + abs(jinja_right[0] - temple_left[0])
            right_left = abs(pos - jinja_right[0]) + abs(temple_left[0] - jinja_right[0])
            distances.append(left_right)
            distances.append(right_left)
            #distances.append("jinja_right and temple_left")
        #print(distances)
        print(min(distances))
        
if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int, input().split())
INF=10**18
s=[-INF] + [int(input()) for i in range(A)] + [INF]
t=[-INF] + [int(input()) for i in range(B)] + [INF]
for q in range(Q):
  x = int(input())
  b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
  res = INF
  for S in [s[b - 1], s[b]]:
    for T in [t[d - 1], t[d]]:
      d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
      res = min(res, d1, d2)
  print(res)
#copy code.

Submission status: Accepted

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

def io_generator():
	return input()

#+++++++++++++++++++

def t_search(a_list, pos):
	oo=10**20
	if pos< a_list[0]:
		pm=oo
		pp=a_list[0]-pos
		return pm,pp
	elif pos>a_list[-1]:
		pm=pos-a_list[-1]
		pp=oo
		return pm,pp
	ok=0
	ng=len(a_list)-1
	while abs(ok-ng)>1:
		mid=(ok+ng)//2
		if a_list[mid]<=pos:
			ok=mid
		else:
			ng=mid
	
	if a_list[ok]==pos:
		return 0,0
	pm=a_list[ok]
	pp=a_list[ok+1]
	return pos-pm, pp-pos

def main(io):
	a,b,q= map(int, io().split())
	syu=list(range(a))
	ten=list(range(b))
	for i in range(a):
		syu[i]=int(io())
	for i in range(b):
		ten[i]=int(io())
		
	ret=list(range(q))
	for i in range(q):
		init_pos=int(io())
		md_syu,pd_syu = t_search(syu,init_pos)
		md_ten,pd_ten= t_search(ten,init_pos)
		r=min(
			max(md_syu,md_ten),
			md_syu*2+pd_ten,
			pd_syu*2+md_ten,
			md_ten*2+pd_syu,
			pd_ten*2+md_syu,
			max(pd_syu,pd_ten)
			)
		ret[i]=str(r)
		
	for r in ret:
		print(r)

#++++++++++++++++++++

if __name__ == "__main__":
	io= lambda : io_generator()
	main(io)

Submission status: Accepted

Solution code:
from bisect import bisect_left

INF = 10**12


def main():
    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 _ in range(Q):
        x = int(input())
        l1 = bisect_left(S, x)
        l2 = bisect_left(T, x)
        tmp = INF
        for s in (S[l1-1], S[l1]):
            for t in (T[l2-1], T[l2]):
                tmp = min(tmp, abs(s-t) + abs(x-s))
                tmp = min(tmp, abs(s-t) + abs(x-t))
        print(tmp)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
A, B, Q = list(map(int,input().split()))
s = [float("-inf")]
t = [float("-inf")]
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()))
s.append(float("inf"))
t.append(float("inf"))
xs = list(x)
xs.sort()
sl = {}
sr = {}
tl = {}
tr = {}
i = 0
for j in range(1, A+2):
  while i<Q and xs[i]<s[j]:
    sl[xs[i]] = s[j-1]
    sr[xs[i]] = s[j]
    i += 1
i = 0
for j in range(1, B+2):
  while i<Q and xs[i]<t[j]:
    tl[xs[i]] = t[j-1]
    tr[xs[i]] = t[j]
    i += 1
for xi in x:
  sli = sl[xi]
  sri = sr[xi]
  tli = tl[xi]
  tri = tr[xi]
  p = [
    xi - min(sli,tli),
    max(sri,tri) - xi,
    min(sri-xi,xi-tli)*2+max(sri-xi,xi-tli),
    min(tri-xi,xi-sli)*2+max(tri-xi,xi-sli),
  ]
  print(min(p))

Submission status: Accepted

Solution code:
import bisect

# https://docs.python.org/ja/3/library/bisect.html

DBG = False

def find_lt(a, x):
    i = bisect.bisect_left(a, x)
    if i:
        return i-1, a[i-1]
    else:
        return 0, a[0]

def readlist(n):
    return list(map(int, (input() for _ in range(n))))

def main():
    A, B, Q = map(int, input().split(' '))
    S = readlist(A)
    T = readlist(B)
    X = readlist(Q)
    if DBG: print(S)
    if DBG: print(T)
    def get_right(lst, left, x):
        if lst[left] > x:
            # x is smaller than lst[0]
            return left, lst[left]
        right = left + 1
        if right < len(lst):
            return right, lst[right]
        else:
            # x is bigger than lst[-1]
            return left, lst[left]
    def print_status(sl_i, sl_v, sr_i, sr_v, tl_i, tl_v, tr_i, tr_v):
        def tostr(i, v):
            return str(i) + " (" + str(v) + ")"
        print("S: " + tostr(sl_i, sl_v), tostr(sr_i, sr_v),
                " T: " + tostr(tl_i, tl_v), tostr(tr_i, tr_v))
    def solve(x):
        if DBG: print("Q:", x)
        sl_i, sl_v = find_lt(S, x)
        sr_i, sr_v = get_right(S, sl_i, x)
        tl_i, tl_v = find_lt(T, x)
        tr_i, tr_v = get_right(T, tl_i, x)
        if DBG: print_status(sl_i, sl_v, sr_i, sr_v, tl_i, tl_v, tr_i, tr_v)
        def distance(p0, p1):
            # first, go to p0 from x.
            d = abs(p0 - x)
            # second, goto p1 from p0.
            d = d + abs(p1 - p0)
            if DBG: print(p0, p1, "->", d)
            return d
        # choose l->l l->r r->l r->r
        #        l<-l l<-r r<-l r<-r
        dists = []
        dists.append(distance(sl_v, tl_v))
        dists.append(distance(tl_v, sl_v))
        dists.append(distance(sl_v, tr_v))
        dists.append(distance(tl_v, sr_v))
        dists.append(distance(sr_v, tl_v))
        dists.append(distance(tr_v, sl_v))
        dists.append(distance(sr_v, tr_v))
        dists.append(distance(tr_v, sr_v))
        if DBG: print(dists)
        return min(dists)
    for x in X:
        print(solve(x))

main()

Submission status: Accepted

Solution code:
a,b,q=(input().split())
a,b,q=int(a),int(b),int(q)
s=[int(input()) for i in range(a)]
t=[int(input()) for i in range(b)]
x=[int(input()) for i in range(q)]
dist=['' for i in range(8)]
dist1=['' for i in range(2)]
dist2=['' for i in range(4)]
sp1=['' for i in range(2)]
tp1=['' for i in range(4)]

import bisect
for k in range(q):

    p1=bisect.bisect_left(s,x[k])

    if p1==0:
        dist1[0]=s[0]-x[k]
        dist1[1]=s[0]-x[k]
        sp1[0]=s[0]
        sp1[1]=s[0]        
    elif p1==a:
        dist1[0]=x[k]-s[a-1]
        dist1[1]=x[k]-s[a-1]
        sp1[0]=s[a-1]
        sp1[1]=s[a-1]
    else:
        dist1[0]=x[k]-s[p1-1]
        dist1[1]=s[p1]-x[k]
        sp1[0]=s[p1-1]
        sp1[1]=s[p1]
 
    p11=bisect.bisect_left(t,sp1[0])

    if p11==0:
        dist2[0]=t[0]-sp1[0]
        dist2[1]=t[0]-sp1[0]
    elif p11==b:
        dist2[0]=sp1[0]-t[b-1]
        dist2[1]=sp1[0]-t[b-1]
    else:
        dist2[0]=sp1[0]-t[p11-1]
        dist2[1]=t[p11]-sp1[0]
        
    p11=bisect.bisect_left(t,sp1[1])

    if p11==0:
        dist2[2]=t[0]-sp1[1]
        dist2[3]=t[0]-sp1[1]
    elif p11==b:
        dist2[2]=sp1[1]-t[b-1]
        dist2[3]=sp1[1]-t[b-1]
    else:
        dist2[2]=sp1[1]-t[p11-1]
        dist2[3]=t[p11]-sp1[1]
        
    dist[0]=dist1[0]+dist2[0]
    dist[1]=dist1[0]+dist2[1]
    dist[2]=dist1[1]+dist2[2]
    dist[3]=dist1[1]+dist2[3]
                

    p1=bisect.bisect_left(t,x[k])

    if p1==0:
        sp1[0]=t[0]
        sp1[1]=t[0]
        dist1[0]=t[0]-x[k]
        dist1[1]=t[0]-x[k]
    elif p1==b:
        sp1[0]=t[b-1]
        sp1[1]=t[b-1]
        dist1[0]=x[k]-t[b-1]
        dist1[1]=x[k]-t[b-1]
    else:
        sp1[0]=t[p1-1]
        sp1[1]=t[p1]
        dist1[0]=x[k]-t[p1-1]
        dist1[1]=t[p1]-x[k]
        
    p11=bisect.bisect_left(s,sp1[0])

    if p11==0:
        dist2[0]=s[0]-sp1[0]
        dist2[1]=s[0]-sp1[0]
    elif p11==a:
        dist2[0]=sp1[0]-s[a-1]
        dist2[1]=sp1[0]-s[a-1]
    else:
        dist2[0]=sp1[0]-s[p11-1]
        dist2[1]=s[p11]-sp1[0]
    
    p11=bisect.bisect_left(s,sp1[1])

    if p11==0:
        dist2[2]=s[0]-sp1[1]
        dist2[3]=s[0]-sp1[1]       
    elif p11==a:
        dist2[2]=sp1[1]-s[a-1]
        dist2[3]=sp1[1]-s[a-1]
    else:
        dist2[2]=sp1[1]-s[p11-1]
        dist2[3]=s[p11]-sp1[1]

    dist[4]=dist1[0]+dist2[0]
    dist[5]=dist1[0]+dist2[1]
    dist[6]=dist1[1]+dist2[2]
    dist[7]=dist1[1]+dist2[3]
    
    ans=min(dist[0],dist[1],dist[2],dist[3],dist[4],dist[5],dist[6],dist[7])

    print(ans)

Submission status: Accepted

Solution code:
#from collections import deque
import bisect

a, b, q = [int(x) for x in input().split()]
s = [-10**12] + [int(input()) for i in range(a)] + [10**12]
t = [-10**12] + [int(input()) for i in range(b)] + [10**12]
#x = [int(input()) for i in range(q)]

#s_que = deque(s)
#s_que.appendleft(-10 ** 12)
#s_que.append(10 ** 12)

#t_que = deque(t)
#t_que.appendleft(-10 ** 12)
#t_que.append(10 ** 12)

for i in range(q):
    x = int(input())
    k = bisect.bisect_left(s, x)
    sb = s[k]
    sa = s[k-1]
    j = bisect.bisect_left(t, x)
    tb = t[j]
    ta = t[j-1]

    y = []
    for h in [sa, sb]:
        for g in [ta, tb]:
            y.append(abs(x-h) + abs(h-g))
    for h in [ta, tb]:
        for g in [sa, sb]:
            y.append(abs(x-h) + abs(h-g))

    print(min(y))

Submission status: Accepted

Solution code:
from bisect import bisect_left
I = lambda x: [-1<<50] + [int(input()) for i in range(x)] + [1<<50]

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

for _ in range(Q):
    x = int(input())
    BLS = bisect_left(S,x)  
    BLT = bisect_left(T,x) 

    LS = x - S[BLS-1]
    RS = S[BLS] - x
    LT = x - T[BLT-1]
    RT = T[BLT] - x
    
    print(min(max(LS,LT),max(RS,RT),LS*2+RT,LT*2+RS,RT*2+LS,RS*2+LT))

Submission status: Accepted

Solution code:
import bisect as bs
a, b, q = map(int, input().split())
INF = 10**18
s = [-INF] + sorted([int(input()) for _ in range(a)]) + [INF]
t = [-INF] + sorted([int(input()) for _ in range(b)]) + [INF]

for _ in range(q):
    z = int(input())
    x, y = bs.bisect_right(s, z), bs.bisect_right(t, z)
    s1, s2, t1, t2 = s[x-1], s[x], t[y-1], t[y]
    print(min(max(z - s1, z - t1), max(s2 - z, t2 - z),
    min(2 * t2 - z - s1, 2 * s2 - z - t1), min(z + t2 - 2 * s1, z + s2 - 2 * t1)))

Submission status: Accepted

Solution code:
from bisect import bisect_left
I = lambda x: [-1<<50] + [int(input()) for i in range(x)] + [1<<50]

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

for _ in range(Q):
    x = int(input())
    BLS = bisect_left(S,x)  
    BLT = bisect_left(T,x) 

    LS = S[BLS-1] 
    RS = S[BLS] 
    LT = T[BLT-1] 
    RT = T[BLT]  
    
    print(min(  
        x-min(LS,LT),
        max(RS,RT)-x,
        (x-LS)*2+(RT-x),
        (x-LT)*2+(RS-x),
        (RT-x)*2+(x-LS),
        (RS-x)*2+(x-LT)
        ))

Submission status: Accepted

Solution code:
from bisect import bisect_left
I = lambda x: [-1<<50] + [int(input()) for i in range(x)] + [1<<50]

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

for _ in range(Q):
    x = int(input())
    LS_ = bisect_left(S,x)
    LT_ = bisect_left(T,x)



    LS = S[LS_-1]
    RS = S[LS_]
    LT = T[LT_-1]
    RT = T[LT_]

    print(min(
        x-min(LS,LT),
        max(RS,RT)-x,
        (x-LS)*2+(RT-x),
        (x-LT)*2+(RS-x),
        (RT-x)*2+(x-LS),
        (RS-x)*2+(x-LT)
        ))

Submission status: Accepted

Solution code:
import bisect
import itertools
 
a, b, q = map(int, input().split())
ss, tt = [], []
for _ in range(a):
  ss.append(int(input()))
for _ in range(b):
  tt.append(int(input()))
  
for _ in range(q):
  x = int(input())
  md = pow(10, 15)
  xs, xt = bisect.bisect_left(ss, x), bisect.bisect_left(tt, x)
  ls, rs, lt, rt = ss[max(0, xs-1)], ss[min(a-1, xs)], tt[max(0, xt-1)], tt[min(b-1, xt)]
  for s, t in itertools.product([ls, rs], [lt, rt]):
    if s > t:
      if t > x:
        md = s - x if s - x < md else md
      elif s > x:
        if md > 2 * (s-x) + x-t:
          md = 2 * (s-x) + x-t
        if md > 2 * (x-t) + s-x:
          md = 2 * (x-t) + s-x
      else:
        md = x - t if x - t < md else md
    else:  # t > s
      if s > x:
        md = t - x if t - x < md else md
      elif t > x:
        if md > 2 * (x-s) + t-x:
          md = 2 * (x-s) + t-x
        if md > 2 * (t-x) + x-s:
          md = 2 * (t-x) + x-s
      else:
        md = x - s if x - s < md else md
  print(md)

Submission status: Accepted

Solution code:
import numpy as np
import bisect
INF = 10**11
def solve(a, b, q, s, t, x):
    for xi in x:
        si = bisect.bisect_left(s, xi)
        ti = bisect.bisect_left(t, xi)
        sl = s[si-1]
        tl = t[ti-1]
        sr = s[si]
        tr = t[ti]
        ans = min([
            max(sr-xi, tr-xi),
            max(xi-sl, xi-tl),
            (sr-xi+sr-tl),
            (xi-tl+sr-tl),
            (tr-xi+tr-sl),
            (xi-sl+tr-sl)
        ])
        print(ans)

a, b, q = map(int, input().split())
s = np.asarray([int(input()) for i in range(a)] + [-INF, INF], dtype=int)
t = np.asarray([int(input()) for i in range(b)] + [-INF, INF], dtype=int)
x = np.asarray([int(input()) for i in range(q)], dtype=int)
s.sort()
t.sort()
solve(a,b,q,s,t,x)

Submission status: Accepted

Solution code:
INF = int(1e18)

def compute():
    from sys import stdin
    A, B, Q = list(map(int, stdin.readline().split()))
    s = sorted(int(stdin.readline().split()[0]) for _ in range(A))
    t = sorted(int(stdin.readline().split()[0]) for _ in range(B))

    from bisect import bisect_left
    for _ in range(Q):
        x = int(stdin.readline().split()[0])

        i1 = bisect_left(s, x)
        i1 = i1 if i1 < A else i1-1
        i2 = i1-1 if (i1>0) and s[i1]!=x else i1

        res = INF
        for y in set((s[i1], s[i2])):
            j1 = bisect_left(t, y)
            j1 = j1 if (j1 < B) else j1-1
            j2 = j1-1 if (j1 > 0) and t[j1]!=y else j1
            for z in set((t[j1],t[j2])):
                # print(x, y, z)
                res = min(res, abs(x-y) + abs(y-z))
                res = min(res, abs(x-z) + abs(z-y))

        print(res)


if __name__ == "__main__":
    compute()

Submission status: Accepted

Solution code:
import math, string, itertools, fractions, heapq, collections, re,  array, bisect, sys, random, time, copy, functools


sys.setrecursionlimit(10**7)
inf = 10 ** 20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]


def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)


def main():
    A, B, Q = LI()
    s, t, x = [], [], []
    [s.append(I()) for i in range(A)]
    [t.append(I()) for i in range(B)]
    [x.append(I()) for i in range(Q)]
    s = [-10**18] + s + [10**18]
    t = [-10**18] + t + [10**18]

    #  print(A, B,Q,s,t,x)
    #  A = 10**5
    #  B = 10 ** 5
    #  Q = 10**5
    #  [s.append(i) for i in range(A)]
    #  [t.append(i) for i in range(B)]
    #  [x.append(i) for i in range(Q)]
    #  s = [-10**18] + s + [10**18]
    #  t = [-10**18] + t + [10**18]
    #  print(len(s), len(t), s[0], s[-1])


    for start in x:
        #  first_temple = [temple for temple in t if temple <= start]
        first_temple_idx = bisect.bisect_left(t, start) - 1
        second_temple_idx = first_temple_idx + 1
        temples = [first_temple_idx, second_temple_idx]
        first_shrine_idx = bisect.bisect_left(s, start) - 1
        second_shrine_idx = first_shrine_idx + 1
        shrines = [first_shrine_idx, second_shrine_idx]
        #  print(temples, shrines)

        #  if len(first_temple) != 0:
        #      first_temple = first_temple[-1:]
        #  second_temple = [temple for temple in t if temple > start]
        #  if len(second_temple) != 0:
        #      second_temple = second_temple[:1]
        #  temples = first_temple + second_temple
        #  #  print('temples', temples)

        #  first_shrine = [sh for sh in s if sh <= start]
        #  if len(first_shrine) != 0:
        #      first_shrine = first_shrine[-1:]
        #  second_shrine = [sh for sh in s if sh > start]
        #  if len(second_shrine) != 0:
        #      second_shrine = second_shrine[:1]
        #  shrines = first_shrine + second_shrine
        #  print('shrines', shrines)

        result = 10**11
        for temple in temples:
            for shrine in shrines:
                #  print('temple/shrine', temple, shrine)
                #  print(temple, shrine)
                near = min(abs(start - t[temple]), abs(start - s[shrine]))
                far = max(abs(start - t[temple]), abs(start - s[shrine]))
                if (t[temple] < start and s[shrine] < start) or (t[temple] > start and s[shrine] > start):
                    result = min(result, far)
                elif (t[temple] < start and s[shrine] > start) or (t[temple] > start and s[shrine] < start):
                    result = min(result, near * 2 + far)
                #  print('on-going result', result)

        #  print('result', result)
        print(result)
if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 24 22:10:01 2019

@author: Yamazaki Kenichi
"""
import numpy as np
import bisect

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 lr(s,c,A):
    si = bisect.bisect(s,c)
    if si == A:
        return [c-s[si-1], 10**11]
    elif si == 0:
        return [10**11, s[0]-c]
    else:
        return [c-s[si-1], s[si]-c]
for c in x:
    ans = 0
    slr = lr(s,c,A)
    tlr = lr(t,c,B)
    ans = min(max(slr[0],tlr[0]),
              max(slr[1],tlr[1]),
              slr[0]*2+ tlr[1],
              slr[0]+ tlr[1]*2,
              slr[1]*2 + tlr[0],
              slr[1]+ tlr[0]*2
              )
    print(ans)

Submission status: Accepted

Solution code:
import bisect

def main():
    A, B, Q = map(int, input().split())
    s = [-float('inf')]
    t = [-float('inf')]
    ans = []
    for _ in range(A):
        s.append(int(input()))
    for _ in range(B):
        t.append(int(input()))
    s.append(float('inf'))
    t.append(float('inf'))
    for _ in range(Q):
        x = int(input())
        i = bisect.bisect_right(s, x)
        j = bisect.bisect_right(t, x)
        a = float('inf')
        for ss in [s[i - 1], s[i]]:
            for tt in [t[j - 1], t[j]]:
                a = min(a, abs(ss - x) + abs(tt - ss),
                        abs(tt - x) + abs(ss - tt))
        ans.append(a)
    for a in ans:
        print(a)


main()

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
import bisect
A,B,Q=map(int,input().split())
INF=10**18
S=[-INF]+[int(input()) for i in range(A)]+[INF]
T=[-INF]+[int(input()) for i in range(B)]+[INF]
for q in range(Q):
    x=int(input())
    i=bisect.bisect_left(S,x)
    j=bisect.bisect_left(T,x)
    ans=INF
    for s in [S[i-1],S[i]]:
        for t in [T[j-1],T[j]]:
            d1=abs(s-x)+abs(s-t)
            d2=abs(t-x)+abs(s-t)
            ans=min(ans,d1,d2)
    print(ans)

Submission status: Accepted

Solution code:
#解説のコードそのもの
import bisect

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

for q in range(Q):
    x = int(input())
    b, d = bisect.bisect_right(s,x), bisect.bisect_right(t,x)
    res = INF
    for S in [s[b-1],s[b]]:
        for T in [t[d-1],t[d]]:
            A,B = abs(S-x)+abs(T-S), abs(T-x)+abs(T-S)
            res = min(res,A,B)
    print(res)