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:
#coding:utf-8
import bisect
A,B,Q = map(int,input().split())
S = []
T = []
X = []
for a in range(A):
    S.append(int(input()))
for b in range(B):
    T.append(int(input()))
for q in range(Q):
    X.append(int(input()))

#print (S,T,X)

def find_nearest(array, point):
    #print ("p",point)
    abs_diff = 10 ** 11
    idx = bisect.bisect_left(array,point)
    #print (array,point)
    #print (idx,len(array))
    for i in range(2):
        try:
            diff = array[idx+i-1] - point
            temp = abs(diff)
            if abs_diff > temp:
                min_diff = diff
                abs_diff = temp
        except:
            pass
            
        
    return min_diff

def calc(first, second,point):
    score = 0
    md = find_nearest(first,point)
    #print("m",md)
    score += abs(md)
    point += md
    md = find_nearest(second,point)
    score += abs(md)
    #print ("m",md)
    #print (score)
    return score

for x in X:
    print (min(calc(S,T,x),calc(T,S,x)))
    #break

Submission status: Wrong Answer

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

aa = []
bb = []
for i in range(a):
	aa.append(int(input()))
for i in range(b):
	bb.append(int(input()))
for i in range(c):
	cc = int(input())
	aaa = bisect.bisect_left(aa,cc)
	bbb = bisect.bisect_left(bb,cc)
	if aaa == 0 and bbb == 0:
		print(max(aa[0],bb[0]) - cc)
	elif aaa == a and bbb == b:
		print(cc - min(aa[a-1],bb[b-1]))
	elif aaa == 0:
		if bbb == b:
			print(min(abs(cc - aa[0]),abs(cc - bb[bbb-1])) + aa[0] - bb[bbb-1])
		else:
			aaaa = min(abs(bb[bbb] - aa[0]),abs(bb[bbb-1] - aa[0]))
			print(min(abs(cc - aa[0]),abs(cc - bb[bbb-1]),abs(cc - bb[bbb])) + aaaa)
	elif bbb == 0:
		if aaa == a:
			print(min(abs(cc - aa[0]),abs(cc - bb[bbb-1])) + bb[0] - aa[aaa-1])
		else:
			bbbb = min(abs(bb[0] - aa[aaa-1]),abs(bb[0] - aa[aaa]))
			print(min(abs(cc - bb[0]),abs(cc - aa[aaa-1]),abs(cc - aa[aaa])) + bbbb)
	elif aaa == a:
		aaaa = min(abs(bb[bbb] - aa[a-1])+min(abs(cc-aa[a-1]),abs(cc-bb[bbb])),abs(bb[bbb-1] - aa[a-1])+min(abs(cc-aa[a-1]),abs(cc-bb[bbb-1])))
		print(aaaa)
	elif bbb == b:
		bbbb = min(abs(bb[b-1] - aa[aaa-1])+min(abs(cc-aa[aaa-1]),abs(cc-bb[b-1])),abs(bb[b-1] - aa[aaa])+min(abs(cc-aa[aaa]),abs(cc-bb[b-1])))
		print(abs(cc - bb[b-1]) + bbbb)
	else:
		aaaa = min(max(aa[aaa],bb[bbb])-cc,cc-min(aa[aaa-1],bb[bbb-1]),2*aa[aaa] - cc - bb[bbb-1],aa[aaa] + cc - 2 * bb[bbb-1])
		print(aaaa)

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


def find_left_and_right(st, start, end, pos):
    if start == end:
        if st[start] > pos:
            return [start-1, start]
        else:
            right = start + 1 if len(st) > (start + 1) else -1
            return [start, right]
    i = int((end - start) / 2)
    if (st[i] - pos) * (st[i-1] - pos) <= 0:
        return [i-1, i]
    l_result = find_left_and_right(st, start, i, pos)
    if l_result:
        return l_result
    r_result = find_left_and_right(st, start, i, pos)
    if r_result:
        return r_result
    return None


def find_optimum(ss, ts, pos):
    (sl_index, sr_index) = find_left_and_right(ss, 0, len(ss), pos)
    (tl_index, tr_index) = find_left_and_right(ts, 0, len(ts), pos)

    penalty = 9999999999999
    s_left = s[sl_index] if 0 <= sl_index else penalty
    s_right = s[sr_index] if 0 <= sr_index else penalty
    t_left = t[tl_index] if 0 <= tl_index else penalty
    t_right = t[tr_index] if 0 <= tr_index else penalty

    dist0 = abs(s_left - pos) + min(abs(t_left - s_left), abs(t_right - s_left))
    dist1 = abs(s_right - pos) + min(abs(t_left - s_right), abs(t_right - s_right))
    dist2 = abs(t_left - pos) + min(abs(s_left - t_left), abs(s_right - t_left))
    dist3 = abs(t_right - pos) + min(abs(s_left - t_right), abs(s_right - t_right))
    return min([dist0, dist1, dist2, dist3])


for x_i in x:
    print(find_optimum(s, t, x_i))

Submission status: Wrong Answer

Solution code:
import bisect

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

def nn(a, x):
    i = bisect.bisect_left(a, x)
    if i == 0:
        return a[0]
    if i == len(a):
        return a[i-1]
    if abs(a[i-1]-x) <= abs(a[i]-x):
        return a[i-1]
    return a[i]

for _ in range(Q):
    x = int(input())
    s = nn(S, x)
    t = nn(T, x)
    st = nn(T, s)
    ts = nn(S, t)
    print(min(abs(x-s) + abs(s-st), abs(x-t) + abs(t-ts)))

Submission status: Wrong Answer

Solution code:
A, B, Q = map(int, input().split())
s = [int(input()) for i in range(A+B)]
x = [int(input()) for i in range(Q)]
for a in range(Q):
	X = x[a]
	diff1 = 10000000000
	ind = 0
	for b in range(A+B):
		l = abs(X-s[b])
		if diff1 > l:
			ind = b
			diff1 = l
	ans = diff1
	X = s[ind]
	diff2 = 10000000000
	if ind >= A:
		for c in range(A):
			l = abs(X - s[c])
			if diff2 > l:
				diff2 = l
	else:
		for c in range(A, A+B):
			l = abs(X - s[c])
			if diff2 > l:
				diff2 = l
	ans = ans + diff2
	print(ans)

Submission status: Wrong Answer

Solution code:
A, B, Q = map(int, input().split())
s_list = [int(input()) for i in range(A)]
t_list = [int(input()) for i in range(B)]
x_list = [int(input()) for _ in range(Q)]

s_list.sort()
t_list.sort()
import bisect

ans = []
for x in x_list:
    tmp = float("inf")
    s_i = bisect.bisect_left(s_list, x)
    t_i = bisect.bisect_left(t_list, x)

    if s_i == A and t_i == B:
        tmp = abs(x - min(s_list[-1], t_list[-1]))
        ans.append(tmp)
        continue
    if s_i == A:
        if t_i != 0:
            tmp = abs(s_list[-1] - x)
            if s_list[-1] <= t_list[t_i] <= x:
                ans.append(tmp)
                continue
            else:
                tmp += min(abs(t_list[t_i] - x) * 2, abs(t_list[t_i - 1] - s_list[-1]))
        else:
            tmp = abs(min(abs(s_list[s_i - 1] - x), abs(t_list[0] - x)) * 2 + max(abs(s_list[s_i - 1] - x),
                                                                                  abs(t_list[0] - x)))
        ans.append(tmp)
        continue
    if t_i == B:
        if s_i != 0:
            tmp = abs(t_list[-1] - x)
            if t_list[-1] <= s_list[s_i] <= x:
                ans.append(tmp)
                continue
            else:
                tmp += min(abs(s_list[s_i] - x) * 2, abs(s_list[s_i - 1] - t_list[-1]))
        else:
            tmp = abs(min(abs(t_list[t_i - 1] - x), abs(s_list[0] - x)) * 2 + max(abs(t_list[t_i - 1] - x),
                                                                                  abs(s_list[0] - x)))
        ans.append(tmp)
        continue

    # S1, T1
    if s_i != 0 and t_i != 0:
        tmp = min(tmp, abs(min(s_list[s_i - 1], t_list[t_i - 1]) - x))
    elif s_i == 0 and t_i == 0:
        tmp = min(tmp, abs(x - max(s_list[0], t_list[0])))
    elif s_i == 0 and t_i != 0:
        tmp = min(tmp, abs(s_list[0] - t_list[t_i]))
    else:
        tmp = min(tmp, abs(t_list[0] - s_list[s_i]))

    # S2, T2
    tmp = min(tmp, abs(max(s_list[s_i], t_list[t_i]) - x))

    # S1, T2
    if s_i != 0:
        tmp = min(tmp, abs(min(abs(t_list[t_i] - x), abs(s_list[s_i - 1] - x)) * 2 + max(abs(t_list[t_i] - x),
                                                                                         abs(s_list[s_i - 1] - x))))
    else:
        tmp = min(tmp, abs(max(t_list[t_i], s_list[0]) - x))
    # S2, T1
    if t_i != 0:
        tmp = min(tmp, abs(min(abs(s_list[s_i] - x), abs(t_list[t_i - 1] - x)) * 2 + max(abs(s_list[s_i] - x),
                                                                                         abs(t_list[t_i - 1] - x))))
    else:
        tmp = min(tmp, abs(max(s_list[s_i], t_list[0]) - x))
    ans.append(tmp)
for a in ans:
    print(a)

Submission status: Wrong Answer

Solution code:
import sys
from collections import deque
import copy
import math
def get_read_func(fileobject):
    if fileobject == None :
        return raw_input
    else:
        return fileobject.readline

def bin_search(S, x):
    L = 0
    R = len(S) - 1

    while 1:
        M = (L + R)/2
        if (R - L) <= 1:
            if abs(S[R] - x) < abs(S[L] - x):
                return (R, -1)
            elif abs(S[R] - x) > abs(S[L] - x):
                return (L, -1)
            else:
                if L != R:
                    return (L, R)
                else:
                    return (L, -1)
        if x == S[L]:
            return (L, -1)
        if x == S[R]:
            return (R, -1)
        if S[M] < x:
            L = M
        else:
            R = M



def main():
    if len(sys.argv) > 1:
        f = open(sys.argv[1])
    else:
        f = None
    read_func = get_read_func(f);
    input_raw = read_func().strip().split()
    [A, B, Q] = [int(input_raw[0]), int(input_raw[1]), int(input_raw[2])]

    jinja = []
    for i in range(A):
        input_raw = read_func().strip().split()
        jinja.append(long(input_raw[0]))
    tera = []
    for i in range(B):
        input_raw = read_func().strip().split()
        tera.append(long(input_raw[0]))

    for i in range(Q):
        input_raw = read_func().strip().split()
        x = long(input_raw[0])
        dist1 = [sys.maxint * sys.maxint* sys.maxint for i in range(2)]
        z = bin_search(jinja, x)
        for j in range(len(z)):
            if z[j] != -1:
                dist1[j] = abs(jinja[z[j]] - x)
                y = bin_search(tera, jinja[z[j]])
                dist1[j]  += abs(tera[y[0]] - jinja[z[j]])

        dist2 = [sys.maxint * sys.maxint * sys.maxint for i in range(2)]
        z = bin_search(tera, x)
        for j in range(len(z)):
            if z[j] != -1:
                dist2[j] = abs(tera[z[j]] - x)
                y = bin_search(jinja, tera[z[j]])
                dist2[j]  += abs(jinja[y[0]] - tera[z[j]])
        print min(min(dist1), min(dist2))



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:

import bisect

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

Submission status: Wrong Answer

Solution code:
A,B,Q=[int(x) for x in input().split()]
LA=[]#神社
LB=[]#寺
for i in range(A):
    LA.append(int(input()))
for i in range(B):
    LB.append(int(input()))
print(LA)
print(LB)
mx=20000000001

for i in range(Q):
    x=int(input())
    if LA[-1]<x:
        sa=mx
        sb=x-LA[-1]
    else:
        for js,s in enumerate(LA):
            if x<s:
                if js==0:
                    sb=mx
                else:
                    sb=x-LA[js-1]
                sa=s-x
                break

    if LB[-1]<x:
        ta=mx
        tb=x-LB[-1]
    else: 
        for jt,t in enumerate(LB):
            if x<t:
                if jt==0:
                    tb=mx
                else:
                    tb=x-LB[jt-1]
                ta=t-x
                break
    
            
    print(min(max(ta,sa),max(tb,sb),tb+sa+min(tb,sa),ta+sb+min(ta,sb)))

Submission status: Wrong Answer

Solution code:
A, B, Q = map(int, input().split())
s = []
t = []
x = []

for _ in range(A):
    s.append(int(input()))
for _ in range(B):
    t.append(int(input()))
for _ in range(Q):
    x.append(int(input()))

for startP in range(Q):
    sp_place = x[startP]
    dist = 10**10
    nextP = None
    archi = None
    move = 0
    for i in range(A):
        tmpdist = abs(s[i] - sp_place)
        if tmpdist < dist:
            dist = tmpdist
            nextP = s[i]
            archi = 's'
    for i in range(B):
        tmpdist = abs(t[i] - sp_place)
        if tmpdist < dist:
            dist = tmpdist
            nextP = t[i]
            archi = 't'
    sp_place = nextP
    move = dist
    dist = 10**10
    if archi == 't':
        for i in range(A):
            tmpdist = abs(s[i] - sp_place)
            if tmpdist < dist:
                dist = tmpdist
    else: #if s
        for i in range(B):
            tmpdist = abs(t[i] - sp_place)
            if tmpdist < dist:
                dist = tmpdist
    move += dist
    print(move)

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


def find_left_and_right(st, start, end, pos):
    if start == end:
        if st[start] > pos:
            return [start-1, start]
        else:
            right = start + 1 if len(st) > (start + 1) else -1
            return [start, right]
    i = int((end - start) / 2)
    if st[i] > pos and st[i-1] < pos:
        return [i-1, i]
    l_result = find_left_and_right(st, start, i, pos)
    if l_result:
        return l_result
    r_result = find_left_and_right(st, start, i, pos)
    if r_result:
        return r_result
    return None


def find_optimum(ss, ts, pos):
    (sl_index, sr_index) = find_left_and_right(ss, 0, len(ss), pos)
    

    (tl_index, tr_index) = find_left_and_right(ts, 0, len(ts), pos)

    penalty = 9999999999999
    s_left = s[sl_index] if 0 <= sl_index else penalty
    s_right = s[sr_index] if 0 <= sr_index else penalty
    t_left = t[tl_index] if 0 <= tl_index else penalty
    t_right = t[tr_index] if 0 <= tr_index else penalty

    dist0 = abs(s_left - pos) + min(abs(t_left - s_left), abs(t_right - s_left))
    dist1 = abs(s_right - pos) + min(abs(t_left - s_right), abs(t_right - s_right))
    dist2 = abs(t_left - pos) + min(abs(s_left - t_left), abs(s_right - t_left))
    dist3 = abs(t_right - pos) + min(abs(s_left - t_right), abs(s_right - t_right))
    return min([dist0, dist1, dist2, dist3])


for x_i in x:
    print(find_optimum(s, t, x_i))

Submission status: Wrong Answer

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

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

Solution code:
import bisect

A, B, Q = map(int, input().split())
s = []
sd = {}
for i in range(A):
    x = int(input())
    s.append(x)
    sd[i] = x
t = []
td = {}
for i in range(B):
    x = int(input())
    t.append(x)
    td[i] = x
i = 0
j = 0
st = [10 ** 10] * A
ts = [10 ** 10] * B
while True:
    st[i] = min(st[i], abs(s[i] - t[j]))
    ts[j] = min(ts[j], abs(s[i] - t[j]))
    if i == A - 1 and j == B - 1:
        break
    if i == A - 1:
        j += 1
        continue
    if j == B - 1:
        i += 1
        continue
    if s[i] < t[j]:
        i += 1
    else:
        j += 1
        
for i in range(Q):
    x = int(input())
    j = bisect.bisect(s, x)
    ans = 2 * 10 ** 10
    if j > 0:
        ans = min(ans, abs(x-sd[j-1])+st[j-1])
    if j < A:
        ans = min(ans, abs(x-sd[j])+st[j])
    j = bisect.bisect(t, x)
    if j > 0:
        ans = min(ans, abs(x-td[j-1])+ts[j-1])
    if j < B:
        ans = min(ans, abs(x-td[j])+ts[j])
    print(ans)

Submission status: Wrong Answer

Solution code:
#!usr/bin/env python3
from collections import defaultdict
from heapq import heappush, heappop
import math
import bisect
import random
def LI(): return list(map(int, input().split()))
def I(): return int(input())
def LS(): return input().split()
def S(): return list(input())
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
mod = 1000000007

#A
"""
s = input().split("/")
if int(s[0]) > 2019:
    print("TBD")
elif int(s[0]) == 2019:
    if int(s[1]) > 4:
        print("TBD")
    elif int(s[1]) == 4:
        if int(s[2]) > 30:
            print("TBD")
        else:
            print("Heisei")
    else:
        print("Heisei")
else:
    print("Heisei")
"""

#B
"""
n = I()
ans = 0
for i in range(n):
    x,u = input().split()
    x = float(x)
    if u == "JPY":
        ans += x
    else:
        ans += x*380000.0
print(ans)
"""

#C
"""
n,a,b,c = LI()
l = IR(n)
f = [True for i in range(3)]
ans = 0
for i in range(n):
    for d in range(3):
        if abs(l[i]-[a,b,c][d]) <= 10 and f[d]:
k = False
for i in f:
    if i:
        k = True
        break
if not k:
    print(ans)
    quit()
"""

#D
a,b,q = LI()
s = IR(a)
t = IR(b)
s.insert(0,-float("inf"))
t.insert(0,-float("inf"))
s.append(float("inf"))
t.append(float("inf"))
for i in range(q):
    x = I()
    c = bisect.bisect_left(s,x)
    d = bisect.bisect_left(t,x)
    ans = float("inf")
    if s[c] < t[d]:
        k = s[c]-x
        k += min(t[d]-s[c],s[c]-t[d-1])
    else:
        k = t[d]-x
        k += min(s[c]-t[d],t[d]-s[c-1])
    ans = min(k,ans)
    if s[c-1] > t[d-1]:
        k = x-s[c-1]
        k += min(s[c-1]-t[d-1],t[d]-s[c-1])
    else:
        k = x-t[d-1]
        k += min(t[d-1]-s[c-1],s[c]-t[d-1])
    ans = min(k,ans)
    print(ans)
#E

#F

#G

#H

#I

#J

#K

#L

#M

#N

#O

#P

#Q

#R

#S

#T

Submission status: Wrong Answer

Solution code:
def search(arry, target):
    left = 0
    right = len(arry) - 1

    while left <= right:
        mid = (left + right) // 2
        if mid == len(arry) - 1:
            return mid
        if arry[mid] <= target < arry[mid+1]:
            result = mid
            break
        elif arry[mid] > target:
            right = mid - 1
        else:
            left = mid + 1
    if target - arry[mid] < arry[mid+1] - target:
        return mid
    else:
        return mid + 1


def near(a, t):
    return a[search(a, t)]


def walk(x):
    # print("target:", x)
    near_a = near(a_s, x)
    near_a_b = near(b_s, near_a)
    sum_ab = abs(near_a - x) + abs(near_a_b - near_a)
    near_b = near(b_s, x)
    if near_b >= sum_ab:
        return sum_ab
    # print("a", near_a, "ab", near_a_b, sum_ab)
    near_b_a = near(a_s, near_b)
    sum_ba = abs(near_b - x) + abs(near_b_a - near_b)
    # print("b", near_b, "ba", near_b_a, sum_ba)
    return sum_ab if sum_ab < sum_ba else sum_ba


A, B, Q = map(int, input().split())
a_s = []
b_s = []
for _ in range(A):
    a_s.append(int(input()))
for _ in range(B):
    b_s.append(int(input()))
# print("===")
for _ in range(Q):
    q = int(input())
    print(walk(q))

Submission status: Wrong Answer

Solution code:
def bisect_left(a,length,x):
  lo, hi = 0, length
  while lo < hi:
    mid = (lo + hi) // 2
    if a[mid] < x:
      lo = mid + 1
    else:
      hi = mid
  return lo

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 x in X:
  s_position = "left" if x < s[0] else "right" if s[A-1] < x else "mid"
  t_position = "left" if x < t[0] else "right" if t[B-1] < x else "mid"
  if(s_position == "right" and t_position == "right"):
    print(x-min(s[A-1],t[B-1]))
    continue
  if(s_position == "left" and t_position == "left"):
    print(max(s[0],t[0])-x)
    continue
  if(s_position == "left" and t_position == "right"):
    print(s[0]-t[B-1]+min(x-t[B-1], s[0]-x))
    continue
  if(s_position == "right" and t_position == "left"):
    print(t[0]-s[A-1]+min(x-s[A-1], t[0]-x))
    continue
  if(s_position == "right" and t_position == "mid"):
    ti = bisect_left(t,B,x)
    print(min(max(x-s[A-1],x-t[ti-1]),(t[ti]-x)+(t[ti]-s[A-1])))
    continue
  if(s_position == "mid" and t_position == "right"):
    si = bisect_left(s,A,x)
    print(min(max(x-t[B-1],x-s[si-1]),(s[si]-x)+(s[si]-t[B-1])))
    continue
  if(s_position == "left" and t_position == "mid"):
    ti = bisect_left(t,B,x)
    print(min(max(s[0]-x,t[ti]-x),(x-t[ti-1])+(s[0]-t[ti-1])))
    continue
  if(s_position == "mid" and t_position == "left"):
    si = bisect_left(s,A,x)
    print(min(max(t[0]-x,s[si]-x),(x-s[si-1])+(t[0]-s[si-1])))
    continue
  if(s_position == "mid" and t_position == "mid"):
    si = bisect_left(s,A,x)
    ti = bisect_left(t,B,x)
    print(
      min(
        max(t[ti]-x,s[si]-x),
        (x-s[si-1])+(t[ti]-s[si-1]),
        max(x-t[ti-1],x-s[si-1]),
        (s[si]-x)+(s[si]-t[ti-1])
      )
    )
    continue

Submission status: Wrong Answer

Solution code:
import bisect
A, B, Q = [int(n) for n in input().split()]
S = []
T = []
X = []

for i in range(A):
    s = int(input())
    S.append(s)

for i in range(B):
    t = int(input())
    T.append(t)

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

for x in X:
    si = bisect.bisect_left(S, x)
    ti = bisect.bisect_left(T, x)
    ans = 0
    smin = 0
    tmin = 0
    if si == 0:
        smin = S[0] - x
    elif si == len(S):
        smin = S[-1] - x
    else:
        smin = S[si] - x if abs(S[si] - x) <= abs(S[si - 1] - x) else S[si - 1] - x
    if ti == 0:
        tmin = T[0] - x
    elif ti == len(T):
        tmin = T[-1] - x
    else:
        tmin = T[ti] - x if abs(T[ti] - x) <= abs(T[ti - 1] - x) else T[ti - 1] - x 

    xs = x + smin
    xti = bisect.bisect_left(T, xs)
    if xti == 0:
        xtmin = T[0] - xs
    elif xti == len(T):
        xtmin = T[-1] - xs
    else:
        xtmin = T[xti] - xs if abs(T[xti] - xs) <= abs(T[xti - 1] - xs) else T[xti - 1] - xs 

    xt = x + tmin
    xsi = bisect.bisect_left(S, xt)
    if xsi == 0:
        xsmin = S[0] - xt
    elif xsi == len(S):
        xsmin = S[-1] - xt
    else:
        xsmin = S[xsi] - xt if abs(S[xsi] - xt) <= abs(S[xsi - 1] - xt) else S[xsi - 1] - xt 

    ans = min(abs(xtmin) + abs(smin), abs(xsmin) + abs(tmin))
    print(ans)

Submission status: Wrong Answer

Solution code:
from copy import copy
data = input().split()  
an = int(data[0])
bn = int(data[1])
qn = int(data[2])

a = []
for i in range(an):
    a.append(int(input()))
b = []
for i in range(bn):
    b.append(int(input()))
q = []
for i in range(qn):
    q.append(int(input()))

def near(lis, po):
    dif = list(map(lambda x: abs(x-po), lis))
    ind = dif.index(min(dif))
    return lis[ind]-po

def nearnext(lis, start, end):
    for point in lis:
        if(start <= point and point <= end):
            return 0
    tmpa = near(lis, start)
    tmpb = near(lis, end)
    if(tmpa < tmpb):
        return tmpa
    else:
        return tmpb

for i in q:
    start=int(i)
    neara=near(a, start)
    #print(a, start)
    #print(neara)
    if(neara < 0):
        neara=abs(neara)+abs(nearnext(b, start+neara, start))
    else:
        neara+=abs(nearnext(b, start, start+neara))
    #print(neara)

    nearb=near(b, start)
    if(nearb < 0):
        nearb=abs(nearb)+abs(nearnext(a, start+nearb, start))
    else:
        nearb+=abs(nearnext(a, start, start+nearb))

    #print(neara, nearb)
    if(neara < nearb):
        print(neara)
    else:
        print(nearb)

Submission status: Wrong Answer

Solution code:
import bisect

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

def nn(a, x):
    i = bisect.bisect(a, x)
    if i == 0:
        return 0
    if i == len(a):
        return i-1
    if abs(a[i-1]-x) <= abs(a[i]-x):
        return i-1
    return i 


for _ in range(Q):
    x = int(input())
    s = S[nn(S, x)]
    t = T[nn(T, x)]
    st = T[nn(T, s)]
    ts = S[nn(S, t)]
    print(min(abs(x-s) + abs(s-st), abs(x-t) + abs(t-ts)))

Submission status: Wrong Answer

Solution code:
def main():
    A, B, Q = list(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)]
    #ans = []
    for i, x in enumerate(xs):
        ss_diff = [(s-x) for s in ss]
        ts_diff = [(t-x) for t in ts]
        #print(ss_diff + ts_diff)
        p = x
        min1 = 1e10
        for a in (ss_diff + ts_diff):
            if abs(a) < min1:
                min1 = abs(a)
                p = a

        #print("p = ", p)
        if p in ss_diff:
            q = sorted([abs(p-t) for t in ts_diff])[0]
            #print("q = ", q)
        else:
            q = sorted([abs(p-s) for s in ss_diff])[0]
            #print("q = ", q)
        #ans.append(p+q)
        print(abs(p)+q)


if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import numpy as np

def getValue(list, num):
  idx = np.abs(np.asarray(list) - num).argmin()
  return list[idx]

def resultjudge(lst1, lst2, qq):
  first = 0
  second = 0
  sum_second = 0
  sum_first = 0
  for j in range(len(lst1)):
    if lst1[j] > qq:
      second = lst1[j]
      if j>0:
        first = lst1[j-1]
      break
  if second==0:
    second = lst1[-1]

  for k in range(len(lst2)):
    tera_second = getValue(lst2, second)
    sum_second = abs(second - qq) + abs(second - tera_second)
    result = sum_second
    if first!=0:
      tera_first = getValue(lst2,first)
      sum_first = abs(first - qq) + abs(first - tera_first)
      if sum_first<sum_second:
        result = sum_first
  return result

  
data = input()
data = data.split()
jinjya = []
tera = []
q = []
for _ in range(int(data[0])):
  jinjya.append(int(input()))
for _ in range(int(data[1])):
  tera.append(int(input()))
for _ in range(int(data[2])):
  q.append(int(input()))

jinjya.sort()
tera.sort()
alllst = jinjya + tera

for i in range(len(q)):
  rr = getValue(alllst, q[i])
  if rr in jinjya:
    lst1 = jinjya
    lst2 = tera
  else:
    lst1 = tera
    lst2 = jinjya
  
  result = resultjudge(lst1, lst2, q[i])
  print(result)