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

icase=0
if icase==0:
    a,b,q=map(int,input().split())
    s=[0]*a
    for i in range(a):
        s[i]=int(input())
    t=[0]*b
    for i in range(b):
        t[i]=int(input())
    x=[0]*q
    for i in range(q):
        x[i]=int(input())
elif icase==1:
    a,b,q=2,3,4
    s=[100, 600]
    t=[400, 900, 1000]
    x=[150,2000,899,799]

si=[0]*a
j=-1
for i in range(a):
    si[i]=b-1
    while j+2<b:
        j+=1
        if abs(s[i]-t[j])<abs(s[i]-t[j+1]):
            si[i]=j
            j-=1
            break

ti=[0]*b
j=-1
for i in range(b):
    ti[i]=a-1
    while j+2<a:
        j+=1
        if abs(t[i]-s[j])<abs(t[i]-s[j+1]):
            ti[i]=j
            j-=1
            break
    
for k in range(q):
    sk=max(min(bisect(s,x[k])-1,a-1),0)
    tk=max(min(bisect(t,x[k])-1,b-1),0)
#    print(sk,tk)
    r1=abs(x[k]-s[sk])+abs(s[sk]-t[si[sk]])
    if sk+1<a:
        r2=abs(x[k]-s[sk+1])+abs(s[sk+1]-t[si[sk+1]])
    else:
        r2=r1
    r3=abs(x[k]-t[tk])+abs(t[tk]-s[ti[tk]])
    if tk+1<b:
        r4=abs(x[k]-t[tk+1])+abs(t[tk+1]-s[ti[tk+1]])
    else:
        r4=r3
#    print(min((r1,r2,r3,r4)),r1,r2,r3,r4)
    print(min((r1,r2,r3,r4)))

Submission status: Accepted

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

import bisect

for i in range(q):
    s2 = 10**12
    t2 = 10**12
    qq = int(input())
    sp = bisect.bisect(s,qq)
    tp = bisect.bisect(t,qq)
    s1 = s[sp-1]
    if sp <a:
        s2 = s[sp]

    t1 = t[tp-1]
    if tp <b:
        t2 = t[tp]
    print(min(abs(qq-s1)+abs(s1-t1),abs(qq-s1)+abs(s1-t2),
              abs(qq-s2)+abs(s2-t1),abs(qq-s2)+abs(s2-t2),
              abs(qq-t1)+abs(t1-s1),abs(qq-t1)+abs(t1-s2),
              abs(qq-t2)+abs(t2-s1),abs(qq-t2)+abs(t2-s2)))

Submission status: Accepted

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

Jinja = []
Tera = []
Ichi = []
for i in range (0, A):
	Jinja.append(int(input()))
for i in range (0, B):
	Tera.append(int(input()))
for i in range (0, Q):
	Ichi.append(int(input()))

import math
import bisect as bi

for i in range (0, Q):
	temp = Ichi[i]
	J = math.inf
	T = math.inf
	JL = bi.bisect_left(Jinja, temp)
	JR = bi.bisect_right(Jinja, temp)
	TL = bi.bisect_left(Tera, temp)
	TR = bi.bisect_right(Tera, temp)
	if JL != JR:
		J = 0
	if TL != TR:
		T = 0
	if JR == 0:
		JW = math.inf
		JE = abs(temp-Jinja[0])
	elif JL == A:
		JW = abs(temp-Jinja[A-1])
		JE = math.inf
	else:
		JW = abs(temp-Jinja[JL-1])
		JE = abs(temp-Jinja[JL])
	if TR == 0:
		TW = math.inf
		TE = abs(temp-Tera[0])	
	elif TL == B:
		TW = abs(temp-Tera[B-1])
		TE = math.inf	
	else:
		TW = abs(temp-Tera[TL-1])
		TE = abs(temp-Tera[TL])
	print(min(J+T, J+TW, J+TE, T+JW, T+JE, max(JW, TW), max(JE, TE), 2*JW+TE, 2*TE+JW, 2*JE+TW, 2*TW+JE))

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int, input().split())
INF = float('inf')
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)

Submission status: Accepted

Solution code:
from bisect import bisect_left
from sys import stdin
input = stdin.buffer.readline

def main():
    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)]

    ans = [0] * q
    for i in range(q):
        start = x[i]
        si = bisect_left(s, start, hi=a-1)
        ti = bisect_left(t, start, hi=b-1)

        sl = (s[si-1], s[si])
        tl = (t[ti-1], t[ti])

        distance = 100000000000
        for j in sl:
            for k in tl:
                if abs(start - j) + abs(j - k) < distance:
                    distance = abs(start - j) + abs(j - k)
                if abs(start - k) + abs(k - j) < distance:
                    distance = abs(start - k) + abs(k - j)

        ans[i] = distance

    for i in ans:
        print(i)

main()

Submission status: Accepted

Solution code:
from bisect import bisect

a, b, q = 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]
x = [int(input()) for _ in range(q)]

for xi in x:
    p, q = bisect(s, xi), bisect(t, xi)
    sl, sr = abs(s[p - 1] - xi), abs(s[p] - xi)
    tl, tr = abs(t[q - 1] - xi), abs(t[q] - xi)
    ans = min(max(sl, tl), sl + tr + min(sl, tr),
              max(sr, tr), sr + tl + min(sr, tl))
    print(ans)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
#D - Lazy Faith
import sys
from bisect import bisect
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
A, B, Q = map(int, readline().split())
INF = 10**31
S = [-INF]
for _ in range(A):
    s = int(readline())
    S.append(s)
S.append(INF)
T = [-INF]
for _ in range(B):
    t = int(readline())
    T.append(t)
T.append(INF)

for _ in range(Q):
    x = int(readline())
    ind_s = bisect(S,x)
    ind_t = bisect(T,x)
    s1,s2 = S[ind_s-1],S[ind_s]
    t1,t2 = T[ind_t-1],T[ind_t]
    d1 = (x-s1) + (t2-s1) if x-s1 < t2-x else (t2-x) + (t2-s1)
    d2 = (x-t1) + (s2-t1) if x-t1 < s2-x else (s2-x) + (s2-t1)
    d3 = x-s1 if s1 < t1 else x-t1
    d4 = t2-x if s2 < t2 else s2-x
    ans = min(d1,d2,d3,d4)
    print(ans)

Submission status: Accepted

Solution code:
def binary_search(n, arr, target, lower=True):
    flg = True
    cnt = 0
    while flg:
        if n >> cnt:
            cnt += 1
        else:
            flg = False
    if lower:
        if target < arr[0]:
            return -1
        if target >= arr[n-1]:
            return n
        l, r = 0, n
        d = (l + r) // 2
        for i in range(cnt+1):
            if arr[d] <= target:
                l = d
                d = (l + r) // 2
            else:
                r = d
                d = (l + r) // 2
        return d

A, B, Q = map(int, input().split())
S = [-int(1e13)] + [int(input()) for _ in range(A)] + [int(1e13)]
T = [-int(1e13)] + [int(input()) for _ in range(B)] + [int(1e13)]
for i in range(Q):
    x = int(input())
    sl = binary_search(A+2, S, x)
    tl = binary_search(B+2, T, x)
    ll = max(x - S[sl], x - T[tl])
    lr = min(T[tl+1] - x + 2 * (x - S[sl]), 2 * (T[tl+1] - x) + x - S[sl])
    rl = min(S[sl+1] - x + 2 * (x - T[tl]), 2 * (S[sl+1] - x) + x - T[tl])
    rr = max(S[sl+1] - x, T[tl+1] - x)
    print(min(ll, lr, rl, rr))

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right
A,B,Q = map(int,input().split())
s = [int(input()) for _ in range(A)]
t = [int(input()) for _ in range(B)]
for _ in range(Q):
    x = int(input())
    a = bisect_right(s, x)
    b = bisect_right(t, x)
    la = x-s[a-1] if a > 0 else None
    ra = s[a]-x if a < A else None
    lb = x-t[b-1] if b > 0 else None
    rb = t[b]-x if b < B else None
    ans = float("inf")
    if la and lb:
        ans = min(ans, max(la, lb))
    if la and rb:
        ans = min(ans, la+2*rb, 2*la+rb)
    if ra and lb:
        ans = min(ans, ra+2*lb, 2*ra+lb)
    if ra and rb:
        ans = min(ans, max(ra, rb))
    print(ans)

Submission status: Accepted

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

ans = []
for q in range(Q):
    x = int(input())
    i = bisect.bisect_right(S,x)
    j = bisect.bisect_right(T,x)
    d = INF
    for s in [S[i-1],S[i]]:
        for t in [T[j-1],T[j]]:
            d1 = abs(x-s) + abs(s-t)
            d2 = abs(x-t) + abs(s-t)
            d = min(d,d1,d2)
    ans.append(d)
print(*ans,sep="\n")

Submission status: Accepted

Solution code:
import bisect
A,B,Q = map(int,input().split())
INF = float('inf')
S = [-INF]+[int(input()) for i in range(A)]+[INF]
T = [-INF]+[int(input()) for i in range(B)]+[INF]
for q in range(Q):
    x = int(input())
    i = bisect.bisect_right(S,x)
    j = bisect.bisect_right(T,x)
    d = 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)
            d = min(d,d1,d2)
    print(d)

Submission status: Accepted

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

for x in X:
  si = bisect(S,x)
  ti = bisect(T,x)
  d1 = x-S[si-1]
  d2 = S[si]-x
  d3 = x-T[ti-1]
  d4 = T[ti]-x
  print(min(2*d1+d4,d1+d4*2,2*d2+d3,d2+d3*2,max(d1,d3),max(d2,d4)))

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 x in X:
    d = float("inf")
    i = bisect.bisect_right(S, x)
    j = bisect.bisect_right(T, x)
    for s in [S[i-1], S[i]]:
        for t in [T[j-1], T[j]]:
            d1 = abs(s-x) + abs(t-s)
            d2 = abs(t-x) + abs(t-s)
            d = min(d, d1, d2)
    print(d)

Submission status: Accepted

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

s = [int(input()) for _ in range(A)]
t = [int(input()) for _ in range(B)]

def get(x, s, t, ans_list):
  l_s = bisect.bisect_left(s, x)-1
  r_s = bisect.bisect_left(s, x)-1 + 1
  if l_s >= 0:
    y = s[l_s]
    l_t = bisect.bisect_left(t, y)-1
    r_t = bisect.bisect_left(t, y)-1 + 1
    if l_t >= 0:
      ans_list.append(abs(x-y) + abs(y-t[l_t]))
    if r_t <= len(t)-1:
      ans_list.append(abs(x-y) + abs(y-t[r_t]))
  if r_s <= len(s)-1:
    y = s[r_s]
    l_t = bisect.bisect_left(t, y)-1
    r_t = bisect.bisect_left(t, y)-1 + 1
    if l_t >= 0:
      ans_list.append(abs(x-y) + abs(y-t[l_t]))
    if r_t <= len(t)-1:
      ans_list.append(abs(x-y) + abs(y-t[r_t]))
  
  
for _ in range(Q):
  ans_list = []
  x = int(input())
  get(x, s, t, ans_list)
  get(x, t, s, ans_list)
  #print(x, ans_list)
  print(min(ans_list))

Submission status: Accepted

Solution code:
from bisect import bisect_right
a, b, q = map(int, input().split())
s = [-float("inf")] + [int(input()) for i in range(a)] + [float("inf")]
t = [-float("inf")] + [int(input()) for i in range(b)] + [float("inf")]
x = [int(input()) for i in range(q)]
for i in range(q):
    X = x[i]
    l, r = bisect_right(s, X), bisect_right(t, X)
    ans = float("inf")
    ans = min(ans, abs(s[l - 1] - X) + abs(t[r - 1] - s[l - 1]), abs(t[r - 1] - X) + abs(s[l - 1] - t[r - 1]))
    ans = min(ans, abs(s[l - 1] - X) + abs(t[r] - s[l - 1]), abs(t[r] - X) + abs(s[l - 1] - t[r]))
    ans = min(ans, abs(s[l] - X) + abs(t[r - 1] - s[l]), abs(t[r - 1] - X) + abs(s[l] - t[r - 1]))
    ans = min(ans, abs(s[l] - X) + abs(t[r] - s[l]), abs(t[r] - X) + abs(s[l] - t[r]))
    print(ans)

Submission status: Accepted

Solution code:
from bisect import bisect

A, B, Q = map(int, input().split())
INF = 10 ** 18
S = [-INF]
T = [-INF]
for i in range(A):
    S.append(int(input()))
for i in range(B):
    T.append(int(input()))
S.append(INF)
T.append(INF)
for i in range(Q):
    x = int(input())
    sr = bisect(S, x)
    sl = sr - 1
    tr = bisect(T, x)
    tl = tr - 1
    def d(y): return abs(x - y)
    ans = min(d(max(S[sr], T[tr])), d(min(S[sl], T[tl])))
    ans = min(ans, 2 * d(S[sr]) + d(T[tl]))
    ans = min(ans, d(S[sr]) + 2 * d(T[tl]))
    ans = min(ans, 2 * d(S[sl]) + d(T[tr]))
    ans = min(ans, d(S[sl]) + 2 * d(T[tr]))
    print(ans)

Submission status: Accepted

Solution code:
from bisect import *
A,B,Q=map(int,input().split())
s = [int(input()) for _ in range(A)]
t = [int(input()) for _ in range(B)]
st = [] # (z, 0or1)0ならs, 1ならt
for i in range(A):
    st.append((s[i], 0))
for i in range(B):
    st.append((t[i], 1))

st.sort(key=lambda x: x[0])
INF = float("inf")

for _ in range(Q):
    x = int(input())
    b_left = bisect_left(st, (x, 0))
    ids = [b_left-1, b_left, b_left+1]
    dists = []
    for idx in ids:
        if 0 <= idx <= A+B-1:
            dists.append((abs(x - st[idx][0]), idx))

    ans = INF
    for start in dists:
        tmp = start[0]
        s_idx = start[1]
        now = st[s_idx][0]
        if st[s_idx][1] == 0: #s
            t_left = bisect_left(t, now)
            additional = []
            for nxt in [t_left-1, t_left, t_left+1]:
                if 0<=nxt<=B-1:
                    additional.append(abs(now - t[nxt]))
            delta = min(additional)
            ans = min(ans, tmp+delta)
        else:
            s_left = bisect_left(s, now)
            additional = []
            for nxt in [s_left-1, s_left, s_left+1]:
                if 0 <= nxt <= A-1:
                    additional.append(abs(now - s[nxt]))
            delta = min(additional)
            ans = min(ans, tmp+delta)
    print(ans)

Submission status: Accepted

Solution code:
import bisect

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

for i in range(q):
    x = int(input())
    temp_s = bisect.bisect(s, x)
    temp_t = bisect.bisect(t, x)
    temp = float("inf")
    if temp_s == 0:
        num = (s[0],)
    elif temp_s == a:
        num = (s[a - 1],)
    else:
        num = (s[temp_s - 1], s[temp_s])
    for j in num:
        temp2 = bisect.bisect(t, j)
        if temp2 == 0:
            num2 = (t[0],)
        elif temp2 == b:
            num2 = (t[b - 1],)
        else:
            num2 = (t[temp2 - 1], t[temp2])
        for k in num2:
            temp = min(temp, abs(x - j) + abs(j - k))
    if temp_t == 0:
        num = (t[0],)
    elif temp_t == b:
        num = (t[b - 1],)
    else:
        num = (t[temp_t - 1], t[temp_t])
    for j in num:
        temp2 = bisect.bisect(s, j)
        if temp2 == 0:
            num2 = (s[0],)
        elif temp2 == a:
            num2 = (s[a - 1],)
        else:
            num2 = (s[temp2 - 1], s[temp2])
        for k in num2:
            temp = min(temp, abs(x - j) + abs(j - k))
    print(temp)

Submission status: Accepted

Solution code:
from bisect import *
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)]
#print(s,t,x)
for i in x:
    ans=float("inf")
    mins=-float("inf")
    mint=-float("inf")
    maxs=float("inf")
    maxt=float("inf")
    sind=bisect(s,i)
    tind=bisect(t,i)

    if sind!=0:
        mins=s[sind-1]
    if tind!=0:
        mint=t[tind-1]
    if sind!=len(s):
        maxs=s[sind]
    if tind!=len(t):
        maxt=t[tind]
    #print(mins,maxs,mint,maxt)
    slist=[mins,maxs]
    tlist=[mint,maxt]
    ans=min(ans,abs(i-mins)+abs(mins-mint))
    ans=min(ans,abs(i-mins)+abs(mins-maxt))
    ans=min(ans,abs(i-maxs)+abs(maxs-mint))
    ans=min(ans,abs(i-maxs)+abs(maxs-maxt))
    ans=min(ans,abs(i-mint)+abs(mint-mins))
    ans=min(ans,abs(i-mint)+abs(mint-maxs))
    ans=min(ans,abs(i-maxt)+abs(maxt-mins))
    ans=min(ans,abs(i-maxt)+abs(maxt-maxs))
    print(ans)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_left
from bisect import bisect_right
input = sys.stdin.readline
a,b,q = map(int, input().split())
INF = 10**20
ss = [-INF] + [int(input()) for i in range(a)] + [INF]
ts = [-INF] + [int(input()) for i in range(b)] + [INF]
xs = [int(input()) for i in range(q)] 

ans = INF
for x in xs:
    si = bisect_left(ss, x)
    ti = bisect_left(ts, x)

    dist1 = abs(x-ss[si-1]) + 2*abs(x-ts[ti])
    dist2 = 2*abs(x-ss[si-1]) + abs(x-ts[ti])
    dist3 = abs(x-ts[ti-1]) + 2*abs(x-ss[si])
    dist4 = 2*abs(x-ts[ti-1]) + abs(x-ss[si])
    dist5 = max(abs(x-ss[si-1]), abs(x-ts[ti-1]))
    dist6 = max(abs(x-ss[si]), abs(x-ts[ti]))
    dist = min(dist1,dist2,dist3,dist4,dist5,dist6)
    # print(dist,"du",x,dist1,dist2,dist3,dist4,dist5,dist6)
    print(dist)

Submission status: Accepted

Solution code:
from bisect import bisect_left

A,B,Q=map(int,input().split())
S=[int(input()) for i in range(A)]
T=[int(input()) for i in range(B)]
for i in range(Q):
    x=int(input())
    si=bisect_left(S,x)
    ti=bisect_left(T,x)
    if 0<si<A and 0<ti<B:
        sl,sr=abs(x-S[si-1]),abs(x-S[si])
        tl,tr=abs(x-T[ti-1]),abs(x-T[ti])
        print(min(max(sr,tr),max(sl,tl),sl+tr+min(sl,tr),sr+tl+min(sr,tl)))
    elif si==0 and ti==0:
        sr=abs(x-S[si])
        tr=abs(x-T[ti])
        print(max(sr,tr))
    elif si==A and ti==B:
        sl=abs(x-S[si-1])
        tl=abs(x-T[ti-1])
        print(max(sl,tl))
    elif si==0 and ti==B:
        sr=abs(x-S[si])
        tl=abs(x-T[ti-1])
        print(sr+tl+min(sr,tl))
    elif si==A and ti==0:
        sl=abs(x-S[si-1])
        tr=abs(x-T[ti])
        print(sl+tr+min(sl,tr))
    elif si==0:
        sr=abs(x-S[si])
        tl,tr=abs(x-T[ti-1]),abs(x-T[ti])
        print(min(max(sr,tr),sr+tl+min(sr,tl)))
    elif si==A:
        sl=abs(x-S[si-1])
        tl,tr=abs(x-T[ti-1]),abs(x-T[ti])
        print(min(max(sl,tl),sl+tr+min(sl,tr)))
    elif ti==0:
        sl,sr=abs(x-S[si-1]),abs(x-S[si])
        tr=abs(x-T[ti])
        print(min(max(sr,tr),sl+tr+min(sl,tr)))
    elif ti==B:
        sl,sr=abs(x-S[si-1]),abs(x-S[si])
        tl=abs(x-T[ti-1])
        print(min(max(sl,tl),sr+tl+min(sr,tl)))

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())
    y1 = bisect.bisect_right(s, x)
    y2 = bisect.bisect_right(t, x)
    res = INF
    # 最も近い神社の候補２つ
    for sx in [s[y1 - 1], s[y1]]:
        # 最も近い寺の候補２つ
        for tx in [t[y2 - 1], t[y2]]:
            # 神社、寺の順で訪れる場合
            d1 = abs(sx - x) + abs(tx - sx)
            # 寺、神社の順で訪れる場合
            d2 = abs(tx - x) + abs(sx - tx)
            res = min(res, d1, d2)
    print(res)

Submission status: Accepted

Solution code:
def is_not_less_than(ls, ind, key):
    if ls[ind] >= key:
        return True
    else:
        return False
def return_min_ind_whose_value_not_less_than(ls,key):
    r = len(ls)
    l = -1
    while True:
        next_ind = (r+l) // 2
        if is_not_less_than(ls, next_ind, key):
            r = next_ind
        else:
            l = next_ind
        if r - l == 1:
            return r
n_shrine,n_temple,Q = map(int,input().split())
shrine_ls = [0] * (n_shrine+1)
temple_ls = [0] * (n_temple+1)
Q_ls = [0] * Q
for i in range(n_shrine):
    shrine_ls[i] = int(input())
shrine_ls[-1] = float('inf')
for i in range(n_temple):
    temple_ls[i] = int(input())
temple_ls[-1] = float('inf')
for i in range(Q):
    Q_ls[i] = int(input())

for q in Q_ls:
    i_Rshrine = return_min_ind_whose_value_not_less_than(shrine_ls,q)
    Rshrine = shrine_ls[i_Rshrine]
    i_Lshrine = i_Rshrine-1
    Lshrine = shrine_ls[i_Lshrine]

    i_Rtemple = return_min_ind_whose_value_not_less_than(temple_ls,q)
    Rtemple = temple_ls[i_Rtemple]
    i_Ltemple = i_Rtemple-1
    Ltemple = temple_ls[i_Ltemple]
    # Temple,Shrine共に右
    RR = max(Rtemple,Rshrine) - q
    # Temple,Shrine共に左
    if i_Lshrine >= 0 and i_Ltemple >= 0:
        LL = abs(min(Ltemple,Lshrine)-q)
    else:
        LL = float('inf')
    #右templeと左shrine
    if i_Lshrine >= 0:
        RtLs = 2*min(Rtemple-q,q-Lshrine) + max(Rtemple-q,q-Lshrine)
    else:
        RtLs = float('inf')
    # 左templeと右shrine
    if i_Ltemple >= 0:
        LtRs = 2*min(Rshrine-q,q-Ltemple) + max(Rshrine-q,q-Ltemple)
    else:
        LtRs = float('inf')

    print(min(LL,RR,RtLs,LtRs))

Submission status: Accepted

Solution code:
import bisect, collections, copy, heapq, itertools, math, string, sys
input = lambda: sys.stdin.readline().rstrip() 
sys.setrecursionlimit(10**7)
INF = float('inf')
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LSS(): return input().split()

def resolve():
    A, B, Q = LI()
    s = [I() for _ in range(A)]
    t = [I() for _ in range(B)]

    # xから一番近い神社に行く→その神社から一番近い寺に行く、またはその逆の2パターン

    # 各神社に対する一番近い寺の距離を求めておく
    len_of_nearest_t = [INF] * A
    for i in range(A):
        idx = bisect.bisect_left(t, s[i])
        len_r = t[idx] - s[i] if 0 <= idx < B else INF
        len_l = s[i] - t[idx-1] if 0 <= idx - 1 < B else INF
        len_of_nearest_t[i] = min(len_l, len_r)
    # print(len_of_nearest_t)

    # 各寺に対する一番近い神社の距離を求めておく
    len_of_nearest_s = [INF] * B
    for i in range(B):
        idx = bisect.bisect_left(s, t[i])
        len_r = s[idx] - t[i] if 0 <= idx < A else INF
        len_l = t[i] - s[idx-1] if 0 <= idx - 1 < A else INF
        len_of_nearest_s[i] = min(len_l, len_r)
    # print(len_of_nearest_s)

    for _ in range(Q):
        x = I()
        # 神社→寺
        idx = bisect.bisect_left(s, x)
        len_r = s[idx] - x + len_of_nearest_t[idx] if 0 <= idx < A else INF
        len_l = x - s[idx-1] + len_of_nearest_t[idx-1] if 0 <= idx - 1 < A else INF
        len_x_s_t = min(len_r, len_l)
        # 寺→神社
        idx = bisect.bisect_left(t, x)
        len_r = t[idx] - x + len_of_nearest_s[idx] if 0 <= idx < B else INF
        len_l = x - t[idx-1] + len_of_nearest_s[idx-1] if 0 <= idx - 1 < B else INF
        len_x_t_s = min(len_r, len_l)
        print(min(len_x_s_t, len_x_t_s))

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
from bisect import*
a,b,q=map(int,input().split())
s=[-10**18]+[int(input()) for _ in range(a)]+[10**18]
t=[-10**18]+[int(input()) for _ in range(b)]+[10**18]
for _ in range(q):
  i=int(input())
  si=bisect_left(s,i)
  ti=bisect_left(t,i)
  print(min(max(s[si],t[ti])-i,i-min(t[ti-1],s[si-1]),
            2*t[ti]-s[si-1]-i,2*s[si]-t[ti-1]-i,
            i+t[ti]-2*s[si-1],i+s[si]-2*t[ti-1]))

Submission status: Accepted

Solution code:
import bisect

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 _ in range(q):
  x = int(input())
  
  ans = [0,0,0]
  
  i = bisect.bisect_left(s,x)
  if i == 0:
    sl = 100000000000
  else:
    sl = abs(s[i-1]-x)
  if i == a:
    sr = 100000000000
  else:
    sr = abs(s[i]-x)
  i = bisect.bisect_left(t,x)
  if i == 0:
    tl = 100000000000
  else:
    tl = abs(t[i-1]-x)
  if i == b:
    tr = 100000000000
  else:
    tr = abs(t[i]-x)
  ans[0] = max(tl,sl)
  ans[1] = max(tr,sr)
  ans[2] = min(2*tl+sr,2*sl+tr,2*sr+tl,2*tr+sl)
  print(min(ans))

Submission status: Accepted

Solution code:
from bisect import *
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())
    bs=bisect_left(s,x)
    if bs!=0:
        sl=x-s[bs-1]
    else:
        sl=float("inf")
    if bs!=a:
        sr=s[bs]-x
    else:
        sr=float("inf")
    bt=bisect_left(t,x)
    if bt!=0:
        tl=x-t[bt-1]
    else:
        tl=float("inf")
    if bt!=b:
        tr=t[bt]-x
    else:
        tr=float("inf")
    print(min(max(sl,tl),max(sr,tr),2*sl+tr,2*tl+sr,sl+tr*2,tl+sr*2))

Submission status: Accepted

Solution code:
# import sys
# input = sys.stdin.readline
INF = 10**11
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]
def binary_search(lis,x):
    ok = 0
    ng = len(lis)-1
    while ng-ok > 1:
        mid = (ok+ng)//2
        if lis[mid] < x:
            ok = mid
        else:
            ng = mid
    return ok
#print(s,t)
for _ in range(Q):
    x = int(input())
    ps = binary_search(s,x)
    pt = binary_search(t,x)
    ans = INF
    #print(ps,pt)
    for i in range(ps,ps+2):
        for j in range(pt,pt+2):
            ans = min(ans,abs(s[i]-x)+abs(s[i]-t[j]), abs(t[j]-x)+abs(t[j]-s[i]))
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
INF = 10**11
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]
def binary_search(lis,x):
    ok = 0
    ng = len(lis)-1
    while ng-ok > 1:
        mid = (ok+ng)//2
        if lis[mid] < x:
            ok = mid
        else:
            ng = mid
    return ok
#print(s,t)
for _ in range(Q):
    x = int(input())
    ps = binary_search(s,x)
    pt = binary_search(t,x)
    ans = INF
    #print(ps,pt)
    for i in range(ps,ps+2):
        for j in range(pt,pt+2):
            ans = min(ans,abs(s[i]-x)+abs(s[i]-t[j]), abs(t[j]-x)+abs(t[j]-s[i]))
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
INF = 10**11
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]
def binary_search(lis,x):
    ok = 0
    ng = len(lis)-1
    while ng-ok > 1:
        mid = (ok+ng)//2
        if lis[mid] < x:
            ok = mid
        else:
            ng = mid
    return ok
#print(s,t)
for _ in range(Q):
    x = int(input())
    ps = binary_search(s,x)
    pt = binary_search(t,x)
    ans = INF
    #print(ps,pt)
    for i in range(ps,ps+2):
        for j in range(pt,pt+2):
            ds = x - s[i]
            dt = x - t[j]
            
            if (ds < 0 and dt < 0) or (ds > 0 and dt > 0):
                ans = min(ans,max(abs(ds),abs(dt)))
            else:
                ans = min(ans,abs(ds)+abs(dt)+min(abs(ds),abs(dt)))
    print(ans)

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
INF = 10**11
A,B,Q = map(int,input().split())
s = [-INF] + [int(input()) for _ in range(A)] + [INF]
s.sort()
t = [-INF] + [int(input()) for _ in range(B)] + [INF]
t.sort()
def binary_search(lis,x):
    ok = 0
    ng = len(lis)-1
    while ng-ok > 1:
        mid = (ok+ng)//2
        if lis[mid] < x:
            ok = mid
        else:
            ng = mid
    return ok
#print(s,t)
for _ in range(Q):
    x = int(input())
    ps = binary_search(s,x)
    pt = binary_search(t,x)
    ans = INF
    #print(ps,pt)
    for i in range(ps,ps+2):
        for j in range(pt,pt+2):
            ds = x - s[i]
            dt = x - t[j]
            
            if (ds < 0 and dt < 0) or (ds > 0 and dt > 0):
                ans = min(ans,max(abs(ds),abs(dt)))
            else:
                ans = min(ans,abs(ds)+abs(dt)+min(abs(ds),abs(dt)))
    print(ans)

Submission status: Accepted

Solution code:
'''
研究室PCでの解答
'''
import math
#import numpy as np
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
mod = 10**9+7 #998244353
dir = [(-1,0),(1,0),(0,-1),(0,1)]
alp = "abcdefghijklmnopqrstuvwxyz"

'''
pythonにsortedsetをくれlower_boundとupper_boundをくれ
'''

def main():
    a,b,q = map(int,ipt().split())
    s = [-10**11]+[int(ipt()) for i in range(a)]+[10**11]
    t = [-10**11]+[int(ipt()) for i in range(b)]+[10**11]

    for i in range(q):
        x = int(ipt())
        ns = bisect.bisect_left(s,x)
        nt = bisect.bisect_left(t,x)
        ls = s[ns-1]-x
        rs = s[ns]-x
        lt = t[nt-1]-x
        rt = t[nt]-x
        ans = []
        ans.append(2*rs-lt)
        ans.append(2*rt-ls)
        ans.append(max(rs,rt))
        ans.append(-min(ls,lt))
        ans.append(rs-2*lt)
        ans.append(rt-2*ls)
        print(min(ans))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

from bisect import bisect_right

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

for x in X:
    b = bisect_right(S, x)
    d = bisect_right(T, x)
    res = INF
    for s in [S[b - 1], S[b]]:
        for t in [T[d - 1], T[d]]:
            dist_0 = abs(x - s) + abs(s - t)
            dist_1 = abs(x - t) + abs(t - s)
            res = min(res, dist_0, dist_1)

    print(res)