Problem:


Score : 400 points

Problem Statement

Along a road running in an east-west direction, there are A shrines and B temples.
The i-th shrine from the west is located at a distance of s_i meters from the west end of the road, and the i-th temple from the west is located at a distance of t_i meters from the west end of the road.

Answer the following Q queries:

Query i (1 \leq i \leq Q): If we start from a point at a distance of x_i meters from the west end of the road and freely travel along the road, what is the minimum distance that needs to be traveled in order to visit one shrine and one temple? (It is allowed to pass by more shrines and temples than required.)

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

1 \leq s_1 < s_2 < ... < s_A \leq 10^{10}

1 \leq t_1 < t_2 < ... < t_B \leq 10^{10}

1 \leq x_i \leq 10^{10}

s_1, ..., s_A, t_1, ..., t_B, x_1, ..., x_Q are all different.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

A B Q
s_1
:
s_A
t_1
:
t_B
x_1
:
x_Q

Output

Print Q lines. The i-th line should contain the answer to the i-th query.

Sample Input 1

2 3 4
100
600
400
900
1000
150
2000
899
799

Sample Output 1

350
1400
301
399

There are two shrines and three temples. The shrines are located at distances of 100, 600 meters from the west end of the road, and the temples are located at distances of 400, 900, 1000 meters from the west end of the road.

Query 1: If we start from a point at a distance of 150 meters from the west end of the road, the optimal move is first to walk 50 meters west to visit a shrine, then to walk 300 meters east to visit a temple.

Query 2: If we start from a point at a distance of 2000 meters from the west end of the road, the optimal move is first to walk 1000 meters west to visit a temple, then to walk 400 meters west to visit a shrine. We will pass by another temple on the way, but it is fine.

Query 3: If we start from a point at a distance of 899 meters from the west end of the road, the optimal move is first to walk 1 meter east to visit a temple, then to walk 300 meters west to visit a shrine.

Query 4: If we start from a point at a distance of 799 meters from the west end of the road, the optimal move is first to walk 199 meters west to visit a shrine, then to walk 200 meters west to visit a temple.

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

The road is quite long, and we may need to travel a distance that does not fit into a 32-bit integer.



Sample input:
2 3 4
100
600
400
900
1000
150
2000
899
799


Sample output:
350
1400
301
399

Submission status: Accepted

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

import sys
from bisect import bisect_left, bisect_right

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 18
MOD = 10 ** 9 + 7

N, M, Q = MAP()
A = [0] * N
for i in range(N):
    A[i] = INT()
B = [0] * M
for i in range(M):
    B[i] = INT()

A.sort()
B.sort()
A = [-INF] + A + [INF]
B = [-INF] + B + [INF]

for i in range(Q):
    q = INT()
    
    # q以下で最大
    al = bisect_right(A, q) - 1
    bl = bisect_right(B, q) - 1
    # q以上で最小
    ar = bisect_left(A, q)
    br = bisect_left(B, q)

    # 両方左
    a = max(q-A[al], q-B[bl])
    # 両方右
    b = max(A[ar]-q, B[br]-q)
    # 左の神社、右の寺
    c = min(q-A[al], B[br]-q) * 2 + max(q-A[al], B[br]-q)
    # 右の神社、左の寺
    d = min(A[ar]-q, q-B[bl]) * 2 + max(A[ar]-q, q-B[bl])

    ans = min(a, b, c, d)
    print(ans)

Submission status: Accepted

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

# In[2]:


import bisect


# In[ ]:


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


# In[ ]:


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


# In[6]:


# A = 2
# B = 3
# Q = 4
# s = [100, 600]
# t = [400, 900, 1000]
# x = [150, 2000, 899, 799]


# In[13]:


def func(i, j):
    ans = []
    if i != 0 and j != 0:
        ans.append(max(y - s[i - 1], y - t[j - 1]))
    if i != len(s) and j != len(t):
        ans.append(max(s[i] - y, t[j] - y))
    if i != 0 and j != len(t):
        ans.append(2*(y-s[i-1]) + (t[j]-y))
        ans.append(2*(t[j]-y) + (y-s[i-1]))
    if i != len(s) and j != 0:
        ans.append(2*(y-t[j-1]) + (s[i]-y))
        ans.append(2*(s[i]-y) + (y-t[j-1]))
    return min(ans)


# In[15]:


ans = []
for y in x:
    i = bisect.bisect_left(s, y)
    j = bisect.bisect_left(t, y)
    ans.append(func(i, j))
print('\n'.join(map(str,ans)))


# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:





# In[ ]:

Submission status: Accepted

Solution code:
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]

def doit(st, x):
    lo, hi = 0, len(st) - 1
    while hi - lo > 1:
        mid = (lo + hi) // 2
        if st[mid] < x:
            lo = mid
        else:
            hi = mid
    mid = (lo + hi) // 2
    return st[mid], st[mid + 1]

for _ in range(q):
    x = int(input())
    s12 = doit(s, x)
    t12 = doit(t, x)
    print(min(min(abs(s1 - x) + abs(t1 - s1), abs(t1 - x) + abs(s1 - t1)) for s1 in s12 for t1 in t12))

Submission status: Accepted

Solution code:
def binarySearch(a, val):
    left, right = -1, len(a)
    while left + 1 < right:
        mid = (left + right) >> 1
        if a[mid] < val:
            left = mid
        else:
            right = mid
    return a[right] if right < len(a) else 1 << 35

def binarySearch2(a, val):
    left, right = -1, len(a)
    while left + 1 < right:
        mid = (left + right) >> 1
        if a[mid] <= val:
            left = mid
        else:
            right = mid
    return a[left] if left >= 0 else -(1 << 35)

nShrines, nTemples, nQueries = map(int, input().split())
shrines = [int(input()) for _ in range(nShrines)]
temples = [int(input()) for _ in range(nTemples)]
starts = [int(input()) for _ in range(nQueries)]
ret = []
for start in starts:
    shrineToRight = binarySearch(shrines, start)
    templeToRight = binarySearch(temples, start)
    shrineToLeft = binarySearch2(shrines, start)
    templeToLeft = binarySearch2(temples, start)
    ret.append(min(
        max(shrineToRight, templeToRight) - start,
        start - min(shrineToLeft, templeToLeft),
        templeToRight - start + templeToRight - shrineToLeft,
        shrineToRight - start + shrineToRight - templeToLeft,
        start - shrineToLeft + templeToRight - shrineToLeft,
        start - templeToLeft + shrineToRight - templeToLeft
    ))
print('\n'.join(map(str, ret)))

Submission status: Accepted

Solution code:
import sys
import bisect
_input = sys.stdin.readlines()
a, b, q = [int(i) for i in _input[0].split()]
data = [int(i) for i in _input[1:]]
s_ls = data[:a]
t_ls = data[a:a+b]
x_ls = data[-q:]
INF = 10 ** 18

for x in x_ls:
    s_ind = min(bisect.bisect_left(s_ls, x), a-1)
    t_ind = min(bisect.bisect_left(t_ls, x), b-1)
    best = INF
    for _s in [-1, 0]:
        if s_ind == 0 and _s == -1:
            continue
        for _t in [-1, 0]:
            if t_ind == 0 and _t == -1:
                continue
            s = s_ls[s_ind + _s]
            t = t_ls[t_ind + _t]
            if (s - x) * (t - x) >= 0:
                dis = max(abs(t - x), abs(s - x))
            else:
                dis = min(abs(t - x), abs(s - x)) * 2 + max(abs(t - x), abs(s - x))
            best = min(dis, best)
    print(best)

Submission status: Accepted

Solution code:
import sys
import bisect
a, b, q = [int(i) for i in sys.stdin.readline().split()]
s_ls = []
t_ls = []
INF = 10 ** 18
for i in range(a):
    s = int(input())
    s_ls.append(s)
for i in range(b):
    t = int(input())
    t_ls.append(t)

for i in range(q):
    x = int(input())
    s_ind = min(bisect.bisect_left(s_ls, x), a-1)
    t_ind = min(bisect.bisect_left(t_ls, x), b-1)
    best = INF
    for _s in [-1, 0]:
        if s_ind == 0 and _s == -1:
            continue
        for _t in [-1, 0]:
            if t_ind == 0 and _t == -1:
                continue
            s = s_ls[s_ind + _s]
            t = t_ls[t_ind + _t]
            if (s - x) * (t - x) >= 0:
                dis = max(abs(t - x), abs(s - x))
            else:
                dis = min(abs(t - x), abs(s - x)) * 2 + max(abs(t - x), abs(s - x))
            best = min(dis, best)
    print(best)

Submission status: Accepted

Solution code:
def main():
    from bisect import bisect_left
    import sys

    input = sys.stdin.readline
    inf = (10 ** 10) * 2 + 10

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

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

        si = bisect_left(s, x) - 1
        ti = bisect_left(t, x) - 1

        ret = inf
        for sx in s[si:si + 2]:
            for tx in t[ti:ti + 2]:
                ret = min(ret, min(abs(x - sx), abs(x - tx)) + abs(sx - tx))
        print(ret)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_left

inf = (10 ** 10) * 2 + 10

a, b, q = map(int, input().split())

s = [-inf]
for _ in range(a):
    s.append(int(input()))
s.append(inf)
s.sort()

t = [-inf]
for _ in range(b):
    t.append(int(input()))
t.append(inf)
t.sort()

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

    si = bisect_left(s, x) - 1
    ti = bisect_left(t, x) - 1

    ret = inf
    for sx in s[si:si + 2]:
        for tx in t[ti:ti + 2]:
            ret = min(ret, min(abs(x - sx), abs(x - tx)) + abs(sx - tx))
    print(ret)

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int, input().split())
INF = 10 ** 18
s = [-INF] + [int(input()) for i in range(A)] + [INF]
t = [-INF] + [int(input()) for i in range(B)] + [INF]

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

Submission status: Accepted

Solution code:
import math
import collections
import itertools
import sys
import bisect
from heapq import heappop,heappush,heapify
sys.setrecursionlimit(10**6)
def MAP(): return list(map(int,input().split()))
def INT(): return int(input())
def FLOAT(): return float(input())
MOD = 10**9+7
INF = 10**18

A,B,Q = MAP()
s = [-INF] + [INT() for _ in range(A)] + [INF]
t = [-INF] + [INT() for _ in range(B)] + [INF]

for i in range(Q):
    cur = INT()
    s_idx = bisect.bisect_right(s,cur)
    t_idx = bisect.bisect_right(t,cur)
    res = INF
    for S in [s[s_idx-1],s[s_idx]]:
        for T in [t[t_idx-1],t[t_idx]]:
            d1,d2 = abs(S-cur) + abs(T-S),abs(T-cur)+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 i in range(A)]
T=[int(input()) for i in range(B)]
X=[int(input()) for i in range(Q)]

def search(x):
    s=bisect.bisect_right(S,x)
    t=bisect.bisect_right(T,x)
    bs1=max(s-1,0)
    bt1=max(t-1,0)
    bs2=min(s,A-1)
    bt2=min(t,B-1)
    r1=abs(S[bs1]-x)+abs(S[bs1]-T[bt1])
    r2=abs(S[bs1]-x)+abs(S[bs1]-T[bt2])
    r3=abs(S[bs2]-x)+abs(S[bs2]-T[bt1])
    r4=abs(S[bs2]-x)+abs(S[bs2]-T[bt2])
    r5=abs(T[bt1]-x)+abs(T[bt1]-S[bs1])
    r6=abs(T[bt1]-x)+abs(T[bt1]-S[bs2])
    r7=abs(T[bt2]-x)+abs(T[bt2]-S[bs1])
    r8=abs(T[bt2]-x)+abs(T[bt2]-S[bs2])
    r=min([r1,r2,r3,r4,r5,r6,r7,r8])
    return r

for i in X:
    print(search(i))

Submission status: Accepted

Solution code:

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

import bisect

for x in X:
    ans = 10**12
    tmpans1 = 0
    pos1 = bisect.bisect_left(S,x)
    if pos1==0:
        tmpans1 += abs(S[pos1]-x)
        p = bisect.bisect_left(T,S[pos1])
        tmpans1 += min(abs(S[pos1]-T[min(p,B-1)]),abs(S[pos1]-T[max(0,p-1)]))
        ans = min(ans,tmpans1)
    elif pos1==A:
        pos1 -= 1
        tmpans1 += abs(x-S[pos1])
        p = bisect.bisect_left(T,S[pos1])
        tmpans1 += min(abs(S[pos1]-T[min(p,B-1)]),abs(S[pos1]-T[max(0,p-1)]))
        ans = min(ans,tmpans1)
    else:
        tmpans1 += abs(S[pos1]-x)
        p = bisect.bisect_left(T,S[pos1])
        tmpans1 += min(abs(S[pos1]-T[min(p,B-1)]),abs(S[pos1]-T[max(0,p-1)]))
        ans = min(ans,tmpans1)
        tmpans1 = 0
        pos1 -= 1
        tmpans1 += abs(x-S[pos1])
        p = bisect.bisect_left(T,S[pos1])
        tmpans1 += min(abs(S[pos1]-T[min(p,B-1)]),abs(S[pos1]-T[max(0,p-1)]))
        ans = min(ans,tmpans1)
    
    tmpans1 = 0
    pos1 = bisect.bisect_left(T,x)
    if pos1==0:
        tmpans1 += abs(T[pos1]-x)
        p = bisect.bisect_left(S,T[pos1])
        tmpans1 += min(abs(T[pos1]-S[min(p,A-1)]),abs(T[pos1]-S[max(0,p-1)]))
        ans = min(ans,tmpans1)
    elif pos1==B:
        pos1 -= 1
        tmpans1 += abs(T[pos1]-x)
        p = bisect.bisect_left(S,T[pos1])
        tmpans1 += min(abs(T[pos1]-S[min(p,A-1)]),abs(T[pos1]-S[max(0,p-1)]))
        ans = min(ans,tmpans1)
    else:
        tmpans1 += abs(T[pos1]-x)
        p = bisect.bisect_left(S,T[pos1])
        tmpans1 += min(abs(T[pos1]-S[min(p,A-1)]),abs(T[pos1]-S[max(0,p-1)]))
        ans = min(ans,tmpans1)
        tmpans1 = 0
        pos1 -= 1
        tmpans1 += abs(T[pos1]-x)
        p = bisect.bisect_left(S,T[pos1])
        tmpans1 += min(abs(T[pos1]-S[min(p,A-1)]),abs(T[pos1]-S[max(0,p-1)]))
        ans = min(ans,tmpans1)
    
    print(ans)

Submission status: Accepted

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

A,B,Q = map(int,input().split())
jinjya = [-float('inf')]+[int(input()) for _ in range(A)]+[float('inf')]#範囲を絞るために両サイドに0と無限を挿入
tera =[-float('inf')]+[int(input()) for _ in range(B)]+[float('inf')]

for i in range(Q):
  x=int(input())
#出発地点の前後の神社と寺の場所を知りたい。つまり出発点より前にある対象のインデックス
  L=0
  R=A+2
  while R-L>1:
    P=(L+R)//2
    if x<jinjya[P]:
      R=P
    else:
      L=P
  jinjya_L=L
  
  L=0
  R=B+2
  while R-L>1:
    P=(L+R)//2
    if x<tera[P]:
      R=P
    else:
      L=P
  tera_L=L
#xの左側の神社と寺のインデックスがわかったのでそれらに対して距離を測って最小を探す。
  a=jinjya[jinjya_L]
  b=jinjya[jinjya_L+1]
  c=tera[tera_L]
  d=tera[tera_L+1]
  if jinjya_L==0:
    a=b
  if tera_L==0:
    c=d
  answer=min(abs(x-a)+abs(a-c),abs(x-c)+abs(c-a),abs(x-b)+abs(b-c),abs(x-c)+abs(c-b),abs(x-a)+abs(a-d),abs(x-d)+abs(d-a),abs(x-b)+abs(b-d),abs(x-d)+abs(d-b))
  print(answer)

Submission status: Accepted

Solution code:
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)]

from bisect import bisect_left
for i in range(len(x)):
    idx1 = bisect_left(s, x[i])
    idx2 = bisect_left(t, x[i])

    cands = [[], []]
    if idx1 != 0 and idx1 != len(s):
        cands[0].append(s[idx1 - 1])
        cands[0].append(s[idx1])
    elif idx1 == 0:
        cands[0].append(-float('inf'))
        cands[0].append(s[idx1])
    elif idx1 == len(s):
        cands[0].append(s[idx1 - 1])
        cands[0].append(float('inf'))
    if idx2 != 0 and idx2 != len(t):
        cands[1].append(t[idx2 - 1])
        cands[1].append(t[idx2])
    elif idx2 == 0:
        cands[1].append(-float('inf'))
        cands[1].append(t[idx2])
    elif idx2 == len(t):
        cands[1].append(t[idx2 - 1])
        cands[1].append(float('inf'))

    # print(cands, x[i])
    print(min(x[i] - min([cands[0][0], cands[1][0]]),
              max([cands[0][1], cands[1][1]]) - x[i],
              (x[i] - cands[1][0]) * 2 + (cands[0][1] - x[i]),
              (x[i] - cands[1][0]) + (cands[0][1] - x[i]) * 2,
              (x[i] - cands[0][0]) * 2 + (cands[1][1] - x[i]),
              (x[i] - cands[0][0]) + (cands[1][1] - x[i]) * 2))

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

def distance(t, s, x):
    dis = abs(t-s) + min(abs(t-x), abs(s-x))
    return dis

def near_search(x, L):
    temp = bisect.bisect_left(L, x)
    if temp == len(L):
        can_f = L[-1]
        can_s = L[-1]
    elif temp == 0:
        can_f = L[0]
        can_s = L[0]
    else:
        can_f = L[temp-1]
        can_s = L[temp]
    return can_f, can_s

for x in X:
    s_f, s_s = near_search(x, S)
    t_f, t_s = near_search(x, T)
    total = min(distance(t_f, s_f, x), distance(t_s, s_f, x), distance(t_f, s_s, x), distance(t_s, s_s, x))
    print(total)

Submission status: Accepted

Solution code:
import sys
import bisect


def solve():
    input = sys.stdin.readline
    mod = 10 ** 9 + 7
    a, b, q = list(map(int, input().rstrip('\n').split()))
    s = [int(input().rstrip('\n')) for _ in range(a)]
    t = [int(input().rstrip('\n')) for _ in range(b)]
    x = [int(input().rstrip('\n')) for _ in range(q)]
    for xv in x:
        ps = bisect.bisect_left(s, xv)
        pt = bisect.bisect_left(t, xv)
        sl = []
        if ps == 0:
            sl.append(s[0])
        elif ps == a:
            sl.append(s[-1])
        else:
            sl.append(s[ps-1])
            sl.append(s[ps])
        tl = []
        if pt == 0:
            tl.append(t[0])
        elif pt == b:
            tl.append(t[-1])
        else:
            tl.append(t[pt-1])
            tl.append(t[pt])
        mt = 10 ** 20
        for sv in sl:
            for tv in tl:
                if xv <= sv and xv <= tv:
                    mt = min(mt, abs(max(sv, tv) - xv))
                elif sv <= xv and tv <= xv:
                    mt = min(mt, abs(min(sv, tv) - xv))
                else:
                    mt = min(mt, min(abs(sv - xv), abs(tv - xv)) + abs(tv - sv))
        print(mt)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
import bisect


a,b,q = [int(_) for _ in input().split()]
s_l = [-float('inf')]
t_l = [-float('inf')]
x_l = []
for i in range(a):
    s_l.append(int(input()))
s_l.append(float('inf'))
for i in range(b):
    t_l.append(int(input()))
t_l.append(float('inf'))
for i in range(q):
    x_l.append(int(input()))
for i in range(q):
    x = x_l[i]
    s1_id = bisect.bisect_left(s_l, x) - 1 
    s2_id = s1_id + 1
    s1 = s_l[s1_id]
    s2 = s_l[s2_id]
    t1_id = bisect.bisect_left(t_l, x) - 1 
    t2_id = t1_id + 1
    t1 = t_l[t1_id]
    t2 = t_l[t2_id]
    res = float('inf')
    for s in [s1,s2]:
        for t in [t1,t2]:
            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:
#ABC119 D - Lazy Faith
from bisect import bisect_left,bisect_right
si = lambda: input()
ni = lambda: int(input())
nm = lambda: map(int, input().split())
nl = lambda: list(map(int, input().split()))

a,b,q = map(int, input().split())
INF = 10**11
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 i in range(q):
    idx_s = bisect_right(S,X[i])
    idx_t = bisect_right(T,X[i])
    ans = INF
    for s in [S[idx_s-1],S[idx_s]]:
        for t in [T[idx_t-1],T[idx_t]]:
            d1,d2 = abs(s-X[i])+abs(s-t),abs(t-X[i])+abs(t-s)
            ans = min(ans,d1,d2)
    print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
from bisect import bisect_left

def solve(A: int, B: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):
    for qi in range(Q):
        start = x[qi]
        nearest_s = bisect_left(s,start)
        nearest_t = bisect_left(t,start)

        left_s = s[nearest_s-1] if nearest_s != 0 else -10**12
        right_s = s[nearest_s] if nearest_s != A else 10**12
        left_t = t[nearest_t-1] if nearest_t != 0 else -10**12
        right_t = t[nearest_t] if nearest_t != B else 10**12
                
        leftleftdist = start - min(left_s,left_t) 
        rightrightdist = max(right_s,right_t)-start 
        leftrightdist = min(start-left_s+right_t-left_s, start-left_t+right_s-left_t)
        rightleftdist = min(right_t-start+right_t-left_s, right_s-start+right_s-left_t)
        answer = min(leftleftdist,rightrightdist,rightleftdist,leftrightdist)
    
        print(answer)
    return

def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    s = [int(next(tokens)) for _ in range(A)]  # type: "List[int]"
    t = [int(next(tokens)) for _ in range(B)]  # type: "List[int]"
    x = [int(next(tokens)) for _ in range(Q)]  # type: "List[int]"
    solve(A, B, Q, s, t, x)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_left
INF = 10**11

a,b,q = map(int,input().split())
ss = [int(input()) for _ in range(a)] 
tt = [int(input()) for _ in range(b)] 
xx = [int(input()) for _ in range(q)] 

ss = sorted(ss)
tt = sorted(tt)

for x in xx:
  left,middle,right = INF,INF,INF
  sp = bisect_left(ss,x)
  tp = bisect_left(tt,x)
  
  l_sp, r_sp = INF, INF
  l_tp, r_tp = INF, INF
      
  if 0 < sp:
    l_sp = sp - 1
  if 0 < tp:
    l_tp = tp - 1
  if sp < a:
    r_sp = sp
  if tp < b:
    r_tp = tp
    
  
  
  left,right,middle_ts, middle_st = INF,INF,INF,INF
  
  if (l_sp != INF) and (l_tp != INF):
    left = abs(x - min(ss[l_sp],tt[l_tp]))    

  if (r_sp != INF) and (r_tp != INF):
    right = abs(max(ss[r_sp],tt[r_tp]) - x)      

  if (l_tp != INF) and (r_sp != INF):
    middle_ts = min(abs(tt[l_tp] - x), abs(ss[r_sp] - x)) + ss[r_sp] - tt[l_tp]
  
  if (l_sp != INF) and (r_tp != INF):
    middle_st = min(abs(ss[l_sp] - x), abs(tt[r_tp] - x)) + tt[r_tp] - ss[l_sp]
    
  print(min(left,right,middle_ts,middle_st))

Submission status: Accepted

Solution code:
a,b,q = list(map(int, input().split()))

s = [0]*a
t = [0]*b
x = [0]*q
for i in range(a):
    s[i] = int(input())
for i in range(b):
    t[i] = int(input())
for i in range(q):
    x[i] = int(input())
s.sort()
t.sort()

INT_MAX = 10**11

#print(s)
#print(t)
import bisect
def func(xi):
    i = bisect.bisect_left(s,xi)
    s_right = INT_MAX
    if i < len(s):
        s_right = s[i] - xi
    s_left = INT_MAX
    if i != 0:
        s_left = xi - s[i-1]
    j = bisect.bisect_left(t,xi)
    t_right = INT_MAX
    if j < len(t):
        t_right = t[j] - xi
    t_left = INT_MAX
    if j != 0:
        t_left = xi - t[j-1]
    #print(i,j,xi)
    #print(s_left,s_right,t_left,t_right)
    return min(max(s_right,t_right), max(s_left,t_left), min(s_left,t_right)*2+max(s_left,t_right), min(s_right,t_left)*2+max(s_right,t_left))

ans = map(func, x)
print("\n".join(map(str,ans)))

Submission status: Accepted

Solution code:
#lazy faith
import sys
input=sys.stdin.readline
import bisect
a,b,q=map(int,input().split())
A=[]
lists1=[int(input()) for i in range(a)]
lists2=[int(input())for i in range(b)]
lists1.insert(0,-10**12)
lists1.insert(1,-10**11)
lists2.insert(0,-10**12)
lists2.insert(1,-10**11)                  
lists1.append(10**11)
lists1.append(10**12)
lists2.append(10**11)
lists2.append(10**12)
for i in range(q):
    x=int(input())
    index1=bisect.bisect_right(lists1,x)
    index2=bisect.bisect_right(lists2,x)
    dis1=[]
    dis2=[]
    dis1.append(lists1[index1-2])
    dis1.append(lists1[index1-1])
    dis1.append(lists1[index1])
    dis1.append(lists1[index1+1])
    dis2.append(lists2[index2-2])
    dis2.append(lists2[index2-1])
    dis2.append(lists2[index2])
    dis2.append(lists2[index2+1])
    distance=[]
    x1=abs(x-dis1[1])
    mini1=10**12
    for i in range(4):
        mini1=min(mini1,abs(dis1[1]-dis2[i]))
    x2=abs(x-dis1[2])
    mini2=10**12
    for i in range(4):
        mini2=min(mini2,abs(dis1[2]-dis2[i]))
    x3=abs(x-dis2[1])
    mini3=10**12
    for i in range(4):
        mini3=min(mini3,abs(dis2[1]-dis1[i]))
    x4=abs(x-dis2[2])
    mini4=10**12
    for i in range(4):
        mini4=min(mini4,abs(dis2[2]-dis1[i]))
    A.append(min(x1+mini1,x2+mini2,x3+mini3,x4+mini4))
for k in A:
    print(k)

Submission status: Accepted

Solution code:
import bisect
a,b,q=map(int,input().split())
ls=[-10**11]
lg=[-10**11]
for i in range(a):
  ls.append(int(input()))
for i in range(b):
  lg.append(int(input()))
ls.append(10**11)
lg.append(10**11)
ls=sorted(ls)
lg=sorted(lg)
for i in range(q):
  x=int(input())
  i1=bisect.bisect_left(ls,x)
  i2=bisect.bisect_left(lg,x)#xはi-1~iにある
  l1=[i1-1,i1]
  l2=[i2-1,i2]
  ans1=10**12
  ans2=10**12
  for k in l1:
    for j in l2:
      ans3=abs(x-ls[k])+abs(ls[k]-lg[j])
      if ans3<ans1:
        ans1=ans3
      ans4=abs(x-lg[j])+abs(ls[k]-lg[j])
      if ans4<ans2:
        ans2=ans4
  print(min(ans1,ans2))

Submission status: Accepted

Solution code:
import bisect
a,b,q=map(int,input().split())
ls=[-10**11]
lg=[-10**11]
for i in range(a):
  ls.append(int(input()))
for i in range(b):
  lg.append(int(input()))
ls.append(10**11)
lg.append(10**11)
ls=sorted(ls)
lg=sorted(lg)
for i in range(q):
  x=int(input())
  i1=bisect.bisect_left(ls,x)
  i2=bisect.bisect_left(lg,x)#xはi-1~iにある
  d1=x-ls[i1-1]
  d2=ls[i1]-x
  d3=x-lg[i2-1]
  d4=lg[i2]-x
  d5=abs(ls[i1-1]-lg[i2-1])
  d6=abs(ls[i1]-lg[i2-1])
  d7=abs(ls[i1-1]-lg[i2])
  d8=abs(ls[i1]-lg[i2])
  ans1=d1+d5
  ans2=d1+d7
  ans3=d2+d6
  ans4=d2+d8
  ans5=d3+d5
  ans6=d3+d6
  ans7=d4+d7
  ans8=d4+d8
  print(min(ans1,ans2,ans3,ans4,ans5,ans6,ans7,ans8))

Submission status: Accepted

Solution code:
import bisect
from sys import stdin
A,B,Q = [int(x) for x in stdin.readline().rstrip().split()]
INF = 10**18
s = [-INF] + [int(input()) for _ in range(A)] + [INF]
t = [-INF] + [int(input()) for _ in range(B)] + [INF]
for _ in range(Q):
    x = int(stdin.readline().rstrip())
    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]]:
            d1 = abs(S-x) + abs(T-S)
            d2 = abs(T-x) + abs(S-T)
            ans = min(ans,d1,d2)
    print(ans)

Submission status: Accepted

Solution code:
import bisect
a,b,q=map(int,input().split())
ff=float("inf")
s=[-ff]
t=[-ff]
for i in range(a):
    v=int(input())
    s.append(v)
for i in range(b):
    w=int(input())
    t.append(w)
s.append(ff)
t.append(ff)
s.sort()
t.sort()
for i in range(q):
    x=int(input())
    a=bisect.bisect_right(s,x)
    b=bisect.bisect_right(t,x)
    res=ff
    for y in [s[a],s[a-1]]:
        for w in [t[b],t[b-1]]:
            d1,d2=abs(y-x)+abs(w-y),abs(w-x)+abs(w-y)
            res=min(res,d1,d2)
    print(res)

Submission status: Accepted

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

def kai(x):
    res = INF
    s1 = bisect.bisect_right(s,x)
    ls = [s1,s1 - 1]
    t1 = bisect.bisect_right(t,x)
    lt = [t1,t1 - 1]
    for ss in ls:
        for st in lt:
            res = min(res,abs(x-s[ss])+abs(s[ss]-t[st]),abs(x-t[st])+abs(s[ss]-t[st]))
    return res

lx = [int(input()) for _ in range(q)]
for x in lx:
    print(kai(x))

Submission status: Accepted

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

INF = float('INF')

A, B, Q = map(int, readline().split())
stx = list(map(int, read().split()))
S = [-INF] + stx[:A] + [INF]
T = [-INF] + stx[A:-Q] + [INF]
X = stx[-Q:]

for x in X:
    S_idx = bisect.bisect_left(S, x)
    T_idx = bisect.bisect_left(T, x)

    s_left, s_right = S[S_idx-1], S[S_idx]
    t_left, t_right = T[T_idx-1], T[T_idx]
    pathA = x - min(s_left, t_left)
    pathB = max(s_right, t_right) - x
    pathC = min(x-s_left, t_right-x) + t_right - s_left
    pathD = min(x-t_left, s_right-x) + s_right - t_left
    print(min(pathA, pathB, pathC, pathD))

Submission status: Accepted

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

INF = float('INF')

a, b, q = map(int, input().split())
S = [-INF] + [int(input()) for _ in range(a)] + [INF]
T = [-INF] + [int(input()) for _ in range(b)] + [INF]
X = [int(input()) for _ in range(q)]

ans = []
for x in X:
    S_idx = bisect.bisect_left(S, x)
    T_idx = bisect.bisect_left(T, x)

    s_left, s_right = S[S_idx-1], S[S_idx]
    t_left, t_right = T[T_idx-1], T[T_idx]
    pathA = x - min(s_left, t_left)
    pathB = max(s_right, t_right) - x
    pathC = min(x-s_left, t_right-x) + t_right - s_left
    pathD = min(x-t_left, s_right-x) + s_right - t_left
    ans.append(str(min(pathA, pathB, pathC, pathD)))

print('\n'.join(ans))

Submission status: Accepted

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

INF = float('INF')

a, b, q = map(int, input().split())
S = [-INF] + [int(input()) for _ in range(a)] + [INF]
T = [-INF] + [int(input()) for _ in range(b)] + [INF]
X = [int(input()) for _ in range(q)]

for x in X:
    S_idx = bisect.bisect_left(S, x)
    T_idx = bisect.bisect_left(T, x)

    s_left, s_right = S[S_idx-1], S[S_idx]
    t_left, t_right = T[T_idx-1], T[T_idx]
    pathA = x - min(s_left, t_left)
    pathB = max(s_right, t_right) - x
    pathC = min(x-s_left, t_right-x) + t_right - s_left
    pathD = min(x-t_left, s_right-x) + s_right - t_left
    print(min(pathA, pathB, pathC, pathD))

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

S.append(float('INF'))
S.append(-float('INF'))
T.append(float('INF'))
T.append(-float('INF'))

S.sort()
T.sort()

for x in X:
    S_idx = bisect.bisect_left(S, x)
    T_idx = bisect.bisect_left(T, x)

    s_left, s_right = S[S_idx-1], S[S_idx]
    t_left, t_right = T[T_idx-1], T[T_idx]
    pathA = x - min(s_left, t_left)
    pathB = max(s_right, t_right) - x
    pathC = min(x-s_left, t_right-x) + t_right - s_left
    pathD = min(x-t_left, s_right-x) + s_right - t_left
    print(min(pathA, pathB, pathC, pathD))