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: Wrong Answer

Solution code:
import sys
import os
import math
import bisect

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: x * y / math.gcd(x, y)

MOD = 10 ** 9 + 7
MAX = float('inf')


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    A, B, Q = il()
    J = [-MAX] + [ii() for _ in range(A)] + [MAX]
    T = [-MAX] + [ii() for _ in range(B)] + [MAX]
    que = [ii() for _ in range(Q)]
    for q in que:
        a = bisect.bisect_left(J, q)
        b = bisect.bisect_left(T, q)
        ret = MAX
        for j in J[a - 1:a]:
            for t in T[b - 1:b + 1]:
                ret = min(ret, abs(j - q) + abs(j - t), abs(t - q) + abs(t - j))
        print(ret)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from fractions import gcd
from itertools import combinations # (string,3) 3回
from collections import deque
from collections import defaultdict
import bisect
#
#    d = m - k[i] - k[j]
#    if kk[bisect.bisect_right(kk,d) - 1] == d:
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#

import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7

def readInts():
  return list(map(int,input().split()))
def main():
    a,b,q = readInts()
    S = [int(input()) for _ in range(a)]
    S = sorted(S)
    T = [int(input()) for _ in range(b)]
    T = sorted(T)
    for i in range(q):
        x = int(input())
        ans = 0
        now = x
        Sa = float("inf")
        Ta = float("inf")
        Sidx = bisect.bisect_right(S,x)
        Tidx = bisect.bisect_right(T,x)
        #print("-!-",x,Sidx,S)
        #print("-?-",x,Tidx,T)
        # ------------------------------------
        if Sidx < len(S):
            Sa = abs(S[Sidx] - x)
            Si = Sidx
        if Sidx - 1 >= 0:
            if Sa > abs(S[Sidx-1] - x):
                Sa = abs(S[Sidx-1] - x)
                Si = Sidx - 1
        # ------------------------------------
        if Tidx < len(T):
            if Ta > abs(T[Tidx] - x):
                Ta = abs(T[Tidx] - x)
                Ti = Tidx
        if Tidx - 1 >= 0:
            if Ta > abs(T[Tidx-1] - x):
                Ta = abs(T[Tidx-1] - x)
                Ti = Tidx - 1
        # ------------------------------------
        #print(Sa,Ta)
        if Ta > Sa:
            now = S[Si]
            ans += Sa
            jin = False
        else:
            now = T[Ti]
            ans += Ta
            jin = True
        #print(ans)
        #print("ans",ans,"now",now,jin)
        mi_ = float("inf")
        if jin:# 次神社を調べろ
            Sidx = bisect.bisect_right(S,now)
            if Sidx < len(S):
                mi_ = abs(now - S[Sidx])
            if Sidx - 1 >= 0:
                mi_ = min(mi_, abs(now - S[Sidx-1]))
            ans += mi_
        else:
            Tidx = bisect.bisect_right(T,now)
            if Tidx < len(T):
                mi_ = abs(now - T[Tidx])
            if Tidx - 1 >= 0:
                mi_ = min(mi_, abs(now - T[Tidx-1]))
            ans += mi_
        print(ans)
        #print("--next--")

if __name__ == '__main__':
  main()

Submission status: Wrong Answer

Solution code:
import bisect
a,b,q = map(int,input().split())
s = []
t = []
s1 = []
t1 = []

for _ in range(a):
    s.append(int(input()))
for _ in range(b):
    t.append(int(input()))

for i in range(a-1):
    s1.append((s[i]+s[i+1])/2)
for i in range(b-1):
    t1.append((t[i]+t[i+1])/2)

for _ in range(q):
    x = int(input())
    xs = s[bisect.bisect_left(s1, x)]
    xt = t[bisect.bisect_left(t1, x)]
    xst = t[bisect.bisect_left(t1, xs)]
    xts = s[bisect.bisect_left(s1, xt)]
    ans1 = abs(x - xs) + abs(xs - xst)
    ans2 = abs(x - xt) + abs(xt - xts)
    print(min(ans1, ans2))

Submission status: Wrong Answer

Solution code:
inf = float("INF")
a,b,q = map(int, input().split())
s = [None] * (a + 3)
s[0:2] = [-inf,-inf]
s[-1] = inf
t = [None] * (b + 3)
t[0:2] = [-inf,-inf]
t[-1] = inf
s[2:-1] = list(map(int, input().split()))
t[2:-1] = list(map(int, input().split()))

from bisect import bisect_left
from collections import defaultdict

dp = defaultdict(lambda: None)

def f(s,t,x,ss,i):
  if dp[(ss,i)] != None: return abs(x - s[ss]) + dp[(ss,i)]
  tr = bisect_left(t, s[ss])
  tl = tr - 1
  dp[(ss,i)] = min(abs(s[ss] - t[tl]), abs(s[ss] - t[tr]))
  return abs(x - s[ss]) + dp[(ss,i)]


for _ in range(q):
  ans = inf
  x = int(input())
  sr = bisect_left(s, x)
  ans = min(ans, f(s,t,x,sr,0))
  ans = min(ans, f(s,t,x,sr - 1,0))
  tr = bisect_left(t, x)
  ans = min(ans, f(t,s,x,tr,1))
  ans = min(ans, f(t,s,x,tr - 1,1))
  print(ans)

Submission status: Wrong Answer

Solution code:
inf = float("INF")
a,b,q = map(int, input().split())
s = [-inf, -inf]+[int(input()) for _ in range(a)]+[inf]
t = [-inf, -inf]+[int(input()) for _ in range(b)]+[inf]

from bisect import bisect_left

ans = inf
for _ in range(q):
  x = int(input())
  sr = bisect_left(s, x)
  sl = sr - 1
  tl = bisect_left(t, s[sr])
  tr = tl - 1
  ans = min(ans, abs(x - s[sr]) + min(abs(s[sr] - t[tl]), abs(s[sr] - t[tr])))
  tl = bisect_left(t, s[sl])
  tr = tl - 1
  ans = min(ans, abs(x - s[sl]) + min(abs(s[sl] - t[tl]), abs(s[sl] - t[tr])))
  tr = bisect_left(t, x)
  tl = tr - 1
  sl = bisect_left(s, t[tr])
  sr = sl - 1
  ans = min(ans, abs(x - t[tr]) + min(abs(t[tr] - s[sl]), abs(t[tr] - s[sr])))
  sl = bisect_left(s, t[tl])
  sr = sl - 1
  ans = min(ans, abs(x - t[tl]) + min(abs(t[tl] - s[sl]), abs(t[tl] - s[sr])))
print(ans)

Submission status: Wrong Answer

Solution code:
a,b,q = map(int,input().split())
sl = []
for _ in range(a):
    s = int(input())
    sl.append(s)
sl = sorted(sl)

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

tl = sorted(tl)

import bisect
for _ in range(q):
    x = int(input())
    idx = bisect.bisect_left(sl, x)
    idx2 = bisect.bisect_left(tl, x)
    # print(idx, idx2)
    if idx == 0:
        s1 = -float("inf")
    else:
        s1 = sl[idx-1]
    if idx < a:
        s2 = sl[idx]
    else:
        s2 = float("inf")
    if idx2 == 0:
        t1 = -float("inf")
    else:
        t1 = tl[idx2-1]
    if idx2 < b:
        t2 = tl[idx2]
    else:
        t2 = float("inf")
    # print(idx,sl,s1,s2)
    # print(idx2,tl,t1,t2)
    A = max(s2, t2) - x
    B = x - min(s1, t1)
    c = (x - t1) + (s2 - t1)
    d = (x - s1) + (t2 - s1)
    e = (t2 - x) + (t2 - s1)
    f = (t1 - x) + (s2 - t1)
    print(min(A,B,c,d,e,f))

Submission status: Wrong Answer

Solution code:
jin,ter,q=map(int,input().split())
jil,tel=[-float("INF")]+[int(input()) for i in range(jin)]+[float("INF")],[-float("INF")]+[int(input()) for i in range(ter)]+[float("INF")]
from bisect import bisect_left as bl
for _ in range(q):
    x=int(input())
    ans=float("INF")
    b,d=bl(jil,x),bl(tel,x)
    for s in jil[b:b+2]:
        for t in tel[d:d+2]:
            ans=min(min(abs(x-s),abs(t-x))+abs(t-s),ans)
    print(ans)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left,bisect_right
a,b,q=map(int,input().split())
s=[-(10**21)]+[int(input())for _ in range(a)]+[10**21]
t=[-(10**21)]+[int(input())for _ in range(b)]+[10**21]
for _ in range(q):
  x=int(input())
  s1,s2=s[bisect_right(s,x)-1],s[bisect_right(s,x)]
  t1,t2=t[bisect_right(t,x)-1],t[bisect_right(t,x)]
  ans=10**11
  for i in [s1,s2]:
    for j in [t1,t2]:
      ans=min(ans,abs(i-j)+min(abs(x-i),abs(x-j)))
print(ans)

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left,bisect_right
a,b,q=map(int,input().split())
s=[-(10**10+7)]+[int(input())for _ in range(a)]+[10**10+7]
t=[-(10**10+7)]+[int(input())for _ in range(b)]+[10**10+7]
for _ in range(q):
  x=int(input())
  s1,s2=s[bisect_right(s,x)-1],s[bisect_right(s,x)]
  t1,t2=t[bisect_right(t,x)-1],t[bisect_right(t,x)]
  ans=10**11
  for i in [s1,s2]:
    for j in [t1,t2]:
      ans=min(ans,abs(i-j)+min(abs(x-i),abs(x-j)))
  print(ans)

Submission status: Wrong Answer

Solution code:
import bisect
from functools import reduce

A, B, Q = map(int,input().split())
INF = float("inf")
s = [-1*INF]
t = [-1*INF]
for _ in range(A):
    s.append(int(input()))
s.append(INF)
for _ in range(B):
    t.append(int(input()))
t.append(INF)
for _ in range(Q):
    x = int(input())
    s_index = bisect.bisect_left(s,x)
    t_index = bisect.bisect_left(t,x)
    s_l = x - s[s_index-1]
    s_r = s[s_index] - x
    t_l = x - t[t_index-1]
    t_r = t[t_index] - x
    l_short, l_long = s_l,t_l
    r_short, r_long = s_r,t_r
    if l_short > l_long:
        l_short, l_long = l_long, l_short
    if r_short > r_long:
        r_short, r_long = r_long, r_short
    short_short = min(l_short, r_short)
    ans = min(l_long, l_short+r_short+short_short, r_long)
    print(ans)

Submission status: Wrong Answer

Solution code:
print('One More Challenge!')

Submission status: Wrong Answer

Solution code:


import bisect

def nearest(x, lst):
    p = bisect.bisect_left(lst, x)
    
    if p == 0:
        return lst[p], None
    if p == len(lst):
        return lst[p - 1], None
    if lst[p] == x:
        return lst[p], None
 
    if abs(x - lst[p - 1]) == abs(x - lst[p]):
        return lst[p - 1], lst[p]
    elif abs(x - lst[p - 1]) < abs(x - lst[p]):
        return lst[p - 1], None
    else:
        return lst[p], None

        


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

    slist = [int(input()) for _ in range(a)]
    tlist = [int(input()) for _ in range(b)]
    qlist = [int(input()) for _ in range(q)]

    near_s = {s: nearest(s, tlist) for s in slist}
    near_t = {t: nearest(t, slist) for t in tlist}

    anss = []
    for q in qlist:
        ans = float('inf')
        # 一番近いs->tの順の場合
        n = nearest(q, slist)
        for e in n:
            if e:
                nn, _ = near_s[e]
                if ans > abs(q - e) + abs(nn - e):
                    ans = abs(q - e) + abs(nn - e)                            
        # 一番近いt->sの順の場合
        n = nearest(q, tlist)
        for e in n:
            if e:
                nn, _ = near_t[e]
                if ans > abs(q - e) + abs(nn - e):
                    ans = abs(q - e) + abs(nn - e)
        anss.append(ans)

    for ans in anss:
        print(ans)


submit()

Submission status: Wrong Answer

Solution code:
import bisect
M = 10**12
a, b, q = [int(x) for x in input().split()]
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
for i in range(q):
  x = int(input())
  lst = []
  i_s = bisect.bisect_left(s, x)
  i_t = bisect.bisect_left(t, x)
  if i_s == 0:
    sl, sr = -M, s[i_s]
  elif i_s == a:
    sl, sr = s[i_s-1], M
  else:
    sl, sr = s[i_s-1], s[i_s]
  if i_t == 0:
    tl, tr = -M, t[i_t]
  elif i_t == b:
    tl, tr = t[i_t-1], M
  else:
    tl, tr = t[i_t-1], t[i_t]
  lst.append(x-min(sl, tl))
  lst.append(max(sr, tr)-x)
  lst.append(2*(x-max(sl, tl)) + min(sr, tr) - x)
  lst.append(2*(min(sr, tr)-x) + x - max(sl, tl))
  print(min(lst))

Submission status: Wrong Answer

Solution code:
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10**7)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations, accumulate, groupby
    #from itertools import product
    from bisect import bisect_left,bisect_right
    import heapq
    from math import floor, ceil
    #from operator import itemgetter

    #inf = 10**17
    #mod = 10**9 + 7

    a,b,q = map(int, input().split())
    s = [int(input()) for _ in range(a)] + [-10**20, 10**20]
    t = [int(input()) for _ in range(b)] + [-10**20, 10**20]
    s.sort()
    t.sort()

    for _ in range(q):
        x = int(input())
        la = bisect_left(s, x) -1 
        lb = bisect_left(t, x) -1
        if s[la] < t[lb]:
            if s[la+1] < t[lb+1]:
                print(min(x-s[la], t[lb+1]-x, s[la+1]-x+(x-t[lb])*2, x-t[lb]+(s[la+1]-x)*2))
            else:
                print(min(x-s[la], s[la+1]-x, t[lb+1]-x+(x-t[lb])*2, x-t[lb]+(t[lb+1]-x)*2))
        else:
            if s[la+1] < t[lb+1]:
                print(min(x-t[lb], t[lb+1]-x, s[la+1]-x+(x-s[la])*2, x-s[la]+(s[la+1]-x)*2))
            else:
                print(min(x-t[lb], s[la+1]-x, t[lb+1]-x+(x-s[la])*2, x-s[la]+(t[lb+1]-x)*2))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python
# coding: utf-8
import os
from sys import stdin, stdout

if(os.getenv('__LOCAL__')):
    __dirname = os.path.dirname(__file__)
    __basename = os.path.splitext(os.path.basename(__file__))[0]
    __inputname = './input/' + __basename + '.txt'
    __outputname = './output/' + __basename + '.txt'
    __input_path = os.path.join(__dirname, __inputname)
    __output_path = os.path.join(__dirname, __outputname)
    stdin = open(__input_path)
    # stdout = open(__output_path, "w")

def main():
    A, B, Q = map(int, stdin.readline().rstrip().split(' '))
    s = list()
    t = list()
    s.append(-1e12)
    t.append(-1e12)
    s += [int(stdin.readline()) for _ in range(A)]
    t += [int(stdin.readline()) for _ in range(B)]
    X = [int(stdin.readline()) for _ in range(Q)]
    ansvec = list()
    s.append(1e12)
    t.append(1e12)
    stdout.write("{}\n".format(s))
    stdout.write("{}\n".format(t))
    stdout.write("{}\n".format(X))
    for x in X:
        ls = 0
        rs = A+2
        lt = 0
        rt = B+2
        while(rs-ls>1):
            mids=(ls+rs)//2
            if(s[mids]<=x):
                ls = mids
            else:
                rs = mids

        while(rt-lt>1):
            midt=(lt+rt)//2
            if(t[midt]<=x):
                lt = midt
            else:
                rt = midt

        if(t[lt]<=s[ls] and s[rs]<=t[rt]):
            ans = min(abs(t[lt]-x),abs(t[rt]-x))
        elif(s[ls]<=t[lt] and t[rt]<=s[rs]):
            ans = min(abs(s[ls]-x),abs(s[rs]-x))
        elif(s[ls]<=t[lt] and s[rs]<=t[rt]):
            ans = min(abs(s[ls]-x),abs(t[rt]-x), 2*abs(s[rs]-x)+abs(t[lt]-x), 2*abs(t[lt]-x)+abs(s[rs]-x))
        elif(t[lt]<=s[ls] and t[rt]<=s[rs]):
            ans = min(abs(t[lt]-x),abs(s[rs]-x), 2*abs(s[ls]-x)+abs(t[rt]-x), 2*abs(t[rt]-x)+abs(s[ls]-x))
        ansvec.append(ans)

    for a in ansvec:
        stdout.write("{}\n".format(a))

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys

read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines

# rstrip().decode('utf-8')
# map(int,input().split())
# import numpy as np

inf=10**18

import bisect

def main():
	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 x:
		si=bisect.bisect_left(s,i)
		ti=bisect.bisect_left(t,i)
		
		l=i-min(s[si-1],t[ti-1])
		r=max(s[si],t[ti])-i
		lr=s[si]-s[si-1]+t[ti]-t[ti-1]-(l+r)+min(s[si]-i,i-s[si-1],t[ti]-i,i-t[ti-1])
		print(min(l,r,lr))

	
	

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

Solution code:
import sys

read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines

# rstrip().decode('utf-8')
# map(int,input().split())
# import numpy as np

inf=10**18

import bisect

def main():
	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 x:
		si=bisect.bisect_left(s,i)
		ti=bisect.bisect_left(t,i)
		
		l=i-min(s[si-1],t[ti-1])
		r=max(s[si],t[ti])-i
		lr=min(s[si],t[ti])-max(s[si-1],t[ti-1])+min(s[si]-i,i-s[si-1],t[ti]-i,i-t[ti-1])
		print(min(l,r,lr))
	
	
	
	
	
	
	
	
	
	
	
	

if __name__ == "__main__":
	main()

Submission status: Wrong Answer

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())
    s_idx = bisect.bisect_left(S, x)
    t_idx = bisect.bisect_left(T, x)
    if s_idx == A and t_idx == B:
        ans = x-min(S[-1], T[-1])
    elif s_idx == A and t_idx == 0:
        ans = min(x-S[-1]*2+T[0], T[0]*2-x-S[-1])
    elif t_idx == B and s_idx == 0:
        ans = min(x-T[-1]*2+S[0], S[0]*2-x-T[-1])
    elif s_idx == A:
        ans = min(x-min(S[-1], T[t_idx-1]), x-S[-1]*2+T[t_idx], T[t_idx]*2-x-S[-1])
    elif t_idx == B:
        ans = min(x-min(T[-1], S[s_idx-1]), x-T[-1]*2+S[s_idx], S[s_idx]*2-x-T[-1])
    elif s_idx == 0 and t_idx == 0:
        ans = max(S[0], T[0])-x
    elif s_idx == 0:
        ans = min(max(S[0], T[t_idx])-x, S[0]*2-x-T[t_idx-1], x-T[t_idx-1]*2+S[0])
    elif t_idx == 0:
        ans = min(max(T[0], S[s_idx])-x, T[0]*2-x-S[s_idx-1], x-S[s_idx-1]*2+T[0])
    else:
        ans = min(max(S[s_idx], T[t_idx])-x, x-min(S[s_idx-1], T[t_idx-1]), S[s_idx]*2-x-T[t_idx-1], T[t_idx]*2-x-S[s_idx-1])
    print(ans)

Submission status: Wrong Answer

Solution code:
import sys, math, bisect
sys.setrecursionlimit(200010)

def input():
    return sys.stdin.readline()[:-1]

def main():
    A, B, Q = map(int,input().split())
    s = [-10**12] + sorted([int(input()) for k in range(A)]) + [10**12]
    t = [-10**12] + sorted([int(input()) for k in range(B)]) + [10**12]
    for _ in range(Q):
        q = int(input())
        s1 = s[bisect.bisect_left(s,q)]
        s2 = s[bisect.bisect_left(s,q)-1]
        t1 = t[bisect.bisect_left(t,q)]
        t2 = t[bisect.bisect_left(t,q)-1]
        d1 = max(q-s2,q-t2)
        d2 = max(s1-q,t1-q)
        d3 = 2*(q-s2)+t1-q
        d4 = 2*(q-t2)+s1-q
        d5 = 2*(s1-q)+q-t2
        d5 = 2*(t1-q)+q-s2
        print(min(d1,d2,d3,d4,d5))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left
A, B, Q, *L = map(int, open(0).read().split())
s = L[:A]
t = L[A:A+B]
x = L[A+B:]

s = [-float('inf')]+s+[float('inf')]
t = [-float('inf')]+t+[float('inf')]
for c in x:
  br = bisect_left(t,c)
  ar = bisect_left(s,c)
  bl = br-1
  al = ar-1
  print(min(s[ar]-t[bl]+min(s[ar]-c,c-t[bl]),t[br]-s[al]+min(t[br]-c,c-s[al]),
            -min(t[bl],s[al]),max(s[ar],t[br])-c))

Submission status: Wrong Answer

Solution code:
#119_D
A,B,Q=map(int,input().split())
INF=10**15
S=[-INF]+[int(input()) for _ in range(A)]+[INF]
T=[-INF]+[int(input()) for _ in range(B)]+[INF]

from bisect import bisect_left

for _ in range(Q):
    Ans=10**11
    x=int(input())
    s=bisect_left(S,x)
    t=bisect_left(T,x)
    
    sr=abs(S[s]-x)
    sl=abs(S[s-1]-x)
    tr=abs(T[t]-x)
    tl=abs(T[t-1]-x)
    
    Ans=min(max(sr,tr),max(sl,tl),2*min(sr,tr)+min(sl,tl),
            min(sr,tr)+2*min(sl,tl))
    
    print(Ans)

Submission status: Wrong Answer

Solution code:
import bisect

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


for _ in range(q):
    
    x = int(input())
    ans = float('inf')
    
    # 最初に寺を訪れる場合と最初に神社を訪れる場合に分ける
    for first, second in [[s, t], [t, s]]:
        d = 0
        # 1箇所目
        r = bisect.bisect_right(first, x)
        if abs(x - first[r]) <= abs(x - first[r-1]):
            d += abs(x - first[r])
            nx = first[r]
        else:
            d += abs(x - first[r-1])
            nx = first[r-1]
        # 2箇所目
        r = bisect.bisect_right(second, nx)
        if abs(nx - second[r]) <= abs(nx - second[r-1]):
            d += abs(nx - second[r])
        else:
            d += abs(nx - second[r-1])
        ans = min(ans, d)
        
    print(ans)

Submission status: Wrong Answer

Solution code:
import bisect

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


for _ in range(q):
    
    x = int(input())
    ans = float('inf')
    
    # 最初に寺を訪れる場合と最初に神社を訪れる場合に分ける
    for first, second in [[s, t], [t, s]]:
        d = 0
        # 1箇所目
        r = bisect.bisect_right(first, x)
        if abs(x - first[r]) <= abs(x - first[r-1]):
            d += abs(x - first[r])
            nx = first[r]
        else:
            d += abs(x - first[r-1])
            nx = first[r-1]
        # 2箇所目
        r = bisect.bisect_right(second, nx)
        if abs(nx - second[r]) <= abs(nx - second[r-1]):
            d += abs(nx - second[r])
        else:
            d += abs(nx - second[r-1])
        ans = min(ans, d)
        
    print(ans)

Submission status: Wrong Answer

Solution code:

import numpy as np
from functools import *
import sys
sys.setrecursionlimit(100000)


def acinput():
    return list(map(int, input().split(" ")))


def II():
    return int(input())

mod = 10**9+7


def factorial(n):
    fact = 1
    for integer in range(1, n + 1):
        fact *= integer
    return fact



def serch(x, count):
    #print("top", x, count)
            

    for d in directions:
        nx = d+x
        #print(nx)
        if np.all(0 <= nx) and np.all(nx < (H, W)):
            if field[nx[0]][nx[1]] == "E":
                count += 1 
                field[nx[0]][nx[1]] = "V"
                count = serch(nx, count)  
                continue
            if field[nx[0]][nx[1]] == "#":
                field[nx[0]][nx[1]] = "V"
                count = serch(nx, count)    
                 
    return count

a,b,q=acinput()

S=[]
for i in range(a):
    S.append(II())

T=[]
for i in range(b):
    T.append(II())

X=[II() for i in range(q)]

import bisect


def near(arr,v):
    t=bisect.bisect(arr,v)

    
    #print(arr,v,t)
    if t>len(arr)-1:
        return len(arr)-1
    if t==0:
        return 0

    t-=1
    m = (abs(arr[t]-v) > abs(arr[t+1]-v))
    res = t+m
    #print(arr, v, res,m)
    return res



for i in range(q):
    x=X[i]

    s=near(S,x)
    t=near(T,S[s])
    res1=abs(S[s]-x)+abs(T[t]-S[s])

    t = near(T, x)
    s = near(S, T[t])
    res2 = abs(T[t]-x)+abs(T[t]-S[s])

    print(min(res1,res2))

Submission status: Wrong Answer

Solution code:

import numpy as np
from functools import *
import sys
sys.setrecursionlimit(100000)


def acinput():
    return list(map(int, input().split(" ")))


def II():
    return int(input())

mod = 10**9+7


def factorial(n):
    fact = 1
    for integer in range(1, n + 1):
        fact *= integer
    return fact



def serch(x, count):
    #print("top", x, count)
            

    for d in directions:
        nx = d+x
        #print(nx)
        if np.all(0 <= nx) and np.all(nx < (H, W)):
            if field[nx[0]][nx[1]] == "E":
                count += 1 
                field[nx[0]][nx[1]] = "V"
                count = serch(nx, count)  
                continue
            if field[nx[0]][nx[1]] == "#":
                field[nx[0]][nx[1]] = "V"
                count = serch(nx, count)    
                 
    return count

a,b,q=acinput()

S=[]
for i in range(a):
    S.append(II())

T=[]
for i in range(b):
    T.append(II())

X=[II() for i in range(q)]

import bisect


def near(arr,v):
    t=bisect.bisect(arr,v)

    
    if t>=len(arr)-1:
        return len(arr)-1
    if t==0:
        return 0
    #print(t)
    t-=1
    m = (abs(arr[t]-v) > abs(arr[t+1]-v))
    res = t+m
   #print(arr, v, res,m)
    return res



for i in range(q):
    x=X[i]

    s=near(S,x)
    t=near(T,S[s])
    res1=abs(S[s]-x)+abs(T[t]-S[s])

    t = near(T, x)
    s = near(S, T[t])
    res2 = abs(T[t]-x)+abs(T[t]-S[s])

    print(min(res1,res2))

Submission status: Wrong Answer

Solution code:

import numpy as np
from functools import *
import sys
sys.setrecursionlimit(100000)


def acinput():
    return list(map(int, input().split(" ")))


def II():
    return int(input())

mod = 10**9+7


def factorial(n):
    fact = 1
    for integer in range(1, n + 1):
        fact *= integer
    return fact



def serch(x, count):
    #print("top", x, count)
            

    for d in directions:
        nx = d+x
        #print(nx)
        if np.all(0 <= nx) and np.all(nx < (H, W)):
            if field[nx[0]][nx[1]] == "E":
                count += 1 
                field[nx[0]][nx[1]] = "V"
                count = serch(nx, count)  
                continue
            if field[nx[0]][nx[1]] == "#":
                field[nx[0]][nx[1]] = "V"
                count = serch(nx, count)    
                 
    return count

a,b,q=acinput()

S=[]
for i in range(a):
    S.append(II())

T=[]
for i in range(b):
    T.append(II())

X=[II() for i in range(q)]

import bisect


def near(arr,v):
    t=bisect.bisect_right(arr,v)

    
    if t==len(arr):
        return len(arr)-1
    if t==0:
        return 0
    #print(t)
    t-=1
    m = (abs(arr[t]-v) > abs(arr[t+1]-v))
    res = t+m
   #print(arr, v, res,m)
    return res



for i in range(q):
    x=X[i]

    s=near(S,x)
    t=near(T,S[s])
    res1=abs(S[s]-x)+abs(T[t]-S[s])

    t = near(T, x)
    s = near(S, T[t])
    res2 = abs(T[t]-x)+abs(T[t]-S[s])

    print(min(res1,res2))

Submission status: Wrong Answer

Solution code:

import numpy as np
from functools import *
import sys
sys.setrecursionlimit(100000)


def acinput():
    return list(map(int, input().split(" ")))


def II():
    return int(input())

mod = 10**9+7


def factorial(n):
    fact = 1
    for integer in range(1, n + 1):
        fact *= integer
    return fact



def serch(x, count):
    #print("top", x, count)
            

    for d in directions:
        nx = d+x
        #print(nx)
        if np.all(0 <= nx) and np.all(nx < (H, W)):
            if field[nx[0]][nx[1]] == "E":
                count += 1 
                field[nx[0]][nx[1]] = "V"
                count = serch(nx, count)  
                continue
            if field[nx[0]][nx[1]] == "#":
                field[nx[0]][nx[1]] = "V"
                count = serch(nx, count)    
                 
    return count

a,b,q=acinput()

S=[]
for i in range(a):
    S.append(II())

T=[]
for i in range(b):
    T.append(II())

X=[II() for i in range(q)]

import bisect


def near(arr,v):
    t=bisect.bisect_right(arr,v)

    #print(arr,t,v)
    if t==len(arr):
        return len(arr)-1
    t-=1
    t=max(t,0)
    return t+(abs(arr[t]-v)<abs(arr[t]-v))



for i in range(q):
    x=X[i]

    s=near(S,x)
    t=near(T,S[s])
    res1=abs(S[s]-x)+abs(T[t]-S[s])

    t = near(T, x)
    s = near(S, T[t])
    res2 = abs(T[t]-x)+abs(T[t]-S[s])

    print(min(res1,res2))

Submission status: Wrong Answer

Solution code:

import numpy as np
from functools import *
import sys
sys.setrecursionlimit(100000)


def acinput():
    return list(map(int, input().split(" ")))


def II():
    return int(input())

mod = 10**9+7


def factorial(n):
    fact = 1
    for integer in range(1, n + 1):
        fact *= integer
    return fact



def serch(x, count):
    #print("top", x, count)
            

    for d in directions:
        nx = d+x
        #print(nx)
        if np.all(0 <= nx) and np.all(nx < (H, W)):
            if field[nx[0]][nx[1]] == "E":
                count += 1 
                field[nx[0]][nx[1]] = "V"
                count = serch(nx, count)  
                continue
            if field[nx[0]][nx[1]] == "#":
                field[nx[0]][nx[1]] = "V"
                count = serch(nx, count)    
                 
    return count

a,b,q=acinput()

S=[]
for i in range(a):
    S.append(II())

T=[]
for i in range(b):
    T.append(II())

X=[II() for i in range(q)]

import bisect

for i in range(q):
    x=X[i]

    t=bisect.bisect(S,x)
    t=min(t,a-1)
    d1=abs(S[t]-x)
    t2=bisect.bisect(T,S[t])
    t2=min(t2,b-1)
    d2=abs(T[t2]-S[t])

    res=d1+d2

    t = bisect.bisect(T, x)
    t = min(t, b-1)
    d1 = abs(T[t]-x)
    t2 = bisect.bisect(S,T[t])
    t2 = min(t2, a-1)
    d2 = abs(S[t2]-T[t])
    res=min(res,d1+d2)
    print(res)