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: Time Limit Exceeded

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)]
inf = 10 ** 18

s.insert(0, -inf)
s.insert(A + 1, inf)
t.insert(0, -inf)
t.insert(B + 1, inf)

sthome = []
for si in s: sthome.append((si, 's'))
for ti in t: sthome.append((ti, 't'))
sthome.sort(key=lambda x: x[0])

st = []
home = []
for sti, homei in sthome:
    st.append(sti)
    home.append(homei)
# print("#", st[2:len(st)-2], home)

    
def binsearch_l(seq, l, r, tar):
    if r - l < 2: return l
    #
    m = l + (r - l) // 2
    # print("##", l, r, (m, seq[m]), tar)
    if seq[m] <= tar:
        return binsearch_l(seq, m, r, tar)
    else:
        return binsearch_l(seq, l, m, tar)

for x_tmp in x:
    i_l = binsearch_l(st, 0, A + B + 4, x_tmp)
    #
    ans = inf
    #
    for i_tmp in (i_l, i_l + 1):
        if st[i_tmp] in (-inf, inf): continue
        ans_tmp = inf
        if home[i_tmp] == 's':
            j_l = binsearch_l(t, 0, B + 2, st[i_tmp])
            for j_tmp in (j_l, j_l + 1):
                if t[j_tmp] in (-inf, inf): continue
                ans_tmp_tmp = abs(x_tmp - st[i_tmp]) + abs(t[j_tmp] - st[i_tmp])
                # print("##", (i_tmp, j_tmp), x_tmp, st[i_tmp], t[j_tmp], ans_tmp_tmp)
                if ans_tmp > ans_tmp_tmp:
                    ans_tmp = ans_tmp_tmp
        else:
            j_l = binsearch_l(s, 0, A + 2, st[i_tmp])
            for j_tmp in (j_l, j_l + 1):
                if s[j_tmp] in (-inf, inf): continue
                ans_tmp_tmp = abs(x_tmp - st[i_tmp]) + abs(s[j_tmp] - st[i_tmp])
                # print("##", (i_tmp, j_tmp), x_tmp, st[i_tmp], s[j_tmp], ans_tmp_tmp)
                if ans_tmp > ans_tmp_tmp:
                    ans_tmp = ans_tmp_tmp
        if ans > ans_tmp:
            ans = ans_tmp
    #
    print(ans)

Submission status: Time Limit Exceeded

Solution code:
# https://tjkendev.github.io/procon-library/python/binary_search_tree/red-black-tree.html
class RedBlackTree():
    def __init__(self, default=None):
        self.root = None
        if default is not None:
            for v in default:
                self.root = self.insert(v)

    # rotate a tree nd
    # d = 0: right rotation
    # d = 1: left rotation
    def rotate(self, nd, d):
        c = nd[d]
        if d:
            e = c[1]
            nd[1] = c[0]
            c[0] = nd
        else:
            e = c[0]
            nd[0] = c[1]
            c[1] = nd

        r = c[3] = nd[3]
        nd[3] = r - (e[3] if e else 0) - 1
        return c

    # insert a node with key = val into a tree t
    def insert(self, val, t=None):
        t = self.root if t is None else t
        x = t
        st = [];
        dr = []
        y = None
        while x:
            y = x
            st.append(x)
            if x[2] == val:
                return t
            d = (x[2] < val)
            dr.append(d)
            x = x[d]

        # [<left>, <right>, <key>, <count>, <color: [BLACK,RED]>]
        nd = [None, None, val, 1, 1]

        if not y:
            nd[4] = 0
            return nd

        y[d] = nd
        for x in st:
            x[3] += 1

        while 1:
            if not st:
                # if nd is the root node
                nd[4] = 0
                return nd

            # nd's parent
            y = st.pop();
            dy = dr.pop()
            if not y[4]:
                # if nd's parent is black
                return t

            # nd's grandparent
            w = st.pop();
            dw = dr.pop()
            # nd's uncle
            z = w[dw ^ 1]
            if z and z[4]:
                # the parent and the uncle is red
                y[4] = z[4] = 0
                w[4] = 1
                nd = w
                continue

            if dw != dy:
                w[dw] = self.rotate(y, dy)
                nd, y = y, nd

            self.rotate(w, dw)
            y[4] = 0
            w[4] = 1

            if st:
                st[-1][dr[-1]] = y
                return t
            return y

    # delete a node nd
    def __delete(self, st, dr, nd):
        x = nd
        if x[0]:
            st.append(x);
            dr.append(0)
            x = x[0]
            while x:
                st.append(x);
                dr.append(1)
                x = x[1]

            y = st.pop();
            dr.pop()
            # copy a value only
            nd[2] = y[2]
        elif x[1]:
            st.append(x);
            dr.append(1)
            x = x[1]
            while x:
                st.append(x);
                dr.append(0)
                x = x[0]

            y = st.pop();
            dr.pop()
            # copy a value only
            nd[2] = y[2]
        else:
            y = nd

        # delete the node (y) with at most one non-leaf child
        for x in st:
            x[3] -= 1

        c = y[0] if y[0] else y[1]
        if st:
            st[-1][dr[-1]] = c

        if y[4]:
            # if nd is red
            return st[0] if st else c

        if c and c[4]:
            # if nd is black and child is red
            c[4] = 0
            return st[0] if st else c

        # nd and child is black: delete in each cases

        n = c
        while st:
            p = st.pop();
            dp = dr.pop()
            # n's sibling
            s = p[dp ^ 1]
            # assert s
            sc = s[dp];
            sd = s[dp ^ 1]

            if s[4]:
                # assert sc and sd
                p[4] = 1;
                s[4] = 0
                if st:
                    st[-1][dr[-1]] = self.rotate(p, dp ^ 1)
                else:
                    self.rotate(p, dp ^ 1)
                st.append(s);
                dr.append(dp)
                # assert p[dp ^ 1] is sc
                s = sc
                sc = s[dp];
                sd = s[dp ^ 1]
                break

            if p[4] or (sc and sc[4]) or (sd and sd[4]):
                break

            s[4] = 1
            n = p
        else:
            return n

        if p[4] and not s[4] and not (sc and sc[4]) and not (sd and sd[4]):
            p[4] = 0;
            s[4] = 1
            return st[0] if st else p

        sc = s[dp];
        sd = s[dp ^ 1]
        if not s[4] and (sc and sc[4]) and not (sd and sd[4]):
            sc[4] = 0;
            s[4] = 1
            sd = s
            s = p[dp ^ 1] = self.rotate(s, dp)

        # assert not s[4] and (sd and sd[4])
        s[4] = p[4]
        p[4] = 0
        sd[4] = 0

        if st:
            st[-1][dr[-1]] = self.rotate(p, dp ^ 1)
        else:
            return self.rotate(p, dp ^ 1)

        return st[0] if st else n

    # delete a node with key = val from a tree t
    def delete(self, val, t=None):
        x = self.root if t is None else t

        st = [];
        dr = []
        while x and val != x[2]:
            d = (x[2] < val)
            st.append(x);
            dr.append(d)
            x = x[d]
        if not x:
            return t
        # x is the node with key = val
        return self.__delete(st, dr, x)

    def bisect_left(self, val):
        x = self.root
        y = None
        res = 0
        while x:
            y = x
            if x[2] == val:
                return res + (x[0][3] if x[0] is not None else 0)
            d = (x[2] < val)
            if d:
                res += 1 + (x[0][3] if x[0] is not None else 0)
            x = x[d]
        return res
        # [<left>, <right>, <key>, <count>, <color: [BLACK,RED]>]

    def __getitem__(self, idx):
        x = self.root
        y = None
        while x:
            y = x
            l_cnt = x[0][3] if x[0] else 0
            if l_cnt == idx:
                return x[2]
            d = (l_cnt < idx)
            if d:
                idx -= 1 + l_cnt
            x = x[d]

import sys
from random import shuffle
input = sys.stdin.readline
A, B, Q = map(int, input().split())
S = [int(input()) for _ in range(A)]
shuffle(S)
S = RedBlackTree(S)
T = [int(input()) for _ in range(B)]
shuffle(T)
T = RedBlackTree(T)

def f(x):
    if 0 <= x and A - 1 >= x:
        return True
    return False
def g(x):
    if 0 <= x and B - 1 >= x:
        return True
    return False

for i in range(Q):
    x = int(input())
    p = S.bisect_left(x)
    m = T.bisect_left(x)

    res = []
    if f(p) and g(m):
        res.append(max(T[m], S[p]) - x)
    if f(p) and g(m - 1):
        res.append(min(S[p] - x, x - T[m - 1]) + S[p] - T[m - 1])
    if f(p - 1) and g(m):
        res.append(T[m] - S[p - 1] + min(T[m] - x, x - S[p - 1]))
    if f(p - 1) and g(m - 1):
        res.append(x - min(T[m - 1], S[p - 1]))
    print(min(res))

Submission status: Time Limit Exceeded

Solution code:
# https://tjkendev.github.io/procon-library/python/binary_search_tree/red-black-tree.html
class RedBlackTree():
    def __init__(self, default=None):
        self.root = None
        if default is not None:
            for v in default:
                self.root = self.insert(v)

    # rotate a tree nd
    # d = 0: right rotation
    # d = 1: left rotation
    def rotate(self, nd, d):
        c = nd[d]
        if d:
            e = c[1]
            nd[1] = c[0]
            c[0] = nd
        else:
            e = c[0]
            nd[0] = c[1]
            c[1] = nd

        r = c[3] = nd[3]
        nd[3] = r - (e[3] if e else 0) - 1
        return c

    # insert a node with key = val into a tree t
    def insert(self, val, t=None):
        t = self.root if t is None else t
        x = t
        st = [];
        dr = []
        y = None
        while x:
            y = x
            st.append(x)
            if x[2] == val:
                return t
            d = (x[2] < val)
            dr.append(d)
            x = x[d]

        # [<left>, <right>, <key>, <count>, <color: [BLACK,RED]>]
        nd = [None, None, val, 1, 1]

        if not y:
            nd[4] = 0
            return nd

        y[d] = nd
        for x in st:
            x[3] += 1

        while 1:
            if not st:
                # if nd is the root node
                nd[4] = 0
                return nd

            # nd's parent
            y = st.pop();
            dy = dr.pop()
            if not y[4]:
                # if nd's parent is black
                return t

            # nd's grandparent
            w = st.pop();
            dw = dr.pop()
            # nd's uncle
            z = w[dw ^ 1]
            if z and z[4]:
                # the parent and the uncle is red
                y[4] = z[4] = 0
                w[4] = 1
                nd = w
                continue

            if dw != dy:
                w[dw] = self.rotate(y, dy)
                nd, y = y, nd

            self.rotate(w, dw)
            y[4] = 0
            w[4] = 1

            if st:
                st[-1][dr[-1]] = y
                return t
            return y

    # delete a node nd
    def __delete(self, st, dr, nd):
        x = nd
        if x[0]:
            st.append(x);
            dr.append(0)
            x = x[0]
            while x:
                st.append(x);
                dr.append(1)
                x = x[1]

            y = st.pop();
            dr.pop()
            # copy a value only
            nd[2] = y[2]
        elif x[1]:
            st.append(x);
            dr.append(1)
            x = x[1]
            while x:
                st.append(x);
                dr.append(0)
                x = x[0]

            y = st.pop();
            dr.pop()
            # copy a value only
            nd[2] = y[2]
        else:
            y = nd

        # delete the node (y) with at most one non-leaf child
        for x in st:
            x[3] -= 1

        c = y[0] if y[0] else y[1]
        if st:
            st[-1][dr[-1]] = c

        if y[4]:
            # if nd is red
            return st[0] if st else c

        if c and c[4]:
            # if nd is black and child is red
            c[4] = 0
            return st[0] if st else c

        # nd and child is black: delete in each cases

        n = c
        while st:
            p = st.pop();
            dp = dr.pop()
            # n's sibling
            s = p[dp ^ 1]
            # assert s
            sc = s[dp];
            sd = s[dp ^ 1]

            if s[4]:
                # assert sc and sd
                p[4] = 1;
                s[4] = 0
                if st:
                    st[-1][dr[-1]] = self.rotate(p, dp ^ 1)
                else:
                    self.rotate(p, dp ^ 1)
                st.append(s);
                dr.append(dp)
                # assert p[dp ^ 1] is sc
                s = sc
                sc = s[dp];
                sd = s[dp ^ 1]
                break

            if p[4] or (sc and sc[4]) or (sd and sd[4]):
                break

            s[4] = 1
            n = p
        else:
            return n

        if p[4] and not s[4] and not (sc and sc[4]) and not (sd and sd[4]):
            p[4] = 0;
            s[4] = 1
            return st[0] if st else p

        sc = s[dp];
        sd = s[dp ^ 1]
        if not s[4] and (sc and sc[4]) and not (sd and sd[4]):
            sc[4] = 0;
            s[4] = 1
            sd = s
            s = p[dp ^ 1] = self.rotate(s, dp)

        # assert not s[4] and (sd and sd[4])
        s[4] = p[4]
        p[4] = 0
        sd[4] = 0

        if st:
            st[-1][dr[-1]] = self.rotate(p, dp ^ 1)
        else:
            return self.rotate(p, dp ^ 1)

        return st[0] if st else n

    # delete a node with key = val from a tree t
    def delete(self, val, t=None):
        x = self.root if t is None else t

        st = [];
        dr = []
        while x and val != x[2]:
            d = (x[2] < val)
            st.append(x);
            dr.append(d)
            x = x[d]
        if not x:
            return t
        # x is the node with key = val
        return self.__delete(st, dr, x)

    def bisect_left(self, val):
        x = self.root
        y = None
        res = 0
        while x:
            y = x
            if x[2] == val:
                return res + (x[0][3] if x[0] is not None else 0)
            d = (x[2] < val)
            if d:
                res += 1 + (x[0][3] if x[0] is not None else 0)
            x = x[d]
        return res
        # [<left>, <right>, <key>, <count>, <color: [BLACK,RED]>]

    def __getitem__(self, idx):
        x = self.root
        y = None
        while x:
            y = x
            l_cnt = x[0][3] if x[0] else 0
            if l_cnt == idx:
                return x[2]
            d = (l_cnt < idx)
            if d:
                idx -= 1 + l_cnt
            x = x[d]

import sys
input = sys.stdin.readline
A, B, Q = map(int, input().split())
S = RedBlackTree([int(input()) for _ in range(A)])
T = RedBlackTree([int(input()) for _ in range(B)])
def f(x):
    if 0 <= x and A - 1 >= x:
        return True
    return False
def g(x):
    if 0 <= x and B - 1 >= x:
        return True
    return False

for i in range(Q):
    x = int(input())
    p = S.bisect_left(x)
    m = T.bisect_left(x)

    res = []
    if f(p) and g(m):
        res.append(max(T[m], S[p]) - x)
    if f(p) and g(m - 1):
        res.append(min(S[p] - x, x - T[m - 1]) + S[p] - T[m - 1])
    if f(p - 1) and g(m):
        res.append(T[m] - S[p - 1] + min(T[m] - x, x - S[p - 1]))
    if f(p - 1) and g(m - 1):
        res.append(x - min(T[m - 1], S[p - 1]))
    print(min(res))