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 -*-

#############
# Libraries #
#############

import sys
input = sys.stdin.readline

import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache

#############
# Constants #
#############

MOD = 10**9+7
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"

#############
# Functions #
#############

######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]

######OUTPUT######
def P(arg): print(arg); return
def Y(): print("Yes"); return
def N(): print("No"); return
def E(): exit()
def PE(arg): print(arg); exit()
def YE(): print("Yes"); exit()
def NE(): print("No"); exit()

#####Shorten#####
def DD(arg): return defaultdict(arg)

#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)

######Combination######
kaijo_memo = []
def kaijo(n):
  if(len(kaijo_memo) > n): return kaijo_memo[n]
  if(len(kaijo_memo) == 0): kaijo_memo.append(1)
  while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
  return kaijo_memo[n]

gyaku_kaijo_memo = []
def gyaku_kaijo(n):
  if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
  if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
  while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
  return gyaku_kaijo_memo[n]

def nCr(n,r):
  if n == r: return 1
  if n < r or r < 0: return 0
  ret = 1
  ret = ret * kaijo(n) % MOD
  ret = ret * gyaku_kaijo(r) % MOD
  ret = ret * gyaku_kaijo(n-r) % MOD
  return ret

######Factorization######
def factorization(n):
  arr = []
  temp = n
  for i in range(2, int(-(-n**0.5//1))+1):
    if temp%i==0:
      cnt=0
      while temp%i==0: 
        cnt+=1 
        temp //= i
      arr.append([i, cnt])
  if temp!=1: arr.append([temp, 1])
  if arr==[]: arr.append([n, 1])
  return arr

#####MakeDivisors######
def make_divisors(n):
  divisors = []
  for i in range(1, int(n**0.5)+1):
    if n % i == 0:
      divisors.append(i)
      if i != n // i: 
        divisors.append(n//i)
  return divisors

#####MakePrimes######
def make_primes(N):
  max = int(math.sqrt(N))
  seachList = [i for i in range(2,N+1)]
  primeNum = []
  while seachList[0] <= max:
    primeNum.append(seachList[0])
    tmp = seachList[0]
    seachList = [i for i in seachList if i % tmp != 0]
  primeNum.extend(seachList)
  return primeNum

#####GCD#####
def gcd(a, b):
    while b: a, b = b, a % b
    return a

#####LCM#####
def lcm(a, b):
    return a * b // gcd (a, b)

#####BitCount#####
def count_bit(n):
  count = 0
  while n:
    n &= n-1
    count += 1
  return count

#####ChangeBase#####
def base_10_to_n(X, n):
  if X//n: return base_10_to_n(X//n, n)+[X%n]
  return [X%n]

def base_n_to_10(X, n):
  return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))

def base_10_to_n_without_0(X, n):
  X -= 1
  if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
  return [X%n]

#####IntLog#####
def int_log(n, a):
  count = 0
  while n>=a:
    n //= a
    count += 1
  return count

#############
# Main Code #
#############

A,B,Q =  IL()
S = ILs(A)
T = ILs(B)
ST = S+T
ST.sort()
dic = DD(str)
for s in S:
  dic[s] = "s"
for t in T:
  dic[t] = "t"


for _ in range(Q):
  q = I()
  p = bisect.bisect(ST,q)
  l = max(0,p-1)
  r = min(p,A+B-1)
  if dic[ST[l]]=="s":
    p = bisect.bisect(T,ST[l])
    ll = max(0,p-1)
    rr = min(p,B-1)
    dl = min(abs(T[ll]-ST[l]),abs(T[rr]-ST[l]))
  else:
    p = bisect.bisect(S,ST[l])
    ll = max(0,p-1)
    rr = min(p,A-1)
    dl = min(abs(S[ll]-ST[l]),abs(S[rr]-ST[l]))
  if dic[ST[r]]=="s":
    p = bisect.bisect(T,ST[r])
    ll = max(0,p-1)
    rr = min(p,B-1)
    dr = min(abs(T[ll]-ST[r]),abs(T[rr]-ST[r]))
  else:
    p = bisect.bisect(S,ST[r])
    ll = max(0,p-1)
    rr = min(p,A-1)
    dr = min(abs(S[ll]-ST[r]),abs(S[rr]-ST[r]))
  print(min(abs(ST[l]-q)+dl,abs(ST[r]-q)+dr))

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/abc119/tasks/abc119_d
# 

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)]
#print(s)
#print(t)
for i in range(Q):
    x=int(input())
    #print(bisect_left(s,x),bisect_left(t,x))
    sl=float("-inf")
    sr=float("inf")
    tl=float("-inf")
    tr=float("inf")
    a=bisect_left(s,x)
    if a>0:
        sl = s[a-1]
    if a<=A-1:
        sr = s[a]
    b=bisect_left(t,x)
    if b>0:
        tl = t[b-1]
    if b<=B-1:
        tr = t[b]
    #print(sl,sr)
    #print(tl,tr)
    
    pat_LL = x - min(sl,tl)
    pat_LR = sr-tl + min(sr-x,x-tl)
    pat_RL = tr-sl + min(tr-x,x-sl)
    pat_RR = max(sr,tr)-x
    
    print(min(pat_LL,pat_LR,pat_RL,pat_RR))

Submission status: Accepted

Solution code:
import bisect
import sys
sys.setrecursionlimit(10**9)

def mi(): return map(int,input().split())
def ii(): return int(input())
def isp(): return input().split()
def deb(text): print("-------\n{}\n-------".format(text))

INF = 10**20
def main():
    A,B,Q=mi()
    X,Y= [], []
    for i in range(A):
        X.append(ii())
    for i in range(B):
        Y.append(ii())
    
    def search_min_dist(Z,z):
        insert_i = bisect.bisect_left(Z,z)
        res = []
        m = INF
        for di in [-2,-1,0,1,2]:
            i = insert_i + di
           
            if 0<= i < len(Z):
                res.append(Z[i])

        return res


    for q in range(Q):
        x=ii()
        minX = search_min_dist(X,x)
        minY = search_min_dist(Y,x)

        ans = INF
        for mx in minX:
            for my in minY:
                min_dist_x,min_dist_y = mx,my
                if not min_dist_x < min_dist_y:
                    min_dist_x,min_dist_y = min_dist_y,min_dist_x

                _ans = 0
                if min_dist_x <= x <= min_dist_y:
                    _ans = min(min_dist_y-x,x-min_dist_x) + min_dist_y - min_dist_x
                elif x <= min_dist_x <= min_dist_y:
                    _ans = min_dist_y - x
                else:
                    _ans = -min_dist_x + x
                
    
                ans = min(ans,_ans)
        print(ans)

        

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import bisect
A,B,Q =list(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()))    
    s_index_af = bisect.bisect(s,x)
    if s_index_af == A:
        s_index_af -= 1
        s_index_bf = s_index_af
    else:
        s_index_bf = s_index_af -1

    t_index_af = bisect.bisect(t,x)
    if t_index_af == B:
        t_index_af -= 1
        t_index_bf = t_index_af
    else:
        t_index_bf = t_index_af -1
   
    jl = [s[s_index_bf]-x,s[s_index_af]-x]
    tl = [t[t_index_bf]-x,t[t_index_af]-x]

    jt = []
    jt.append(abs(jl[0])+abs(tl[0]-jl[0]))
    jt.append(abs(jl[0])+abs(tl[1]-jl[0]))
    jt.append(abs(jl[1])+abs(tl[0]-jl[1]))
    jt.append(abs(jl[1])+abs(tl[1]-jl[1]))

    jt.append(abs(tl[0])+abs(jl[0]-tl[0]))
    jt.append(abs(tl[0])+abs(jl[1]-tl[0]))
    jt.append(abs(tl[1])+abs(jl[0]-tl[1]))
    jt.append(abs(tl[1])+abs(jl[1]-tl[1]))

            
    print(min(jt))

Submission status: Accepted

Solution code:
#左右それぞれで一番近い神社
#その神社それぞれの左右それぞれで一番近い寺
#はい２ぶたん

INF = 10**12

from bisect import bisect_right
 
A,B,Q = map(int,input().split())
s = [int(input()) for i in range(A)]
t = [int(input()) for i in range(B)]
ans =[]
for i in range(0,Q,1):
    tmpans = INF

    q = int(input())
    sr = bisect_right(s,q)
    sl = sr-1
    sr = min(sr,A-1)
    sl = max(0,sl)
    for j in (sr,sl):
        tr = bisect_right(t,s[j])
        tl = tr-1
        tr = min(tr,B-1)
        tl = max(0,tl)
        ansR=abs(s[j]-q)+abs(s[j]-t[tr])
        ansL=abs(s[j]-q)+abs(s[j]-t[tl])
        tmpans = min(tmpans,ansR,ansL)

    
    tr = bisect_right(t,q)
    tl = tr-1
    tr = min(tr,B-1)
    tl = max(0,tl)
    for j in (tr,tl):
        sr = bisect_right(s,t[j])
        sl = sr-1
        sr = min(sr,A-1)
        sl = max(0,sl)
        ansR=abs(t[j]-q)+abs(t[j]-s[sr])
        ansL=abs(t[j]-q)+abs(t[j]-s[sl])
        tmpans = min(tmpans,ansR,ansL)
    
    ans.append(tmpans)

for i in range(0,Q,1):
    print(ans[i])

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 i in range(Q):
    x = int(input())
    b = bisect.bisect_right(s, x)
    d = bisect.bisect_right(t, x)
    ans = INF
    for S in [s[b-1], s[b]]:
        for T in [t[d-1], t[d]]:
            ans1 = abs(S-x) + abs(S-T)
            ans2 = abs(T-x) + abs(T-S)
            ans = min(ans, ans1, ans2)
    print(ans)

Submission status: Accepted

Solution code:
#float型を許すな
#numpyはpythonで
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

a,b,q=MI()
lis1=[I() for i in range(a)]
lis2=[I() for i in range(b)]
lis1.append(inf)
lis2.append(inf)
lis1=[-inf]+lis1
lis2=[-inf]+lis2
#print(lis1)
#print(lis2)
for i in range(q):
    u=I()
    x=bisect_left(lis1,u)
    y=bisect_left(lis2,u)
    #print(u,x,y)
    Lll=u-min(lis1[x-1],lis2[y-1])
    Lrr=max(lis1[x],lis2[y])-u
    Llr1=2*(u-lis1[x-1])+(lis2[y]-u)
    Llr2=2*(lis2[y]-u)+u-lis1[x-1]
    Lrl1=2*(u-lis2[y-1])+lis1[x]-u
    Lrl2=2*(lis1[x]-u)+u-lis2[y-1]
    #print(Lll,Lrr,Lrl1,Lrl2,Llr1,Llr2)
    print(min(Lll,Lrr,Lrl1,Lrl2,Llr1,Llr2))

Submission status: Accepted

Solution code:
#float型を許すな
#numpyはpythonで
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**7)
from collections import Counter, deque
from collections import defaultdict
from itertools import combinations, permutations, accumulate, groupby, product
from bisect import bisect_left,bisect_right
from heapq import heapify, heappop, heappush
from math import floor, ceil,pi,factorial
from operator import itemgetter
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI2(): return [int(input()) for i in range(n)]
def MXI(): return [[LI()]for i in range(n)]
def SI(): return input().rstrip()
def printns(x): print('\n'.join(x))
def printni(x): print('\n'.join(list(map(str,x))))
inf = 10**17
mod = 10**9 + 7

a,b,q=MI()
lis1=[-inf]
lis2=[-inf]
for i in range(a):
    lis1.append(I())
for i in range(b):
    lis2.append(I())
lis1.append(inf)
lis2.append(inf)
#print(lis1)
#print(lis2)
for i in range(q):
    u=I()
    x=bisect_left(lis1,u)
    y=bisect_left(lis2,u)
    #print(u,x,y)
    Lll=u-min(lis1[x-1],lis2[y-1])
    Lrr=max(lis1[x],lis2[y])-u
    Llr1=2*(u-lis1[x-1])+(lis2[y]-u)
    Llr2=2*(lis2[y]-u)+u-lis1[x-1]
    Lrl1=2*(u-lis2[y-1])+lis1[x]-u
    Lrl2=2*(lis1[x]-u)+u-lis2[y-1]
    #print(Lll,Lrr,Lrl1,Lrl2,Llr1,Llr2)
    print(min(Lll,Lrr,Lrl1,Lrl2,Llr1,Llr2))

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 i in range(Q):
    x = int(input())
    b = bisect.bisect_right(s, x)
    d = bisect.bisect_right(t, x)
    ans = INF
    for S in [s[b-1], s[b]]:
        for T in [t[d-1], t[d]]:
            ans1 = abs(S-x) + abs(S-T)
            ans2 = abs(T-x) + abs(T-S)
            ans = min(ans, ans1, ans2)
    print(ans)

Submission status: Accepted

Solution code:
import bisect
import itertools
import sys

def main(args):
    
    A, B, Q = map(int,input().split())
    S = [0]*A
    T = [0]*B
    for i in range(A):
        S[i] = int(input())
    for i in range(B):
        T[i] = int(input())
    
    S = [-10**18] + S + [10**18]
    T = [-10**18] + T +[10**18]
    
    def solve(j, t, start):
        jinja_l = S[j-1]
        jinja_r = S[j]
        tera_l = T[t-1]
        tera_r = T[t]
        jinja = [jinja_l, jinja_r]
        tera = [tera_l ,tera_r]
        
        ans = float('inf')
        for u,v in list(itertools.product(jinja, tera)):
            ans = min(ans, abs(start-u)+abs(v-u))
            ans = min(ans, abs(v-start)+abs(v-u))
        
        return ans
    
    for i in range(Q):
        x = int(input())
        ans = solve(bisect.bisect_left(S, x), bisect.bisect_left(T ,x), x)
        print(ans)
        
if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Accepted

Solution code:
import bisect
INF=10**11
A,B,q=map(int,input().split())
a=[-INF]+[int(input()) for _ in range(A)]+[INF]
b=[-INF]+[int(input()) for _ in range(B)]+[INF]
for _ in range(q):
  x=int(input())
  i=bisect.bisect_left(a,x)
  j=bisect.bisect_left(b,x)
  ans=min(max(a[i],b[j])-x,x-min(a[i-1],b[j-1]),a[i]-b[j-1]+min(a[i]-x,x-b[j-1]),b[j]-a[i-1]+min(b[j]-x,x-a[i-1]))
  print(ans)

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]

# print("s", s)
# print("t", t)
for q in range(Q):
    x = int(input())
    b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
    # print(f"b{b}, d{d}")

    res = INF

    for S in [s[b-1], s[b]]:
        for T in [t[d-1], t[d]]:
            # print(f"S{S}, T{T}")
            d1, d2 = abs(S-x)+abs(T-S), abs(T-x)+abs(T-S)
            res = min(res, d1, d2)
    print(res)

Submission status: Accepted

Solution code:
import sys
import bisect
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')

INF = 10**12


def main():

    A, B, Q = in_nn()
    tmp = list(map(int, read().split()))
    s = [-INF] + tmp[:A] + [INF]
    t = [-INF] + tmp[A:A + B] + [INF]
    x = tmp[A + B:]

    a = [0] * Q
    d = lambda a, b: abs(a - b)

    for i in range(Q):

        n = x[i]

        si = bisect.bisect_right(s, n)
        a1 = s[si - 1]
        a2 = s[si]

        ti = bisect.bisect_right(t, n)
        b1 = t[ti - 1]
        b2 = t[ti]

        ans = d(n, a1) + min(d(a1, b1), d(a1, b2))
        ans = min(ans, d(n, a2) + min(d(a2, b1), d(a2, b2)))
        ans = min(ans, d(n, b1) + min(d(b1, a1), d(b1, a2)))
        ans = min(ans, d(n, b2) + min(d(b2, a1), d(b2, a2)))
        a[i] = ans

    print('\n'.join(map(str, a)))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
import bisect
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_s = lambda: readline().rstrip().decode('utf-8')

INF = 10**12
d = lambda a, b: abs(a - b)


def main():

    A, B, Q = in_nn()
    tmp = list(map(int, read().split()))
    s = tmp[:A]
    t = tmp[A:A + B]
    x = tmp[A + B:]

    a = [0] * Q

    for i in range(Q):

        n = x[i]

        if n <= s[0]:
            a1 = -INF
            a2 = s[0]
        elif n >= s[-1]:
            a1 = s[-1]
            a2 = INF
        else:
            si = bisect.bisect_right(s, n)
            a1 = s[si - 1]
            a2 = s[si]

        if n <= t[0]:
            b1 = -INF
            b2 = t[0]
        elif n >= t[-1]:
            b1 = t[-1]
            b2 = INF
        else:
            ti = bisect.bisect_right(t, n)
            b1 = t[ti - 1]
            b2 = t[ti]

        # print(a1, a2, b1, b2)
        ans = d(n, a1) + min(d(a1, b1), d(a1, b2))
        ans = min(ans, d(n, a2) + min(d(a2, b1), d(a2, b2)))
        ans = min(ans, d(n, b1) + min(d(b1, a1), d(b1, a2)))
        ans = min(ans, d(n, b2) + min(d(b2, a1), d(b2, a2)))
        a[i] = ans

    print('\n'.join(map(str, a)))


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]
q = [int(input()) for i in range(Q)]
for x in q:
    b,d = bisect.bisect_left(s,x),bisect.bisect_left(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())
s=[int(input()) for _ in range(A)]
t=[int(input()) for _ in range(B)]
x=[int(input()) for _ in range(Q)]

st=[0]*A
ts=[0]*B

for i in range(A):
  tmp=bisect.bisect_left(t, s[i])
  if tmp==0:
    st[i]=t[0]-s[i]
  elif tmp==B:
    st[i]=s[i]-t[-1]
  else:
    st[i]=min(s[i]-t[tmp-1], t[tmp]-s[i])
    
for i in range(B):
  tmp=bisect.bisect_left(s, t[i])
  if tmp==0:
    ts[i]=s[0]-t[i]
  elif tmp==A:
    ts[i]=t[i]-s[-1]
  else:
    ts[i]=min(t[i]-s[tmp-1], s[tmp]-t[i])

for i in range(Q):
  cand=set()
  tmp=bisect.bisect_left(s, x[i])
  if tmp>0:
    cand.add(x[i]-s[tmp-1]+st[tmp-1])
  if tmp<A:
    cand.add(s[tmp]-x[i]+st[tmp])
    
  tmp=bisect.bisect_left(t, x[i])
  if tmp>0:
    cand.add(x[i]-t[tmp-1]+ts[tmp-1])
  if tmp<B:
    cand.add(t[tmp]-x[i]+ts[tmp])
    
  print(min(cand))

Submission status: Accepted

Solution code:
a,b,q = map(int,input().split())
tl=[]
qlist=[]
for i in range(a):tl.append((int(input()),0,i))
for i in range(b):tl.append((int(input()),1,i))
for i in range(q):
    q1=int(input())
    tl.append((q1,2,i))
    qlist.append(q1)
tl.sort()
prea=[-1]*q
preb=[-1]*q
ta=tb=-1
for i,c in enumerate(tl):
    if   c[1]==0:ta=c[0]
    elif c[1]==1:tb=c[0]
    elif c[1]==2:prea[c[2]],preb[c[2]]=ta,tb
posta=[-1]*q
postb=[-1]*q
ra=rb=-1
for i,c in enumerate(tl[::-1]):
    if   c[1]==0:ra=c[0]
    elif c[1]==1:rb=c[0]
    elif c[1]==2:posta[c[2]],postb[c[2]]=ra,rb

def cal(pra,poa,prb,pob,q):
    gmin = 999999999999
    if pra!=-1 and prb!=-1:
        if pra<prb:gmin=min(gmin,q-pra)
        else:      gmin=min(gmin,q-prb)
    if pra!=-1 and pob!=-1:gmin=min(gmin,pob-pra+min(q-pra,pob-q))
    if prb!=-1 and poa!=-1:gmin=min(gmin,poa-prb+min(poa-q,q-prb))
    if poa!=-1 and pob!=-1:
        if poa<pob:gmin=min(gmin,pob-q)
        else:      gmin=min(gmin,poa-q)
    return gmin
for a1,a2,b1,b2,q in zip(prea,posta,preb,postb,qlist):print(cal(a1,a2,b1,b2,q))

Submission status: Accepted

Solution code:
import bisect
A,B,Q=map(int,input().split())
s=[-10**15]
t=[-10**15]
ans=[]
for _ in range(A):
    s.append(int(input()))
for _ in range(B):
    t.append(int(input()))
s.append(10**15)
t.append(10**15)
def search(a,b,q):
    dis=10**15
    S=[s[a-1],s[a]]
    T=[t[b-1],t[b]]
    for i in range(2):
        for j in range(2):
            A=min(abs(S[i]-q),abs(T[j]-q))+abs(S[i]-T[j])
            dis=min(dis,A)
    return dis
for _ in range(Q):
    q=int(input())
    r=bisect.bisect_left(s,q)
    l=bisect.bisect_left(t,q)
    ans.append(search(r,l,q))
for i in ans:
    print(i)

Submission status: Accepted

Solution code:
import sys
import math
from collections import deque
import bisect

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()


def make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
	A, B, Q = NMI()
	S = [-float("inf")] + [NI() for _ in range(A)] + [float("inf")]
	T = [-float("inf")] + [NI() for _ in range(B)] + [float("inf")]
	Q = [NI() for _ in range(Q)]

	for q in Q:
		s_idx = bisect.bisect_left(S, q)
		t_idx = bisect.bisect_left(T, q)
		sl, sr, tl, tr = S[s_idx-1], S[s_idx], T[t_idx-1], T[t_idx]
		LL = max(abs(q - sl), abs(q - tl))
		RR = max(abs(q - sr), abs(q - tr))
		LR = abs(q - sl) * 2 + abs(q - tr)
		RL = abs(q - sr) * 2 + abs(q - tl)
		LR2 = abs(q - tl) * 2 + abs(q - sr)
		RL2 = abs(q - tr) * 2 + abs(q - sl)
		res = min(LL, RR, LR, LR2, RL, RL2)
		print(res)


if __name__ == "__main__":
	main()

Submission status: Accepted

Solution code:
#!/usr/bin/python3
import bisect
# from collections import Counter, deque, OrderedDict, defaultdict
# from copy import copy, deepcopy # pythonのみ．copyは1次元，deepcopyは多次元．
# from functools import reduce
# from heapq import heapify, heappop, heappush
# from itertools import accumulate, permutations, combinations, combinations_with_replacement, groupby, product
# import math
# import numpy as np  # Pythonのみ！
# from operator import xor
# import re
# from scipy.sparse.csgraph import connected_components  # Pythonのみ！
# ↑cf.  https://note.nkmk.me/python-scipy-connected-components/
# from scipy.sparse import csr_matrix
# import statistics # Pythonのみ
# import string
import unittest
from io import StringIO
import sys
sys.setrecursionlimit(10 ** 5 + 10)


def input(): return sys.stdin.readline().strip()


def resolve():
    A, B, Q = map(int, input().split())
    INF = 10**20
    s = [-INF]+[int(input()) for _ in range(A)]+[INF]
    t = [-INF]+[int(input()) for _ in range(B)]+[INF]

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

        res = 10**20

        for ss in (sa, sb):
            for tt in (ta, tb):
                res = min(res, abs(x-ss)+abs(ss-tt))
        
        for tt in (ta, tb):
            for ss in (sa, sb):
                res = min(res, abs(x-tt)+abs(tt-ss))


        print(res)


resolve()

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_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:
a,b,q = map(int,input().split())
s = sorted([int(input()) for i in range(a)])
t = sorted([int(input()) for i in range(b)])

from bisect import bisect

for i in range(q):
    x = int(input())

    s_i = bisect(s,x)
    d1 = d2 = 10**11
    if s_i<a:
        d1 = s[s_i]-x
        t_i = bisect(t,s[s_i])
        buf = 10**11
        if t_i<b:
            buf = t[t_i]-s[s_i]
        if t_i>0:
            buf = min(buf,s[s_i]-t[t_i-1])
        d1 += buf
    if s_i>0:
        d2 = x-s[s_i-1]
        t_i = bisect(t,s[s_i-1])
        buf = 10**11
        if t_i<b:
            buf = t[t_i]-s[s_i-1]
        if t_i>0:
            buf = min(buf,s[s_i-1]-t[t_i-1])
        d2 += buf
    
    t_i = bisect(t,x)
    d3 = d4 = 10**11
    if t_i<b:
        d3 = t[t_i]-x
        s_i = bisect(s,t[t_i])
        buf = 10**11
        if s_i<a:
            buf = s[s_i]-t[t_i]
        if s_i>0:
            buf = min(buf,t[t_i]-s[s_i-1])
        d3 += buf
    if t_i>0:
        d4 = x-t[t_i-1]
        s_i = bisect(s,t[t_i-1])
        buf = 10**11
        if s_i<a:
            buf = s[s_i]-t[t_i-1]
        if s_i>0:
            buf = min(buf,t[t_i-1]-s[s_i-1])
        d4 += buf

    print(min(d1,d2,d3,d4))

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]
import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))

A, B, Q = mi()

S = [ii() for _ in range(A)]
T = [ii() for _ in range(B)]

S_ = [S[0]] + S + [S[A-1]]
T_ = [T[0]] + T + [T[B-1]]

for _ in range(Q):
    f = ii()
    to_s = bisect.bisect_left(S, f)
    to_t = bisect.bisect_left(T, f)

    ans = float('inf')

    for i in [S_[to_s], S_[to_s+1]]:
        for j in [T_[to_t], T_[to_t+1]]:
            tmp = min(abs(i - f), abs(j - f)) + abs(i - j)
            ans = min(ans, tmp)
    '''
    ans = min(abs(S_[to_s+1] - f) + abs(S_[to_s+1] - T_[to_t+1]), float('inf'))
    ans = min(abs(S_[to_s+1] - T_[to_t+1]) + abs(f - T_[to_t+1]), ans)
    ans = min(abs(S_[to_s+1] - f) + abs(S_[to_s+1] - T_[to_t]), ans)
    ans = min(abs(S_[to_s+1] - T_[to_t]) + abs(f - T_[to_t]), ans)
    ans = min(abs(S_[to_s] - f) + abs(S_[to_s] - T_[to_t+1]), ans)
    ans = min(abs(S_[to_s] - T_[to_t+1]) + abs(f - T_[to_t+1]), ans)
    ans = min(abs(S_[to_s] - f) + abs(S_[to_s] - T_[to_t]), ans)
    ans = min(abs(S_[to_s] - T_[to_t]) + abs(f - T_[to_t]), ans)
    '''
    print(ans)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**8)
def ii(): return int(sys.stdin.readline())
def mi(): return map(int, sys.stdin.readline().split())
def li(): return list(map(int, sys.stdin.readline().split()))
def li2(N): return [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def dp2(ini, i, j): return [[ini]*i for _ in range(j)]
import bisect #bisect.bisect_left(B, a)
#from collections import defaultdict #d = defaultdict(int) d[key] += value
#from collections import Counter # a = Counter(A).most_common()
#from itertools import accumulate #list(accumulate(A))

A, B, Q = mi()

S = [ii() for _ in range(A)]
T = [ii() for _ in range(B)]

S_ = [S[0]] + S + [S[A-1]]
T_ = [T[0]] + T + [T[B-1]]

for _ in range(Q):
    f = ii()
    to_s = bisect.bisect_left(S, f)
    to_t = bisect.bisect_left(T, f)
    #ans_1 = ans_2 = 0
    #print(to_s, to_t)

    #ans_1 += abs(S_[to_s+1] - f)
    #ans_2 += abs(f - S_[to_s])
    #print(ans_1, ans_2)

    #ans_1 = min(ans_1 + abs(S_[to_s+1] - T_[to_t+1]), ans_1 + abs(S_[to_s+1] - T_[to_t]))
    #ans_2 = min(ans_2 + abs(S_[to_s] - T_[to_t+1]), ans_2 + abs(S_[to_s] - T_[to_t]))

    ans = min(abs(S_[to_s+1] - f) + abs(S_[to_s+1] - T_[to_t+1]), float('inf'))
    ans = min(abs(S_[to_s+1] - T_[to_t+1]) + abs(f- T_[to_t+1]), ans)
    ans = min(abs(S_[to_s+1] - f) + abs(S_[to_s+1] - T_[to_t]), ans)
    ans = min(abs(S_[to_s+1] - T_[to_t]) + abs(f- T_[to_t]), ans)
    ans = min(abs(S_[to_s] - f) + abs(S_[to_s] - T_[to_t+1]), ans)
    ans = min(abs(S_[to_s] - T_[to_t+1]) + abs(f- T_[to_t+1]), ans)
    ans = min(abs(S_[to_s] - f) + abs(S_[to_s] - T_[to_t]), ans)
    ans = min(abs(S_[to_s] - T_[to_t]) + abs(f- T_[to_t]), ans)
    print(ans)