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:

from bisect import bisect_right

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:
    # Shrine -> Temple
    idx_s = bisect_right(S, x)
    if abs(S[min(A - 1, idx_s)] - x) > abs(S[max(0, idx_s - 1)] - x):
        x_s = S[max(0, idx_s - 1)]
    else:
        x_s = S[min(A - 1, idx_s)]

    idx_t = bisect_right(T, x_s)
    if abs(T[min(A - 1, idx_t)] - x_s) > abs(T[max(0, idx_t - 1)] - x_s):
        x_t = T[max(0, idx_t - 1)]
    else:
        x_t = T[min(B - 1, idx_t)]

    cand_0 = abs(x_s - x) + abs(x_t - x_s)

    # Temple -> Shrine
    idx_t = bisect_right(T, x)
    if abs(T[min(A - 1, idx_t)] - x) > abs(T[max(0, idx_t - 1)] - x):
        x_t = T[max(0, idx_t - 1)]
    else:
        x_t = T[min(B - 1, idx_t)]

    idx_s = bisect_right(S, x_t)
    if abs(S[min(A - 1, idx_s)] - x_t) > abs(S[max(0, idx_s - 1)] - x_t):
        x_s = S[max(0, idx_s - 1)]
    else:
        x_s = S[min(A - 1, idx_s)]

    cand_1 = abs(x_t - x) + abs(x_s - x_t)

    print(min(cand_0, cand_1))

Submission status: Runtime Error

Solution code:

from bisect import bisect_right

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:
    # Shrine -> Temple
    idx_s = bisect_right(S, x)
    if abs(S[min(A - 1, idx_s)] - x) > abs(S[max(0, idx_s - 1)] - x):
        x_s = S[max(0, idx_s - 1)]
    else:
        x_s = S[min(A - 1, idx_s)]

    idx_t = bisect_right(T, x_s)
    if abs(T[min(A - 1, idx_t)] - x_s) > abs(T[max(0, idx_t - 1)] - x_s):
        x_t = T[max(0, idx_t - 1)]
    else:
        x_t = T[min(A - 1, idx_t)]

    cand_0 = abs(x_s - x) + abs(x_t - x_s)

    # Temple -> Shrine
    idx_t = bisect_right(T, x)
    if abs(T[min(A - 1, idx_t)] - x) > abs(T[max(0, idx_t - 1)] - x):
        x_t = T[max(0, idx_t - 1)]
    else:
        x_t = T[min(A - 1, idx_t)]

    idx_s = bisect_right(S, x_t)
    if abs(S[min(A - 1, idx_s)] - x_t) > abs(S[max(0, idx_s - 1)] - x_t):
        x_s = S[max(0, idx_s - 1)]
    else:
        x_s = S[min(A - 1, idx_s)]

    cand_1 = abs(x_t - x) + abs(x_s - x_t)

    print(min(cand_0, cand_1))

Submission status: Runtime Error

Solution code:
import sys
import re
import math
import collections
import bisect
import itertools
import fractions
import functools
import copy
import heapq
import decimal
import statistics
import queue

# import numpy as np

sys.setrecursionlimit(10 ** 9)
INF = 10 ** 16
MOD = 10 ** 9 + 7
# MOD = 998244353

ni = lambda: int(sys.stdin.readline())
ns = lambda: map(int, sys.stdin.readline().split())
na = lambda: list(map(int, sys.stdin.readline().split()))
na1 = lambda: list(map(lambda x: int(x) - 1, sys.stdin.readline().split()))


# ===CODE===

def disLR(a, idx):
    small = a[max(0, idx - 1)]
    large = a[min(len(a) - 1, idx)]
    return small, large


def main():
    a, b, q = ns()
    s = [ni() for _ in range(a)]
    t = [ni() for _ in range(b)]

    for _ in range(q):
        ans = INF

        x = ni()

        idxs = bisect.bisect_left(s, x)
        a1 = [disLR(s, idxs)]

        idxt = bisect.bisect_left(t, x)
        a2 = [disLR(t, idxt)]

        for ta1 in a1:
            for ta2 in a2:
                tmp1 = abs(x - a1) + abs(a2 - a1)
                tmp2 = abs(x - a2) + abs(a1 - a2)
                ans = min(ans, tmp1, tmp2)

        print(ans)


if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
def main():
    from bisect import bisect_left
    import sys
    input = sys.stdin.buffer.readline
    def dist(x, s, t):
        if s < x and t < x:
            return x - min(s, t)
        elif s > x and t > x:
            return max(s, t) - x
        else:
            if (ds := abs(x - s)) <= (dt := abs(x - t)):
                return 2 * ds + dt
            else:
                return ds + 2 * dt
    def near(A, x):
        if (i := bisect_left(A, x)) == 0:
            return [A[0], ]
        elif 0 < i < a:
            return [A[i - 1], A[i]]
        else:
            return [A[-1], ]
    a, b, q = map(int, input().split())
    S = [int(input()) for _ in range(a)]
    T = [int(input()) for _ in range(b)]
    for _ in range(q):
        x = int(input())
        ans = 100000000000
        for s in near(S, x):
            for t in near(T, x):
                ans = min(ans, dist(x, s, t))
        print(ans)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
from bisect import bisect_left

sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
f_inf = float('inf')
mod = 10 ** 9 + 7


def resolve():
    a, b, q = map(int, input().split())
    S = list(int(input()) for _ in range(a))
    T = list(int(input()) for _ in range(b))

    for _ in range(q):
        x = int(input())
        idx_s = bisect_left(S, x)

        kouho_s = []
        if idx_s != 0:
            kouho_s.append(idx_s - 1)
        if idx_s != a:
            kouho_s.append(idx_s)

        res = f_inf
        for idx_s in kouho_s:
            dist = abs(x - S[idx_s])
            now = S[idx_s]
            idx_t = bisect_left(T, now)
            kouho_t = []
            if idx_t != 0:
                kouho_t.append(idx_t - 1)
            if idx_t != b:
                kouho_t.append(idx_t)
            for idx_t in kouho_t:
                dist += abs(now - T[idx_t])
                res = min(res, dist)

        kouho_t = []
        if idx_t != 0:
            kouho_t.append(idx_t - 1)
        if idx_t != b:
            kouho_t.append(idx_t)

        for idx_t in kouho_t:
            dist = abs(x - T[idx_t])
            now = T[idx_t]
            idx_s = bisect_left(S, now)
            kouho_s = []
            if idx_s != 0:
                kouho_s.append(idx_s - 1)
            if idx_s != b:
                kouho_s.append(idx_s)
            for idx_s in kouho_s:
                dist += abs(now - S[idx_t])
                res = min(res, dist)
        print(res)


if __name__ == '__main__':
    resolve()

Submission status: Runtime Error

Solution code:
#左右それぞれで一番近い神社
#その神社それぞれの左右それぞれで一番近い寺
#はい２ぶたん
from bisect import bisect_right

A,B,Q = map(int,input().split())
s = [int(input())for i in range(A)]
t = [int(input())for i in range(B)]

ans = []
for i in range(0,Q,1):
    q = int(input())
    sr = min(bisect_right(s,q),A-1)
    sl = max(0,sr-1)

    tr = min(bisect_right(t,q),B-1)
    tl = max(0,sl-1)


    ans.append(min(
    abs(q-s[sr])+ abs(t[min(bisect_right(t,s[sr]),B-1)]-s[sr]),
    abs(q-s[sl])+ abs(t[min(bisect_right(t,s[sl]),B-1)]-s[sl]),
    abs(q-t[tr])+ abs(s[min(bisect_right(s,t[tr]),A-1)]-t[tr]),
    abs(q-t[tl])+ abs(s[min(bisect_right(s,t[tl]),A-1)]-t[tl]),
    abs(q-s[sr])+ abs(t[max(bisect_right(t,s[sr])-1,0)]-s[sr]),
    abs(q-s[sl])+ abs(t[max(bisect_right(t,s[sl])-1,0)]-s[sl]),
    abs(q-t[tr])+ abs(s[max(bisect_right(s,t[tr])-1,0)]-t[tr]),
    abs(q-t[tl])+ abs(s[max(bisect_right(s,t[tl])-1,0)]-t[tl]))
    )

for i in range(0,Q,1):
    print(ans[i])

Submission status: Runtime Error

Solution code:
import bisect
a,b,q=map(int,input().split())
INF=10**18
S=[-INF]+[int(input()) for _ in range(a)]+[INF]
T=[-INF]+[int(input()) for _ in range(b)]+[INF]
for i in range(q):
  x=int(input())
  i=bisect.bisect_left(S,x)
  j=bisect.bisect_left(T,x)
  d=INF
  for s in [S[i],S[i+1]]:
    for t in [T[i],T[j+1]]:
      d1=abs(s-x)+abs(t-s)
      d2=abs(t-x)+abs(t-s)
      d=min(d,d1,d2)
  print(d)

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

using namespace std;

using ll = long long;
using P = pair<ll, ll>;
using Graph = vector<vector<ll>>;
#define rep(i, n) for(ll i=0;i<(ll)(n);i++)
#define rep2(i, m, n) for(ll i=m;i<(ll)(n);i++)
#define rrep(i, n, m) for(ll i=n;i>=(ll)(m);i--)
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const int ddx[8] = {0, 1, 1, 1, 0, -1, -1, -1};
const int ddy[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const ll MOD = 1000000007;
const ll INF = 1000000000000000000L;
#ifdef __DEBUG

/**
 * For DEBUG
 * https://github.com/ta7uw/cpp-pyprint
 */
#include "cpp-pyprint/pyprint.h"

#endif

void Main() {
    ll A, B, Q; cin >> A >> B >> Q;
    vector<ll> s(A + 2), t(B + 2);
    // 左右端の処理が面倒なので-INF/INFを詰める
    rep(i, A){cin >> s.at(i + 1);} s.at(0) = -INF;  s.at(A + 1) = INF;
    rep(i, B){cin >> t.at(i + 1);} t.at(0) = -INF;  t.at(B + 1) = INF;

    vector<ll> vec;
    rep(i, Q){
        ll x; cin >> x;
        auto iter_s = upper_bound(s.begin(), s.end(), x);
        ll right_ind_s = distance(s.begin(), iter_s);
        ll left_ind_s = right_ind_s - 1;

        auto iter_t = upper_bound(t.begin(), t.end(), x);
        ll right_ind_t = distance(t.begin(), iter_t);
        ll left_ind_t = right_ind_t - 1;

        // ll ans = INF;
        vector<ll> answers;

        // 4パターン網羅しなきゃいけない
        answers.push_back(x - min(s.at(left_ind_s), t.at(left_ind_t))); // (左，左)
        answers.push_back(max(s.at(right_ind_s), t.at(right_ind_t)) - x); // (右，右)
        answers.push_back(min(
            2 * (x - s.at(left_ind_s)) + (t.at(right_ind_t) - x),
            (x - s.at(left_ind_s)) + 2 * (t.at(right_ind_t) - x)
        )); // (左，右)
        answers.push_back(min(
            2 * (x - t.at(left_ind_t)) + (s.at(right_ind_s) - x),
            (x - t.at(left_ind_t)) + 2 * (s.at(right_ind_s) - x)
        )); // (右，左)
        vec.push_back(*min_element(answers.begin(), answers.end()));
    }
    for (auto v: vec){cout << v << endl;}
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(15);
    Main();
    return 0;
}

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>

using namespace std;

using ll = long long;
using P = pair<ll, ll>;
using Graph = vector<vector<ll>>;
#define rep(i, n) for(ll i=0;i<(ll)(n);i++)
#define rep2(i, m, n) for(ll i=m;i<(ll)(n);i++)
#define rrep(i, n, m) for(ll i=n;i>=(ll)(m);i--)
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const int ddx[8] = {0, 1, 1, 1, 0, -1, -1, -1};
const int ddy[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const ll MOD = 1000000007;
const ll INF = 1000000000000000000L;
#ifdef __DEBUG

/**
 * For DEBUG
 * https://github.com/ta7uw/cpp-pyprint
 */
#include "cpp-pyprint/pyprint.h"

#endif

void Main() {
    ll A, B, Q; cin >> A >> B >> Q;
    vector<ll> s(A + 2), t(B + 2);
    // 左右端の処理が面倒なので-INF/INFを詰める
    rep(i, A){cin >> s.at(i + 1);} s.at(0) = -INF;  s.at(A + 1) = INF;
    rep(i, B){cin >> t.at(i + 1);} t.at(0) = -INF;  t.at(B + 1) = INF;

    rep(i, Q){
        ll x; cin >> x;
        auto iter_s = upper_bound(s.begin(), s.end(), x);
        ll right_ind_s = distance(s.begin(), iter_s);
        ll left_ind_s = right_ind_s - 1;

        auto iter_t = upper_bound(t.begin(), t.end(), x);
        ll right_ind_t = distance(t.begin(), iter_t);
        ll left_ind_t = right_ind_t - 1;

        // ll ans = INF;
        vector<ll> answers;
        // cout << s.at(left_ind_s) << " " << x << " " << s.at(right_ind_s) << endl;
        // cout << t.at(left_ind_t) << " " << x << " " << t.at(right_ind_t) << endl;

        // 4パターン網羅しなきゃいけない
        answers.push_back(x - min(s.at(left_ind_s), t.at(left_ind_t))); // (左，左)
        answers.push_back(max(s.at(right_ind_s), t.at(right_ind_t)) - x); // (右，右)
        answers.push_back(min(
            2 * (x - s.at(left_ind_s)) + (t.at(right_ind_t) - x),
            (x - s.at(left_ind_s)) + 2 * (t.at(right_ind_t) - x)
        )); // (左，右)
        answers.push_back(min(
            2 * (x - t.at(left_ind_t)) + (s.at(right_ind_s) - x),
            (x - t.at(left_ind_t)) + 2 * (s.at(right_ind_s) - x)
        )); // (右，左)
        cout << *min_element(answers.begin(), answers.end()) << endl;
    }
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(15);
    Main();
    return 0;
}

Submission status: Runtime Error

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

A = []
for x in X:
    SL, SR, TL, TR = 10**20, 10**20, 10**20, 10**20
    i = bisect.bisect_left(S, x)
    if i != 0:
        SL = x-S[i-1]
    if i != A:
        SR = S[i]-x

    j = bisect.bisect_left(T, x)
    if j != 0:
        TL = x-T[j-1]
    if j != B:
        TR = T[j]-x

    ans = min(max(SL, TL), min(2*SL+TR, SL+2*TR),
              min(2*TL+SR, TL+2*SR), max(SR, TR))
    A.append(ans)
print(*A, sep='\n')

Submission status: Runtime Error

Solution code:
from bisect import bisect_right
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())
    inds = bisect_right(S,x)
    indt = bisect_right(T,x)
    if inds==A and indt==B:
        ans = max(x-S[inds-1],x-T[indt-1])
    elif inds==A and indt<B:
        if T[indt-1]>=S[inds-1]:
            ans = x-S[inds-1]
        else:
            ans = min(T[indt]-x+T[indt]-S[inds-1],x-T[indt-1])
    elif inds<B and indt==B:
        if S[inds-1]>=T[intd-1]:
            ans = x-T[indt-1]
        else:
            ans = min(S[inds]-x+S[inds]-T[indt-1],x-S[inds-1])
    else:
        ans = min(max(S[inds]-x,T[indt]-x),max(x-S[inds-1],x-T[indt-1]),S[inds]-x+S[inds]-T[indt-1],T[indt]-x+T[indt]-S[inds-1])
print(ans)

Submission status: Runtime Error

Solution code:
def find_min_fuka_idx(lst, x):
  ok = -1
  ng = len(lst)
  while abs(ok-ng)>1:
    mid = (ok+ng)//2
    if x>=lst[mid]:
      ok = mid
    else:
      ng = mid
  return ng

a,b,q = map(int, input().split())
s = [-10**18]
s_mid = [int(input()) for i in range(a)]
s.extend(s_mid)
s.append(10**18)
  
t = [-10**18]
t_mid = [int(input()) for i in range(b)]
t.extend(t_mid)
t.append(10**18)
x = [(int(input()), i) for i in range(q)]
x = sorted(x)
si = 1
tj = 1
ans = []
for i in range(q):
  si = find_min_fuka_idx(s[si-1:], x[i][0])
  tj = find_min_fuka_idx(t[tj-1:], x[i][0])
  ssi = s[si]
  ssi1 = s[si-1]
  ttj = t[tj]
  ttj1 = t[tj-1]
  ans.append((min(abs(x-ssi)+abs(ssi-ttj),\
            abs(x-ssi)+abs(ssi-ttj1),\
           abs(x-ttj)+abs(ttj-ssi),\
            abs(x-ttj)+abs(ttj-ssi1),\
            abs(x-ssi1)+abs(ssi1-ttj),\
            abs(x-ssi1)+abs(ssi1-ttj1),\
           abs(x-ttj1)+abs(ttj1-ssi),\
            abs(x-ttj1)+abs(ttj1-ssi1)), x[i][1]))

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

Submission status: Runtime Error

Solution code:
def find_min_fuka_idx(lst, x):
  ok = -1
  ng = len(lst)
  while abs(ok-ng)>1:
    mid = (ok+ng)//2
    if x>=lst[mid]:
      ok = mid
    else:
      ng = mid
  return ng

a,b,q = map(int, input().split())
s = [-10**18]
s_mid = [int(input()) for i in range(a)]
s.extends(s_mid)
s.append(10**18)

t = [-10**18]
t_mid = [int(input()) for i in range(b)]
t.extends(t_mid)
t.append(10**18)

for i in range(q):
  x = int(input())
  si = find_min_fuka_idx(s, x)
  tj = find_min_fuka_idx(t, x)
  print(min(abs(x-s[si])+abs(s[si]-t[tj]),\
            abs(x-s[si])+abs(s[si]-t[tj-1]),\
           abs(x-t[tj])+abs(t[tj]-s[si]),\
            abs(x-t[tj])+abs(t[tj]-s[si-1]),\
            abs(x-s[si-1])+abs(s[si-1]-t[tj]),\
            abs(x-s[si-1])+abs(s[si-1]-t[tj-1]),\
           abs(x-t[tj-1])+abs(t[tj-1]-s[si]),\
            abs(x-t[tj-1])+abs(t[tj-1]-s[si-1])))

Submission status: Runtime Error

Solution code:
def find_min_fuka_idx(lst, x):
  ok = -1
  ng = len(lst)
  while abs(ok-ng)>1:
    mid = (ok+ng)//2
    if x>=lst[mid]:
      ok = mid
    else:
      ng = mid
  return ng

a,b,q = map(int, input().split())
s = [-10**18]
for i in range(a):
  s.append(int(input()))
s.append(10**18)
t = [-10**18]
for i in range(b):
  t.append(int(input()))
t.append(10**18)

for i in range(q):
  x = int(input())
  si = find_min_fuka_idx(s, x)
  tj = find_min_fuka_idx(t, x)
  print(min(abs(x-s[si])+abs(s[si]-t[tj]),\
            abs(x-s[si])+abs(s[si]-t[tj-1]),\
           abs(x-t[tj])+abs(t[tj]-s[si]),\
            abs(x-t[tj])+abs(t[tj]-s[si-1]),\
            abs(x-s[si-1])+abs(s[si-1]-t[tj]),\
            abs(x-s[si-1])+abs(s[si-1]-t[tj-1]),\
           abs(x-t[tj-1])+abs(t[tj-1]-s[si]),\
            abs(x-t[tj]-1)+abs(t[tj-1]-s[si-1]))

Submission status: Runtime Error

Solution code:
n=int(input())

Submission status: Runtime Error

Solution code:
#include <bits/stdc++.h>
using namespace std;

const long long INF=1e12;

int main() {
    int a, b, q;
    cin >> a >> b >> q;
    vector<long long> s(a+1),t(b+1);
    s[0]=-INF;
    t[0]=-INF;
    for ( int i=1; i<=a; i++ ) {
        cin >> s[i];
    }
    for ( int i=1; i<=b; i++ ) {
        cin >> t[i];
    }
    s.push_back(INF);
    t.push_back(INF);
    sort(s.begin(), s.end());
    sort(t.begin(), t.end());
    while ( q-- ) {
        long long x;
        cin >> x;
        int ai=lower_bound(s.begin(), s.end(), x)-s.begin();
        int bi=lower_bound(t.begin(), t.end(), x)-t.begin();
        long long sx[2], tx[2];
        sx[1]=s[ai]; sx[0]=s[ai-1];
        tx[1]=t[bi]; tx[0]=t[bi-1];
        long long ans=INF;
        for ( int i=0; i<2; i++ ) {
            for ( int j=0; j<2; j++ ) {
                ans=min(ans, abs(x-sx[i])+abs(sx[i]-tx[j]));
                ans=min(ans, abs(x-tx[j])+abs(tx[j]-sx[i]));
            }
        }
        cout << ans << '\n';
    }
    return 0;
}

Submission status: Runtime Error

Solution code:
import sys
import bisect

def main():
  input = sys.stdin.readline
  inf = pow(10, 18)
  a, b, q = map(int, input().split())
  s = [-inf]+[int(input()) for _ in range(a)]+[inf]
  t = [-inf]+[int(input()) for _ in range(b)]+[inf]
  
  for _ in range(q):
    x = int(input())
    i = bisect.bisect_left(s, x)
    j = bisect.bisect_left(t, x)
    ans = inf
    for l in range(2):
      for m in range(2):
        sub = min([abs(x-s[i+l]), abs(x-t[j+m])])+abs(s[i+l]-t[j+m])
        if ans > sub:
          ans = sub
    print(ans)

if __name__ == "__main__":
  main()

Submission status: Runtime Error

Solution code:
import numpy as np

a, b, q = map(int, input().split())
sh = []
te = []

"""
def getNearestValue(list, num):
    
    概要: リストからある値に最も近い値を返却する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return list[idx]
"""


def getNearestValue(data, target):

    if len(data) == 0:
        return None
    if len(data) == 1:
        return data[0]
    min_diff = float('inf')
    imin = 0
    imax = len(data) - 1
    closest_num = None
    while imin <= imax:
        imid = imin + (imax - imin) // 2
        #　中心の左右の値と目標との差を計算する。
        if imid + 1 < len(data):
            min_diff_right = abs(data[imid+1] - target)
        if imid > 0:
            min_diff_left = abs(data[imid-1] - target)
        # 最初の差と最も最小に近い値を更新する。
        if min_diff_left < min_diff:
            min_diff = min_diff_left
            closest_num = data[imid-1]
        if min_diff_right < min_diff:
            min_diff = min_diff_right
            closest_num = data[imid+1]
        # 2分探索する。
        if data[imid] < target:
            imin = imid + 1
        elif data[imid] > target:
            imax = imid - 1
        else:
            return data[imid]
    return closest_num


def checkshrine(x):
    x_near_sh = getNearestValue(sh, x)
    xsash = np.abs(x_near_sh - x)
    sh_near_te = getNearestValue(te, x_near_sh)
    return xsash + np.abs(sh_near_te - x_near_sh)


def checktemple(x):
    x_near_te = getNearestValue(te, x)
    xsate = np.abs(x_near_te - x)
    te_near_sh = getNearestValue(sh, x_near_te)
    return xsate + np.abs(te_near_sh - x_near_te)


sh = [int(input()) for _ in range(a)]
te = [int(input()) for _ in range(b)]

for i in range(q):
    x = int(input())
    checkshrinevalue = checkshrine(x)
    checktemplevalue = checktemple(x)
    if (checkshrinevalue > checktemplevalue):
        print(checktemplevalue)
    else:
        print(checkshrinevalue)

Submission status: Runtime Error

Solution code:
import numpy as np

a, b, q = map(int, input().split())
sh = []
te = []

"""
def getNearestValue(list, num):
    
    概要: リストからある値に最も近い値を返却する関数
    @param list: データ配列
    @param num: 対象値
    @return 対象値に最も近い値
    

    # リスト要素と対象値の差分を計算し最小値のインデックスを取得
    idx = np.abs(np.asarray(list) - num).argmin()
    return list[idx]
"""


def getNearestValue(data, target):

    if len(data) == 0:
        return None
    if len(data) == 1:
        return data[0]
    min_diff = float('inf')
    imin = 0
    imax = len(data) - 1
    closest_num = None
    while imin <= imax:
        imid = imin + (imax - imin) // 2
        #　中心の左右の値と目標との差を計算する。
        if imid + 1 < len(data):
            min_diff_right = abs(data[imid+1] - target)
        if imid > 0:
            min_diff_left = abs(data[imid-1] - target)
        # 最初の差と最も最小に近い値を更新する。
        if min_diff_left < min_diff:
            min_diff = min_diff_left
            closest_num = data[imid-1]
        if min_diff_right < min_diff:
            min_diff = min_diff_right
            closest_num = data[imid+1]
        # 2分探索する。
        if data[imid] < target:
            imin = imid + 1
        elif data[imid] > target:
            imax = imid - 1
        else:
            return data[imid]
    return closest_num


def checkshrine(x):
    x_near_sh = getNearestValue(sh, x)
    xsash = np.abs(x_near_sh - x)
    sh_near_te = getNearestValue(te, x_near_sh)
    return xsash + np.abs(sh_near_te - x_near_sh)


def checktemple(x):
    x_near_te = getNearestValue(te, x)
    xsate = np.abs(x_near_te - x)
    te_near_sh = getNearestValue(sh, x_near_te)
    return xsate + np.abs(te_near_sh - x_near_te)


for i in range(a):
    sh.append(int(input()))

for i in range(b):
    te.append(int(input()))

for i in range(q):
    x = int(input())
    checkshrinevalue = checkshrine(x)
    checktemplevalue = checktemple(x)
    if (checkshrinevalue > checktemplevalue):
        print(checktemplevalue)
    else:
        print(checkshrinevalue)

Submission status: Runtime Error

Solution code:
import bisect
A, B, Q = map(int, input().split())
s = [-INF] + [int(input()) for _ in range(A)] + [INF]
t = [-INF] + [int(input()) for _ in range(B)] + [INF]
for i in range(Q):
  x = int(input())
  sw = bisect.bisect_right(s, x)-1 #xより西で一番近い(同じ場所でもいい)神社の番号
  se = sw + 1 #xより東で一番近い神社の番号
  tw = bisect.bisect_right(t, x)-1
  te = tw + 1
  res = INF
  for S in [sw, se]:
    for T in [tw, te]:
      d1, d2 = abs(x-S) + abs(T-S), abs(x-T) + abs(S-T)
      res = min(res, d1, d2)
  print(res)

Submission status: Runtime Error

Solution code:
import bisect
a,b,q=map(int,input().split())
S=[];T=[]
for _ in range(a):
    s=int(input())
    S.append(s)
for _ in range(b):
    t=int(input())
    T.append(t)
S.append(10**12)
T.append(10**12)

for _ in range(q):
    x=int(input())
    idx_s=bisect.bisect_left(S,x)
    idx_t=bisect.bisect_left(T,x)
    se=S[idx_s]
    sw=S[idx_s-1]
    te=T[idx_t]
    tw=T[idx_t-1]

    ans=float("inf")
    for ss in [se,sw]:
        for tt in [te,tw]:
            ans=min(ans,abs(ss-x)+abs8tt-ss),abs(tt-x)+abs(tt-ss))
    print(ans)

Submission status: Runtime Error

Solution code:
import bisect
a,b,q=map(int,input().split())
S=[];T=[]
for _ in range(a):
    s=int(input())
    S.append(s)
for _ in range(b):
    t=int(input())
    T.append(t)
S.append(10**12)
T.appent(10**12)

for _ in range(q):
    x=int(input())
    idx_s=bisect.bisect_left(S,x)
    idx_t=bisect.bisect_left(T,x)
    se=S[idx_s]
    sw=S[idx_s-1]
    te=T[idx_t]
    tw=T[idx_t-1]

    m1=abs(x-se)+abs(se-te)
    m2=abs(x-se)+abs(se-tw)
    m3=abs(x-sw)+abs(sw-te)
    m4=abs(x-sw)+abs(sw-tw)
    m5=abs(x-te)+abs(te-se)
    m6=abs(x-te)+abs(te-sw)
    m7=abs(x-tw)+abs(tw-se)
    m8=abs(x-tw)+abs(tw-sw)
    print(min(m1,m2,m3,m4,m5,m6,m7,m8))

Submission status: Runtime Error

Solution code:
import bisect,sys 
input=sys.stdin.readline 
a,b,Q=map(int,input().split())
INF=10**18
s=[-INF]+[int(input()) for _ in range(a)]+[INF]
t=[-INF]+[int(input()) for _ in range(b)]+[INF]
for q in range(Q):
    x=int(input())
    b,d=bisect.bisect_right(s,x),bisect.bisect_right(t,x)
    res=INF 
    for S in [s(b-1),s(b)]:
        for T in [t(d-1),t(d)]:
            d1,d2=abs(S-x)+abs(T-S),abs(T-x)+abs(T-S)
            res=min(res,d1,d2)
    print(res)

Submission status: Runtime Error

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

Submission status: Runtime Error

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

a,b,q = map(int,input().split())
s = []
t = []
s1 = []
t1 = []

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

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

for _ in range(q):
    x = int(input())
    s_index = bisect.bisect_left(s1, x)
    t_index = bisect.bisect_left(t1, x)
    xs = []
    xt = []
    for i in range(-2, 3):
        if 0 <= s_index + i < a:
            xs.append(s[s_index+i])
        if 0 <= t_index + i < a:
            xt.append(t[t_index+i])
    ans = 10**20
    for i in xs:
        for j in xt:
            ans = min(ans, abs(x-i) + abs(i-j), abs(x-j) + abs(j-i))

    print(ans)

Submission status: Runtime Error

Solution code:
A, B, Q = map(int, input().split())
S = [int(input()) for _ in range(A)]
T = [int(input()) for _ in range(B)]
query, X = [], {}

for i in range(Q):
    q = int(input())
    query.append(q)
    X[q] = i
query.sort()

near_s = [0 for _ in range(Q)]
near_t = [0 for _ in range(Q)]
j = 0
while j < Q and query[j] < S[0]:
    near_s[j] = [0, S[0]]
    j += 1    
for i in range(A-1):
    while j < Q and S[i] < query[j] < S[i+1]:
        near_s[j] = [S[i], S[i+1]]
        j += 1
near_s = near_s[:j] + [[S[A-1],0] for _ in range(Q-j)]

j = 0
while j < Q and query[j] < T[0]:
    near_t[j] = [0, T[0]]
    j += 1
for i in range(B-1):
    while j < Q and T[i] < query[j] < T[i+1]:
        near_t[j] = [T[i], T[i+1]]
        j += 1
near_t = near_t[:j] + [[T[B-1],0] for _ in range(Q-j)]

ans = [0]*Q
for i in range(Q):
    q, s0, s1, t0, t1 = query[i], *near_s[i], *near_t[i]
    l1 = q - min(s0, t0)
    l2 = max(s1, t1) - q
    l3 = s1 - t0 + min(s1 - q, q - t0)
    l4 = t1 - s0 + min(t1 - q, q - s0)
    if s0 == 0:
        l1, l4 = float('inf'), float('inf')
    if s1 == 0:
        l2, l3 = float('inf'), float('inf')
    if t0 == 0:
        l1, l3 = float('inf'), float('inf')
    if t1 == 0:
        l2, l4 = float('inf'), float('inf')
    ans[X[q]] = min(l1, l2, l3, l4)

for a in ans:
    print(a)

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)