Problem:


Score : 400 points

Problem Statement

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

Answer the following Q queries:

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

Constraints

1 \leq A, B \leq 10^5

1 \leq Q \leq 10^5

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

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

1 \leq x_i \leq 10^{10}

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

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

Output

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

Sample Input 1

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

Sample Output 1

350
1400
301
399

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

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

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

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

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

Sample Input 2

1 1 3
1
10000000000
2
9999999999
5000000000

Sample Output 2

10000000000
10000000000
14999999998

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



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


Sample output:
350
1400
301
399

Submission status: Accepted

Solution code:
import bisect
a,b,q=map(int,input().split())
s=[]
t=[]
for i in range(a):
  s.append(int(input()))
for i in range(b):
  t.append(int(input()))
s.sort()
t.sort()
INF=10**18
for i in range(q):
  x=int(input())
  if s[0]<x<s[-1]:
    s_left=s[bisect.bisect_left(s,x)-1]
    s_right=s[bisect.bisect_left(s,x)]
  elif x<s[0]:
    s_left=-INF
    s_right=s[bisect.bisect_left(s,x)]
  elif x>s[-1]:
    s_left=s[bisect.bisect_left(s,x)-1]
    s_right=INF
  if t[0]<x<t[-1]:
    t_left=t[bisect.bisect_left(t,x)-1]
    t_right=t[bisect.bisect_left(t,x)]
  elif x<t[0]:
    t_left=-INF
    t_right=t[bisect.bisect_left(t,x)]
  elif x>t[-1]:
    t_left=t[bisect.bisect_left(t,x)-1]
    t_right=INF
  v=x-min(s_left,t_left)
  w=max(s_right,t_right)-x
  u=min(min(x-s_left,s_right-x),min(x-t_left,t_right-x))*2+max(min(x-s_left,s_right-x),min(x-t_left,t_right-x))
  print(min(v,w,u))

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
import sys
from bisect import bisect_left, bisect_right
import itertools

A,B,Q=map(int, sys.stdin.readline().split())

S=[  int(sys.stdin.readline()) for i in range(A) ]
T=[  int(sys.stdin.readline()) for i in range(B) ]
X=[  int(sys.stdin.readline()) for i in range(Q) ]


for x in X:
	sx=bisect_left(S, x)
	tx=bisect_left(T, x)

	s_temp=[]
	if sx==0:
		s_temp.append(S[sx])	
	elif 0<sx<A:
		s_temp.append(S[sx-1])
		s_temp.append(S[sx])
	else:
		s_temp.append(S[sx-1] )


	t_temp=[]
	if tx==0:
		t_temp.append(T[tx])	
	elif 0<tx<B:
		t_temp.append(T[tx-1])
		t_temp.append(T[tx])
	else:
		t_temp.append(T[tx-1] )


	ans=float("inf")

	for s in s_temp:
		for t in t_temp:
			ans=min(ans, abs(s-x)+abs(s-t) )

	for t in t_temp:
		for s in s_temp:	
			ans=min(ans, abs(t-x)+abs(s-t) )

	print ans

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 16 20:52:46 2019

@author: Owner
"""


import collections
import scipy.misc
import sys
import numpy as np
import math
from operator import itemgetter
import itertools
import copy
import bisect

#素因数を並べる
def prime_decomposition(n):
  i = 2
  table = []
  while i * i <= n:
    while n % i == 0:
      n /= i
      table.append(int(i))
    i += 1
  if n > 1:
    table.append(int(n))
  return table   
# 桁数を吐く
def digit(i):
    if i > 0:
        return digit(i//10) + [i%10]
    else:
        return []
    
def getNearestValueIndex(list, num):
    """
    概要: リストからある値に最も近い値のインデックスを取得する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    """

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return idx

"""
N, X = map(int, input().split())

x = [0]*N
x[:] = map(int, input().split())

P = [0]*N
Y = [0]*N
for n in range(N):
    P[n], Y[n] = map(int, input().split())

    
all(nstr.count(c) for c in '753')

# 複数配列を並び替え
ABT = zip(A, B, totAB)
result = 0
# itemgetterには何番目の配列をキーにしたいか渡します
sorted(ABT,key=itemgetter(2))
A, B, totAB = zip(*ABT)
A.sort(reverse=True)

# 2進数のbit判定
(x >> i) & 1

# dp最小化問題
dp = [np.inf]*N
for n in range(N):
    if n == 0:
        dp[n] = 0
    else:
        for k in range(1,K+1):
            if n-k >= 0:
                dp[n] = min(dp[n], dp[n-k] + abs(h[n]-h[n-k]))
            else:
                break

"""

A, B, Q = map(int, input().split())
INF = 10**18

s = [-INF] +[int(input()) for i in range(A)] + [INF]
t = [-INF] +[int(input()) for i in range(B)] + [INF]

x = [0]*Q
for i in range(Q):
    x[i] = int(input())
    se, te = bisect.bisect_right(s, x[i]), bisect.bisect_right(t, x[i])
    res = INF
    for S in [s[se-1], s[se]]:
        for T in [t[te-1], t[te]]:
            d1, d2 = abs(S-x[i]) + abs(T-S), abs(T-x[i]) + abs(T-S)
            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=[]
t=[]
for _ in range(A):
    s.append(int(input()))
for _ in range(B):
    t.append(int(input()))
# s.sort()
# t.sort()
# s = [int(input()) for _ in range(A)]
# t = [int(input()) for _ in range(B)]
# s.append(INF)
# t.append(INF)

def solve(x):
    sr = bisect.bisect(s,x)
    tr = bisect.bisect(t,x)
    sRight = s[sr] if sr < A else s[sr-1]
    tRight = t[tr] if tr < B else t[tr-1]
    sLeft = s[sr-1] if sr>0 else s[sr] 
    tLeft = t[tr-1] if tr>0 else t[tr]
    # return(min(
    # print([[sr,sLeft,sRight],[tr,tLeft,tRight]])
    # cand = [
    #     abs(x-sRight) + abs(sRight-tRight),
    #     abs(x-sRight) + abs(sRight-tLeft),
    #     abs(x-tRight) + abs(tRight-sRight),
    #     abs(x-tRight) + abs(tRight-sLeft),
    #     abs(x-sLeft) + abs(sLeft-tLeft),
    #     abs(x-sLeft) + abs(sLeft-tRight),
    #     abs(x-tLeft) + abs(tLeft-sRight),
    #     abs(x-tLeft) + abs(tLeft-sLeft),
    # ]
    # # print(cand)
    # return(min(cand))
    return(min(
        abs(x-sRight) + abs(sRight-tRight),
        abs(x-sRight) + abs(sRight-tLeft),
        abs(x-tRight) + abs(tRight-sRight),
        abs(x-tRight) + abs(tRight-sLeft),
        abs(x-sLeft) + abs(sLeft-tLeft),
        abs(x-sLeft) + abs(sLeft-tRight),
        abs(x-tLeft) + abs(tLeft-sRight),
        abs(x-tLeft) + abs(tLeft-sLeft),
    ))
for _ in range(Q):
    print(solve(int(input())))

Submission status: Accepted

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

def solve(x):
    sr = bisect.bisect(s,x)
    tr = bisect.bisect(t,x)
    sRight = s[sr] if sr < A else s[sr-1]
    tRight = t[tr] if tr < B else t[tr-1]
    sLeft = s[sr-1] if sr>0 else s[sr] 
    tLeft = t[tr-1] if tr>0 else t[tr]
    # return(min(
    # print([[sr,sLeft,sRight],[tr,tLeft,tRight]])
    # cand = [
    #     abs(x-sRight) + abs(sRight-tRight),
    #     abs(x-sRight) + abs(sRight-tLeft),
    #     abs(x-tRight) + abs(tRight-sRight),
    #     abs(x-tRight) + abs(tRight-sLeft),
    #     abs(x-sLeft) + abs(sLeft-tLeft),
    #     abs(x-sLeft) + abs(sLeft-tRight),
    #     abs(x-tLeft) + abs(tLeft-sRight),
    #     abs(x-tLeft) + abs(tLeft-sLeft),
    # ]
    # # print(cand)
    # return(min(cand))
    return(min(
        abs(x-sRight) + abs(sRight-tRight),
        abs(x-sRight) + abs(sRight-tLeft),
        abs(x-tRight) + abs(tRight-sRight),
        abs(x-tRight) + abs(tRight-sLeft),
        abs(x-sLeft) + abs(sLeft-tLeft),
        abs(x-sLeft) + abs(sLeft-tRight),
        abs(x-tLeft) + abs(tLeft-sRight),
        abs(x-tLeft) + abs(tLeft-sLeft),
    ))
for _ in range(Q):
    print(solve(int(input())))

Submission status: Accepted

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

def solve(x):
    sr = bisect.bisect(s,x)
    tr = bisect.bisect(t,x)
    sRight = s[sr] if sr < A else s[sr-1]
    tRight = t[tr] if tr < B else t[tr-1]
    sLeft = s[sr-1] if sr>0 else s[sr] 
    tLeft = t[tr-1] if tr>0 else t[tr]
    # return(min(
    # print([[sr,sLeft,sRight],[tr,tLeft,tRight]])
    cand = [
        abs(x-sRight) + abs(sRight-tRight),
        abs(x-sRight) + abs(sRight-tLeft),
        abs(x-tRight) + abs(tRight-sRight),
        abs(x-tRight) + abs(tRight-sLeft),
        abs(x-sLeft) + abs(sLeft-tLeft),
        abs(x-sLeft) + abs(sLeft-tRight),
        abs(x-tLeft) + abs(tLeft-sRight),
        abs(x-tLeft) + abs(tLeft-sLeft),
    ]
    # print(cand)
    return(min(cand))
for _ in range(Q):
    print(solve(int(input())))

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int, input().split())
inf = 10**18
lisS = [-inf] + [int(input()) for x in range(A)] + [inf]
lisT = [-inf] + [int(input()) for x in range(B)] + [inf]
for _ in range(Q):
  x = int(input())
  i = bisect.bisect_right(lisS, x)
  j = bisect.bisect_right(lisT, x)
  res = inf
  for S in [lisS[i - 1], lisS[i]]:
    for T in [lisT[j - 1], lisT[j]]:
      r1 = abs(S - x) + abs(S - T)
      r2 = abs(T - x) + abs(S - T)
      res = min(res, r1, r2)
  print(res)

Submission status: Accepted

Solution code:
import bisect
A, B, Q = map(int, input().split())
INF = 10 ** 18
s = [-INF] + [int(input()) for i in range(A)] + [INF]
t = [-INF] + [int(input()) for i in range(B)] + [INF]
for q in range(Q):
  x = int(input())
  b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
  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 = 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)]
s.sort()
t.sort()
for i in x:
    si = bisect.bisect(s, i)
    ti = bisect.bisect(t, i)
    sl = s[si-1] if si > 0 else s[0]
    sr = s[si] if si < a else s[-1]
    tl = t[ti-1] if ti > 0 else t[0]
    tr = t[ti] if ti < b else t[-1]
    print(min(
        abs(i-sl)+abs(sl-tl),
        abs(i-sl)+abs(sl-tr),
        abs(i-sr)+abs(sr-tl),
        abs(i-sr)+abs(sr-tr),
        abs(i-tl)+abs(sl-tl),
        abs(i-tl)+abs(sr-tl),
        abs(i-tr)+abs(sl-tr),
        abs(i-tr)+abs(sr-tr),
    ))

Submission status: Accepted

Solution code:
#coding:utf-8
import sys
import bisect

if __name__ == "__main__":
    A, B, Q = map(int, input().split())
    S = [-sys.maxsize] + [int(input()) for _ in range(A)] + [sys.maxsize]
    T = [-sys.maxsize] + [int(input()) for _ in range(B)] + [sys.maxsize]

    for _ in range(Q):
        x = int(input())
        sx = bisect.bisect_left(S, x)
        tx = bisect.bisect_left(T, x)
        result = sys.maxsize
        for s in [S[sx-1], S[sx]]:
            for t in [T[tx-1], T[tx]]:
                result = min(result, abs(s-x)+abs(t-s), abs(t-x)+abs(s-t))

        print(result)

Submission status: Accepted

Solution code:
def zengo(l,n):
    if n<l[0]:
        return 0,l[0]-n
    elif n>l[-1]:
        return n-l[-1],0
    else:
        st=0
        ed=len(l)
        while ed-st>1:
            md=(st+ed)//2
            if n<l[md]:
                ed=md
            else:
                st=md
        return n-l[st],l[ed]-n

near=lambda x,y:min(x,y) if x*y else max(x,y)

jn,tn,qn,*tmp=map(int,open(0).read().split())
jz=tmp[:jn]
tz=tmp[jn:jn+tn]
q=tmp[jn+tn:]
for i in q:
    jb,jf=zengo(jz,i)
    tb,tf=zengo(tz,i)
    ans=[]
    if jb*tb:
        ans.append(max(jb,tb))
    if jf*tf:
        ans.append(max(jf,tf))
    jd=near(jb,jf)
    td=near(tb,tf)
    ans.append(jd+td+min(jd,td))
    print(min(ans))

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())
    s_idx = bisect.bisect_left(S, x)
    s1, s2 = S[s_idx - 1], S[s_idx]
    
    t_idx = bisect.bisect_left(T, x)
    t1, t2 = T[t_idx - 1], T[t_idx]
    
    ans = inf
    for i in s1, s2:
        for j in t1, t2:
            ans = min(ans, abs(x - i) + abs(i - j))
            ans = min(ans, abs(x - j) + abs(i - j))
                
    print(ans)

Submission status: Accepted

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

def solve(a, b, q, s, t, u, qa):

    INF = 3 * (10 ** 10)

    u.sort()
    ux = [x[0] for x in u]
    st = [s, t]
    len_st = [a, b]

    for x in qa:
        r = INF
        i = bisect.bisect_left(ux, x)
        ys = []
        if 0 < i:
            ys.append(u[i - 1])
        if i < a + b:
            ys.append(u[i])
        for v in ys:
            y, p = v
            j = bisect.bisect_left(st[p], y)
            if 0 < j:
                z = st[p][j - 1]
                r = min(r, abs(y - x) + abs(z - y))
            if j < len_st[p]:
                z = st[p][j]
                r = min(r, abs(y - x) + abs(z - y))
        print(r)


def main():
    a, b, q = input().split()
    a = int(a)
    b = int(b)
    q = int(q)
    s = []
    t = []
    u = []
    qa = []
    for _ in range(a):
        v = input()
        v = int(v)
        s.append(v)
        u.append((v, 1))
    for _ in range(b):
        v = input()
        v = int(v)
        t.append(v)
        u.append((v, 0))
    for _ in range(q):
        v = input()
        v = int(v)
        qa.append(v)

    solve(a, b, q, s, t, u, qa)


if __name__ == '__main__':
    main()

Submission status: Accepted

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


def solve(A: int, B: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):
    b, d = bisect_right(s, x), bisect_right(t, x)
    INF = 10e11
    ret = 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)
            ret = min(ret, d1, d2)
    print(ret)


# Generated by 1.1.3 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    INF = 10e11
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    s = [-INF] + [int(next(tokens)) for _ in range(A)] + [INF]  # type: "List[int]"
    t = [-INF] + [int(next(tokens)) for _ in range(B)] + [INF]  # type: "List[int]"

    for x in range(Q):
        x = int(input())
        solve(A, B, Q, s, t, x)


if __name__ == "__main__":
    main()

Submission status: Accepted

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

INF = 10e11

def solve(A: int, B: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):
    b, d = bisect_right(s, x), bisect_right(t, x)
    ret = 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)
            ret = min(ret, d1, d2)
    print(ret)


# Generated by 1.1.3 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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 = [-INF] + [int(next(tokens)) for _ in range(A)] + [INF]  # type: "List[int]"
    t = [-INF] + [int(next(tokens)) for _ in range(B)] + [INF]  # type: "List[int]"

    for x in range(Q):
        x = int(input())
        solve(A, B, Q, s, t, x)


if __name__ == "__main__":
    main()

Submission status: Accepted

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


def solve(A: int, B: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):
    b, d = bisect_right(s, x), bisect_right(t, x)
    ret = 10e18

    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)
            ret = min(ret, d1, d2)
    print(ret)


# Generated by 1.1.3 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word

    tokens = iterate_tokens()
    INF = 10e18
    A = int(next(tokens))  # type: int
    B = int(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    s = [-INF] + [int(next(tokens)) for _ in range(A)] + [INF]  # type: "List[int]"
    t = [-INF] + [int(next(tokens)) for _ in range(B)] + [INF]  # type: "List[int]"

    for x in range(Q):
        x = int(input())
        solve(A, B, Q, s, t, x)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
from bisect import bisect_right
# 入力
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)]

# 計算の便宜のため番兵を導入
INF = 10 ** 18
S = [-INF] + s + [INF]
T = [-INF] + t + [INF]


# 指定した変位に対する問に二分探索を用いて回答
def f(y):
    i = bisect_right(S, y)
    j = bisect_right(T, y)
    return min(
        abs(b - a) + min(abs(a - y), abs(b - y))
        for a in (S[i - 1], S[i])
        for b in (T[j - 1], T[j])
    )


# 各問に対して、fにより解を得る
ans = '\n'.join(map(str, map(f, x)))

# 出力
print(ans)

Submission status: Accepted

Solution code:
import bisect
import sys
INF = 10**18

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)]
s.sort()
t.sort()
"""
A,B,Q = 2,3,4
s=[-INF,100,600,INF]#要ソート
t=[-INF,400,900,1000,INF]
x=[150,2000,899,799]"""
ls = len(s)
lt = len(t)
for xi in x:
    s2 = bisect.bisect_left(s,xi)#誰の左に入るかが出力される
    s1=s2-1
    t1 = 0
    t2 = bisect.bisect_left(t,xi)
    t1=t2-1
    l1 = l2 = l3 = l4 = sys.maxsize
    l1 = max(abs(s[s1]-xi),abs(t[t1]-xi))
    l2 = max(abs(s[s2]-xi),abs(t[t2]-xi))
    if abs(s[s1]-xi)<abs(t[t1]-xi):
        l3 = 2*abs(s[s1]-xi) + abs(t[t2]-xi)
    else:
        l3 = 2*abs(t[t1]-xi) + abs(s[s2]-xi)
    if abs(s[s2]-xi)<abs(t[t2]-xi):
        l4 = 2*abs(s[s2]-xi) + abs(t[t1]-xi)
    else:
        l4 = 2*abs(t[t2]-xi) + abs(s[s1]-xi)
    l = [l1,l2,l3,l4]
    print(min(l))

Submission status: Accepted

Solution code:
A, B, Q = [int(x) for x in 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


def f(x):
    # X の左にあるのをS[i-1], T[j-1]
    # X もしくは Xの右にあるのをS[i], T[j] とする
    i = bisect.bisect_left(S, x)
    j = bisect.bisect_left(T, x)
    a1 = a2 = a3 = a4 = a5 = a6 = float("inf")

    # (1) S[i] --> T[j] or T[j] --> S[i]
    if len(S) > i and len(T) > j:
        a1 = max(S[i], T[j]) - x

    # (2) S[i] --> T[j-1]
    if len(S) > i and j - 1 >= 0:
        a2 = S[i] - x + S[i] - T[j - 1]

    # (3) T[j] --> S[i-1]
    if i - 1 >= 0 and len(T) > j:
        a3 = T[j] - x + T[j] - S[i - 1]

    # (4) S[i-1]  --> T[j]
    if i - 1 >= 0 and len(T) > j:
        a4 = x - S[i - 1] + T[j] - S[i - 1]

    # (5) T[j-1]  --> S[i]
    if len(S) > i and j - 1 >= 0:
        a5 = x - T[j - 1] + S[i] - T[j - 1]

    # (6) S[i-1] --> T[j-1] or T[j-1] --> S[i-1]
    if i - 1 >= 0 and j - 1 >= 0:
        a6 = x - min(S[i - 1], T[j - 1])

    return min(a1, a2, a3, a4, a5, a6)


for x in X:
    print(f(x))

Submission status: Accepted

Solution code:
import bisect
A, B, Q =  map(int, (input().split(' ')))
power = 10**11+1
a_list = [-power]+[int(input()) for _ in range(A)] + [power]
b_list = [-power]+[int(input()) for _ in range(B)] + [power]
for _ in range(Q):
    x = int(input())
    right_s = abs(x - a_list[bisect.bisect_left(a_list, x)])
    right_t = abs(x - b_list[bisect.bisect_left(b_list, x)])
    left_s = abs(x - a_list[bisect.bisect_right(a_list, x)-1])
    left_t = abs(x - b_list[bisect.bisect_right(b_list, x)-1])
    print(
            min(
                max(left_t, left_s),
                max(right_t, right_s),
                left_t + (left_t + right_s),
                left_s + (left_s + right_t),
                right_t + (right_t + left_s),
                right_s + (right_s + left_t)
            )
    )

Submission status: Accepted

Solution code:
import bisect

A, B, Q = [int(i) for i in input().split()]

s = [-10**12] + [int(input()) for i in range(A)] + [10**12]
t = [-10**12] + [int(input()) for i in range(B)] + [10**12]
x = [int(input()) for i in range(Q)]

for item in x:
    a, c = bisect.bisect_left(s, item), bisect.bisect_left(t, item)
    min_value = 10**12
    for item_a in [s[a-1], s[a]]:
        for item_c in [t[c-1], t[c]]:
            pata = abs(item_a - item) + abs(item_a - item_c)
            patb = abs(item_c - item) + abs(item_a - item_c)
            min_value = min(min_value, pata, patb)
    print(min_value)

Submission status: Accepted

Solution code:
A,B,Q = map(int,(input().split()))
si = [-(10**10)]+[int(input()) for _ in range(A)]+[2*(10**10)]
ti = [-(10**10)]+[int(input()) for _ in range(B)]+[2*(10**10)]
xi = [(i,int(input())) for i in range(Q)]
A +=2
B +=2

#xを小さい順に考える
xi.sort(key = lambda x:x[1])
ans = [0]*Q
x = xi[0][1]
for i_sr,sr in enumerate(si):
    if sr>x:
        sl = si[i_sr-1]
        break
for i_tr,tr in enumerate(ti):
    if tr>x:
        tl = ti[i_tr-1]
        break
for i,x in xi:
    while sr < x:
        sl = sr
        i_sr += 1
        sr = si[i_sr]
    while tr < x:
        tl = tr
        i_tr += 1
        tr = ti[i_tr]
    dsl = x-sl
    dsr = sr-x
    dtl = x-tl
    dtr = tr-x
    ans[i] = min(max(dsr,dtr),max(dsl,dtl),dsl+dtr+min(dsl,dtr),dsr+dtl+min(dsr,dtl))
for out in ans:
    print(out)

Submission status: Accepted

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

ans = {}
s = 1
t = 1
for i in range(Q):
    dist = -1
    x = X[i][0]
    while s <= A and S[s] < x:
        s += 1
    while t <= B and T[t] < x:
        t += 1
    s_l = S[s-1]
    s_r = S[s]
    t_l = T[t-1]
    t_r = T[t]
    d = min(max(s_r-x, t_r-x),
            (s_r-x)*2 + (x-t_l),
            (t_r-x)*2 + (x-s_l),
            (s_r-x) + (x-t_l)*2,
            (t_r-x) + (x-s_l)*2,
            max(x-s_l,x-t_l))
    ans[X[i][1]] = str(d)
print("\n".join(ans[i] for i in range(Q)))

Submission status: Accepted

Solution code:
def solve():
    import bisect
    A, B, Q = map(int, input().split())
    INF = 10 ** 13
    s = [-INF] + [int(input()) for i in range(A)] + [INF]
    t = [-INF] + [int(input()) for i in range(B)] + [INF]
    for q in range(Q):
        x = int(input())
        b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
        res = INF
        for S in [s[b - 1], s[b]]:
            for T in [t[d - 1], t[d]]:
                d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
                res = min(res, d1, d2)
        print(res)
if __name__ == '__main__':
  	solve()

Submission status: Accepted

Solution code:
def solve():
    import bisect
    import sys
    A, B, Q = map(int, input().split())
    INF = 10 ** 13
    s = [-INF] + [int(input()) for i in range(A)] + [INF]
    t = [-INF] + [int(input()) for i in range(B)] + [INF]
    xs = [int(sys.stdin.readline()) for i in range(Q)]
    for x in xs:
        b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
        res = INF
        for S in [s[b - 1], s[b]]:
            for T in [t[d - 1], t[d]]:
                d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
                res = min(res, d1, d2)
        print(res)
if __name__ == '__main__':
  	solve()

Submission status: Accepted

Solution code:
# 学習用
import bisect
A , B , Q = map(int, input().split())
INF = 10 ** 18
Sa = [-INF] + [int(input()) for s in range(A)] + [INF]
Tb = [-INF] + [int(input()) for s in range(B)] + [INF]
Xq = [int(input()) for s in range(Q)]
for x in Xq:
    b  , d = bisect.bisect_right(Sa,x) , bisect.bisect_right(Tb,x) 
    res = INF 
    for S in [Sa[b -1] , Sa[b]]:
        for T in [Tb[d-1], Tb[d]]:
            d1 , d2 = abs(S-x) + abs(T -S) , abs(T-x)+abs(S-T)
            res = min(res , d1 , d2)
    print(res)

Submission status: Accepted

Solution code:
from bisect import bisect_left

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

x = [int(input()) for i in range(Q)]

# x[i]の東にある神社・寺のうち１番近いのと２番めに近いものEastShrine EastTemple
# x[i]の西にある神社・寺のうち１番近いのと２番めに近いものをみてWest~~
# EastShrine,EastTemple
# EastShrine,WastTemple
# WestShrine,EastTemple
# WestShrine,WestTemple

# x[i]-s[i]の符号が変わるタイミングで近い２点を求める
# ではなく二分探索しましょう
# print(s)
# print(t)

for x_i in x:
    s_index = bisect_left(s, x_i)
    t_index = bisect_left(t, x_i)
    WestShrine, EastShrine = s[s_index - 1], s[s_index]
    WestTemple, EastTemple = t[t_index - 1], t[t_index]

    """
    for i in range(len(s)):
        if s[i] < x_i:
            pass
        elif s[i] == x_i:
            if abs(s[i - 1] - x_i) > abs(s[i + 1] - x_i):
                EastShrine = s[i + 1]
                WestShrine = s[i]
            else:
                EastShrine = s[i]
                WestShrine = s[i - 1]
        else:
            WestShrine = s[i - 1]
            EastShrine = s[i]
            #print(WestShrine, EastShrine)
            break
    """
    """
        if t[i] < x_i:
            pass
        elif t[i] == x_i:

            if i == 0:
                WestTemple = t[i]
                EastTemple = t[i + 1]
            elif i == len(t) - 1:
                WestTemple = t[i-1]
                EastTemple = t[i]

            if abs(t[i - 1] - x_i) > abs(t[i + 1] - x_i):
                EastTemple = t[i + 1]
                WestTemple = t[i]
            else:
                EastTemple = t[i]
                WestTemple = t[i - 1]
        else:
            WestTemple = t[i - 1]
            EastTemple = t[i]
            #print(WestTemple, EastTemple)
            break
        """
    #print("WS:", WestShrine, "ES:", EastShrine)
    #print("WT:", WestTemple, "ET:", EastTemple)

    ans1 = abs(max([EastShrine, EastTemple]) - x_i)
    ans2 = abs(min([WestShrine, WestTemple]) - x_i)

    smaller = min(abs(x_i - EastShrine), abs(x_i - WestTemple))
    larger = max(abs(x_i - EastShrine), abs(x_i - WestTemple))
    #print("S:", smaller, "L:", larger)
    ans3 = smaller * 2 + larger

    smaller = min(abs(x_i - WestShrine), abs(x_i - EastTemple))
    larger = max(abs(x_i - WestShrine), abs(x_i - EastTemple))
    ans4 = smaller * 2 + larger

    #print(WestShrine, EastShrine)
    #print(WestTemple, EastTemple)
    #print(ans1, ans2, ans3, ans4)
    print(min([ans1, ans2, ans3, ans4]))

Submission status: Accepted

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

jinjya = []
otera = []

for i in range(a):
    jinjya.append(int(input()))
for i in range(b):
    otera.append(int(input()))

INF = 10**18
jinjya = [-INF] + jinjya + [INF]
otera = [-INF] + otera + [INF]


for i in range(q):
    res = INF
    pos = int(input())
    j,o = bisect.bisect_right(jinjya,pos),bisect.bisect_right(otera,pos)
    for a in [jinjya[j-1],jinjya[j]]:
        for b in [otera[o-1],otera[o]]:
            res = min(res,abs(pos-a)+abs(a-b),abs(pos-b)+abs(a-b))
    print(res)

Submission status: Accepted

Solution code:
from bisect import bisect_left
A, B, Q = map(int, input().split())
minf, inf = -(10**18), 10**18
jinja = [minf] + list(map(int, (input() for _ in range(A)))) + [inf]
tera = [minf] + list(map(int, (input() for _ in range(B)))) + [inf]
ans = []
append = ans.append

for q in map(int, list(map(int, (input() for _ in range(Q))))):
    i = bisect_left(jinja, q)
    j = bisect_left(tera, q)
    left_jinja, right_jinja = q-jinja[i-1], jinja[i]-q
    left_tera, right_tera = q-tera[j-1], tera[j]-q
 
    append(min(
        left_jinja if left_jinja > left_tera else left_tera,
        left_jinja + right_tera + (left_jinja if left_jinja < right_tera else right_tera),
        right_jinja + left_tera + (right_jinja if right_jinja < left_tera else left_tera),
        right_jinja if right_jinja > right_tera else right_tera
    ))
 
print(*ans, sep="\n")

Submission status: Accepted

Solution code:
from bisect import bisect_left
A, B, Q = map(int, input().split())
minf, inf = -(10**18), 10**18
jinja = [minf] + list(map(int, (input() for _ in [0]*A))) + [inf]
tera = [minf] + list(map(int, (input() for _ in [0]*B))) + [inf]
ans = []
append = ans.append

for q in map(int, list(map(int, (input() for _ in [0]*Q)))):
    i = bisect_left(jinja, q)
    j = bisect_left(tera, q)
    left_jinja, right_jinja = q-jinja[i-1], jinja[i]-q
    left_tera, right_tera = q-tera[j-1], tera[j]-q
 
    append(min(
        left_jinja if left_jinja > left_tera else left_tera,
        left_jinja + right_tera + (left_jinja if left_jinja < right_tera else right_tera),
        right_jinja + left_tera + (right_jinja if right_jinja < left_tera else left_tera),
        right_jinja if right_jinja > right_tera else right_tera
    ))
 
print(*ans, sep="\n")