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

Submission status: Accepted

Solution code:
import bisect

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

shrines = []
for i in range(A):
    shrines.append(int(input()))

temples = []
for i in range(B):
    temples.append(int(input()))

shortest_s_to_t = {}
for shrine in shrines:
    index = bisect.bisect_left(temples, shrine)
    if index == 0:
        distance = abs(shrine - temples[index])
        shortest_s_to_t[shrine] = distance
    elif index == B:
        distance = abs(shrine - temples[index - 1])
        shortest_s_to_t[shrine] = distance
    else:
        distance_left = abs(shrine - temples[index - 1])
        distance_right = abs(shrine - temples[index])
        shortest_s_to_t[shrine] = min(distance_left, distance_right)

shortest_t_to_s = {}
for temple in temples:
    index = bisect.bisect_left(shrines, temple)
    if index == 0:
        distance = abs(temple - shrines[index])
        shortest_t_to_s[temple] = distance
    elif index == A:
        distance = abs(temple - shrines[index - 1])
        shortest_t_to_s[temple] = distance
    else:
        distance_left = abs(temple - shrines[index - 1])
        distance_right = abs(temple - shrines[index])
        shortest_t_to_s[temple] = min(distance_left, distance_right)

for i in range(Q):
    x = int(input())

    # shrine to temple
    index = bisect.bisect_left(shrines, x)
    ans = 10**11
    if index > 0:
        left_shrine = shrines[index - 1]
        candidate = abs(x - left_shrine) + shortest_s_to_t[left_shrine]
        ans = min(ans, candidate)
    if index < A:
        right_shrine = shrines[index]
        candidate = abs(x - right_shrine) + shortest_s_to_t[right_shrine]
        ans = min(ans, candidate)

    # temple to shrine
    index = bisect.bisect_left(temples, x)
    if index > 0:
        left_temple = temples[index - 1]
        candidate = abs(x - left_temple) + shortest_t_to_s[left_temple]
        ans = min(ans, candidate)
    if index < B:
        right_temple = temples[index]
        candidate = abs(x - right_temple) + shortest_t_to_s[right_temple]
        ans = min(ans, candidate)

    print(ans)

Submission status: Accepted

Solution code:
a, b, q = [int(i) for i in input().split(" ")]

s = [0] * a
t = [0] * b
x = [[0, 0]] * q

#a, b, q = [2, 3, 4]
#s = [100, 600]
#t = [400, 900, 1000]
#x = [[0, 150], [1, 2000], [2, 899], [3, 799]]

sd = 0
td = 0

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

x = sorted(x, key = lambda k: k[1])
ans = [[0, 0]] * q

def sdd(i, x):
    if i < 0 or i >= a:
        return 10**12
    else:
        return abs(s[i] - x)
    
def tdd(i, x):
    if i < 0 or i >= b:
        return 10**12
    else:
        return abs(t[i] - x)
        
for j in range(0, q):
    bf = False
    for i in range(sd, a):
        if s[i] > x[j][1]:
            sd = i
            bf = True
            break
    if not bf:
        sd = a
        
    bf = False

    for i in range(td, b):
        if t[i] > x[j][1]:
            td = i
            bf = True
            break
    if not bf:
        td = b
    
    xj = x[j][1]
    a1 = min(max(sdd(sd - 1, xj), tdd(td - 1, xj)), max(sdd(sd, xj), tdd(td, xj)))
    a2 = min(2 * sdd(sd - 1, xj) + tdd(td, xj), 2 * tdd(td - 1, xj) + sdd(sd, xj), sdd(sd - 1, xj) + 2 * tdd(td, xj), tdd(td - 1, xj) + 2 * sdd(sd, xj))
    ans[j] = [x[j][0], min(a1, a2)]

ans = sorted(ans, key = lambda k: k[0])
for i in range(0, q):
    print(ans[i][1])

Submission status: Accepted

Solution code:
import bisect

A, B, Q = map(int, input().split())
s = [None] * A
t = [None] * B
x = [None] * Q

for i in range(A):
    s[i] = int(input())
for i in range(B):
    t[i] = int(input())
for i in range(Q):
    x[i] = int(input())

s.sort()
t.sort()

def calc(s, t, x):
    len_s = len(s)
    len_t = len(t)

    def f_nishi_pos(l, x):
        p1 = bisect.bisect_left(l, x)
        #p2 = bisect.bisect_right(l, x)
        #if p2 == len(l):
        #    return p1-1
        #if l[p1] == l[p2]:
        #    return max(p2-1, 0)
        #else:
        #    return p1
        if p1 == len(l):
            return p1 - 1
        else:
            if l[p1] == x:
                return p1
            else:
                return p1 - 1

    def f_higashi_pos(l, x):
        #p1 = bisect.bisect_left(l, x)
        p2 = bisect.bisect_right(l, x)
        #if p1 == len(l):
        #    return p1-1
        #if l[p1] == l[p2]:
        #    return min(p1, len(l)-1)
        #else:
        #    return p1
        if p2 == len(l):
            return p2 - 1
        else:
            return p2

    # 神社 -> 寺
    ## 西の神社
    j_nishi_pos = f_nishi_pos(s, x)
    j_nishi = s[j_nishi_pos]
    ## 東の神社
    j_higashi_pos = f_higashi_pos(s, x)
    j_higashi = s[j_higashi_pos]

    ## 西の神社の西の寺
    j_nishi_t_nishi_pos = f_nishi_pos(t, j_nishi)
    j_nishi_t_nishi = t[j_nishi_t_nishi_pos]
    ## 西の神社の東の寺
    j_nishi_t_higashi_pos = f_higashi_pos(t, j_nishi)
    j_nishi_t_higashi = t[j_nishi_t_higashi_pos]
    ## 東の神社の西の寺
    j_higashi_t_nishi = t[f_nishi_pos(t, j_higashi)]
    ## 東の神社の東の寺
    j_higashi_t_higashi = t[f_higashi_pos(t, j_higashi)]


    # 寺 -> 神社
    t_nishi = t[f_nishi_pos(t, x)]
    t_higashi = t[f_higashi_pos(t, x)]
    
    ## 西の寺の西の神社
    t_nishi_j_nishi = s[f_nishi_pos(s, t_nishi)]
    ## 西の寺の東の神社
    t_nishi_j_higashi = s[f_higashi_pos(s, t_nishi)]
    ## 東の寺の東の神社
    t_higashi_j_nishi = s[f_nishi_pos(s, t_higashi)]
    ## 東の寺の東の神社
    t_higashi_j_higashi = s[f_higashi_pos(s, t_higashi)]


    return min(
        abs(x - j_nishi) + abs(j_nishi - j_nishi_t_nishi),
        abs(x - j_nishi) + abs(j_nishi - j_nishi_t_higashi),
        abs(x - j_higashi) + abs(j_higashi - j_higashi_t_nishi),
        abs(x - j_higashi) + abs(j_higashi - j_higashi_t_higashi),
        abs(x - t_nishi) + abs(t_nishi - t_nishi_j_nishi),
        abs(x - t_nishi) + abs(t_nishi - t_nishi_j_higashi),
        abs(x - t_higashi) + abs(t_higashi - t_higashi_j_nishi),
        abs(x - t_higashi) + abs(t_higashi - t_higashi_j_higashi)
    )

for xx in x:
    print(calc(s, t, xx))

Submission status: Accepted

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

A, B, Q = map(int, input().split())
s = []
for i in range(A):
    s.append(int(input()))
t = []
for i in range(B):
    t.append(int(input()))
for i in range(Q):
    x = int(input())
    j = bisect.bisect(s, x)
    ans = 2 * 10 ** 10
    if j > 0:
        k = bisect.bisect(t, s[j - 1])
        if k > 0:
            ans = min(ans,abs(x-s[j-1])+abs(s[j-1]-t[k-1]))
        if k < B:
            ans = min(ans, abs(x-s[j-1])+abs(s[j-1]-t[k]))
    if j < A:
        k = bisect.bisect(t, s[j])
        if k > 0:
            ans = min(ans, abs(x-s[j])+abs(s[j]-t[k-1]))
        if k < B:
            ans = min(ans, abs(x-s[j])+abs(s[j]-t[k]))
    j = bisect.bisect(t, x)
    if j > 0:
        k = bisect.bisect(s, t[j - 1])
        if k > 0:
            ans = min(ans,abs(x-t[j-1])+abs(t[j-1]-s[k-1]))
        if k < A:
            ans = min(ans, abs(x-t[j-1])+abs(t[j-1]-s[k]))
    if j < B:
        k = bisect.bisect(s, t[j])
        if k > 0:
            ans = min(ans, abs(x-t[j])+abs(t[j]-s[k-1]))
        if k < A:
            ans = min(ans, abs(x-t[j])+abs(t[j]-s[k]))
    print(ans)

Submission status: Accepted

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

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

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

Submission status: Accepted

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
import bisect
A,B,Q = getList()
temple = []
shrine = []
for i in range(A):
    temple.append(getN())

for i in range(B):
    shrine.append(getN())

temple.sort()
shrine.sort()

near_sh = []
for t in temple:
    a = bisect.bisect_left(shrine, t)
    if a == 0:
        l = -1000000000000
    else:
        l = shrine[a-1]
    if a == B:
        r = 1000000000000
    else:
        r = shrine[a]
    near_sh.append((l,r))

def calc(x, a, direction):
    #l=1
    try:
        near_temp = temple[a-direction]
    except:
        return 100000000000
    cost_outshrine = abs(x-near_sh[a-direction][1-direction])
    cost_inshrine = abs(x-near_temp)
    if cost_inshrine < abs(near_temp - near_sh[a-direction][0+direction]):
        #print("cost", near_sh[a - direction][0 + direction], cost_inshrine)
        cost_inshrine = (abs(near_temp - near_sh[a-direction][0+direction])) + min(cost_inshrine, abs(x- near_sh[a - direction][0 + direction]))

    #print("inoput", cost_inshrine,cost_outshrine,a,direction)
    return min(cost_inshrine, cost_outshrine)

#print(shrine)
#print(temple)
#print(near_sh)
for i in range(Q):
    x = getN()
    a = bisect.bisect_left(temple,x)
    if a != 0:
        cost_l = calc(x,a,1)
    else:
        cost_l = 1000000000000
    if a != A:
        cost_r = calc(x,a,0)
    else:
        cost_r = 1000000000000

    print(min(cost_l, cost_r))

Submission status: Accepted

Solution code:
import sys
import bisect
a,b,q=map(int,input().split())
s=sorted([int(input()) for i in range(a)])
t=sorted([int(input()) for i in range(b)])
i=0
for line in sys.stdin:
    ans=999999999999
    x=int(line)
    w=bisect.bisect_left(s,x)
    for j in range(2):
        if not 0<=w-j<len(s):
            continue
        z=bisect.bisect_left(t,s[w-j])
        for k in range(2):
            if not 0<=z-k<len(t):
                continue
            tmp=abs(x-s[w-j])+abs(s[w-j]-t[z-k])
            if ans>tmp:
                ans=tmp
    w=bisect.bisect_left(t,x)
    for j in range(2):
        if not 0<=w-j<len(t):
            continue
        z=bisect.bisect_left(s,t[w-j])
        for k in range(2):
            if not 0<=z-k<len(s):
                continue
            tmp=abs(x-t[w-j])+abs(t[w-j]-s[z-k])
            if ans>tmp:
                ans=tmp
    print(ans)
    i+=1

Submission status: Accepted

Solution code:
from bisect import bisect_left, bisect_right
mx = 10**10

def index(a, x):
    'Locate the leftmost value exactly equal to x'
    i = bisect_left(a, x)
    if i != len(a) and a[i] == x:
        return i
    raise ValueError

def find_lt(a, x):
    'Find rightmost value less than x'
    i = bisect_left(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_le(a, x):
    'Find rightmost value less than or equal to x'
    i = bisect_right(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bisect_right(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

def find_ge(a, x):
    'Find leftmost item greater than or equal to x'
    i = bisect_left(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

a, b, q = map(int, input().split())
aa = []
bb = []
for i in range(a):
  aa.append(int(input()))
for i in range(b):
  bb.append(int(input()))

aa.append(mx * 2)
bb.append(mx * 2)
aa.insert(0, -mx * 2)
bb.insert(0, -mx * 2)
#print(f'aa={aa}, bb={bb}')

for i in range(q):
  qi = int(input())
  #print(f'q = {qi}')

  a_low = find_lt(aa, qi)
  a_high = find_gt(aa, qi)

  b_low = find_lt(bb, qi)
  b_high = find_gt(bb, qi)

  len1 = qi - min([a_low, b_low])
  len2 = max([a_high, b_high]) - qi
  len3 = (a_high - qi) + (a_high - b_low)
  len4 = (b_high - qi) + (b_high - a_low)
  len5 = (qi - b_low) + (a_high - b_low)
  len6 = (qi - a_low) + (b_high - a_low)
  lens = [len1, len2, len3, len4, len5, len6]
  print(min(lens))

Submission status: Accepted

Solution code:
INF = int(1e40)

from sys import stdin, stdout
from bisect import bisect_left as bl, bisect_right as br

def f(x, s, t):
    a = abs(x - s) + abs(s - t)
    a = min(a, abs(x - t) + abs(t - s))
    return a

a, b, q = map(int, raw_input().strip().split())
inp = stdin.readlines()
out = []

s = [0 for i in xrange(a)]
t = [0 for i in xrange(b)]

ctr = 0
for i in xrange(a):
    s[i] = int(inp[i + ctr].strip())

ctr = a
for i in xrange(b):
    t[i] = int(inp[i + ctr].strip())

ctr += b
for i in xrange(q):
    x = int(inp[i + ctr].strip())
    idx_s = bl(s, x)

    s1 = -INF
    s2 = INF
    if idx_s:
        s1 = s[idx_s - 1]
    try: s2 = s[idx_s]
    except: pass

    idx_t = bl(t, x)
    t1 = -INF
    t2 = INF
    if idx_t:
        t1 = t[idx_t - 1]
    try: t2 = t[idx_t]
    except: pass
    
    ans = f(x, s1, t1)
    ans = min(ans, f(x, s1, t2))
    ans = min(ans, f(x, s2, t2))
    ans = min(ans, f(x, s2, t1))

    out.append(str(ans))

stdout.write("\n".join(out))

Submission status: Accepted

Solution code:
#!/usr/bin/env python2
"""
This file is part of https://github.com/cheran-senthil/PyRival
Copyright 2019 Cheran Senthilkumar <hello@cheran.io>

"""
from __future__ import division, print_function

import itertools
import os
import sys
from atexit import register
from io import BytesIO


class dict(dict):
    """dict() -> new empty dictionary"""

    def items(self):
        """D.items() -> a set-like object providing a view on D's items"""
        return dict.iteritems(self)

    def keys(self):
        """D.keys() -> a set-like object providing a view on D's keys"""
        return dict.iterkeys(self)

    def values(self):
        """D.values() -> an object providing a view on D's values"""
        return dict.itervalues(self)


def gcd(x, y):
    """greatest common divisor of x and y"""
    while y:
        x, y = y, x % y
    return x


range = xrange

filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip

sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size))
sys.stdout = BytesIO()
register(lambda: os.write(1, sys.stdout.getvalue()))

input = lambda: sys.stdin.readline().rstrip('\r\n')


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

    s = sorted(int(input()) for _ in range(a))
    t = sorted(int(input()) for _ in range(b))

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

        lo, hi = 0, a - 1
        while lo < hi:
            mi = lo + (hi - lo) // 2
            if s[mi] > x:
                hi = mi
            else:
                lo = mi + 1

        if lo == 0:
            p1, _p1 = s[0] - x, s[0] - x
        else:
            p1, _p1 = s[lo - 1] - x, s[lo] - x

        lo, hi = 0, b - 1
        while lo < hi:
            mi = lo + (hi - lo) // 2
            if t[mi] > x:
                hi = mi
            else:
                lo = mi + 1

        if lo == 0:
            p2, _p2 = t[0] - x, t[0] - x
        else:
            p2, _p2 = t[lo - 1] - x, t[lo] - x

        res = float('inf')

        if p1 <= 0 and p2 <= 0:
            res = min(res, abs(min(p1, p2)))

        if p1 <= 0 and _p2 <= 0:
            res = min(res, abs(min(p1, _p2)))

        if _p1 <= 0 and p2 <= 0:
            res = min(res, abs(min(_p1, p2)))

        if _p1 <= 0 and _p2 <= 0:
            res = min(res, abs(min(_p1, _p2)))

        if p1 >= 0 and p2 >= 0:
            res = min(res, max(p1, p2))

        if p1 >= 0 and _p2 >= 0:
            res = min(res, max(p1, _p2))

        if _p1 >= 0 and p2 >= 0:
            res = min(res, max(_p1, p2))

        if _p1 >= 0 and _p2 >= 0:
            res = min(res, max(_p1, _p2))

        res = min(res, 2 * abs(p1) + abs(p2))
        res = min(res, 2 * abs(p1) + abs(_p2))
        res = min(res, 2 * abs(_p1) + abs(p2))
        res = min(res, 2 * abs(_p1) + abs(_p2))

        res = min(res, 2 * abs(p2) + abs(p1))
        res = min(res, 2 * abs(p2) + abs(_p1))
        res = min(res, 2 * abs(_p2) + abs(p1))
        res = min(res, 2 * abs(_p2) + abs(_p1))

        print(res)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import bisect


def solve(A, B, Q, Ss, Ts, Xs):
    ans = []
    Ss.append(10 ** 21)
    Ss.insert(0, -10 ** 21)
    Ts.append(10 ** 21)
    Ts.insert(0, -10 ** 21)
    for x in Xs:
        s_right = bisect.bisect_right(Ss, x)
        s_left = max(s_right - 1, 0)
        t_right = bisect.bisect_right(Ts, x)
        t_left = max(t_right - 1, 0)

        s_right = Ss[s_right]
        s_left = Ss[s_left]
        t_right = Ts[t_right]
        t_left = Ts[t_left]

        d_s_right = abs(s_right - x)
        d_s_left = abs(s_left - x)
        d_t_right = abs(t_right - x)
        d_t_left = abs(t_left - x)

        tans = 10 ** 35
        if x <= s_right and x <= t_right:
            tans = min(tans, max(d_t_right, d_s_right))
        if s_right <= x and t_right <= x:
            tans = min(tans, max(d_t_right, d_s_right))
        if s_left <= x and t_left <= x:
            tans = min(tans, max(d_s_left, d_t_left))
        tans = min(tans, min(d_s_right, d_t_left) * 2 + max(d_s_right, d_t_left))
        tans = min(tans, min(d_t_right, d_s_left) * 2 + max(d_t_right, d_s_left))
        ans.append(str(tans))
    return "\n".join(ans)

if __name__ == "__main__":
    A, B, Q = tuple(map(int, input().split(" ")))
    Ss = [int(input()) for _ in range(A)]
    Ts = [int(input()) for _ in range(B)]
    Xs = [int(input()) for _ in range(Q)]
    print(solve(A, B, Q, Ss, Ts, Xs))

Submission status: Accepted

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

MAX_VAL = 2e+10


def make(src, dst):
  points = [v[0] for v in dst]

  for i in range(len(src)):
    p = src[i][0]
    j = bisect.bisect(points, p)

    if j == 0:
      v = dst[j][0] - p
    elif j == len(dst):
      v = p - dst[j - 1][0]
    else:
      v = min(dst[j][0] - p, p - dst[j - 1][0])

    src[i] = (p, v)


def main():
  a, b, s = map(int, input().split())
  shrines = [(int(input()),) for _ in range(a)]
  temples = [(int(input()),) for _ in range(b)]
  starts = [int(input()) for _ in range(s)]

  make(shrines, temples)
  make(temples, shrines)

  s_index = 0
  t_index = 0
  places = []

  while len(places) < len(shrines) + len(temples):
    if s_index == len(shrines):
      places.append(temples[t_index])
      t_index += 1
    elif t_index == len(temples):
      places.append(shrines[s_index])
      s_index += 1
    elif temples[t_index][0] < shrines[s_index][0]:
      places.append(temples[t_index])
      t_index += 1
    else:
      places.append(shrines[s_index])
      s_index += 1

  points = [p for p, _ in places]

  for start in starts:
    idx = bisect.bisect(points, start)
    value = None

    if idx == 0:
      value = points[idx] - start + places[idx][1]
    elif idx == len(points):
      value = start - points[idx - 1] + places[idx - 1][1]
    else:
      value = min(points[idx] - start + places[idx][1], start - points[idx - 1] + places[idx - 1][1])

    print(value, flush=True)


if __name__ == '__main__':
  main()

Submission status: Accepted

Solution code:
import bisect
a,b,q=map(int,input().split())
s=[int(input())for i in range(a)]
t=[int(input())for i in range(b)]
for i in range(q):
    x=int(input())
    c=bisect.bisect_left(s,x)
    d=bisect.bisect_left(t,x)
    p=[]
    if c!=a and d!=b:
        p.append(max(abs(s[c]-x),abs(t[d]-x)))
    if c!=0 and d!=0:
        p.append(max(abs(s[c-1]-x),abs(t[d-1]-x)))
    if c!=a and d!=0:
        p.append(min(abs(s[c]-x)*2+abs(t[d-1]-x),abs(s[c]-x)+2*abs(t[d-1]-x)))
    if c!=0 and d!=b:
        p.append(min(abs(s[c-1]-x)*2+abs(t[d]-x),abs(s[c-1]-x)+2*abs(t[d]-x)))
    print(min(p))

Submission status: Accepted

Solution code:
from bisect import bisect_left
A, B, Q = map( int, input().split())
S = [ int( input()) for _ in range(A)]
T = [ int( input()) for _ in range(B)]
X = [ int( input()) for _ in range(Q)]
for i in range(Q):
    q = X[i]
    ANS = []
    # jinja kara
    JP = []
    s = bisect_left(S, q)
    if s == 0:
        JP.append(S[0])
    elif s == A:
        JP.append(S[A-1])
    else:
        JP.append(S[s])
        JP.append(S[s-1])
    while JP:
        f = JP.pop()
        z = abs(f-q)
        t = bisect_left(T, f)
        if t == 0:
            ANS.append( z + abs(f - T[0]))
        elif t == B:
            ANS.append( z + abs(f - T[B-1]))
        else:
            ANS.append( z + abs(f - T[t]))
            ANS.append( z + abs(f - T[t-1]))
    # tera kara
    TP = []
    t = bisect_left(T, q)
    if t == 0:
        TP.append(T[0])
    elif t == B:
        TP.append(T[B-1])
    else:
        TP.append(T[t])
        TP.append(T[t-1])
    while TP:
        f = TP.pop()
        z = abs(f-q)
        s = bisect_left(S, f)
        if s == 0:
            ANS.append( z + abs(f - S[0]))
        elif s == A:
            ANS.append( z + abs(f - S[A-1]))
        else:
            ANS.append( z + abs(f - S[s]))
            ANS.append( z + abs(f - S[s-1]))
    print( min(ANS))

Submission status: Accepted

Solution code:
import sys
from bisect import bisect

fin = sys.stdin.readline
A, B, Q = [int(elem) for elem in fin().split()]
s_list = tuple([-float('inf')]) + tuple(int(fin()) for _ in range(A)) + tuple([float('inf')])
t_list = tuple([-float('inf')]) + tuple(int(fin()) for _ in range(B)) + tuple([float('inf')])
x_list = tuple(int(fin()) for _ in range(Q))


def search_shortest_dist(s_list, t_list, x):
    s_closest_idx = bisect(s_list, x)
    t_closest_idx = bisect(t_list, x)
    min_dist = float('inf')
    for s_idx in (s_closest_idx - 1, s_closest_idx):
        s = s_list[s_idx]
        for t_idx in (t_closest_idx - 1, t_closest_idx):
            t = t_list[t_idx]
            if s <= t <= x:
                dist = x - s
            elif s <= x <= t:
                dist = t - s + min(x - s, t - x)
            elif t <= s <= x:
                dist = x - t
            elif t <= x <= s:
                dist = s - t + min(x - t, s - x)
            elif x <= s <= t:
                dist = t - x
            else:  # x <= t <= s
                dist = s - x
            min_dist = min(min_dist, dist)
    return min_dist


for x in x_list:
    print(search_shortest_dist(s_list, t_list, x))

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


for x in X:
    s_index= bisect.bisect_left(s,x)
    #print(s_index)
    t_index= bisect.bisect_left(t,x)
    #print(t_index)
    if s_index == 0 and t_index == 0:
        print(max(t[0]-x,s[0]-x))
    elif s_index == 0:
        if t_index != b:
            if t[t_index] < s[0]:
                print(s[0]-x)
            else:
                ans  =min(2*s[0]-x - t[t_index-1],t[t_index]-x,x+s[0]-2*t[t_index-1])
                print(ans)
        else:
            print(min(2*s[s_index]-x-t[t_index-1],s[s_index]+x-2*t[t_index-1]))
    elif t_index == 0:
        if s_index != a:
            if s[s_index] < t[0]:
                print(t[0]-x)
            else:
                ans  =min(2*t[0]- x- s[s_index-1],s[s_index]-x,x+t[0]-2*s[s_index-1])
                print(ans)
        else:
            print(min(2*t[t_index]-x-s[s_index-1],t[t_index]+x-2*s[s_index-1]))
    elif s_index == a and t_index == b:
        print(max(x-s[a-1],x-t[b-1]))
    elif s_index == a:
        if s[a-1] < t[t_index-1]:
            print(x-s[a-1])
        else:
            ans = min(x-t[t_index-1],t[t_index]+x-2*s[a-1],2*t[t_index]-x-s[a-1])
            print(ans)
    elif t_index == b:
        if t[b-1] < s[s_index-1]:
            print(x-t[b-1])
        else:
            ans = min(x - s[s_index - 1], s[s_index] + x - 2 * t[b - 1],2*s[s_index]-x-t[b-1])
            print(ans)

    else:
        if s[s_index-1] < t[t_index-1] and s[s_index] < t[t_index]:
            ans = min(x-s[s_index-1],x+s[s_index]-2*t[t_index-1],2*s[s_index]-x-t[t_index-1],t[t_index]-x)
            print(ans)
        if t[t_index - 1] < s[s_index - 1] and t[t_index] < s[s_index]:
            ans = min(x - t[t_index - 1], x + t[t_index] - 2 * s[s_index - 1], 2 * t[t_index] - x - s[s_index - 1],
                      s[s_index] - x)
            print(ans)
        if s[s_index-1] < t[t_index-1] and t[t_index] < s[s_index]:
            ans = min(x-s[s_index-1],s[s_index]-x)
            print(ans)
        if t[t_index - 1] < s[s_index - 1] and s[s_index] < t[t_index]:
            ans = min(x - t[t_index - 1], t[t_index] - x)
            print(ans)

Submission status: Accepted

Solution code:
import bisect

a,b,n=map(int,input().split())
l1=[int(input()) for i in range(a)]
l2=[int(input()) for i in range(b)]
x=[int(input()) for i in range(n)]
l1.sort()
l2.sort()
for i in range(n):
    idx1=bisect.bisect_left(l1,x[i])
    if idx1<a:
        p=abs(l1[idx1-1]-x[i])
        q=abs(l1[idx1]-x[i])
        for j in range(2):
            if j==0:
                po=l1[idx1-1]
                idx3=bisect.bisect_left(l2,po)
                if idx3<b:
                    dis=min(abs(l2[idx3-1]-po),abs(l2[idx3]-po))
                else:
                    dis=po-l2[-1]
                dis1=p+dis
            else:
                po=l1[idx1]
                idx3=bisect.bisect_left(l2,po)
                if idx3<b:
                    dis=min(abs(l2[idx3-1]-po),abs(l2[idx3]-po))
                else:
                    dis=po-l2[-1]
                dis1=min(dis1,q+dis)
    else:
        p=x[i]-l1[-1]
        po=l1[-1]
        idx3=bisect.bisect_left(l2,po)
        if idx3<b:
            dis=min(abs(l2[idx3-1]-po),abs(l2[idx3]-po))
            dis1=dis+p
        else:
            dis1=po-l2[-1]+p
    idx2=bisect.bisect_left(l2,x[i])
    if idx2<b:
        p=abs(l2[idx2-1]-x[i])
        q=abs(l2[idx2]-x[i])
        for j in range(2):
            if j==0:
                po=l2[idx2-1]
                idx3=bisect.bisect_left(l1,po)
                if idx3<a:
                    dis=min(abs(l1[idx3-1]-po),abs(l1[idx3]-po))
                else:
                    dis=po-l1[-1]
                dis2=p+dis
            else:
                po=l2[idx2]
                idx3=bisect.bisect_left(l1,po)
                if idx3<a:
                    dis=min(abs(l1[idx3-1]-po),abs(l1[idx3]-po))
                else:
                    dis=po-l1[-1]
                dis2=min(dis2,q+dis)
    else:
        p=x[i]-l2[-1]
        po=l2[-1]
        idx3=bisect.bisect_left(l1,po)
        if idx3<a:
            dis=min(abs(l1[idx3-1]-po),abs(l1[idx3]-po))
            dis2=dis+p
        else:
            dis2=po-l1[-1]+p
    print(min(dis1,dis2))