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:
a, b, q = list(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)]

def bs(z, st):
    l = 0
    r = len(st) - 1
    while r - l != 1:
        m = (l + r) // 2
        if st[m] <= z:
            l = m
        else:
            r = m
    return l

for xi in x:
    tmps = []
    tmpt = []
    if xi <= s[0]:
        tmps.append(s[0] - xi)
    elif s[-1] <= xi:
        tmps.append(s[-1] - xi)
    else:
        tmp = bs(xi, s)
        tmps.append(s[tmp] - xi)
        tmps.append(s[tmp + 1] - xi)

    if xi <= t[0]:
        tmpt.append(t[0] - xi)
    elif t[-1] <= xi:
        tmpt.append(t[-1] - xi)
    else:
        tmp = bs(xi, t)
        tmpt.append(t[tmp] - xi)
        tmpt.append(t[tmp + 1] - xi)
    anss = []
    for i in tmps:
        for j in tmpt:
            if i // abs(i) == j // abs(j):
                anss.append(max(abs(i), abs(j)))
            else:
                maxij = max(abs(i), abs(j)) 
                minij = min(abs(i), abs(j)) 
                anss.append(abs(maxij + minij * 2))
    anss.sort()
    print(anss[0])

Submission status: Accepted

Solution code:
import bisect

INF = 1 << 64
A, B, Q = map(int, input().split())
S = [int(input()) for a in range(A)]
T = [int(input()) for b in range(B)]

def cost(S, A, x):
    index_s = bisect.bisect_left(S, x)
    ws = INF if index_s == 0 else x - S[index_s - 1]
    es = INF if index_s == A else S[index_s] - x
    return ws, es


for q in range(Q):
    x = int(input())
    ws, es = cost(S, A, x)
    wt, et = cost(T, B, x)

    print(min(max(ws, wt), max(es, et), min(ws, et) + ws + et, min(es, wt) + es + wt))

Submission status: Accepted

Solution code:
a,b,q=map(int, input().split())
x=[-10**11]+[int(input()) for i in range(a)]+[10**11]
y=[-10**11]+[int(input()) for i in range(b)]+[10**11]
p=[int(input()) for i in range(q)]
import bisect
ans=[]
for i in p:
    xi=bisect.bisect_left(x,i)
    yi=bisect.bisect_left(y,i)
    a1=max(x[xi],y[yi])-i
    a2=x[xi]-i+x[xi]-y[yi-1]
    a3=y[yi]-i+y[yi]-x[xi-1]
    a4=i-x[xi-1]+y[yi]-x[xi-1]
    a5=i-y[yi-1]+x[xi]-y[yi-1]
    a6=abs(min(x[xi-1],y[yi-1])-i)
    ans.append(min(a1,a2,a3,a4,a5,a6))
for i in ans:print(i)

Submission status: Accepted

Solution code:
import sys
from bisect import bisect_right

def solve():
    def getINearests(ss, ts):
        iNearests = [-1] * len(ss)
        for iS, s in enumerate(ss):
            iT = bisect_right(ts, s)
            if iT == len(ts):
                iNearests[iS] = iT-1
            elif iT == 0:
                iNearests[iS] = 0
            else:
                d1 = abs(s - ts[iT-1])
                d2 = abs(s - ts[iT])
                if d1 <= d2:
                    iNearests[iS] = iT-1
                else:
                    iNearests[iS] = iT
        return iNearests


    A, B, Q = map(int, input().split())
    ss = [int(sys.stdin.readline()) for _ in range(A)]
    ts = [int(sys.stdin.readline()) for _ in range(B)]
    xs = [int(sys.stdin.readline()) for _ in range(Q)]

    iTNearests = getINearests(ss, ts)
    iSNearests = getINearests(ts, ss)

    anss = [0] * Q
    for iX, x in enumerate(xs):
        ans = float('inf')

        # 初手: 神社
        iS = bisect_right(ss, x)
        if iS > 0:
            cost = abs(x - ss[iS-1])
            cost += abs(ss[iS-1] - ts[iTNearests[iS-1]])
            if cost < ans: ans = cost
        if iS < A:
            cost = abs(x - ss[iS])
            cost += abs(ss[iS] - ts[iTNearests[iS]])
            if cost < ans: ans = cost

        # 初手: 寺
        iT = bisect_right(ts, x)
        if iT > 0:
            cost = abs(x - ts[iT-1])
            cost += abs(ts[iT-1] - ss[iSNearests[iT-1]])
            if cost < ans: ans = cost
        if iT < B:
            cost = abs(x - ts[iT])
            cost += abs(ts[iT] - ss[iSNearests[iT]])
            if cost < ans: ans = cost

        anss[iX] = ans

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

solve()

Submission status: Accepted

Solution code:
A,B,Q = list(map(int, input().split()))
s,t,xx=[],[],[]

for i in range(A):
    s.append(int(input()))
for i in range(B):
    t.append(int(input()))
for i in range(Q):
    xx.append(int(input()))
    
import bisect
M = 10000000000000

for x in xx:
    i = bisect.bisect_left(s,x)
    j = bisect.bisect_left(t,x)
    
    if (i > 0) and (j > 0):
        ll = abs(min(s[i-1]-x, t[j-1]-x))
    else:
        ll = M
        
    if (i > 0) and (j < B):
        lr = abs(s[i-1]-x) * 2 + (t[j]-x)
    else:
        lr = M
        
    if (i < A) and (j > 0):
        lr_2 = abs(t[j-1]-x) * 2 + (s[i]-x)
    else:
        lr_2 = M
        
    if (i < A) and (j > 0):
        rl = (s[i]-x) * 2 + abs(t[j-1] - x)
    else:
        rl = M
        
    if (i > 0) and (j < B):
        rl_2 = (t[j]-x) * 2 + abs(s[i-1] - x)
    else:
        rl_2 = M
        
    if (i < A) and (j < B):
        rr = max(s[i]-x,t[j]-x)
    else:
        rr = M

    print(min(ll,lr,rl,rr,lr_2,rl_2))

Submission status: Accepted

Solution code:
A, B, Q = map(int, input().split())
S = [-10**12]
for _ in range(A):
    S.append(int(input()))
S.append(10**12)
T = [-10**12]
for _ in range(B):
    T.append(int(input()))
T.append(10**12)
X = []
for _ in range(Q):
    X.append(int(input()))

import bisect
for x in X:
    i = bisect.bisect_left(S, x)
    ls, rs = abs(S[i-1]-x), abs(S[i]-x)
    j = bisect.bisect_left(T, x)
    lt, rt = abs(T[j-1]-x), abs(T[j]-x)
    result = min(max(lt, ls), max(rt, rs),
                 rt + 2*ls, ls + 2*rt,
                 rs + 2*lt, lt + 2*rs)
    print(result)

Submission status: Accepted

Solution code:
import bisect
A,B,Q = map(int, input().split())
SList=[]
TList=[]
for i in range(A):
  SList.append(int(input()))
for i in range(B):
  TList.append(int(input()))


  
for i in range(Q):
  x=int(input())
  kouho=[]
  insert_indexS=bisect.bisect_left(SList,x)
  if not insert_indexS==0:
    kyoriS0 = x-SList[insert_indexS-1]
    insert_indexT=bisect.bisect_left(TList,SList[insert_indexS-1])
    if not insert_indexT==0:
      kyoriS00 = kyoriS0+SList[insert_indexS-1]-TList[insert_indexT-1]
      kouho.append(kyoriS00)
    if not insert_indexT==len(TList):
      kyoriS01 = kyoriS0+TList[insert_indexT]-SList[insert_indexS-1]
      kouho.append(kyoriS01)
  if not insert_indexS == len(SList):
    kyoriS1=SList[insert_indexS]-x
    insert_indexT=bisect.bisect_left(TList,SList[insert_indexS])
    if not insert_indexT==0:
      kyoriS10 = kyoriS1+SList[insert_indexS]-TList[insert_indexT-1]
      kouho.append(kyoriS10)
    if not insert_indexT==len(TList):
      kyoriS11 = kyoriS1+TList[insert_indexT]-SList[insert_indexS]
      kouho.append(kyoriS11)

  insert_indexT=bisect.bisect_left(TList,x)
  if not insert_indexT==0:
    kyoriT0 = x-TList[insert_indexT-1]
    insert_indexS=bisect.bisect_left(SList,TList[insert_indexT-1])
    if not insert_indexS==0:
      kyoriT00 = kyoriT0+TList[insert_indexT-1]-SList[insert_indexS-1]
      kouho.append(kyoriT00)
    if not insert_indexS==len(SList):
      kyoriT01 = kyoriT0+SList[insert_indexS]-TList[insert_indexT-1]
      kouho.append(kyoriT01)
  if not insert_indexT == len(TList):
    kyoriT1=TList[insert_indexT]-x
    insert_indexS=bisect.bisect_left(SList,TList[insert_indexT])
    if not insert_indexS==0:
      kyoriT10 = kyoriT1+TList[insert_indexT]-SList[insert_indexS-1]
      kouho.append(kyoriT10)
    if not insert_indexS==len(SList):
      kyoriT11 = kyoriT1+SList[insert_indexS]-TList[insert_indexT]
      kouho.append(kyoriT11)
  print(min(kouho))

Submission status: Accepted

Solution code:
A, B, Q = [int(_) for _ in input().split()]
S = [int(input()) for i in range(A)]
T = [int(input()) for i in range(B)]
Q = [int(input()) for i in range(Q)]

#print(S, T, Q)

def calc_m(xs):
    return [(a + b) / 2 for a, b in zip(xs, xs[1:])]

sm = calc_m(S)
tm = calc_m(T)

#print(sm)
#print(tm)

import bisect

def calc_nearest_0(xs, y, ym):
    result = []
    i = 0
    for x in xs:
        while i < len(ym) and x >= ym[i]:
            i += 1
        result.append(y[i])
    return result

def calc_nearest(xs, y, ym):
    result = []
    for x in xs:
        i = bisect.bisect(ym, x)
        result.append(y[i])
    return result

sn = calc_nearest(S, T, tm)
tn = calc_nearest(T, S, sm)

#print(sn)
#print(tn)

def solve(q, S, T, sn, tn):
    nsp = bisect.bisect(S, q)
    ntp = bisect.bisect(T, q)

    rs = []

    if 0 <= nsp < len(S):
        rs.append(abs(S[nsp] - q) + abs(S[nsp] - sn[nsp]))
    nsp -= 1
    if 0 <= nsp < len(S):
        rs.append(abs(S[nsp] - q) + abs(S[nsp] - sn[nsp]))

    if 0 <= ntp < len(T):
        rs.append(abs(T[ntp] - q) + abs(T[ntp] - tn[ntp]))
    ntp -= 1
    if 0 <= ntp < len(T):
        rs.append(abs(T[ntp] - q) + abs(T[ntp] - tn[ntp]))

    # print("Q", q, S, T, sn, tn, r1, r2)
    return min(rs)

for q in Q:
    print(solve(q, S, T, sn, tn))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
from itertools import product
from bisect import bisect, bisect_left
def inpl(): return list(map(int, input().split()))
A, B, Q = inpl()
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
X = [int(input()) for _ in range(Q)]

for x in X:
    ans = 1e12
    ls, lt = S[max(0, bisect(S, x)-1)], T[max(0, bisect(T, x)-1)]
    rs, rt = S[min(A-1, bisect_left(S, x))], T[min(B-1, bisect_left(T, x))]
    for s in [ls, rs]:
        for t in [lt, rt]:
            if s < t:
                a, b = s, t
            else:
                a, b = t, s

            if x < a:
                ans = min(ans, b-x)
            elif b < x:
                ans = min(ans, x-a)
            else:
                ans = min(ans, 2*(x-a) + (b-x), (x-a) + 2*(b-x))
    print(ans)

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int, input().split())
sl = []
tl = []
xl = []
for i in range(A):
    sl.append(int(input()))
for i in range(B):
    tl.append(int(input()))
for i in range(Q):
    xl.append(int(input()))
sl.sort()
tl.sort()
def func(i):
    slm = bisect.bisect_right(sl, xl[i])
    try:
        sleft = xl[i] - sl[slm-1]
        assert sleft >= 0
    except:
        sleft = float('inf')
    
    try:
        sright = sl[slm] - xl[i]
    except:
        sright = float('inf')
    
    tlm = bisect.bisect_right(tl, xl[i])
    try:
        tleft = xl[i] - tl[tlm-1]
        assert tleft >= 0
    except:
        tleft = float('inf')
        
    try:
        tright = tl[tlm] - xl[i]
    except:
        tright = float('inf')
    
    ll = max(sleft, tleft)
    lr = sleft + tright + min(sleft, tright)
    rl = sright + tleft + min(sright, tleft)
    rr = max(sright, tright)
    
    print(min(ll, lr, rl, rr))

for i in range(Q):
    func(i)

Submission status: Accepted

Solution code:
import bisect
import sys
input = sys.stdin.readline

a, b, q = map(int, input().split())
s = [int(input()) for _ in range(a)]
t = [int(input()) for _ in range(b)]

INF = float('inf')
for _ in range(q):
    x = int(input())
    if x > s[a-1]:
        sl = x - s[a-1]
        sr = INF
    elif x < s[0]:
        sl = INF
        sr = s[0] - x
    else:
        si = bisect.bisect_right(s, x)
        sl = x - s[si-1]
        sr = s[si] - x

    if x > t[b-1]:
        tl = x - t[b-1]
        tr = INF
    elif x < t[0]:
        tl = INF
        tr = t[0] - x
    else:
        ti = bisect.bisect_right(t, x)
        tl = x - t[ti-1]
        tr = t[ti] - x

    ans = min(max(sl, tl), max(sr, tr))

    ans = min(ans, sr*2+tl)
    ans = min(ans, sr+tl*2)
    ans = min(ans, sl*2+tr)
    ans = min(ans, sl+tr*2)

    print(ans)

Submission status: Accepted

Solution code:
import bisect
A, B, Q = [int(_) for _ in input().split()]
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
X = [int(input()) for _ in range(Q)]
for x in X:
    i_sl = bisect.bisect_left(S, x)
    i_tl = bisect.bisect_left(T, x)
    D_sr = D_sl = D_tl = D_tr = float('inf')
    if i_sl < A:
        D_sl = S[i_sl] - x
    if i_tl < B:
        D_tl = T[i_tl] - x
    if i_sl:
        D_sr = x - S[i_sl - 1]
    if i_tl:
        D_tr = x - T[i_tl - 1]
    print(
        min([
            max(D_sl, D_tl),
            max(D_sr, D_tr),
            min(D_sl, D_tr) + D_tr + D_sl,
            min(D_tl, D_sr) + D_sr + D_tl
        ]))

Submission status: Accepted

Solution code:
def main():
  A, B, Q = list(map(int, input().split()))
  D = []
  q = []
  for i in range(A):
    D.append([int(input()), 1])
  for i in range(B):
    D.append([int(input()), 2])
  for i in range(Q):
    t = int(input())
    D.append([t, 0, i])
    q.append(t)
  
  D.sort()

  x  = [[0, 0, 0, 0] for i in range(Q)] 
  a = 0
  b = 0
  for i in D:
    if i[1] == 1:
      a = i[0]
    elif i[1] == 2:
      b = i[0]
    else:
      x[i[2]][0] = a
      x[i[2]][2] = b
  a = 0
  b = 0
  for i in D[::-1]:
    if i[1] == 1:
      a = i[0]
    elif i[1] == 2:
      b = i[0]
    else:
      x[i[2]][1] = a
      x[i[2]][3] = b
  
  for i in range(Q):
    mi = 1e11
    for j in range(2):
      if x[i][j] == 0:
        continue
      t = abs(q[i] - x[i][j])
      for k in range(2, 4):
        if x[i][k] == 0:
          continue
        tt = t + abs(x[i][j] - x[i][k])
        if tt < mi:
          mi = tt
    for j in range(2, 4):
      if x[i][j] == 0:
        continue
      t = abs(q[i] - x[i][j])
      for k in range(2):
        if x[i][k] == 0:
          continue
        tt = t + abs(x[i][j] - x[i][k])
        if tt < mi:
          mi = tt
    print(mi)
      
main()

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

for i in range(Q):
    x = X[i]
    s_index = bisect.bisect_left(s, x)
    t_index = bisect.bisect_left(t, x)

    if s_index == 0:
        s_left = -float("inf")
    else:
        s_left = s[s_index - 1]
    
    if s_index == A:
        s_right = float("inf")
    else:
        s_right = s[s_index]
        
    if t_index == 0:
        t_left = -float("inf")
    else:
        t_left = t[t_index - 1]

    if t_index == B:
        t_right = float("inf")
    else:
        t_right = t[t_index]

    ans = float("inf")

    if s_index != 0 and t_index != 0:
        ans = x - min(s_left, t_left)

    if s_index != 0 and t_index != B:
        temp = min(x - s_left, t_right - x)
        ans = min(ans, (x - s_left) + (t_right - x) + temp)

    if s_index != A and t_index != 0:
        temp = min(x - t_left, s_right - x)
        ans = min(ans, (x - t_left) + (s_right - x) + temp)

    if t_index != B and s_index != A:
        ans = min(ans, max(s_right, t_right) - x)

    print(ans)

Submission status: Accepted

Solution code:
import bisect
A, B, Q = [int(i) for i in input().split()]
S=list()
T=list()
X=list()
for i in range(A):
    S.append(int(input()))
for i in range(B):
    T.append(int(input()))
for i in range(Q):
    X.append(int(input()))

for Q in X:
    SS=list()
    TT=list()
    i = bisect.bisect_left(S,Q)
    #print(i)
    if i>0:
        SS.append(S[i-1])
    if i<A:
        SS.append(S[i])
    i = bisect.bisect_left(T, Q)
    #print(i)
    if i > 0:
        TT.append(T[i - 1])
    if i<B:
        TT.append(T[i])
    minlen=9999999999999
    #print(SS,TT)
    for i in SS:
        for j in TT:
            len=min(abs(Q-i)+abs(i-j),abs(Q-j)+abs(i-j))
            minlen=min(minlen,len)
    print(minlen)

Submission status: Accepted

Solution code:
from bisect import bisect_left

A, B, Q = map(int, input().split())
s = [int(input()) for _ in range(A)]
t = [int(input()) for _ in range(B)]
x = [int(input()) for _ in range(Q)]

for xx in x:
    # 神先
    ps_r = 0
    s_r = bisect_left(s, xx)
    if s_r < A:
        ps_r += s[s_r] - xx
        t_r = bisect_left(t, s[s_r])
        t_l = t_r - 1

        b = 0
        if t_r < B:
            b = t[t_r] - s[s_r]
        if 0 <= t_l < B:
            if b == 0:
                b = s[s_r] - t[t_l]
            else:
                b = min(b, s[s_r] - t[t_l])
        ps_r += b
    else:
        ps_r = 10 ** 12

    ps_l = 0
    s_l = s_r - 1
    if 0 <= s_l < A:
        ps_l += xx - s[s_l]
        t_r = bisect_left(t, s[s_l])
        t_l = t_r - 1

        b = 0
        if t_r < B:
            b = t[t_r] - s[s_l]
        if 0 <= t_l < B:
            if b == 0:
                b = s[s_l] - t[t_l]
            else:
                b = min(b, s[s_l] - t[t_l])
        ps_l += b
    else:
        ps_l = 10 ** 12

    # 寺前
    pt_r = 0
    t_r = bisect_left(t, xx)
    if t_r < B:
        pt_r += t[t_r] - xx
        s_r = bisect_left(s, t[t_r])
        s_l = s_r - 1

        b = 0
        if s_r < A:
            b = s[s_r] - t[t_r]
        if 0 <= s_l < A:
            if b == 0:
                b = t[t_r] - s[s_l]
            else:
                b = min(b, t[t_r] - s[s_l])
        pt_r += b
    else:
        pt_r = 10 ** 12

    pt_l = 0
    t_l = t_r - 1
    if 0 <= t_l < B:
        pt_l += xx - t[t_l]
        s_r = bisect_left(s, t[t_l])
        s_l = s_r - 1

        b = 0
        if s_r < A:
            b = s[s_r] - t[t_l]
        if 0 <= s_l < A:
            if b == 0:
                b = t[t_l] - s[s_l]
            else:
                b = min(b, t[t_l] - s[s_l])
        pt_l += b
    else:
        pt_l = 10 ** 12

    # print(ps_r, ps_l, pt_r, pt_l)
    print(min(ps_r, ps_l, pt_r, pt_l))

Submission status: Accepted

Solution code:
import bisect as bi
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):
    c = []
    d = []
    x = int(input())
    tmp = bi.bisect_left(s, x)
    if tmp != a : c.append(s[tmp])
    if tmp != 0 : c.append(s[tmp-1])
    tmp = bi.bisect_left(t, x)
    if tmp != b : d.append(t[tmp])
    if tmp != 0 : d.append(t[tmp-1])
    ans = 2**64
    for e in c:
        for f in d:
            g = abs(x-e)
            h = abs(x-f)
            if (x-e)*(x-f) > 0:
                ans = min(ans, max(g, h))
            else:
                if g > h : g,h = h,g
                ans = min(ans, 2*g+h)
    print(ans)

Submission status: Accepted

Solution code:
import bisect

A,B,Q=map(int,input().split())
AA=[int(input()) for x in range(A)]
BB=[int(input()) for y in range(B)]

for i in range(Q):
  p=int(input())
  a=bisect.bisect_left(AA,p)
  b=bisect.bisect_left(BB,p)
  if a!=A and b!=B and a!=0 and b!=0:
    la=abs(AA[a-1]-p)
    ra=abs(AA[a]-p)
    lb=abs(BB[b-1]-p)
    rb=abs(BB[b]-p)
    print(min(max(la,lb),max(ra,rb),min(ra,lb)*2+max(ra,lb),min(la,rb)*2+max(la,rb)))
  else:
    if a!=0:
      la=abs(AA[a-1]-p)
    else:
      la=10**15
    if b!=0:
      lb=abs(BB[b-1]-p)
    else:
      lb=10**15
    if a!=A:
      ra=abs(AA[a]-p)
    else:
      ra=10**15
    if b!=B:
      rb=abs(BB[b]-p)
    else:
      rb=10**15
    print(min(max(la,lb),max(ra,rb),min(ra,lb)*2+max(ra,lb),min(la,rb)*2+max(la,rb)))

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)]
q = [int(input()) for _ in range(q)]
for qi in q:
    qans = 10**18
    ai = bisect_left(s, qi)
    bi = bisect_left(t, qi)
    ac = []
    bc = []
    for i in range(2):
        if (0 <= ai + i < a):
            ac.append(ai + i);
        if (0 <= ai - i < a):
            ac.append(ai - i);
    for i in range(2):
        if (0 <= bi + i < b):
            bc.append(bi + i);
        if (0 <= bi - i < b):
            bc.append(bi - i);
    for i in ac:
        for j in bc:
            aa = s[i];
            bb = t[j];
            if (max(aa, bb) <= qi):
                qans = min(qans, qi - min(aa, bb))
            elif (qi <= min(aa, bb)):
                qans = min(qans, max(aa, bb) - qi)
            else:
                qans = min(qans, min(abs(aa - qi), abs(bb - qi)) * 2 + max(abs(aa - qi), abs(bb - qi)))
    print(qans)

Submission status: Accepted

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


inf = float('inf')

def main():
    A, B, Q = list(map(int, input().split()))
    ls = []
    lt = []
    lx = []
    for _ in range(A):
        ls.append(int(input()))
    for _ in range(B):
        lt.append(int(input()))
    for i in range(Q):
        lx.append((int(input()), i))
    ls.sort()
    lt.sort()
    lx.sort()
    ans = {}
    s = 0
    t = 0
    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] if s > 0 else ls[0]
        s_max = ls[s] if s < A else ls[s-1]
        t_min = lt[t-1] if t > 0 else lt[0]
        t_max = lt[t] if t < B else lt[t-1]
        if s_min > x:
            s_min = -inf
        if t_min > x:
            t_min = -inf
        if s_max < x:
            s_max = inf
        if t_max < x:
            t_max = inf
        assert(t_max > x)
        assert(s_max > x)
        assert(t_min < x)
        assert(s_min < x)
        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:
# D
from bisect import bisect_left
A, B, Q = map(int, input().split())

s_list = [0]*A
t_list = [0]*B
q_list = [0]*Q

for i in range(A):
    s_list[i] = int(input())
for i in range(B):
    t_list[i] = int(input())
for i in range(Q):
    q_list[i] = int(input())
    
def query_dist(q):
    res = 10**11
    # s -> t
    ind_s = bisect_left(s_list, q)
    if ind_s != len(s_list):
        s = s_list[ind_s]
        ind_t = bisect_left(t_list, s)
        if ind_t != len(t_list):
            t = t_list[ind_t]
            res = min(res, abs(s-q)+abs(t-s))
        if ind_t != 0:
            t = t_list[ind_t-1]
            res = min(res, abs(s-q)+abs(t-s))
    if ind_s != 0:
        s = s_list[ind_s-1]
        ind_t = bisect_left(t_list, s)
        if ind_t != len(t_list):
            t = t_list[ind_t]
            res = min(res, abs(s-q)+abs(t-s))
        if ind_t != 0:
            t = t_list[ind_t-1]
            res = min(res, abs(s-q)+abs(t-s))
            
    ind_t = bisect_left(t_list, q)
    if ind_t != len(t_list):
        t = t_list[ind_t]
        ind_s = bisect_left(s_list, t)
        if ind_s != len(s_list):
            s = s_list[ind_s]
            res = min(res, abs(t-q)+abs(s-t))
        if ind_s != 0:
            s = s_list[ind_s-1]
            res = min(res, abs(t-q)+abs(s-t))
    if ind_t != 0:
        t = t_list[ind_t-1]
        ind_s = bisect_left(s_list, t)
        if ind_s != len(s_list):
            s = s_list[ind_s]
            res = min(res, abs(t-q)+abs(s-t))
        if ind_s != 0:
            s = s_list[ind_s-1]
            res = min(res, abs(t-q)+abs(s-t))
    return res

for q in q_list:
    print(query_dist(q))

Submission status: Accepted

Solution code:
import bisect

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

TERA=[]
JINJA=[]
for _ in range(A):
  TERA.append(int(input()))
for _ in range(B):
  JINJA.append(int(input()))
  
TERAJINJAlist=[]
TJlist=[]

JINJAcount=0
for i in range(A):
  while(True):
    if JINJAcount==B-1 or abs(TERA[i]-JINJA[JINJAcount])<abs(TERA[i]-JINJA[JINJAcount+1]):
      break
    JINJAcount+=1
  TERAJINJAlist.append([TERA[i],JINJA[JINJAcount]])
  TJlist.append(TERA[i])
TERAcount=0
for i in range(B):
  while(True):
    if TERAcount==A-1 or abs(JINJA[i]-TERA[TERAcount])<abs(JINJA[i]-TERA[TERAcount+1]):
      break
    TERAcount+=1
  TERAJINJAlist.append([JINJA[i],TERA[TERAcount]])
  TJlist.append(JINJA[i])
TERAJINJAlist.sort()
TJlist.sort()

#print(TERAJINJAlist)
length=len(TJlist)
for i in range(Q):
  x=int(input())
  ind=bisect.bisect_left(TJlist,x)
  #print(ind)
  if ind==0:
    print(TERAJINJAlist[ind][0]-x+abs(TERAJINJAlist[ind][1]-TERAJINJAlist[ind][0]))
  elif ind==length:
    print(x-TERAJINJAlist[ind-1][0]+abs(TERAJINJAlist[ind-1][1]-TERAJINJAlist[ind-1][0]))
  else:
    left=abs(x-TERAJINJAlist[ind-1][0])+abs(TERAJINJAlist[ind-1][1]-TERAJINJAlist[ind-1][0])
    right=abs(x-TERAJINJAlist[ind][0])+abs(TERAJINJAlist[ind][1]-TERAJINJAlist[ind][0])
    print(min(left,right))

Submission status: Accepted

Solution code:
import bisect
inf=10**20+10

def slove(ss,tt):
    if ss*tt<0:
        return min(abs(ss),abs(tt))*2+max(abs(ss),abs(tt))
    else:
        return max(abs(ss),abs(tt))

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

s.sort()
t.sort()
s.append(inf)
t.append(inf)

for xx in x:
    s_in=bisect.bisect_left(s,xx)
    t_in=bisect.bisect_left(t,xx)
    sl,sr=s[s_in-1]-xx,s[s_in]-xx
    tl,tr=t[t_in-1]-xx,t[t_in]-xx
    ans=inf
    ans=min(slove(sl,tl),slove(sl,tr),slove(sr,tl),slove(sr,tr))
    print(ans)

Submission status: Accepted

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

for _ in range(Q):
    x = int(input())
    a = bisect.bisect_left(S, x)
    b = bisect.bisect_left(T, x)
    print(min(x - min(S[a-1], T[b-1]), max(S[a], T[b]) - x, x+T[b]-2*S[a-1], x+S[a]-2*T[b-1], 2*T[b]-x-S[a-1], 2*S[a]-x-T[b-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 j in range(b):
    t.append(int(input()))

def main(s,t,xi):
    sidx=bisect.bisect_left(s,xi)
    if sidx==0:
        shidari=10**11
        smigi=s[sidx]-xi
    elif sidx==len(s):
        shidari=xi-s[sidx-1]
        smigi=10**11
    elif s[sidx]==xi:
        shidari=0
        smigi=0
    else:
        shidari=xi-s[sidx-1]
        smigi=s[sidx]-xi
    tidx=bisect.bisect_left(t,xi)
    if tidx==0:
        thidari=10**11
        tmigi=t[tidx]-xi
    elif tidx==len(t):
        thidari=xi-t[tidx-1]
        tmigi=10**11
    elif t[tidx]==xi:
        thidari=0
        tmigi=0
    else:
        thidari=xi-t[tidx-1]
        tmigi=t[tidx]-xi
    k=min(2*shidari+tmigi,2*tmigi+shidari,2*smigi+thidari,2*thidari+smigi)
    return min(max(thidari,shidari),max(tmigi,smigi),k)
for k in range(q):
    print(main(s,t,int(input())))

Submission status: Accepted

Solution code:
from bisect 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)]
qs = [int(input()) for i in range(Q)]

st = []
for s in S:
    ti = bisect(T,s)
    if ti == 0:
        st.append(abs(s-T[0]))
    elif ti == B:
        st.append(abs(s-T[-1]))
    else:
        tmp = min(abs(s-T[ti-1]), abs(s-T[ti]))
        st.append(tmp)

ts = []
for t in T:
    si = bisect(S,t)
    if si == 0:
        ts.append(abs(t-S[0]))
    elif si == A:
        ts.append(abs(t-S[-1]))
    else:
        tmp = min(abs(t-S[si-1]), abs(t-S[si]))
        ts.append(tmp)

ans = []
for q in qs:
    si = bisect(S,q)
    if si == 0:
        a = abs(q-S[0]) + st[0]
    elif si == A:
        a = abs(q-S[-1]) + st[-1]
    else:
        a = min(abs(q-S[si-1]) + st[si-1], abs(q-S[si]) + st[si])

    ti = bisect(T,q)
    if ti == 0:
        b = abs(q-T[0]) + ts[0]
    elif ti == B:
        b = abs(q-T[-1]) + ts[-1]
    else:
        b = min(abs(q-T[ti-1]) + ts[ti-1], abs(q-T[ti]) + ts[ti])

    ans.append(min(a,b))

print(*ans, sep='\n')

Submission status: Accepted

Solution code:
#119-D
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(input())
def S(): return input()
import bisect
a,b,q=IL()
s=[]
t=[]
for i in range(a):
    tmp=I()
    s.append(tmp)
for i in range(b):
    tmp=I()
    t.append(tmp)
inf=10**15
for i in range(q):
    rs,ls,rt,lt=inf,inf,inf,inf
    x=I()
    ts=bisect.bisect(s,x)
    tt=bisect.bisect(t,x)
    if ts!=0:
        ls=abs(x-s[ts-1])
    if tt!=0:
        lt=abs(x-t[tt-1])
    if ts!=a:
        rs=abs(s[ts]-x)
    if tt!=b:
        rt=abs(t[tt]-x)
    print(min(min(rs,lt)*2+max(rs,lt),min(rt,ls)*2+max(rt,ls),max(lt,ls),max(rt,rs)))