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: Runtime Error

Solution code:
import math

A, B, Q = list(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)]

def binary_search(target, data):
    def _binary_search(target, data, left, right):
        # print(left, right)
        is_found = right - left == 1
        if is_found:
            diff_left = abs(target - data[left])
            diff_right = abs(target - data[right])
            if diff_left < diff_right: return left
            else : return right

        center = int((right - left) / 2)
        base = data[center]

        if target <= base:
            new_left = left
            new_right = center
        else:
            new_left = center
            new_right = right

        found = _binary_search(target, data, new_left, new_right)

        return found

    left = 0
    right = len(data) - 1
    found = _binary_search(target, data, left, right)

    return data[found]
for xi in x:
    x_to_s = binary_search(xi, s)
    s_to_t = binary_search(x_to_s, t)
    x_s_t = abs(xi - x_to_s) + abs(x_to_s - s_to_t)

    x_to_t = binary_search(xi, t)
    t_to_s = binary_search(x_to_t, s)
    x_t_s = abs(xi - x_to_t) + abs(x_to_t - t_to_s)

    answer = min(x_s_t, x_t_s)

    print(answer)

Submission status: Runtime Error

Solution code:
import math

A, B, Q = list(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)]

def binary_search(target, data):
    def _binary_search(target, data, left, right):
        # print(left, right)
        is_found = right - left == 1
        if is_found:
            diff_left = abs(target - data[left])
            diff_right = abs(target - data[right])
            if diff_left < diff_right: return left
            else : return right

        center = int((right - left) / 2)
        base = data[center]

        if target <= base:
            new_left = left
            new_right = center
        else:
            new_left = center
            new_right = right

        found = _binary_search(target, data, new_left, new_right)

        return found

    left = 0
    right = len(data) - 1
    found = _binary_search(target, data, left, right)

    return data[found]

for xi in x:
   s_to_t = binary_search(x_to_s, t)
    x_s_t = abs(xi - x_to_s) + abs(x_to_s - s_to_t)

    x_to_t = binary_search(xi, t)
    t_to_s = binary_search(x_to_t, s)
    x_t_s = abs(xi - x_to_t) + abs(x_to_t - t_to_s)

    answer = min(x_s_t, x_t_s)

    print(answer)

Submission status: Runtime Error

Solution code:
def main():
  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
  for i in range(a):
      s[i+2] = int(input())
  for i in range(b):
      t[i+2] = int(input())

  from bisect import bisect_left

  dp0 = [None] * (a+3)
  dp1 = [None] * (b+3)

  for _ in range(q):
    ans = inf
    x = int(input())
    sr = bisect_right(s, x)
    tr = bisect_right(t, x)    
    for si in (sr, sr-1):
      for ti in (tr, tr-1):
        ans = min(ans, abs(x-s[si]) + abs(s[si]-t[ti]), abs(x-t[ti]) + abs(s[si]-t[ti]))
    print(ans)
  
if __name__ == "__main__":
  main()

Submission status: Runtime Error

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
from collections import defauldict

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: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
typedef pair<int, int> P;
typedef long long ll;
int main()
{
    int a, b, q;
    ;
    cin >> a >> b >> q;
    vector<ll> s(a), t(b);
    rep(i, a)
    {
        cin >> s[i];
    }
    rep(i, b)
    {
        cin >> t[i];
    }
    sort(s.begin(), s.end());
    sort(t.begin(), t.end());

    rep(i, q)
    {
        ll x;
        cin >> x;

        ll res = 1e18;

        // 先に s
        int it = lower_bound(s.begin(), s.end(), x) - s.begin();
        for (int i = max(0, it - 1); i < min(a, it + 1); i++)
        {
            ll y = s[i];
            int it2 = lower_bound(t.begin(), t.end(), y) - t.begin();
            for (int j = max(0, it2 - 1); j < min(b, it2 + 1); j++)
            {
                res = min(res, abs(x - y) + abs(y - t[j]));
            }
        }

        // 先に t
        it = lower_bound(t.begin(), t.end(), x) - t.begin();
        for (int i = max(0, it - 1); i < min(b, it + 1); ++i)
        {
            ll y = t[i];
            int it2 = lower_bound(s.begin(), s.end(), y) - s.begin();
            for (int j = max(0, it2 - 1); j < min(a, it2 + 1); ++j)
            {
                res = min(res, abs(x - y) + abs(y - s[j]));
            }
        }
        cout << res << endl;
    }
}

Submission status: Runtime Error

Solution code:
from bisect import bisect_left, bisect_right
a, b, q = map(int, input().split())
shrine = [int(input()) for _ in range(a)]
temple = [int(input()) for _ in range(b)]

inf = 10**18
for _ in range(q):
    ans = inf
    x = int(input())
    index_s = bisect_left(shrine, x)
    index_t = bisect_right(temple, x)
    for i in range(index_s-1, index_s+1):
        if i == a:
            continue
        s = shrine[i]
        i_t = bisect_left(temple, s)

        if i_t == 0:
            t0 = inf
        else:
            t0 = temple[i_t - 1]
        if i_t <= b:
            t1 = temple[i_t]
        else:
            t1 = inf

        ans = min(
            ans,
            abs(x - s) + abs(s - t0),
            abs(x - s) + abs(s - t1),
        )
    for i in range(index_t-1, index_t+1):
        if i == b or i < 0:
            continue
        t = temple[i]
        i_s = bisect_left(shrine, t)
        if i_s == 0:
            s0 = inf
        else:
            s0 = shrine[i_s - 1]

        if i_s <= a-1:
            s1 = shrine[i_s]
        else:
            s1 = inf
        ans = min(
            ans,
            abs(x - t) + abs(t - s0),
            abs(x - t) + abs(t - s1),
        )

    print(ans)

Submission status: Runtime Error

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

a=[-float("inf")]
b=[-float("inf")]
for i in range(A):
    a.append(int(input()))
for i in range(B):
    b.append(int(input()))   
a+=[float("inf")]
b+=[float("inf")]

for i in range(Q):
    q = int(input())
    x = bisect.bisect_left(a, q[i])
    y = bisect.bisect_left(b, q[i])
    for j in [a[x-1], a[x]]:
        for k in [b[y-1], b[y]]:
            ans1 = abs(j-q)+abs(j-k)
            ans2 = abs(k-q)+abs(j-k)
            ans = min(ans, ans1, ans2)
    print(ans)

Submission status: Runtime Error

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

a,b,q = map(int, input().split())
m = {}
st = []
for _ in range(a):
    num = int(input())
    st.append(num)
    m[num] = "A"
for _ in range(b):
    num = int(input())
    st.append(num)
    m[num] = "B"
st.sort()

def search_left(idx):
    t = {"A": False, "B": False}
    for i in st[:idx][::-1]:
        if m[i] == "A":t["A"]=True
        if m[i] == "B":t["B"]=True
        if t["A"] and t["B"]:return i
    return 0
def search_right(idx):
    t = {"A": False, "B": False}
    for i in st[idx:]:
        if m[i] == "A":t["A"]=True
        if m[i] == "B":t["B"]=True
        if t["A"] and t["B"]:return i
    return 0
def search_left_one(idx, c):
    for i in st[:idx][::-1]:
        if m[i] == c:return i
def search_right_one(idx, c):
    for i in st[idx:]:
        if m[i] == c:return i
for _ in range(q):
    x = int(input())
    idx = bisect.bisect_left(st,x)
    if idx == 0:
        most_right = search_right(0)
        print(abs(x-most_right))
        continue
    elif idx == a+b:
        most_left = search_left(a+b)
        print(abs(x-most_left))
        continue        
    left = st[idx-1]
    right = st[idx]
    c = "A" if m[left]=="B" else "B"
    most_right = search_right_one(idx, c)
    ans = abs(abs(x-left)+most_right-left)
    c = "A" if m[right]=="B" else "B"
    most_left = search_left_one(idx, c)
    ans = min(ans,abs(abs(x-right)+right-most_left))
    most_left = search_left(idx)
    if most_left != 0:ans = min(ans,abs(x-most_left))
    most_right = search_right(idx)
    if most_right != 0:ans = min(ans,abs(x-most_right))
    print(ans)

Submission status: Runtime Error

Solution code:
def main():
    import numpy as np
    import sys
    input=sys.stdin.readline

    a,b,q=map(int,input().split())
    S=np.array([int(input()) for _ in range(a)])
    T=np.array([int(input()) for _ in range(b)])
    Q=np.array([int(input()) for _ in range(q)])
    idxs=np.searchsorted(S,Q)
    idxt=np.searchsorted(T,Q)
    
    for i in range(q):
        x=Q[i]
        s=idxs[i]
        t=idxt[i]
        
        if s==0 and t==0:
            print(max(S[0],T[0])-x)
        elif s==0 and t==b:
            print(S[0]-T[-1]+min(S[0]-x,x-T[-1]))               
        elif s==a and t==0:
            print(T[0]-S[-1]+min(T[0]-x,x-S[-1]))
        elif s==a and t==b:
            print(x-min(S[-1],T[-1]))
        
        elif s==0:
            print(min(max(S[0],T[t])-x,min(S[0]-x,x-T[t-1])+S[0]-T[t-1]))
        elif s==a:
            print(min(x-min(S[-1],T[t-1]),min(T[t]-x,x-S[-1])+T[t]-S[-1]))                  
        elif t==0:
            print(min(max(T[0],S[s])-x,min(T[0]-x,x-S[s-1])+T[0]-S[s-1]))
        elif t==b:
            print(min(x-min(T[-1],S[s-1]),min(S[t]-x,x-T[-1])+S[s]-T[-1]))
            
        else:
            print(min(max(T[t],S[s])-x,x-min(T[t-1],S[s-1])))   
  
if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
def main():
    import numpy as np
    import sys
    input=sys.stdin.readline
    sys.setrecursionlimit(1000000000)

    a,b,q=map(int,input().split())
    S=np.array([int(input()) for _ in range(a)])
    T=np.array([int(input()) for _ in range(b)])
    Q=np.array([int(input()) for _ in range(q)])
    idxs=np.searchsorted(S,Q)
    idxt=np.searchsorted(T,Q)
    
    for i in range(q):
        x=Q[i]
        s=idxs[i]
        t=idxt[i]
        if s==0 and t==0:
            print(max(S[0],T[0])-x)
        elif s==0 and t==b:
            print(S[0]-T[-1]+min(S[0]-x,x-T[-1]))
        elif s==0:
            print(min(max(S[0],T[t])-x,min(S[0]-x,x-T[t-1])+S[0]-T[t-1]))
                  
        elif s==a and t==0:
            print(T[0]-S[-1]+min(T[0]-x,x-S[-1]))
        elif s==a and t==b:
            print(x-min(S[-1],T[-1]))
        elif s==a:
            print(min(x-min(S[-1],T[t-1]),min(T[t]-x,x-S[-1])+T[t]-S[-1]))
                  
        elif t==0:
            print(min(max(T[0],S[s])-x,min(T[0]-x,x-S[s-1])+T[0]-S[s-1]))
        elif t==b:
            print(min(x-min(T[-1],S[s-1]),min(S[t]-x,x-T[-1])+S[s]-T[-1]))
        else:
            print(min(max(T[t],S[s])-x,x-min(T[t-1],S[s-1])))   
  
if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
def main():
    import numpy as np
    import sys
    input=sys.stdin.readline
    sys.setrecursionlimit(1000000000)

    a,b,q=map(int,input().split())
    S=np.array([int(input()) for _ in range(a)])
    T=np.array([int(input()) for _ in range(b)])
    
    for _ in range(q):
        x=int(input())
        s=np.searchsorted(S,x)
        t=np.searchsorted(T,x)
        if s==0 and t==0:
            print(max(S[0],T[0])-x)
        elif s==0 and t==b:
            print(S[0]-T[-1]+min(S[0]-x,x-T[-1]))
        elif s==0:
            print(min(max(S[0],T[t])-x,min(S[0]-x,x-T[t-1])+S[0]-T[t-1]))
                  
        elif s==a and t==0:
            print(T[0]-S[-1]+min(T[0]-x,x-S[-1]))
        elif s==a and t==b:
            print(x-min(S[-1],T[-1]))
        elif s==a:
            print(min(x-min(S[-1],T[t-1]),min(T[t]-x,x-S[-1])+T[t]-S[-1]))
                  
        elif t==0:
            print(min(max(T[0],S[s])-x,min(T[0]-x,x-S[s-1])+T[0]-S[s-1]))
        elif t==b:
            print(min(x-min(T[-1],S[s-1]),min(S[t]-x,x-T[-1])+S[s]-T[-1]))
        else:
            print(min(max(T[t],S[s])-x,x-min(T[t-1],S[s-1])))   
  
if __name__=='__main__':
    main()

Submission status: Runtime Error

Solution code:
from bisect import bisect_left

INF = 2 * 10**10

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 x in X:
    sr = bisect_left(S, x) 
    sl = sr -1
    if sr != len(S) and S[sr] == x:
        sl = sr
    tr = bisect_left(T, x)
    tl = tr - 1
    if tr != len(T) and T[tr] == x:
        tl = tr

    ll = INF if sl == -1 or tl == -1 else x - min(S[sl], T[tl])
    rr = INF if sr == len(S) or tl == len(T) else max(S[sr], T[tr]) - x
    lsrt = INF if sl == -1 or tr == len(T) else 2*(x-S[sl]) + (T[tr] - x)
    ltrs = INF if tl == -1 or sr == len(S) else 2*(x-T[tl]) + (S[sr] - x)
    rslt = INF if tl == -1 or sr == len(S) else 2*(S[sr] - x) + (x - T[tl])
    rtls = INF if sl == -1 or tr == len(T) else 2*(T[tr] - x) + (x - S[sl])

    ans = min(ll, rr, lsrt, ltrs, rslt, rtls)
    print(ans)

Submission status: Runtime Error

Solution code:
import numpy as np
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')]
sls = np.searchsorted(s,x)
tls = np.searchsorted(t,x)
for ar, br, c in zip(sls,tls,x):
  bl = br-1
  al = ar-1
  n = s[ar]-t[bl]+min(s[ar]-c,c-t[bl])
  m = t[br]-s[al]+min(t[br]-c,c-s[al])
  p = c-min(t[bl],s[al])
  q = max(s[ar],t[br])-c
  print(min(n,m,p,q))

Submission status: Runtime Error

Solution code:
import bisect

A, B, Q = map(int, input().split())
S = []
T = []
X = []

ans = 10 ** 15

for lst, num in ((S, A), (T, B), (X, Q)):
	for _ in range(num):
		lst.append(int(input()))


for x in X:
	# 先に神社パターン
	# 右
	distance = 0
	nearest_s = S[min(bisect.bisect_left(S, x), A - 1)]
	distance += abs(x - nearest_s)
	nearest_t = bisect.bisect_left(T, nearest_s)
	distance += min(abs(nearest_s - T[nearest_t]), abs(nearest_s - T[max(0, nearest_t - 1)]))
	ans = min(ans, distance)
	
	# 左
	distance = 0
	nearest_s = S[max(bisect.bisect_right(S, x) - 1, 0)]
	distance += abs(x - nearest_s)
	nearest_t = bisect.bisect_left(T, nearest_s)
	distance += min(abs(nearest_s - T[nearest_t]), abs(nearest_s - T[max(0, nearest_t - 1)]))
	ans = min(ans, distance)
	
	# 先に寺パターン
	# 右
	distance = 0
	nearest_t = T[min(bisect.bisect_left(T, x), B - 1)]
	distance += abs(x - nearest_t)
	nearest_s = bisect.bisect_left(S, nearest_t)
	distance += min(abs(nearest_t - S[nearest_s]), abs(nearest_t - S[max(0, nearest_s - 1)]))
	ans = min(ans, distance)
	
	# 左
	distance = 0
	nearest_t = T[max(bisect.bisect_right(T, x) - 1, 0)]
	distance += abs(x - nearest_t)
	nearest_s = bisect.bisect_left(S, nearest_t)
	distance += min(abs(nearest_t - S[nearest_s]), abs(nearest_t - S[max(0, nearest_s - 1)]))
	ans = min(ans, distance)
	
	print(ans)

Submission status: Runtime Error

Solution code:
import bisect

A, B, Q = map(int, input().split())
S = []
T = []
X = []

ans = 10 ** 15

for lst, num in ((S, A), (T, B), (X, Q)):
	for _ in range(num):
		lst.append(int(input()))

print(S)
print(T)

for x in X:
	# 先に神社パターン
	# 右
	distance = 0
	nearest_s = S[min(bisect.bisect_left(S, x), A - 1)]
	distance += abs(x - nearest_s)
	nearest_t = bisect.bisect_left(T, nearest_s)
	distance += min(abs(nearest_s - T[nearest_t]), abs(nearest_s - T[max(0, nearest_t - 1)]))
	ans = min(ans, distance)
	
	# 左
	distance = 0
	nearest_s = S[max(bisect.bisect_right(S, x) - 1, 0)]
	distance += abs(x - nearest_s)
	nearest_t = bisect.bisect_left(T, nearest_s)
	distance += min(abs(nearest_s - T[nearest_t]), abs(nearest_s - T[max(0, nearest_t - 1)]))
	ans = min(ans, distance)
	
	# 先に寺パターン
	# 右
	distance = 0
	nearest_t = T[min(bisect.bisect_left(T, x), B - 1)]
	distance += abs(x - nearest_t)
	nearest_s = bisect.bisect_left(S, nearest_t)
	distance += min(abs(nearest_t - S[nearest_s]), abs(nearest_t - S[max(0, nearest_s - 1)]))
	ans = min(ans, distance)
	
	# 左
	distance = 0
	nearest_t = T[max(bisect.bisect_right(T, x) - 1, 0)]
	distance += abs(x - nearest_t)
	nearest_s = bisect.bisect_left(S, nearest_t)
	distance += min(abs(nearest_t - S[nearest_s]), abs(nearest_t - S[max(0, nearest_s - 1)]))
	ans = min(ans, distance)
	
	print(ans)

Submission status: Runtime Error

Solution code:
from bisect import *
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)]
value1=2*(10**10)
for x in range(X):
    value=value1
    s1=bisect_left(S,x)
    for s in [s1-1,s1]:
        if -1< s < A:
            t1=bisect_left(T,S[s])
            for t in [t1-1,t1]:
                a=0
                if -1< t < B:
                    if x>S[s]:
                        a+=x-S[s]
                    else:
                        a+=S[s]-x
                    if S[s]>T[t]:
                        a+=S[s]-T[t]
                    else:
                        a+=T[t]-S[s]
                    if value>a:
                        value=a
    t1=bisect_left(T,x)
    for t in [t1-1,t1]:
        if -1< t < B:
            s1=bisect_left(S,T[t])
            for s in [s1-1,s1]:
                a=0
                if -1< s < A:
                    if x>T[t]:
                        a+=x-T[t]
                    else:
                        a+=T[t]-x
                    if S[s]>T[t]:
                        a+=S[s]-T[t]
                    else:
                        a+=T[t]-S[s]
                    if value>a:
                        value=a

    print(value)

Submission status: Runtime Error

Solution code:
import sys, bisect, math, itertools, string, queue, copy
# import numpy as np
# import scipy
from collections import Counter,defaultdict,deque
from itertools import permutations, combinations
from heapq import heappop, heappush
input = sys.stdin.readline
sys.setrecursionlimit(10**8)
mod = 10**9+7
def inp(): return int(input()) # n=1
def inpm(): return map(int,input().split()) # x=1,y=2
def inpl(): return list(map(int, input().split())) # a=[1,2,3,4,5,...,n]
def inpls(): return list(input().split())  # a=['1','2','3',...,'n']
def inplm(n): return list(int(input()) for _ in range(n)) # x=[] 複数行
def inplL(n): return [list(input()) for _ in range(n)]
def inplT(n): return [tuple(input()) for _ in range(n)]
def inpll(n): return [list(map(int, input().split())) for _ in range(n)] # [[2,2,2,2],[1,1,1,1],[3,3,3,3]] 
def inplls(n): return sorted([list(map(int, input().split())) for _ in range(n)]) # [[1,1,1,1],[2,2,2,2],[3,3,3,3]] 
def graph():
    n=inp()
    g=[[] for _ in range(n)]
    for i in range(n):
        a = inp()
        a -= 1
        g[i].append(a)
        g[a].append(i)
    return n,g

def f(li, x):
    n = len(li)
    ok = -1
    ng = n
    while abs(ok-ng) > 1:
        mid = (ok+ng)//2
        if li[mid] < x:
            ok = mid
        else:
            ng = mid
    return ok

def main():
    a,b,q = inpm()
    s = inplm(a)
    t = inplm(b)
    x = inplm(q)
    s = tuple(s)
    t = tuple(t)
    x = tuple(x)
    for i in range(q):
        start = x[i]
        n = len(s)
        ok = -1
        ng = n
        while abs(ok-ng) > 1:
            mid = (ok+ng)//2
            if s[mid] < x:
                ok = mid
            else:
                ng = mid
        index_s = ok
        n = len(t)
        ok = -1
        ng = n
        while abs(ok-ng) > 1:
            mid = (ok+ng)//2
            if t[mid] < x:
                ok = mid
            else:
                ng = mid
        index_t = ok
        a1 = 10**11
        b1 = 10**11
        c1 = 10**11
        d1 = 10**11
        if index_t+1 < b and index_s+1 < a:
            d1 = abs(max(s[index_s+1],t[index_t+1]) - start)
        if index_s >= 0 and index_t+1 < b:
            a1 = min(abs(start - s[index_s]) + abs(s[index_s] - t[index_t+1]), abs(start - t[index_t+1]) + abs(s[index_s] - t[index_t+1]) )  
        if index_t >= 0 and index_s+1 < a:
            b1 = min(abs(start - t[index_t]) + abs(s[index_s+1] - t[index_t]),abs(start - s[index_s+1]) + abs(s[index_s+1] - t[index_t]))
        if index_s >= 0 and index_t >= 0:
            c1 = abs(start - min(s[index_s],t[index_t]))
        print(min(a1,b1,c1,d1))

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:
#A

"""
s = input().split("/")
if int(s[1]) <= 4:
    print("Heisei")
else:
    print("TBD")
"""
#B
"""
n = int(input())
ans = 0
for i in range(n):
    a = input().split()
    if a[1] == "JPY":
        ans += int(a[0])
    else:
        ans +=  float(a[0]) * 380000
print(ans)
"""

#C
import itertools

n, a, b, c = map(int, input().split())
abc = [a, b, c]
ans = float("INF")
x = [int(input()) for i in range(n)]
nums = list(itertools.product([0, 1, 2, 3], repeat = n))
#print(nums)
for i in nums:
    tmp = 0
    aa = 0
    ba = 0
    ca = 0
    for number, k in enumerate(i):
        if k == 1:
            if aa != 0:
                tmp += 10
            aa += x[number]
        if k == 2:
            if ba != 0:
                tmp += 10
            ba += x[number]
        if k == 3:
            if ca != 0:
                tmp += 10
            ca += x[number]
    if aa == 0 or ba == 0 or ca == 0:
        tmp = float("INF")
    else:
        tmp += abs(aa - a)
        tmp += abs(ba - b)
        tmp += abs(ca - c)
    ans = min(tmp, ans)
print(ans)
        
        
            


#D

"""
a, b, q = map(int, input().split())
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
s.sort()
t.sort()

import bisect


for i in range(q):
    x = int(input())
    s_l = bisect.bisect_left(s, x) - 1
    t_l = bisect.bisect_left(t, x) - 1
    s_r = s_l + 1
    t_r = t_l + 1
    if s_l == -1:
        s_l = 0
    if t_l == -1:
        t_l = 0
    if s_l == a :
        s_l = a - 1
        s_r = a - 1
    if s_r == a:
        s_r = a - 1
    if t_l == b:
        t_l = b - 1
        t_r = b - 1
    if t_r == b:
        t_r = b - 1
    ans = min(abs(t[t_l] - s[s_r]) + min(abs(t[t_l] - x), abs(s[s_r] - x)),
    abs(s[s_l] - t[t_r]) + min(abs(s[s_l] - x), abs(t[t_r] - x)),
    abs(s[s_l] - t[t_l]) + min(abs(s[s_l] - x), abs(t[t_l] - x)),
    abs(s[s_r] - t[t_r]) + min(abs(s[s_r] - x), abs(t[t_r] - x)),
    )
    
    print(ans)
"""

Submission status: Runtime Error

Solution code:
import bisect

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

ans = []
for i in range(Q):
    x = int(input())
    s = bisect.bisect_left(S, x)
    s = min([s,len(S)-1])
    kyori_s = S[s]
    st1 = min([bisect.bisect_left(T, kyori_s), len(T)-1])
    st2 = max([st1-1,0])
    kyori1 = abs(kyori_s-x) + min([abs(T[st1]-kyori_s),abs(T[st2]-kyori_s)])

    s = max([s-1,0])
    kyori_s = S[s]
    st1 = min([bisect.bisect_left(T, kyori_s), len(T)-1])
    st2 = max([st1-1,0])
    kyori2 = abs(kyori_s-x) + min([abs(T[st1]-kyori_s),abs(T[st2]-kyori_s)])

    t = bisect.bisect_left(T, x)
    t = min([t,len(T)-1])
    kyori_t = T[t]
    ts1 = min([bisect.bisect_left(S, kyori_t), len(S)-1])
    ts2 = max([st2-1,0])
    kyori3 = abs(kyori_t-x) + min([abs(S[ts1]-kyori_t),abs(S[ts2]-kyori_t)])

    t = max([t-1,0])
    kyori_t = T[t]
    ts1 = min([bisect.bisect_left(S, kyori_t), len(S)-1])
    ts2 = max([st2-1,0])
    kyori4 = abs(kyori_t-x) + min([abs(S[ts1]-kyori_t),abs(S[ts2]-kyori_t)])

    ans.append(min([kyori1,kyori2,kyori3,kyori4]))

for i in ans:
    print(i)

Submission status: Runtime Error

Solution code:
from bisect import bisect
# import numpy as np
a,b,q = map(int, input().split())
s = [int(input()) for i in range(a)]
t = [int(input()) for i in range(b)]
inf = float('INF')

for _ in range(q):
    x = int(input())
    # print('x', x)
    ss = bisect(s, x)
    tt = bisect(t, x)
    ans = inf
    # print(s[min(ss,a-1)], t[min(tt,b-1)], x)
    j,l = abs(t[max(tt-1,0)] - x), abs(t[min(b-1,tt)] - x)
    if ss :
        i = abs(s[ss-1] - x)
        if tt :
            if sorted([s[ss-1], x, t[tt-1]]).index(x) == 1:
                if ans > i+j+min(i,j):
                    ans = i+j+min(i,j)
            else:
                if ans > max(i,j):
                    ans = max(i,j)
        if tt < b:
            if sorted([s[ss-1], x, t[tt]]).index(x) == 1:
                if ans > i+l+min(i,l):
                    ans = i+l+min(i,l)
            else:
                if ans > max(i,l):
                    ans = max(i,l)
    if ss < a:
        k = abs(s[ss] - x)
        if tt:
            if sorted([s[ss], x, t[tt-1]]).index(x) == 1:
                if ans > i+j+min(k,j):
                    ans = i+j+min(k,j)
            else:
                if ans > max(k,j):
                    ans = max(k,j)
        elif tt < b:
            if sorted([s[ss], x, t[tt]]).index(x) == 1:
                if ans > i+j+min(k,l):
                    ans = i+j+min(k,l)
            else:
                if ans > max(k,l):
                    ans = max(k,l)
    print(ans)

Submission status: Runtime Error

Solution code:

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

def binary_search(target, N, left, right):
  if right - left <= 1:
    return (left, right)

  mid = (left + right) // 2

  if target == N[mid]:
    return mid

  if target <= N[mid]:
    return binary_search(target, N, left, mid)
  else:
    return binary_search(target, N, mid, right)

s_size = len(S)
t_size = len(T)
inf = 999999999999999999999

for x in X:
  s_left, s_right = binary_search(x, S, 0, s_size)
  t_left, t_right = binary_search(x, T, 0, s_size)

  slv = S[s_left] if s_left < s_size else inf
  srv = S[s_right] if s_right < s_size else inf
  tlv = T[t_left] if t_left < t_size else inf
  trv = T[t_right] if t_right < t_size else inf

  sl = [slv, srv]
  tl = [tlv, trv]
  mini = inf

  for n in [slv, srv]:
    c1 = abs(x - n)
    for m in [tlv, trv]:
      c2 = abs(n-m)
      mini = min(mini, c1+c2)

  for n in [tlv, trv]:
    c1 = abs(x - n)
    for m in [slv, srv]:
      c2 = abs(n-m)
      mini = min(mini, c1+c2)
  print(mini)

Submission status: Runtime Error

Solution code:
import bisect
a,b,q=map(int,input().split())
A=[-10**11]
for i in range(a):
  A.append(int(input()))
A.append(10**11)
B=[-10**11]
for i in range(b):
  B.append(int(input()))
B.append(10**11)
for i in range(q):
  x=int(input())
  c=bisect.bisect_left(A,x,hi=len(A))
  d=bisect.bisect_left(B,x,hi=len(A))
  ans=min(abs(A[c-1]-x)+abs(B[d-1]-A[c-1]),abs(A[c-1]-x)+abs(B[d]-A[c-1]),abs(A[c]-x)+abs(B[d-1]-A[c]),abs(A[c]-x)+abs(B[d]-A[c]),abs(B[d-1]-x)+abs(B[d-1]-A[c-1]),abs(B[d-1]-x)+abs(B[d-1]-A[c]),abs(B[d]-x)+abs(B[d]-A[c-1]),abs(B[d]-x)+abs(B[d]-A[c]))
  print(ans)

Submission status: Runtime Error

Solution code:
def p_d():
    from bisect import bisect_right
    A, B, Q = map(int, input().split())
    INF = 10 ** 9
    s = [-INF] + [int(input()) for _ in range(A)] + [INF]
    t = [-INF] + [int(input()) for _ in range(B)] + [INF]
    ans = []
    for _ in range(Q):
        x = int(input())
        b, d = bisect_right(s, x), bisect_right(t, x)
        res = INF
        for S in [s[b - 1], s[b]]:
            for T in [t[d - 1], t[d]]:
                d1, d2 = abs(S - x) + abs(T - S), abs(T - x) + abs(S - T)
                res = min((d1, d2, res))
        ans.append(str(res))
    print("\n".join(ans))


if __name__ == '__main__':
    p_d()

Submission status: Runtime Error

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


if __name__ == '__main__':
    p_d()