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:
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 bisect
A, B, Q = map(int, input().split())
ss = [int(input()) for i in range(A)]
ts = [int(input()) for i in range(B)]
xs = [int(input()) for i in range(Q)]
INF = 10**11

ss = [-INF] + ss + [INF]
ts = [-INF] + ts + [INF]
 
# s_e is index the nearest s on the east side of x
for x in xs:
  s_e_ix = bisect.bisect_left(ss, x)
  s_e = ss[s_e_ix]
  s_w = ss[s_e_ix - 1]
  
  t_e_ix = bisect.bisect_left(ts, x)
  t_e = ts[t_e_ix]
  t_w = ts[t_e_ix - 1]
  
  d = INF
  for s in [s_w, s_e]:
    for t in [t_w, t_e]:
      d0 = abs(s-x) + abs(t-s)
      d1 = abs(t-x) + abs(s-t)
      d = min(d0, d1, d)
  print(d)

Submission status: Accepted

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]

'''
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)
'''
for q in range(Q):
	x = int(input())
	b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
	res = 10**13
	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

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

Submission status: Accepted

Solution code:
import bisect

a, b, q = map(int,input().split())
a_lst,b_lst = [],[]
for _ in range(a):
    a_lst.append(int(input()))
for _ in range(b):
    b_lst.append(int(input()))

for _ in range(q):
    n = int(input())
    a_index = bisect.bisect_left(a_lst, n)
    b_index = bisect.bisect_left(b_lst, n)
    a_next = 10 ** 100 if a_index == a else a_lst[a_index] - n
    b_next = 10 ** 100 if b_index == b else b_lst[b_index] - n
    a_bef = 10 ** 100 if a_index == 0 else n - a_lst[a_index-1]
    b_bef = 10** 100 if b_index == 0 else n - b_lst[b_index-1]
    
    if a_next >= b_next:
        ans = min(a_next, 2*b_next + a_bef)
    else:
        ans = min(b_next, 2*a_next + b_bef)
    if a_bef >= b_bef:
        ans = min(ans, a_bef, 2*b_bef + a_next)
    else:
        ans = min(ans, b_bef, 2*a_bef + b_next)
    print(ans)

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc119/tasks/abc119_d
import itertools
import collections
import bisect

def main():
    # big value
    INF = int(1e15)
    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]
    X = [int(input()) for _ in range(Q)]

    for x in X:
        pos_s = bisect.bisect(S, x)  # xより大きい S の最小値のインデックス
        pos_t = bisect.bisect(T, x)  # xより大きい T の最小値のインデックス
        s1, s2 = S[pos_s - 1], S[pos_s]
        t1, t2 = T[pos_t - 1], T[pos_t]

        ans = INF
        for st, tt in itertools.product([s1, s2], [t1, t2]):
            path1 = abs(x - st) + abs(st - tt)
            path2 = abs(x - tt) + abs(st - tt)
            ans = min(ans, path1, path2)
        print(ans)

if __name__ == '__main__':
    main()

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]
for q in range(Q):
    x = int(sys.stdin.readline())
    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:
#coding:utf-8
import bisect,sys
A,B,Q=map(int,raw_input().split())
s=[0]*A
t=[0]*B
for i in range(A):    
    s[i]=int(raw_input())
for i in range(B):
    t[i]=int(raw_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)


for i in xrange(Q):
    x=int(raw_input())
    ans=f(x)
    print(ans)

Submission status: Accepted

Solution code:
import bisect

(a, b, q) = map(int, input().split())
s = [-10 ** 19]
for _ in range(a):
    s.append(int(input()))
s.append(10 ** 19)
t = [-10 ** 19]
for _ in range(b):
    t.append(int(input()))
t.append(10 ** 19)
x = [int(input()) for _ in range(q)]

for x_i in x:
    ss = bisect.bisect_left(s, x_i)
    tt = bisect.bisect_left(t, x_i)

    sc = [ss - 1, ss]
    tc = [tt - 1, tt]
    optimum = 10 ** 19
    for s_i in sc:
        for t_i in tc:
            dist = abs(s[s_i] - x_i) + abs(s[s_i] - t[t_i])
            if dist < optimum:
                optimum = dist
            dist = abs(t[t_i] - x_i) + abs(t[t_i] - s[s_i])
            if dist < optimum:
                optimum = dist
    print(optimum)

Submission status: Accepted

Solution code:
#coding:utf-8
import bisect,sys
A,B,Q=map(int,raw_input().split())
s=[0]*A
t=[0]*B
for i in range(A):    
    s[i]=int(sys.stdin.readline())
for i in range(B):
    t[i]=int(sys.stdin.readline())
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]=int(sys.stdin.readline())
r=map(f,I)
print("\n".join(r))

Submission status: Accepted

Solution code:
import bisect
import io
import sys

LINES = sys.stdin.read().splitlines()[::-1]


def readline():
    return LINES.pop()


A, B, Q = map(int, readline().split())
ss = [int(readline()) for _ in range(A)]
ts = [int(readline()) for _ in range(B)]
xs = [int(readline()) 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: Accepted

Solution code:
#!/usr/bin/env python3
from bisect import bisect
import sys
input = sys.stdin.readline
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 _ in range(Q):
    x = int(input())
    sl = s[bisect(s, x) - 1]
    sr = s[bisect(s, x)]
    tl = t[bisect(t, x) - 1]
    tr = t[bisect(t, x)]
    ans = INF
    ans = min(ans, max(abs(x - sl), abs(x - tl)))
    ans = min(ans, max(abs(x - sr), abs(x - tr)))
    ans = min(ans, min(abs(x - sl), abs(x - tr)) * 2 + max(abs(x - sl), abs(x - tr)))
    ans = min(ans, min(abs(x - sr), abs(x - tl)) * 2 + max(abs(x - sr), abs(x - tl)))
    print(ans)

Submission status: Accepted

Solution code:
# coding:utf-8

import sys
from bisect import bisect_left

INF = 10 ** 18
MOD = 10 ** 9 + 7

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 LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return input()


a, b, q = LI()
A = [-INF] + [II() for _ in range(a)] + [INF]
B = [-INF] + [II() for _ in range(b)] + [INF]

for _ in range(q):
    x = II()
    s = bisect_left(A, x)
    t = bisect_left(B, x)

    res = INF
    for aa in [A[s - 1], A[s]]:
        for bb in [B[t - 1], B[t]]:
            d1 = abs(x - aa) + abs(aa - bb)
            d2 = abs(x - bb) + abs(bb - aa)
            res = min(res, d1, d2)

    print(res)

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)
    #print(b,d)
    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:
#!/usr/bin/env python
# coding: utf-8

import sys
input = sys.stdin.readline

inf = float('inf')

def main():
    A, B, Q = list(map(int, input().split()))
    ls = [-inf] + [int(input()) for _ in range(A)] + [inf]
    lt = [-inf] + [int(input()) for _ in range(B)] + [inf]
    lx = [(int(input()), i) for i in range(Q)]
    ls.sort()
    lt.sort()
    lx.sort()
    ans = {}
    s = 1
    t = 1
    for i in range(Q):
        dist = -1
        x = lx[i][0]
        while s <= A and ls[s] < x:
            s += 1
        while t <= B and lt[t] < x:
            t += 1
        s_min = ls[s-1]
        s_max = ls[s]
        t_min = lt[t-1]
        t_max = lt[t]
        d = min(max(s_max-x, t_max-x),
                (s_max-x)*2 + (x-t_min),
                (t_max-x)*2 + (x-s_min),
                (s_max-x) + (x-t_min)*2,
                (t_max-x) + (x-s_min)*2,
                max(x-s_min,x-t_min))
        ans[lx[i][1]] = str(d)
    print("\n".join(ans[i] for i in range(Q)))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

import sys
input = sys.stdin.readline

inf = float('inf')

def main():
    A, B, Q = list(map(int, input().split()))
    ls = [-inf] + [int(input()) for _ in range(A)] + [inf]
    lt = [-inf] + [int(input()) for _ in range(B)] + [inf]
    lx = [(int(input()), i) for i in range(Q)]
    ls.sort()
    lt.sort()
    lx.sort()
    ans = {}
    s = 1
    t = 1
    for i in range(Q):
        dist = -1
        x = lx[i][0]
        while s <= A and ls[s] < x:
            s += 1
        while t <= B and lt[t] < x:
            t += 1
        s_min = ls[s-1]
        s_max = ls[s]
        t_min = lt[t-1]
        t_max = lt[t]
        d = min(max(s_max-x, t_max-x),
                (s_max-x)*2 + (x-t_min),
                (t_max-x)*2 + (x-s_min),
                (s_max-x) + (x-t_min)*2,
                (t_max-x) + (x-s_min)*2,
                max(x-s_min,x-t_min))
        ans[lx[i][1]] = d
    for i in range(Q):
        print(ans[i])


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect
import sys

def main():
  input = sys.stdin.readline
  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())
    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)


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]
x = [int(input()) for i in range(Q)]

for xi in x:
    b, d = bisect.bisect_right(s, xi), bisect.bisect_right(t, xi)
    min_d = INF
    for S in [s[b - 1], s[b]]:
        for T in [t[d - 1], t[d]]:
            d1 = abs(S - xi) + abs(T - S)
            d2 = abs(T - xi) + abs(S - T)
            min_d = min(min_d, d1, d2)
    print(min_d)

Submission status: Accepted

Solution code:
import bisect
import sys
input = sys.stdin.readline
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: Accepted

Solution code:
from bisect import bisect

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

INF = 10**11
S = [-INF] + sorted([int(input()) for i in range(A)]) + [INF]
T = [-INF] + sorted([int(input()) for i in range(B)]) + [INF]
X = [int(input()) for i in range(Q)]

for x in X :
    right_s = bisect(S,x)
    right_t = bisect(T,x)
    left_s = right_s - 1
    left_t = right_t - 1
    
    calc1 = x - min(S[left_s], T[left_t])
    calc2 = -x + max(S[right_s], T[right_t])
    calc3 = (x-S[left_s]) + (T[right_t] - S[left_s])
    calc4 = (x-T[left_t]) + (S[right_s] - T[left_t])
    calc5 = (-x+S[right_s]) + (S[right_s] - T[left_t])
    calc6 = (-x+T[right_t]) + (T[right_t] - S[left_s])
    
    print(min(calc1,calc2,calc3,calc4,calc5,calc6))

Submission status: Accepted

Solution code:
import bisect
a,b,q=map(int,input().split(' '))
INF=10**19
s=[-INF]+[int(input()) for i in range(a)]+[INF]
t=[-INF]+[int(input()) for i in range(b)]+[INF]
s.sort()
t.sort()
for i in range(q):
    x=int(input())
    b,d=bisect.bisect(s,x),bisect.bisect(t,x)
    mi=INF
    for j in [s[b-1],s[b]]:
        for k in [t[d-1],t[d]]:
            mi=min(mi,abs(j-x)+abs(j-k),abs(k-x)+abs(j-k))
    print(mi)

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():
    n,m,q = LI()
    s = [I() for _ in range(n)]
    t = [I() for _ in range(m)]
    x = [I() for _ in range(q)]

    rr = []
    for y in x:
        r = inf
        si = bisect.bisect(s, y)
        if si > 0:
            z = s[si-1]
            k = y - z
            ti = bisect.bisect(t, z)
            if ti > 0:
                u = k + z - t[ti-1]
                if r > u:
                    r = u
            if ti < m:
                u = k + t[ti] - z
                if r > u:
                    r = u
        if si < n:
            z = s[si]
            k = z - y
            ti = bisect.bisect(t, z)
            if ti > 0:
                u = k + z - t[ti-1]
                if r > u:
                    r = u
            if ti < m:
                u = k + t[ti] - z
                if r > u:
                    r = u

        ti = bisect.bisect(t, y)
        if ti > 0:
            z = t[ti-1]
            k = y - z
            si = bisect.bisect(s, z)
            if si > 0:
                u = k + z - s[si-1]
                if r > u:
                    r = u
            if si < n:
                u = k + s[si] - z
                if r > u:
                    r = u
        if ti < m:
            z = t[ti]
            k = z - y
            si = bisect.bisect(s, z)
            if si > 0:
                u = k + z - s[si-1]
                if r > u:
                    r = u
            if si < n:
                u = k + s[si] - z
                if r > u:
                    r = u

        rr.append(r)

    return '\n'.join(map(str, rr))



print(main())

Submission status: Accepted

Solution code:
import sys
import bisect

_input = sys.stdin.readlines()
A, B, Q = [int(i) for i in _input[0].split()]
data = [int(i) for i in _input[1:]]
"""
A, B, Q = [int(i.strip()) for i in input().split()]
data = list()
for l in range(A+B+Q):
    data.append(int(input()))
"""
s_ls = sorted(data[:A] + [1e30,-1e30])
t_ls = sorted(data[A:A+B] + [1e30,-1e30])
x_ls = data[-Q:]

for x in x_ls:
    s_pos = bisect.bisect_left(s_ls, x)
    s_left = s_ls[s_pos-1]
    s_right = s_ls[s_pos]
    t_pos = bisect.bisect_left(t_ls, x)
    t_left = t_ls[t_pos-1]
    t_right = t_ls[t_pos]
    a = abs(x - min(s_left, t_left))
    b = abs(x- max(s_right, t_right))
    c = abs(x - s_left) + abs(x - t_right) + min(abs(x - s_left), abs(x - t_right))
    d = abs(x - t_left) + abs(x - s_right) + min(abs(x - t_left), abs(x - s_right))
    dis = min(a,
              b,
              c,
              d)
    print(dis)

Submission status: Accepted

Solution code:
# from sys import stdin #入力の高速化にはあまりつながらなかった
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 [0]*A]+[INF]
T = [-INF] + [int(input()) for _ in [0]*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: Accepted

Solution code:
from sys import stdin
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]


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

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

S = [-INF] + list(map(int, (stdin.readline() for _ in range(A))))+[INF]
T = [-INF] + list(map(int, (stdin.readline() 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: Accepted

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

S = [-INF] + [int(stdin.readline()) for _ in range(A)]+[INF]
T = [-INF] + [int(stdin.readline()) 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: Accepted

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

S = [-INF] + [int(input()) for _ in range(A)]+[INF]
T = [-INF] + [int(input()) for _ in range(B)]+[INF]

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

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

S = [-INF] + [int(input()) for _ in range(A)]+[INF]
T = [-INF] + [int(input()) for _ in range(B)]+[INF]

from bisect import 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: Accepted

Solution code:
import sys
from bisect import bisect_right
input = sys.stdin.readline
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]
xs = [int(input()) for i in range(Q)]
for x in xs:
    b, d = bisect_right(s, x), 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 numpy as np
import bisect
a,b,q = map(int,input().split())
s = np.array([-np.inf]+[int(input()) for i in range(a)]+[np.inf])
t = np.array([-np.inf]+[int(input()) for i in range(b)]+[np.inf])
x = np.array([int(input()) for i in range(q)])


  
def distance(s,t,xi):
  s_ = bisect.bisect_left(s,xi)
  s_m = abs(s[s_-1]-xi)
  s_p = abs(s[s_]-xi)
  t_ = bisect.bisect_left(t,xi)
  t_m = abs(t[t_-1]-xi)
  t_p = abs(t[t_]-xi)
  
  return min(max(s_m,t_m),s_m+t_p+min(s_m,t_p),s_p+t_m+min(s_p,t_m),max(s_p,t_p))
 
for i in x:
  print(int(distance(s,t,i)))

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)]
inf = [10**13, -10**13]
s = sorted(s+inf)
t = sorted(t+inf)

for i in range(Q):
    s_r = s[bisect.bisect_right(s, x[i])]
    s_l = s[bisect.bisect_left(s, x[i])-1]
    t_r = t[bisect.bisect_right(t, x[i])]
    t_l = t[bisect.bisect_left(t, x[i])-1]
    long = sorted([abs(t_r-s_r)+s_r-x[i], abs(t_l-s_r)+s_r-x[i], abs(t_l-s_l)+x[i]-s_l, abs(t_r-s_l)+x[i]-s_l,
     abs(s_r-t_r)+t_r-x[i], abs(s_l-t_r)+t_r-x[i], abs(s_r-t_l)+x[i]-t_l, abs(s_l-t_l)+x[i]-t_l])
    print(long[0])