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())
ss = []
for i in range(A):
  s = int(input())
  ss.append(s)
ts = []
for i in range(B):
  t = int(input())
  ts.append(t)
#print(ss, ts)
for i in range(Q):
  x = int(input())
  Is = bisect.bisect_left(ss, x)
  It = bisect.bisect_left(ts, x)
  ss2 = ss[Is-1 if Is > 0 else Is:Is+1]
  ts2 = ts[It-1 if It > 0 else It:It+1]
  #print(x, Is, It, ss2, ts2)
  rs = []
  for s in ss2:
    for t in ts2:
      r = abs(s-x)+abs(t-s)
      rs.append(r)
      r = abs(t-x)+abs(s-t)
      rs.append(r)
  r = min(rs)
  print(r)

Submission status: Accepted

Solution code:
import sys
import math
from collections import defaultdict

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def II(): return map(int, input().split())
def III(): return list(map(int, input().split()))
def Line(N):
    read_all = [tuple(map(int, input().split())) for _ in range(N)]
    return map(list,zip(*read_all))

#################

from bisect import bisect_left, bisect_right

A,B,Q = II()
s = [I() for _ in range(A)]
t = [I() for _ in range(B)]
x = [I() for _ in range(Q)]

for i in range(Q):
    val = float('inf')
    a = bisect_left(s,x[i])
    if a<=A-1:
        b = bisect_left(t,s[a])
        if b<=B-1:
            val = min(val, abs(x[i]-s[a]) + abs(s[a]-t[b]))
        if b>=1:
            val = min(val, abs(x[i]-s[a]) + abs(s[a]-t[b-1]))
    if a>=1:
        b = bisect_left(t,s[a-1])
        if b<=B-1:
            val = min(val, abs(x[i]-s[a-1]) + abs(s[a-1]-t[b]))
        if b>=1:
            val = min(val, abs(x[i]-s[a-1]) + abs(s[a-1]-t[b-1]))

    b = bisect_left(t,x[i])
    if b<=B-1:
        a = bisect_left(s,t[b])
        if a<=A-1:
            val = min(val, abs(x[i]-t[b]) + abs(t[b]-s[a]))
        if a>=1:
            val = min(val, abs(x[i]-t[b]) + abs(t[b]-s[a-1]))
    if b>=1:
        a = bisect_left(s,t[b-1])
        if a<=A-1:
            val = min(val, abs(x[i]-t[b-1]) + abs(t[b-1]-s[a]))
        if a>=1:
            val = min(val, abs(x[i]-t[b-1]) + abs(t[b-1]-s[a-1]))
    
    print(val)

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 i 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(d1, d2, res)
  print(res)

Submission status: Accepted

Solution code:
INF = float('inf')
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)]
def f(x, s, t):
  result = INF
  i = bisect_left(s, x)
  if i > 0:
    j = bisect_left(t, s[i - 1])
    if j > 0:
      result = min(result, (x - s[i - 1]) + (s[i - 1] - t[j - 1]))
    if j < len(t):
      result = min(result, (x - s[i - 1]) + (t[j] - s[i - 1]))
  if i < len(s):
    j = bisect_left(t, s[i])
    if j > 0:
      result = min(result, (s[i] - x) + (s[i] - t[j - 1]))
    if j < len(t):
      result = min(result, (s[i] - x) + (t[j] - s[i]))
  return result
for i in range(q):
  x = int(input())
  print(min(f(x, s, t), f(x, t, s)))

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)]
def f(x, s, t):
  result = float('inf')
  i = bisect_left(s, x)
  if i > 0:
    j = bisect_left(t, s[i - 1])
    if j > 0:
      result = min(result, (x - s[i - 1]) + (s[i - 1] - t[j - 1]))
    if j < len(t):
      result = min(result, (x - s[i - 1]) + (t[j] - s[i - 1]))
  if i < len(s):
    j = bisect_left(t, s[i])
    if j > 0:
      result = min(result, (s[i] - x) + (s[i] - t[j - 1]))
    if j < len(t):
      result = min(result, (s[i] - x) + (t[j] - s[i]))
  return result
for i in range(q):
  x = int(input())
  print(min(f(x, s, t), f(x, t, s)))

Submission status: Accepted

Solution code:
import bisect
a, b, q = map(int, input().split())
inf = 10**18
lst1 = [-inf] + [(int(input())) for i in range(a)] + [inf]
lst2 = [-inf] + [(int(input())) for i in range(b)] + [inf]
left = 0
for i in range(q):
    x = int(input())
    j = bisect.bisect_right(lst1, x)
    k = bisect.bisect_right(lst2, x)
    res = inf
    for s in [lst1[j-1], lst1[j]]:
        for t in [lst2[k-1], lst2[k]]:
            ans1 = abs(x-s) + abs(s-t)
            ans2 = abs(x-t) + abs(t-s)
            res = min(res, ans1, ans2)
    print(res)

Submission status: Accepted

Solution code:
import bisect


def resolve():
    A, B, Q = map(int, input().split())
    INF = 10 ** 18
    s = [-INF] + list(int(input()) for _ in range(A)) + [INF]
    t = [-INF] + list(int(input()) for _ in range(B)) + [INF]
    for q in range(Q):
        x = int(input())
        b, d = bisect.bisect_right(s, x), bisect.bisect_right(t, x)
        res = INF
        for S in [s[b - 1], s[b]]:
            for T in [t[d - 1], t[d]]:
                d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
                res = min(res, d1, d2)
        print(res)


if __name__ == "__main__":
    resolve()

Submission status: Accepted

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

for i in range(Q):
  x = int(input())
  ai = bisect_left(als,x)
  bi = bisect_left(bls,x)
  res = INF
  for S in [als[ai], als[ai-1]]:
    for T in [bls[bi], bls[bi-1]]:
      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

INF = 10**24

A, B, Q = map(int, input().split())
S, T, X = [[int(input()) for _ in range(m)] for m in [A, B, Q]]

S = [-INF] + S + [INF]
T = [-INF] + T + [INF]

for x in X:
    s_i = bisect(S, x)
    t_i = bisect(T, x)
    points = [S[s_i-1], S[s_i], T[t_i-1], T[t_i]]
    min_cost = INF
    for j, p_j in enumerate(points):
        for k, p_k in enumerate(points):
            if j//2 == k//2:
                continue
            cost = abs(p_j-x) + abs(p_k-p_j)
            min_cost = min(min_cost, cost)
    print(min_cost)

Submission status: Accepted

Solution code:
import bisect

a,b,q = map(int,input().split())
s = [0] * a
t = [0] * b
ans = []

for i in range(a):
    s[i] = int(input())
for j in range(b):
    t[j] = int(input())
for x in range(q):
    x = int(input())
    shr = bisect.bisect_left(s,x)
    if shr == 0:
        shrr = shr
    elif shr == a:
        shr = a - 1
        shrr = a - 1
    else:
        shrr = shr - 1
    
    tem = bisect.bisect_left(t,x)
    if tem == 0:
        temm = tem
    elif tem == b:
        tem = b - 1
        temm = b - 1
    else:
        temm = tem - 1
    
    can = []
    l = [[shr,tem],[shr,temm],[shrr,tem],[shrr,temm]]
    
    for i in range(4):
        can.append(min(abs(s[l[i][0]]-x)+abs(t[l[i][1]]-s[l[i][0]]),abs(t[l[i][1]]-x)+abs(s[l[i][0]]-t[l[i][1]])))
    
    ans.append(min(can))

for p in ans:
    print(p)

Submission status: Accepted

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

import bisect

INF = 1e+11
A,B,Q=map(int, input().split())
s=[-INF]+[int(input()) for _ in range(A)]+[INF]
t=[-INF]+[int(input()) for _ in range(B)]+[INF]
x=[int(input()) for _ in range(Q)]

for i in range(Q):
    a,b=bisect.bisect_right(s,x[i]), bisect.bisect_right(t,x[i])
    ans = INF
    for j in [s[a-1], s[a]]:
        for k in [t[b-1], t[b]]:
            d1 = abs(j-x[i])+abs(j-k)
            d2 = abs(k-x[i])+abs(j-k)
            ans = min(ans, d1, d2)
    print(ans)

Submission status: Accepted

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

import bisect

INF = 1e+11
A,B,Q=map(int, input().split())
s = [-INF]+[int(input()) for _ in range(A)]+[INF]
t = [-INF]+[int(input()) for _ in range(B)]+[INF]
x = [int(input()) for _ in range(Q)]

for i in range(Q):
    a,b= bisect.bisect_right(s,x[i]), bisect.bisect_right(t,x[i])
    ans = INF
    for S in [s[a-1], s[a]]:
        for T in [t[b-1], t[b]]:
            d1 = abs(S-x[i])+abs(S-T)
            d2 = abs(T-x[i])+abs(S-T)
            ans = min(ans, d1, d2)
    print(ans)

Submission status: Accepted

Solution code:
def main():
    from bisect import bisect_left,bisect
    import sys
    input = sys.stdin.readline
    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)]
    
    for i in X:
        ans = float("inf")
        j = min(bisect(S,i),A-1)
        k = min(bisect(T,i),B-1)
        l = [min(bisect(T,S[j]),B-1), min(bisect(T,S[j-1]),B-1)]
        r = [min(bisect(S,T[k]),A-1), min(bisect(S,T[k-1]),A-1)]
        for p in range(2):
            for q in range(2):
                tmp = abs(S[j-p] - i) + abs(T[l[p]-q] - S[j-p])
                if tmp < ans:
                    ans = tmp
                tmp = abs(T[k-p] - i) + abs(S[r[p]-q] - T[k-p])
                if tmp < ans:
                    ans = tmp
        print(ans)
    
    
    
    
main()

Submission status: Accepted

Solution code:
def main():
    A, B, Q = map(int, input().split())
    S = [float("-inf")]
    T = [float("-inf")]
    X = []
    for _ in range(A): S.append(int(input()))
    for _ in range(B): T.append(int(input()))
    for i in range(Q): X.append([int(input()), i])
    S.append(float("inf"))
    T.append(float("inf"))
    X.sort(key = lambda x: x[0])
    A = len(S)
    B = len(T)

    ans = []
    i, j = 0, 0
    for k in range(Q):
        min_d = float('inf')
        x, l = X[k]
        while i < A and S[i] < x: i += 1
        while j < B and T[j] < x: j += 1

        if i-1 < A and j-1 < B:
            min_d = min(min_d, max(x-S[i-1], x-T[j-1]))
        if i < A and j < B:
            min_d = min(min_d, max(S[i]-x, T[j]-x))
        if i < A and j-1 < B:
            min_d = min(min_d, S[i]-T[j-1] + min(S[i]-x, x-T[j-1]))
        if i-1 < A and j < B:
            min_d = min(min_d, T[j]-S[i-1] + min(T[j]-x, x-S[i-1]))

        ans.append([l, min_d])
    ans.sort(key = lambda x: x[0])
    return [a for _, a in ans]


if __name__ == '__main__':
    output = main()
    for a in output:
        print(a)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect_left

def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

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

for q in x:
	b, d = bisect_left(s, q), bisect_left(t, q)
	res = INF
	for S in [s[b-1], s[b]]:
		for T in [t[d-1], t[d]]:
			d1, d2 = abs(S-q) + abs(T-S), abs(T-q) + abs(S-T)
			res = min(res, d1, d2)
	print(res)

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right
INF = 10**12
A, B, Q = map(int, input().split())
shrines = [-INF] + [int(input()) for _ in range(A)] + [INF]
temples = [-INF] + [int(input()) for _ in range(B)] + [INF]
for _ in range(Q):
  query = int(input())
  sh_pos = bisect_left(shrines, query)
  te_pos = bisect_left(temples, query)
  ans = INF
  for s in shrines[sh_pos-1:sh_pos+1]:
    for t in temples[te_pos-1:te_pos+1]:
      dis = min(abs(s-query)+abs(s-t),abs(t-query)+abs(t-s))
      ans = min(ans, dis)
  print(ans)

Submission status: Accepted

Solution code:
import bisect

SList = []
TList = []
QList = []
minpos = -1*(10**10)
maxpos = 10*(10**10)

def ans(x):
    index = bisect.bisect_left(SList,x)
    s = [SList[index-1],SList[index]]

    index = bisect.bisect_left(TList,x)
    t = [TList[index-1],TList[index]]

    min1 = abs(x-s[0])+abs(t[0]-s[0])
    diff = abs(x-s[0])+abs(t[1]-s[0])
    if diff < min1:
        min1 = diff
    diff = abs(x-s[1])+abs(t[0]-s[1])
    if diff < min1:
        min1 = diff
    diff = abs(x-s[1])+abs(t[1]-s[1])
    if diff < min1:
        min1 = diff
    diff = abs(x-t[0])+abs(s[0]-t[0])
    if diff < min1:
        min1 = diff
    diff = abs(x-t[0])+abs(s[1]-t[0])
    if diff < min1:
        min1 = diff
    diff = abs(x-t[1])+abs(s[0]-t[1])
    if diff < min1:
        min1 = diff
    diff = abs(x-t[1])+abs(s[1]-t[1])
    if diff < min1:
        min1 = diff
    return min1

A,B,Q = map(int,input().split())
for _ in range(A):
    SList.append(int(input()))
for _ in range(B):
    TList.append(int(input()))
for _ in range(Q):
    QList.append(int(input()))

SList.insert(0,minpos)
SList.append(maxpos)
TList.insert(0,minpos*2)
TList.append(maxpos*2)
for q in QList:
    print(ans(q))

Submission status: Accepted

Solution code:
import bisect
A,B,Q = map(int, input().split())
S,T,X = [],[],[]
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 i in range(Q):
  ans = []
  sin = bisect.bisect_left(S, X[i])
  if sin == 0:
    s1,s2 = S[sin], -(10**12)
  elif sin == A:
    s1,s2 = (10**12),S[sin-1]
  else:
    s1,s2 = S[sin],S[sin-1]
  tin = bisect.bisect_left(T, X[i])
  if tin == 0:
    t1,t2 = T[tin], -(10**12)
  elif tin == B:
    t1,t2 = (10**12),T[tin-1]
  else:
    t1,t2 = T[tin],T[tin-1]
  for j in [s1,s2]:
    for k in [t1,t2]:
      for l in [0,1]:
        if l ==0:
          ans.append(abs(j-X[i])+abs(k-j))
        else:
          ans.append(abs(k-X[i])+abs(j-k)) 
          
  print(min(ans))

Submission status: Accepted

Solution code:
import bisect


A, B, Q = map(int, input().split())
INF = 10**18
S = [-INF] + [int(input()) for _ in range(A)] + [INF]
T = [-INF] + [int(input()) for _ in range(B)] + [INF]
for _ in range(Q):
    x = int(input())
    i = bisect.bisect_right(S, x)
    j = bisect.bisect_right(T, x)
    d = INF
    for s in [S[i-1], S[i]]:
        for t in [T[j-1], T[j]]:
            d1 = abs(s-x) + abs(s-t)
            d2 = abs(t-x) + abs(s-t)
            d = min(d, d1, d2)
    print(d)

Submission status: Accepted

Solution code:
from bisect import bisect_left
from itertools import product
I = lambda n: [int(input()) for _ in range(n)]
def f(S, x):
    p = bisect_left(S, x)
    return [S[p-1], S[p]]
g = lambda x, s, t: abs(x-s)+abs(s-t)
INF = 10**11
a, b, q = map(int, input().split())
S, T, X = [-INF]+I(a)+[INF], [-INF]+I(b)+[INF], I(q)
for x in X:
    min_ = INF
    for s, t in product(f(S, x), f(T, x)):
        min_ = min(min_, g(x, s, t), g(x, t, s))
    print(min_)

Submission status: Accepted

Solution code:
import bisect
from itertools import product
I = lambda n: [int(input()) for _ in range(n)]
def f(S, x):
    p = bisect.bisect_left(S, x)
    return [S[p-1], S[p]]
g = lambda x, s, t: abs(x-s)+abs(s-t)
INF = 10**11
a, b, q = map(int, input().split())
S, T, X = [-INF]+I(a)+[INF], [-INF]+I(b)+[INF], I(q)
for x in X:
    min_ = INF
    for s, t in product(f(S, x), f(T, x)):
        min_ = min(min_, g(x, s, t), g(x, t, s))
    print(min_)

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

sentinel = lambda x: [-9e20] + x + [9e20]
s = sentinel(s)
t = sentinel(t)

for i in x:
    ss = bisect(s, i)
    tt = bisect(t, i)

    ll = max(s[ss], t[tt]) - i
    rr = i - min(s[ss-1], t[tt-1])
    rl = min((s[ss]- i) + s[ss] - t[tt-1], (t[tt]- i) + t[tt] - s[ss-1])
    lr = min((i - s[ss-1]) + t[tt] - s[ss-1], (i - t[tt-1]) + s[ss] - t[tt-1])

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

Submission status: Accepted

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

for q in range(q):
    x = int(input())
    m,n = bisect.bisect_right(shrine,x),bisect.bisect_right(temple,x)
    res = inf
    for s in [shrine[m-1],shrine[m]]:
        for t in [temple[n-1],temple[n]]:
            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

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

def nearest2(ssortt, position) :
    l = len(ssortt)
    i = bisect(ssortt, position)
    if i == 0 : return (ssortt[0],)
    if i == l : return (ssortt[-1],)
    return (ssortt[i-1], ssortt[i])

for x in xx :
    ll = []
    for s in nearest2(ss, x) :
        for t in nearest2(tt, s) :
            ll.append(abs(s-x)+abs(t-s))
    for t in nearest2(tt, x) :
        for s in nearest2(ss, t) :
            ll.append(abs(t-x)+abs(s-t))
    print(min(ll))

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline

#n = int(input())
#n,a = [int(i) for i in readline().split()]
a,b,q = [int(i) for i in readline().split()]
s = [-10**12]+[int(readline()) for i in range(a)]+[10**12]
t = [-10**12]+[int(readline()) for i in range(b)]+[10**12]

xx = [int(readline()) for i in range(q)]

from bisect import *
for x in xx:
    ans = 10**11
    i = bisect_left(s,x)
    j = bisect_left(t,x)
    d1 = max(s[i],t[j])-x
    d2 = x- min(s[i-1],t[j-1])

    d3 = (x-s[i-1]) + (t[j]-x) + min((x-s[i-1]), (t[j]-x))
    d4 = (x-t[j-1]) + (s[i]-x) + min((x-t[j-1]), (s[i]-x))

#    print(ans,d1,d2,d3,d4)
    ans = min(ans,d1,d2,d3,d4)
    print(ans)

Submission status: Accepted

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

a, b, q = map(int, input().split())
al = [-float("INF")] + [int(input()) for _ in range(a)] + [float("INF")]
bl = [-float("INF")] + [int(input()) for _ in range(b)] + [float("INF")]
for _ in range(q):
    res = float("INF")
    x = int(input())
    b, d = bisect.bisect_right(al, x), bisect.bisect_right(bl, x)
    ans = min(max(abs(al[b-1] - x), abs(bl[d-1] - x)),
              abs(al[b-1] - x) * 2 + abs(bl[d] - x),  # 左の神社行って右の寺
              abs(bl[d-1] - x) * 2 + abs(al[b] - x),  # 左の寺行って右の神社
              abs(al[b] - x) * 2 + abs(bl[d-1] - x),  # 右の神社行って左の寺
              abs(bl[d] - x) * 2 + abs(al[b-1] - x),  # 右の寺行って左の神社
              max(abs(al[b] - x), abs(bl[d] - x)),
              )
    print(ans)

Submission status: Accepted

Solution code:
import bisect

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

s = [-1 * float("inf")]
t = [-1 * float("inf")]

for i in range(A):

    S = int(input())
    s.append(S)

for i in range(B):

    T = int(input())
    t.append(T)

s.append(float("inf"))
t.append(float("inf"))

for i in range(Q):

    x = int(input())

    si = bisect.bisect_left(s,x)
    ti = bisect.bisect_left(t,x)

    now = min( max(s[si],t[ti]) - x  ,  x - min(s[si-1],t[ti-1]) )
    now = min( now , 2 * min( s[si] - x , x - t[ti-1] ) + max(s[si] - x , x - t[ti-1]))
    now = min( now , 2 * min( t[ti] - x , x - s[si-1] ) + max(t[ti] - x , x - s[si-1]))

    print (now)

Submission status: Accepted

Solution code:
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)]
import bisect
for _ in range(q):
    x=int(input())
    sb=bisect.bisect_left(s,x)
    tb=bisect.bisect_left(t,x)
    ss=[x-s[max(sb-1,0)],x-s[min(sb,a-1)]]
    tt=[x-t[max(tb-1,0)],x-t[min(tb,b-1)]]
    l=[]
    for i in ss:
        for j in tt:
            if i*j>=0:
                l.append(max(abs(i),abs(j)))
            else:
                l.append(max(abs(i),abs(j))+2*min(abs(i),abs(j)))
    print(min(l))

Submission status: Accepted

Solution code:
import sys
from bisect import bisect as br
A, B, Q = map(int, input().split())
inf = 10**11
S = [-inf] + [int(sys.stdin.readline()) for _ in range(A)] + [inf]
T = [-inf] + [int(sys.stdin.readline()) for _ in range(B)] + [inf]
X = [int(sys.stdin.readline()) for _ in range(Q)]

StoT = [0]*A
for i, s in enumerate(S[1:-1]):
    x = br(T, s)
    StoT[i] = (s, min(s - T[x-1], T[x] - s))

TtoS = [0]*B
for i, t in enumerate(T[1:-1]):
    x = br(S, t)
    TtoS[i] = (t, min(t - S[x-1], S[x] - t))

M = [(-inf, inf)] + TtoS + StoT + [(inf, inf)]
M.sort()
Mk , Mv = list(map(list, zip(*M)))
for x in X:
    idx = br(Mk, x)
    print(min(Mk[idx] - x + Mv[idx], x - Mk[idx-1] + Mv[idx-1]))

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)]
import bisect
for _ in range(q):
    x=int(input())
    sb=bisect.bisect_left(s,x)
    tb=bisect.bisect_left(t,x)
    ss=[x-s[max(sb-1,0)],x-s[min(sb,a-1)]]
    tt=[x-t[max(tb-1,0)],x-t[min(tb,b-1)]]
    l=[]
    for i in ss:
        for j in tt:
            if i*j>=0:
                l.append(max(abs(i),abs(j)))
            else:
                l.append(max(abs(i),abs(j))+2*min(abs(i),abs(j)))
    print(min(l))

Submission status: Accepted

Solution code:
import bisect

A, B, Q = map(int, input().split())
s = [None] * A
t = [None] * B
for i in range(A):
  s[i] = int(input())
for i in range(B):
  t[i] = int(input())
  
for _ in range(Q):
  x = int(input())
  sr = bisect.bisect_left(s, x)
  if sr == A:
    sr -= 1
  sl = max([0, sr - 1])
  tr = bisect.bisect_left(t, x)
  if tr == B:
    tr -= 1
  tl = max([0, tr - 1])
  sr = s[sr]
  sl = s[sl]
  tr = t[tr]
  tl = t[tl]
  cand = [abs(tl - x) + abs(sl - tl), abs(tl - x) + abs(sr - tl),
         abs(tr - x) + abs(sl - tr), abs(tr - x) + abs(sr - tr),
         abs(sl - x) + abs(tl - sl), abs(sl - x) + abs(tr - sl),
         abs(sr - x) + abs(tl - sr), abs(sr - x) + abs(tr - sr),]
  print(min(cand))

Submission status: Accepted

Solution code:
# お約束
INF = float("inf")
MOD = int(1e9 + 7)
def int1(n):
    return int(n) - 1
def parse(args, *params):
    return tuple(p(v) for p, v in zip(params, next(args).split()))

# 二分探索
def bsr(a, v, lo=0, hi=None):
    if hi == None:
        hi = len(a) - 1
    if hi < lo:
        return lo
    mi = (lo + hi) // 2
    if v < a[mi]:
        return bsr(a, v, lo, mi - 1)
    else:
        return bsr(a, v, mi + 1, hi)

# エントリーポイント
def main(args):
    A, B, Q = parse(args, int, int, int)
    S = list(int(next(args)) for _ in range(A))
    T = list(int(next(args)) for _ in range(B))
    X = tuple(int(next(args)) for _ in range(Q))

    s = [-INF] + S + [INF]
    t = [-INF] + T + [INF]
    for x in X:
        sr = bsr(s, x)
        sl = sr - 1
        tr = bsr(t, x)
        tl = tr - 1
        min_cost = INF
        for st in [s[sl], s[sr]]:
            for tt in [t[tl], t[tr]]:
                min_cost = min(min_cost, abs(st - x) + abs(tt - st))
                min_cost = min(min_cost, abs(tt - x) + abs(tt - st))
        print(min_cost)

import sys
if __name__ == '__main__':
    main(iter(sys.stdin.read().split("\n")))

Submission status: Accepted

Solution code:
# お約束
INF = float("inf")
MOD = int(1e9 + 7)
def int1(n):
    return int(n) - 1
def parse(args, *params):
    return tuple(p(v) for p, v in zip(params, next(args).split()))

from bisect import bisect_right as bsr

# エントリーポイント
def main(args):
    A, B, Q = parse(args, int, int, int)
    S = list(int(next(args)) for _ in range(A))
    T = list(int(next(args)) for _ in range(B))
    X = tuple(int(next(args)) for _ in range(Q))

    s = [-INF] + S + [INF]
    t = [-INF] + T + [INF]
    for x in X:
        sr = bsr(s, x)
        sl = sr - 1
        tr = bsr(t, x)
        tl = tr - 1
        min_cost = INF
        for st in [s[sl], s[sr]]:
            for tt in [t[tl], t[tr]]:
                min_cost = min(min_cost, abs(st - x) + abs(tt - st))
                min_cost = min(min_cost, abs(tt - x) + abs(tt - st))
        print(min_cost)

import sys
if __name__ == '__main__':
    main(iter(sys.stdin.read().split("\n")))

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


A, B, Q = list(map(int, input().split()))
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]

for _ in range(Q):
    x = int(input())
    i = bl(S, x)
    j = bl(T, x)
    d = set()
    if i < A:
        a = S[i]
        if j < B:
            if T[j] <= a:
                d.add(a - x)
            else:
                d.add(T[j] - x)
                if j > 0:
                    k, l = a - x, x - T[j-1]
                    if k < l:
                        d.add(2 * k + l)
                    else:
                        d.add(2 * l + k)
        else:
            k, l = a - x, x - T[j-1]
            if k < l:
                d.add(2 * k + l)
            else:
                d.add(2 * l + k)
    if i > 0:
        a = S[i-1]
        if j > 0:
            if T[j-1] >= a:
                d.add(x - a)
            else:
                d.add(x - T[j-1])
                if j < B:
                    k, l = x - a, T[j] - x
                    if k < l:
                        d.add(2 * k + l)
                    else:
                        d.add(2 * l + k)
        else:
            k, l = x - a, T[j] - x
            if k < l:
                d.add(2 * k + l)
            else:
                d.add(2 * l + k)
    print(min(d))

Submission status: Accepted

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

INF = 10**18

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

for q in range(Q):
  x = int(input())
  b = bisect.bisect_right(s, x)
  d = bisect.bisect_right(t, x)
  res = 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)
      res = min(res, d1, d2)
      
  print(res)

Submission status: Accepted

Solution code:
import bisect
a,b,q = map(int,input().split())
s = list(int(input()) for _ in range(a))
t = list(int(input()) for _ in range(b))
x = list(int(input()) for _ in range(q))

s.insert(0,-10**18)
s.append(10**18)
t.insert(0,-10**18)
t.append(10**18)

for i in range(q):
    insert_xs = bisect.bisect_left(s,x[i])
    insert_xt = bisect.bisect_left(t,x[i])
    answer = 10**18
    for k1 in range(2):
        for k2 in range(2):
            distant = abs(s[insert_xs - k1]-x[i]) + abs(s[insert_xs - k1]-t[insert_xt - k2])
            if distant < answer:
                answer = distant
            distant = abs(t[insert_xt - k2]-x[i]) + abs(t[insert_xt - k2]-s[insert_xs - k1])
            if distant < answer:
                answer = distant
    print(answer)

Submission status: Accepted

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


def solve(A: int, B: int, Q: int, s: "List[int]", t: "List[int]", x: "List[int]"):
    s = [-1e18] + s + [1e18]
    t = [-1e18] + t + [1e18]
    for q in x:
        sRight = bisect.bisect_left(s, q)
        tRight = bisect.bisect_left(t, q)
        sLeft = sRight - 1
        tLeft = tRight - 1

        rr = max(s[sRight]-q, t[tRight]-q)
        ll = max(q-s[sLeft], q-t[tLeft])

        rl = min(
            2 * (s[sRight]-q) + (q-t[tLeft]),
            2 * (t[tRight]-q) + (q-s[sLeft]),
            2 * (q-s[sLeft]) + (t[tRight]-q),
            2 * (q-t[tLeft]) + (s[sRight]-q),
        )
        print(min(rr, ll, rl))
    return


# Generated by 1.1.4 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 = [ 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()