Problem:
Problem I: Hard Beans
Problem
大津大学では豆が盛んです。
N
個の豆が一直線上に並んでいます。
それぞれ0から順に
N
−1まで番号がふられており、
i
番目の豆の硬さを
a
i
とします。
シアン君は理想の豆の硬さを
D
だと考えています。しかし、シアン君は面倒くさがりなのであまり遠くにある豆を取りに行きたくありません。したがって、シアン君は
l
番目の豆から
r
番目の豆の中で硬さが
D
に最も近い豆を知りたいと思っています。
シアン君は
Q
個の質問をしてくるので、それぞれの質問に対し閉区間[
l
,
r
]番目にある　|
豆の硬さ
−
D
|　の最小値を求めるプログラムを作成してください。(ただし、|
a
| は
a
の絶対値を表します。)
Input
入力は以下の形式で与えられる。
N
a
0
a
1
...
a
N−1
Q
l
0
r
0
D
0
l
1
r
1
D
1
.
.
.
l
Q−1
r
Q−1
D
Q−1
1行目に、1つの整数
N
が与えられる。2行目に、
N
つの整数が空白区切りで与えられる。3行目に、クエリの数が１つの整数
Q
として与えられる。続く4行から3+
Q
行までにクエリの値
l
,
r
,
D
が与えられる。
Constraints
入力は以下の制約を満たす。
1 ≤
N
≤ 10
5
0 ≤
|a
i
|
≤ 10
6
(0 ≤
i
≤
N
−1)
1 ≤
Q
≤ 10
5
0 ≤
D
i
≤ 10
6
0 ≤
l
i
≤
r
i
≤
N
−1
Output
各クエリに対し、
D
と[
l
,
r
]番目の豆の中で硬さ
D
に最も近い豆の硬さとの差の絶対値を1行に出力せよ。
Sample Input1
3
1 2 3
3
0 2 2
0 2 4
0 0 2
Sample Output1
0
1
1
Sample Input2
10
4 5 0 21 9 100 12 9 0 8
5
0 3 20
2 5 100
8 9 9
5 5 10
0 9 20
Sample Output2
1
0
1
90
1

Submitted solutions:

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

enum {
    NOTFOUND = 1000000000000000000LL
};

class SuccinctBitVector {
private:
    const uint64_t size;    // ビットベクトルのサイズ
    static const uint64_t blockBitNum = 16;
    static const uint64_t LEVEL_L = 512;
    static const uint64_t LEVEL_S = 16;

    vector<uint64_t> L;   // 大ブロック
    vector<uint16_t> S;   // 小ブロック
    vector<uint16_t> B;   // ビットベクトル

    uint64_t numOne = 0;       // 1bitの数

public:
    explicit SuccinctBitVector(const uint64_t n) : size(n) {
        const uint64_t s = (n + blockBitNum - 1) / blockBitNum + 1;   // ceil(n, blockSize)
        this->B.assign(s, 0);
        this->L.assign(n / LEVEL_L + 1, 0);
        this->S.assign(n / LEVEL_S + 1, 0);
    }

    // B[pos] = bit
    void setBit(const uint64_t bit, const uint64_t pos){
        assert(bit == 0 or bit == 1);
        assert(pos < this->size);

        const uint64_t blockPos = pos / blockBitNum;
        const uint64_t offset = pos % blockBitNum;
        if (bit == 1) { B.at(blockPos) |= (1LLU << offset); }
        else          { B.at(blockPos) &= (~(1LLU << offset)); }
    }

    // B[pos]
    uint64_t access(const uint64_t pos) {
        assert(pos < this->size);
        const uint64_t blockPos = pos / blockBitNum;
        const uint64_t offset   = pos % blockBitNum;
        return ((B.at(blockPos) >> offset) & 1);
    }

    void build() {
        uint64_t num = 0;
        for (uint64_t i = 0; i <= size; i++){
            if (i % LEVEL_L == 0) {
                L.at(i / LEVEL_L) = num;
            }
            if (i % LEVEL_S == 0) {
                S.at(i / LEVEL_S) = num - L.at(i / LEVEL_L);
            }
            if (i != size and i % blockBitNum == 0) {
                num += this->popCount(this->B.at(i / blockBitNum));
            }
        }
        this-> numOne = num;
    }

    // B[0, pos)のbitの数
    uint64_t rank(const uint64_t bit, const uint64_t pos) {
        assert(bit == 0 or bit == 1);
        assert(pos <= this->size);

        if (bit) {
            return L[pos / LEVEL_L] + S[pos / LEVEL_S] + popCount(B[pos / blockBitNum] & ((1 << (pos % blockBitNum)) - 1));
        }
        else {
            return pos - rank(1, pos);
        }
    }

    // rank番目のbitの位置 + 1(rankは1-origin)
    uint64_t select(const uint64_t bit, const uint64_t rank) {
        assert(bit == 0 or bit == 1);
        assert(rank > 0);
        if (bit == 0 and rank > this->size - this-> numOne) { return NOTFOUND; }
        if (bit == 1 and rank > this-> numOne)              { return NOTFOUND; }

        // 大ブロックL内を検索
        uint64_t large_idx = 0;
        {
            uint64_t left = 0;
            uint64_t right = L.size();
            while (right - left > 1) {
                uint64_t mid = (left + right) / 2;
                uint64_t r = L.at(mid);
                r = (bit) ? r : mid * LEVEL_L - L.at(mid);

                if (r < rank) {
                    left = mid;
                    large_idx = mid;
                } else {
                    right = mid;
                }
            }
        }

        // 小ブロックS内を検索
        uint64_t small_idx = (large_idx * LEVEL_L) / LEVEL_S;
        {
            uint64_t left = (large_idx * LEVEL_L) / LEVEL_S;
            uint64_t right = min(((large_idx  + 1) * LEVEL_L) / LEVEL_S, (uint64_t)S.size());
            while (right - left > 1) {
                uint64_t mid = (left + right) / 2;
                uint64_t r = L.at(large_idx) + S.at(mid);
                r = (bit) ? r :mid * LEVEL_S - r;

                if (r < rank) {
                    left = mid;
                    small_idx = mid;
                } else {
                    right = mid;
                }
            }
        }

        // Bをブロック単位で順番に探索
        uint64_t rank_pos = 0;
        {
            const uint64_t begin_block_idx = (small_idx * LEVEL_S) / blockBitNum;
            uint64_t total_bit = L.at(large_idx) + S.at(small_idx);
            if (bit == 0) {
                total_bit = small_idx * LEVEL_S - total_bit;
            }
            for (uint64_t i = 0;; ++i) {
                uint64_t b = popCount(B.at(begin_block_idx + i));
                if (bit == 0) {
                    b = blockBitNum - b;
                }
                if (total_bit + b >= rank) {
                    uint64_t block = (bit) ? B.at(begin_block_idx + i) : ~B.at(begin_block_idx + i);
                    rank_pos = (begin_block_idx + i) * blockBitNum + selectInBlock(block, rank - total_bit);
                    break;
                }
                total_bit += b;
            }
        }

        return rank_pos + 1;
    }

    uint64_t getNumOne() const {
        return numOne;
    }

    void debug() {
        cout << "LEVEL_L(" << L.size() << ")" << endl;
        for (uint64_t i = 0 ; i < L.size(); ++i) {
            cout << L.at(i) << ", ";
        }
        cout << endl;
        cout << "LEVEL_S(" << S.size() << ")" << endl;
        for (uint64_t i = 0 ; i < S.size(); ++i) {
            cout << S.at(i) << ", ";
        }
        cout << endl;
    }

private:
    uint64_t popCount(uint64_t x) {
        x = (x & 0x5555555555555555ULL) + ((x >> 1) & 0x5555555555555555ULL);
        x = (x & 0x3333333333333333ULL) + ((x >> 2) & 0x3333333333333333ULL);
        x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0fULL;
        x = x + (x >>  8);
        x = x + (x >> 16);
        x = x + (x >> 32);
        return x & 0x7FLLU;
    }

    uint64_t selectInBlock(uint64_t x, uint64_t rank) {
        uint64_t x1 = x - ((x & 0xAAAAAAAAAAAAAAAALLU) >> 1);
        uint64_t x2 = (x1 & 0x3333333333333333LLU) + ((x1 >> 2) & 0x3333333333333333LLU);
        uint64_t x3 = (x2 + (x2 >> 4)) & 0x0F0F0F0F0F0F0F0FLLU;

        uint64_t pos = 0;
        for (;;  pos += 8){
            uint64_t rank_next = (x3 >> pos) & 0xFFLLU;
            if (rank <= rank_next) break;
            rank -= rank_next;
        }

        uint64_t v2 = (x2 >> pos) & 0xFLLU;
        if (rank > v2) {
            rank -= v2;
            pos += 4;
        }

        uint64_t v1 = (x1 >> pos) & 0x3LLU;
        if (rank > v1){
            rank -= v1;
            pos += 2;
        }

        uint64_t v0  = (x >> pos) & 0x1LLU;
        if (v0 < rank){
            rank -= v0;
            pos += 1;
        }

        return pos;
    }
};

class WaveletMatrix {
private:
    vector<SuccinctBitVector> bit_arrays;
    vector<uint64_t> begin_one;                    // 各bitに着目したときの1の開始位置
    map<uint64_t, uint64_t> begin_alphabet;        // 最後のソートされた配列で各文字の開始位置
    vector<vector<uint64_t>> cumulative_sum;  // 各bitに着目したときの累積和

    uint64_t size;                                 // 与えられた配列のサイズ
    uint64_t maximum_element;                      // 文字数
    uint64_t bit_size;                             // 文字を表すのに必要なbit数

public:
    WaveletMatrix (const vector<uint64_t> &array) {
        assert(array.size() > 0);
        size = array.size();
        maximum_element =  *max_element(array.begin(), array.end()) + 1;
        bit_size = get_num_of_bit(maximum_element);
        if (bit_size == 0) {
            bit_size = 1;
        }

        for (uint64_t i = 0; i < bit_size; ++i) {
            SuccinctBitVector sv(size);
            bit_arrays.push_back(sv);
        }
        this->begin_one.resize(bit_size);
        this->cumulative_sum.resize(bit_size + 1, vector<uint64_t>(size + 1, 0));

        for (uint64_t j = 0; j < array.size(); ++j) {
            this->cumulative_sum.at(0).at(j + 1) = this->cumulative_sum.at(0).at(j) + array[j];
        }

        vector<uint64_t> v(array);
        for (uint64_t i = 0; i < bit_size; ++i) {

            vector<uint64_t> temp;
            // 0をtempにいれてく
            for (uint64_t j = 0; j < v.size(); ++j) {
                uint64_t c = v.at(j);
                uint64_t bit = (c >> (bit_size - i - 1)) & 1;  //　上からi番目のbit
                if (bit == 0) {
                    temp.push_back(c);
                    bit_arrays.at(i).setBit(0, j);
                }
            }

            this->begin_one.at(i) = temp.size();

            // 1をtempにいれてく
            for (uint64_t j = 0; j < v.size(); ++j) {
                uint64_t c = v.at(j);
                uint64_t bit = (c >> (bit_size - i - 1)) & 1;  //　上からi番目のbit
                if (bit == 1) {
                    temp.push_back(c);
                    bit_arrays.at(i).setBit(1, j);
                }
            }

            for (uint64_t j = 0; j < temp.size(); ++j) {
                this->cumulative_sum.at(i + 1).at(j + 1) = this->cumulative_sum.at(i + 1).at(j) + temp.at(j);
            }

            bit_arrays.at(i).build();
            v = temp;
        }

        // ソートされた配列内での各文字の位置を取得
        for (int i = v.size() - 1; i >= 0; --i) {
            this->begin_alphabet[v.at(i)] = i;
        }
    }

    // v[pos]
    uint64_t access(uint64_t pos) {
        if (pos >= this->size) { return NOTFOUND; }

        uint64_t c = 0;
        for (uint64_t i = 0; i < bit_arrays.size(); ++i) {
            uint64_t bit = bit_arrays.at(i).access(pos);   // もとの数値のi番目のbit
            c = (c <<= 1) | bit;
            pos = bit_arrays.at(i).rank(bit, pos);
            if (bit) {
                pos += this->begin_one.at(i);
            }
        }
        return c;
    }

    // i番目のcの位置 + 1を返す。rankは1-origin
    uint64_t select(uint64_t c, uint64_t rank) {
        assert(rank > 0);
        if (c >= maximum_element) {
            return NOTFOUND;
        }
        if (this->begin_alphabet.find(c) == this->begin_alphabet.end()) {
            return NOTFOUND;
        }

        uint64_t index = this->begin_alphabet.at(c) + rank;
        for (uint64_t i = 0; i < bit_arrays.size(); ++i){
            uint64_t bit = ((c >> i) & 1);      // 下からi番目のbit
            if (bit == 1) {
                index -= this->begin_one.at(bit_size - i - 1);
            }
            index = this->bit_arrays.at(bit_size - i - 1).select(bit, index);
        }
        return index;
    }

    // v[begin_pos, end_pos)で最大値のindexを返す
    uint64_t maxRange(uint64_t begin_pos, uint64_t end_pos) {
        return quantileRange(begin_pos, end_pos, end_pos - begin_pos - 1);
    }

    // v[begin_pos, end_pos)で最小値のindexを返す
    uint64_t minRange(uint64_t begin_pos, uint64_t end_pos) {
        return quantileRange(begin_pos, end_pos, 0);
    }

    // v[begin_pos, end_pos)でk番目に小さい数値のindexを返す(kは0-origin)
    // つまり小さい順に並べてk番目の値
    uint64_t quantileRange(uint64_t begin_pos, uint64_t end_pos, uint64_t k) {
        if ((end_pos > size || begin_pos >= end_pos) || (k >= end_pos - begin_pos)) {
            return NOTFOUND;
        }

        uint64_t val = 0;
        for (uint64_t i = 0; i < bit_size; ++i) {
            const uint64_t num_of_zero_begin = bit_arrays.at(i).rank(0, begin_pos);
            const uint64_t num_of_zero_end = bit_arrays.at(i).rank(0, end_pos);
            const uint64_t num_of_zero = num_of_zero_end - num_of_zero_begin;     // beginからendまでにある0の数
            const uint64_t bit = (k < num_of_zero) ? 0 : 1;                       // k番目の値の上からi番目のbitが0か1か

            if (bit) {
                k -= num_of_zero;
                begin_pos = this->begin_one.at(i) + begin_pos - num_of_zero_begin;
                end_pos = this->begin_one.at(i) + end_pos - num_of_zero_end;
            }
            else {
                begin_pos = num_of_zero_begin;
                end_pos = num_of_zero_begin + num_of_zero;
            }

            val = ((val << 1) | bit);
        }

        uint64_t left = 0;
        for (uint64_t i = 0; i < bit_size; ++i) {
            const uint64_t bit = (val >> (bit_size - i - 1)) & 1;  // 上からi番目のbit
            left = bit_arrays.at(i).rank(bit, left);               // cのi番目のbitと同じ数値の数
            if (bit) {
                left += this->begin_one.at(i);
            }
        }

        const uint64_t rank = begin_pos + k - left + 1;
        return select(val, rank) - 1;
    }

    // v[0, pos)のcの数
    uint64_t rank(uint64_t c, uint64_t pos) {
        assert(pos < size);
        if (c >= maximum_element) {
            return 0;
        }
        if (this->begin_alphabet.find(c) == this->begin_alphabet.end()) {
            return 0;
        }

        for (uint64_t i = 0; i < bit_size; ++i) {
            uint64_t bit = (c >> (bit_size - i - 1)) & 1;  // 上からi番目のbit
            pos = bit_arrays.at(i).rank(bit, pos);         // cのi番目のbitと同じ数値の数
            if (bit) {
                pos += this->begin_one.at(i);
            }
        }

        uint64_t begin_pos = this->begin_alphabet.at(c);
        return pos - begin_pos;
    }

    // v[begin_pos, end_pos)で[min, max)に入る値の個数
    uint64_t rangeFreq(uint64_t begin_pos, uint64_t end_pos, uint64_t min_c, uint64_t max_c) {
        if ((end_pos > size || begin_pos >= end_pos) || (min_c >= max_c) || min_c >= maximum_element) {
            return 0;
        }

        const auto maxi_t = rankAll(max_c, begin_pos, end_pos);
        const auto mini_t = rankAll(min_c, begin_pos, end_pos);
        return get<1>(maxi_t) - get<1>(mini_t);
    }

    // v[0, pos)でcより小さい文字の数
    uint64_t rankLessThan(uint64_t c, uint64_t begin, uint64_t end) {
        auto t = rankAll(c, begin, end);
        return get<1>(t);
    }

    // v[0, pos)でcより大きい文字の数
    uint64_t rankMoreThan(uint64_t c, uint64_t begin, uint64_t end) {
        auto t = rankAll(c, begin, end);
        return get<2>(t);
    }

    // v[begin, end)で(cと同じ値の数、cより小さい値の数、cより大きい値の数)を求める
    tuple<uint64_t, uint64_t, uint64_t> rankAll(const uint64_t c, uint64_t begin, uint64_t end) {
        assert(end <= size);
        const uint64_t num = end - begin;

        if (begin >= end) {
            return make_tuple(0, 0, 0);
        }
        if (c >= maximum_element || end == 0) {
            return make_tuple(0, num, 0);
        }

        uint64_t rank_less_than = 0, rank_more_than = 0;
        for (size_t i = 0; i < bit_size && begin < end; ++i) {
            const uint64_t bit = (c >> (bit_size - i - 1)) & 1;

            const uint64_t rank0_begin = this->bit_arrays.at(i).rank(0, begin);
            const uint64_t rank0_end = this->bit_arrays.at(i).rank(0, end);
            const uint64_t rank1_begin = begin - rank0_begin;
            const uint64_t rank1_end = end - rank0_end;

            if (bit) {
                rank_less_than += (rank0_end - rank0_begin);    // i番目のbitが0のものは除外される
                begin = this->begin_one.at(i) + rank1_begin;
                end = this->begin_one.at(i) + rank1_end;
            } else {
                rank_more_than += (rank1_end - rank1_begin);    // i番目のbitが1のものは除外される
                begin = rank0_begin;
                end = rank0_end;
            }
        }

        const uint64_t rank = num - rank_less_than - rank_more_than;
        return make_tuple(rank, rank_less_than, rank_more_than);
    }

    // T[s, e)で出現回数が多い順にk個の(値，頻度)を返す
    // 頻度が同じ場合は値が小さいものが優先される
    vector<pair<uint64_t, uint64_t>> topk(uint64_t s, uint64_t e, uint64_t k) {
        assert(s < e);
        vector<pair<uint64_t, uint64_t>> result;

        // (頻度，深さ，値)の順でソート
        auto c = [](const tuple<uint64_t, uint64_t, uint64_t, uint64_t, uint64_t> &l, const tuple<uint64_t, uint64_t, uint64_t, uint64_t, uint64_t> &r) {
            // width
            if (get<0>(l) != get<0>(r)) {
                return get<0>(l) < get<0>(r);
            }
            // depth
            if (get<3>(l) != get<3>(r)) {
                return get<3>(l) > get<3>(r);
            }
            // value
            if (get<4>(l) != get<4>(r)) {
                return get<4>(l) > get<4>(r);
            }
            return true;
        };

        priority_queue<tuple<uint64_t, uint64_t, uint64_t, uint64_t, uint64_t>, vector<tuple<uint64_t, uint64_t, uint64_t, uint64_t, uint64_t>>, decltype(c)> que(c);  // width, left, right, depth, value
        que.push(make_tuple(e - s, s, e, 0, 0));

        while (not que.empty()) {
            auto element = que.top(); que.pop();
            uint64_t width, left, right, depth, value;
            tie(width, left, right, depth, value) = element;

            if (depth >= this->bit_size) {
                result.emplace_back(make_pair(value, right - left));
                if (result.size() >= k) {
                    break;
                }
                continue;
            }

            // 0
            const uint64_t left0 = this->bit_arrays.at(depth).rank(0, left);
            const uint64_t right0 = this->bit_arrays.at(depth).rank(0, right);
            if (left0 < right0) {
                que.push(make_tuple(right0 - left0, left0, right0, depth + 1, value));
            }

            // 1
            const uint64_t left1 = this->begin_one.at(depth) + this->bit_arrays.at(depth).rank(1, left);
            const uint64_t right1 = this->begin_one.at(depth) + this->bit_arrays.at(depth).rank(1, right);
            if (left1 < right1) {
                que.push(make_tuple(right1 - left1, left1, right1, depth + 1, value | (1 << (bit_size - depth - 1))));
            }
        }

        return result;
    };

    // T[begin_pos, end_pos)でx <= c < yを満たすcの和を返す
    uint64_t rangeSum(const uint64_t begin, const uint64_t end, const uint64_t x, const uint64_t y) {
        return rangeSum(begin, end, 0, 0, x, y);
    }

    // T[begin_pos, end_pos)でx <= c < yを満たす最大のcを返す
    uint64_t prevValue(const uint64_t begin_pos, const uint64_t end_pos, const uint64_t x, uint64_t y) {
        assert(end_pos <= size);
        const uint64_t num = end_pos - begin_pos;

        if (x >= y or y == 0) {
            return NOTFOUND;
        }
        if (y > maximum_element) {
            y = maximum_element;
        }

        if (begin_pos >= end_pos) {
            return NOTFOUND;
        }
        if (x >= maximum_element || end_pos == 0) {
            return NOTFOUND;
        }

        y--; // x <= c <= yにする

        stack<tuple<uint64_t, uint64_t, uint64_t, uint64_t, bool>> s;   // (begin, end, depth, c, tight)
        s.emplace(make_tuple(begin_pos, end_pos, 0, 0, true));

        while (not s.empty()) {
            uint64_t b, e, depth, c;
            bool tight;
            tie(b, e, depth, c, tight) = s.top(); s.pop();

            if (depth == bit_size) {
                if (c >= x) {
                    return c;
                }
                continue;
            }

            const uint64_t bit = (y >> (bit_size - depth - 1)) & 1;

            const uint64_t rank0_begin = this->bit_arrays.at(depth).rank(0, b);
            const uint64_t rank0_end = this->bit_arrays.at(depth).rank(0, e);
            const uint64_t rank1_begin = b - rank0_begin;
            const uint64_t rank1_end = e - rank0_end;

            // d番目のbitが0のものを使う
            const uint64_t b0 = rank0_begin;
            const uint64_t e0 = rank0_end;
            if (b0 != e0) { // 範囲がつぶれてない
                const uint64_t c0 = ((c << 1) | 0);
                s.emplace(make_tuple(b0, e0, depth + 1, c0, tight and bit == 0));
            }

            // d番目のbitが1のものを使う
            const uint64_t b1 = this->begin_one.at(depth) + rank1_begin;
            const uint64_t e1 = this->begin_one.at(depth) + rank1_end;
            if (b1 != e1) {
                if (not tight or bit == 1) {
                    const auto c1 = ((c << 1) | 1);
                    s.emplace(make_tuple(b1, e1, depth + 1, c1, tight));
                }
            }
        }

        return NOTFOUND;
    }

    // T[begin_pos, end_pos)でx <= c < yを満たす最小のcを返す
    uint64_t nextValue(const uint64_t begin_pos, const uint64_t end_pos, const uint64_t x, const uint64_t y) {
        assert(end_pos <= size);
        const uint64_t num = end_pos - begin_pos;

        if (x >= y or y == 0) {
            return NOTFOUND;
        }

        if (begin_pos >= end_pos) {
            return NOTFOUND;
        }
        if (x >= maximum_element || end_pos == 0) {
            return NOTFOUND;
        }

        stack<tuple<uint64_t, uint64_t, uint64_t, uint64_t, bool>> s;   // (begin, end, depth, c, tight)
        s.emplace(make_tuple(begin_pos, end_pos, 0, 0, true));

        while (not s.empty()) {
            uint64_t b, e, depth, c;
            bool tight;
            tie(b, e, depth, c, tight) = s.top(); s.pop();

            if (depth == bit_size) {
                if (c < y) {
                    return c;
                }
                continue;
            }

            const uint64_t bit = (x >> (bit_size - depth - 1)) & 1;

            const uint64_t rank0_begin = this->bit_arrays.at(depth).rank(0, b);
            const uint64_t rank0_end = this->bit_arrays.at(depth).rank(0, e);
            const uint64_t rank1_begin = b - rank0_begin;
            const uint64_t rank1_end = e - rank0_end;

            // d番目のbitが1のものを使う
            const uint64_t b1 = this->begin_one.at(depth) + rank1_begin;
            const uint64_t e1 = this->begin_one.at(depth) + rank1_end;
            if (b1 != e1) {
                const auto c1 = ((c << 1) | 1);
                s.emplace(make_tuple(b1, e1, depth + 1, c1, tight and bit == 1));
            }

            // d番目のbitが0のものを使う
            const uint64_t b0 = rank0_begin;
            const uint64_t e0 = rank0_end;
            if (b0 != e0) {
                if (not tight or bit == 0) {
                    const uint64_t c0 = ((c << 1) | 0);
                    s.emplace(make_tuple(b0, e0, depth + 1, c0, tight));
                }
            }
        }

        return NOTFOUND;
    }

    // T[s1, e1)とT[s2, e2)に共通して出現する要素を求める
    vector<tuple<uint64_t, uint64_t, uint64_t>> intersect(uint64_t _s1, uint64_t _e1, uint64_t _s2, uint64_t _e2) {
        assert(_s1 < _e1);
        assert(_s2 < _e2);

        vector<tuple<uint64_t, uint64_t, uint64_t>> intersection;

        queue<tuple<uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t>> que; // s1, e1, s2, e2, depth, value
        que.push(make_tuple(_s1, _e1, _s2, _e2, 0, 0));
        while (not que.empty()) {
            auto e = que.front(); que.pop();
            uint64_t s1, e1, s2, e2, depth, value;
            tie(s1, e1, s2, e2, depth, value) = e;

            if (depth >= this->bit_size) {
                intersection.emplace_back(make_tuple(value, e1 - s1, e2 - s2));
                continue;
            }

            // 0
            uint64_t s1_0 = this->bit_arrays.at(depth).rank(0, s1);
            uint64_t e1_0 = this->bit_arrays.at(depth).rank(0, e1);
            uint64_t s2_0 = this->bit_arrays.at(depth).rank(0, s2);
            uint64_t e2_0 = this->bit_arrays.at(depth).rank(0, e2);

            if (s1_0 != e1_0 and s2_0 != e2_0) {
                que.push(make_tuple(s1_0, e1_0, s2_0, e2_0, depth + 1, value));
            }

            // 1
            uint64_t s1_1 = this->begin_one.at(depth) + this->bit_arrays.at(depth).rank(1, s1);
            uint64_t e1_1 = this->begin_one.at(depth) + this->bit_arrays.at(depth).rank(1, e1);
            uint64_t s2_1 = this->begin_one.at(depth) + this->bit_arrays.at(depth).rank(1, s2);
            uint64_t e2_1 = this->begin_one.at(depth) + this->bit_arrays.at(depth).rank(1, e2);

            if (s1_1 != e1_1 and s2_1 != e2_1) {
                que.push(make_tuple(s1_1, e1_1, s2_1, e2_1, depth + 1, value | (1 << bit_size - depth - 1)));
            }
        }

        return intersection;
    };

private:
    uint64_t get_num_of_bit(uint64_t x) {
        if (x == 0) return 0;
        x--;
        uint64_t bit_num = 0;
        while (x >> bit_num) {
            ++bit_num;
        }
        return bit_num;
    }

    uint64_t rangeSum(const uint64_t begin, const uint64_t end, const uint64_t depth, const uint64_t c, const uint64_t x, const uint64_t y) {
        if (begin == end) {
            return 0;
        }

        if (depth == bit_size) {
            if (x <= c and c < y) {
                return c * (end - begin);   // 値 * 頻度
            }
            return 0;
        }

        const uint64_t next_c = ((uint64_t)1 << (bit_size - depth - 1)) | c;                   // 上からdepth番目のbitを立てる
        const uint64_t all_one_c = (((uint64_t)1 << (bit_size - depth - 1)) - 1) | next_c;     // depth以降のbitをたてる(これ以降全部1を選んだときの値)
        if(all_one_c < x or y <= c) {
            return 0;
        }

        // [begin, pos)のすべての要素は[x, y)
        if (x <= c and all_one_c < y) {
            return this->cumulative_sum.at(depth).at(end) - this->cumulative_sum.at(depth).at(begin);
        }

        const uint64_t rank0_begin = this->bit_arrays.at(depth).rank(0, begin);
        const uint64_t rank0_end = this->bit_arrays.at(depth).rank(0, end);
        const uint64_t rank1_begin = begin - rank0_begin;
        const uint64_t rank1_end = end - rank0_end;

        return rangeSum(rank0_begin, rank0_end, depth + 1, c, x, y) +
               rangeSum(this->begin_one.at(depth) + rank1_begin, this->begin_one[depth] + rank1_end, depth + 1, next_c, x, y);
    }
};

int main(){
	int n; cin>>n;
	vector<uint64_t> v(n); for(auto &x:v)cin>>x;
	WaveletMatrix wv(v);
	int q; cin>>q; while(q--){
		int l,r;uint64_t k; cin>>l>>r>>k;
		auto x=wv.prevValue(l,r+1,0,k+1);
		auto y=wv.nextValue(l,r+1,k,1000000000000000000LL);
		// cout<<x<<' '<<y<<' '<<k<<endl;
		cout<<min(llabs(k-x),llabs(y-k))<<endl;
	}
}
accuracy: 1
time_ms: 290
memory_kb: 27480
final_rank: 20

code_snippet: #include <bits/stdc++.h>

#pragma GCC optimize("O2")

using namespace std;

#ifdef LOCAL
#    include "local/debug.h"
#else
#    define debug(...) (static_cast<void>(0))
#endif

constexpr long long mods[2] = {998244353, 1000000007};

template <typename T>
struct WaveletMatrix {

    explicit WaveletMatrix(const vector<T> &data) : WaveletMatrix(data, 0, *max_element(data.begin(), data.end())) {}
    explicit WaveletMatrix(const vector<T> &data, T lower, T upper) {
        offset = -1 + lower;
        maxlog = 1 + (int) log2(shift(upper));
        build(data);
    }

    inline T operator[] (const int k) {
        return access(k);
    }

    // count occurrences of value c in [0, pos)
    int rank(T c, int pos) const {

        int l = 0;
        int r = pos;

        T cc = shift(c);

        for (int level = maxlog - 1; level >= 0; --level) {

            if (((cc >> level) & 1)) {
                l = mid[level] + (l - zeros[level][l]);
                r = mid[level] + (r - zeros[level][r]);
            } else {
                l = zeros[level][l];
                r = zeros[level][r];
            }
        }

        return r - l;
    }

    // largest element < x in [l, r)
    T upper_bound(int l, int r, T x) {

        int cnt = frequency_less_than(r, x) - frequency_less_than(l, x);

        if (cnt == 0) {
            return numeric_limits<T>::min();
        }

        return kth(l, r, cnt - 1);
    }

    // x <= smallest element in [l, r)
    T lower_bound(int l, int r, T x) {

        int cnt = frequency_less_than(r, x) - frequency_less_than(l, x);

        if (r - l <= cnt) {
            return numeric_limits<T>::max();
        }

        return kth(l, r, cnt);
    }

    // [l, r)
    inline T range_min(int l, int r) {
        return kth(l, r, 0);
    }

    // [l, r)
    inline T range_max(int l, int r) {
        return kth(l, r, r - l - 1);
    }

    // [l, r)
    inline T kth_min(int l, int r, int k) {
        return kth(l, r, k);
    }

    // lower <= x < upper
    inline int range_frequency(int l, int r, T lower, T upper) {
        return frequency_less_than(r, upper) - frequency_less_than(l, upper) - (frequency_less_than(r, lower) - frequency_less_than(l, lower));
    }

private:
    int n;
    int maxlog;
    T offset;
    vector<vector<bool>> mat;
    vector<vector<int>> zeros;
    vector<int> mid;

    inline T adjust(T x) {
        return x + offset;
    }

    inline T shift(T x) {
        return x - offset;
    }

    void build(const vector<T> &data) {

        n = data.size();
        mat.assign(maxlog, vector<bool>(n));
        zeros.assign(maxlog, vector<int>(n + 1, 0));
        mid.assign(maxlog, 0);

        vector<T> cur(n);
        vector<T> next(n);
        for (int i = 0; i < n; i++) {
            cur[i] = shift(data[i]);
        }

        for (int level = maxlog - 1; -1 < level; --level) {

            // build bitvector and zero prefix sums
            for (int i = 0; i < n; ++i) {
                bool b = (cur[i] >> level) & 1;
                mat[level][i] = b;
                zeros[level][i + 1] = zeros[level][i] + (b == 0);
            }

            mid[level] = zeros[level][n];

            // reorder
            int p0 = 0;
            int p1 = mid[level];

            for (int i = 0; i < n; ++i) {

                if (!mat[level][i]) {
                    next[p0++] = cur[i];
                } else {
                    next[p1++] = cur[i];
                }
            }

            cur.swap(next);
        }

    }

    T access(int pos) {

        T x = 0;

        for (int level = maxlog - 1; -1 < level; --level) {

            if (mat[level][pos]) {
                pos = mid[level] + (pos - zeros[level][pos]);
                x |= (1LL << level);
            } else {
                pos = zeros[level][pos];
            }
        }

        return adjust(x);
    }

    // [l, r)
    T kth(int l, int r, int k) {

        T x = 0;

        for (int level = maxlog - 1; -1 < level; --level) {

            int cnt0 = zeros[level][r] - zeros[level][l];

            if (k < cnt0) {
                l = zeros[level][l];
                r = zeros[level][r];
            } else {
                x |= (1LL << level);
                k -= cnt0;
                l = mid[level] + (l - zeros[level][l]);
                r = mid[level] + (r - zeros[level][r]);
            }
        }

        return adjust(x);
    }

    // [0, pos)
    int frequency_less_than(int pos, T c) {

        assert(0 <= pos);

        int l = 0;
        int r = pos;
        int cnt = 0;

        T cc = shift(c);

        for (int level = maxlog - 1; -1 < level; --level) {

            if (((cc >> level) & 1)) {
                cnt += zeros[level][r] - zeros[level][l];
                l = mid[level] + (l - zeros[level][l]);
                r = mid[level] + (r - zeros[level][r]);
            } else {
                l = zeros[level][l];
                r = zeros[level][r];
            }
        }

        return cnt;
    }

};

void solve() {

    int n;
    cin >> n;
    vector<int> a(n);

    for (auto &v : a) {
        cin >> v;
    }

    int v = 1e6;
    WaveletMatrix<int> wm{a, -1 * v, v};
    int q;
    cin >> q;

    while (q--) {
        int l, r, d;
        cin >> l >> r >> d;
        ++r;

        int ans = 1 << 30;
        int left = wm.upper_bound(l, r, d);
        int right = wm.lower_bound(l, r, d);
        debug(left, right);

        if (left != numeric_limits<int>::min()) {
            ans = min(ans, d - left);
        }

        if (right != numeric_limits<int>::max()) {
            ans = min(ans, right - d);
        }

        cout << ans << '\n';
    }
}

int main() {

    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    int t;
    t = 1;
    // cin >> t;

    while (t--) {
        solve();
    }

    return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 13092
final_rank: 8

code_snippet: #include <bits/stdc++.h>

#pragma GCC optimize("O2")

using namespace std;

#ifdef LOCAL
#    include "local/debug.h"
#else
#    define debug(...) (static_cast<void>(0))
#endif

constexpr long long mods[2] = {998244353, 1000000007};

template <typename T>
struct WaveletMatrix {

    explicit WaveletMatrix(const vector<T> &data) : WaveletMatrix(data, 0) {}
    explicit WaveletMatrix(const vector<T> &data, T _offset) {
        offset = -1 + _offset;
        build(data);
    }

    inline T operator[] (const int k) {
        return access(k);
    }

    // count occurrences of value c in [0, pos)
    int rank(T c, int pos) const {

        int l = 0;
        int r = pos;

        T cc = shift(c);

        for (int level = maxlog - 1; level >= 0; --level) {

            if (((cc >> level) & 1)) {
                l = mid[level] + (l - zeros[level][l]);
                r = mid[level] + (r - zeros[level][r]);
            } else {
                l = zeros[level][l];
                r = zeros[level][r];
            }
        }

        return r - l;
    }

    // largest element < x in [l, r)
    T upper_bound(int l, int r, T x) {

        int cnt = frequency_less_than(r, x) - frequency_less_than(l, x);

        if (cnt == 0) {
            return numeric_limits<T>::min();
        }

        return kth(l, r, cnt - 1);
    }

    // x <= smallest element in [l, r)
    T lower_bound(int l, int r, T x) {

        int cnt = frequency_less_than(r, x) - frequency_less_than(l, x);

        if (r - l <= cnt) {
            return numeric_limits<T>::max();
        }

        return kth(l, r, cnt);
    }

    // [l, r)
    inline T range_min(int l, int r) {
        return kth(l, r, 0);
    }

    // [l, r)
    inline T range_max(int l, int r) {
        return kth(l, r, r - l - 1);
    }

    // [l, r)
    inline T kth_min(int l, int r, int k) {
        return kth(l, r, k);
    }

    // lower <= x < upper
    inline int range_frequency(int l, int r, T lower, T upper) {
        return frequency_less_than(r, upper) - frequency_less_than(l, upper) - (frequency_less_than(r, lower) - frequency_less_than(l, lower));
    }

private:
    int n;
    int maxlog;
    T offset;
    vector<vector<bool>> mat;
    vector<vector<int>> zeros;
    vector<int> mid;

    inline T adjust(T x) {
        return x + offset;
    }

    inline T shift(T x) {
        return x - offset;
    }

    void build(const vector<T> &data) {

        n = data.size();
        T max_v = *max_element(data.begin(), data.end());

        maxlog = 1 + (int) log2(shift(max_v));

        mat.assign(maxlog, vector<bool>(n));
        zeros.assign(maxlog, vector<int>(n + 1, 0));
        mid.assign(maxlog, 0);

        vector<T> cur(n);
        vector<T> next(n);
        for (int i = 0; i < n; i++) {
            cur[i] = shift(data[i]);
        }

        for (int level = maxlog - 1; -1 < level; --level) {

            // build bitvector and zero prefix sums
            for (int i = 0; i < n; ++i) {
                bool b = (cur[i] >> level) & 1;
                mat[level][i] = b;
                zeros[level][i + 1] = zeros[level][i] + (b == 0);
            }

            mid[level] = zeros[level][n];

            // reorder
            int p0 = 0;
            int p1 = mid[level];

            for (int i = 0; i < n; ++i) {

                if (!mat[level][i]) {
                    next[p0++] = cur[i];
                } else {
                    next[p1++] = cur[i];
                }
            }

            cur.swap(next);
        }

    }

    T access(int pos) {

        T x = 0;

        for (int level = maxlog - 1; -1 < level; --level) {

            if (mat[level][pos]) {
                pos = mid[level] + (pos - zeros[level][pos]);
                x |= (1LL << level);
            } else {
                pos = zeros[level][pos];
            }
        }

        return adjust(x);
    }

    // [l, r)
    T kth(int l, int r, int k) {

        T x = 0;

        for (int level = maxlog - 1; -1 < level; --level) {

            int cnt0 = zeros[level][r] - zeros[level][l];

            if (k < cnt0) {
                l = zeros[level][l];
                r = zeros[level][r];
            } else {
                x |= (1LL << level);
                k -= cnt0;
                l = mid[level] + (l - zeros[level][l]);
                r = mid[level] + (r - zeros[level][r]);
            }
        }

        return adjust(x);
    }

    // [0, pos)
    int frequency_less_than(int pos, T c) {

        assert(0 <= pos);

        int l = 0;
        int r = pos;
        int cnt = 0;

        T cc = shift(c);

        for (int level = maxlog - 1; -1 < level; --level) {

            if (((cc >> level) & 1)) {
                cnt += zeros[level][r] - zeros[level][l];
                l = mid[level] + (l - zeros[level][l]);
                r = mid[level] + (r - zeros[level][r]);
            } else {
                l = zeros[level][l];
                r = zeros[level][r];
            }
        }

        return cnt;
    }

};

void solve() {

    int n;
    cin >> n;
    vector<int> a(n);

    for (auto &v : a) {
        cin >> v;
    }

    int v = 1e6;
    a.push_back(v + 1);
    WaveletMatrix<int> wm{a, -1 * (int) (1e6)};
    int q;
    cin >> q;

    while (q--) {
        int l, r, d;
        cin >> l >> r >> d;
        ++r;

        int ans = 1 << 30;
        int left = wm.upper_bound(l, r, d);
        int right = wm.lower_bound(l, r, d);
        debug(left, right);

        if (left != numeric_limits<int>::min()) {
            ans = min(ans, d - left);
        }

        if (right != numeric_limits<int>::max()) {
            ans = min(ans, right - d);
        }

        cout << ans << '\n';
    }
}

int main() {

    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    int t;
    t = 1;
    // cin >> t;

    while (t--) {
        solve();
    }

    return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 13164
final_rank: 9

code_snippet: #ifdef t9unkubj
#include"my_template.h"
//#include"my_template_no_debug.h"
#else
#define dbg(...) 199958
#pragma GCC optimize("O3")
#include"bits/stdc++.h"
using namespace std;
using uint=unsigned;
using ll=long long;
using ull=unsigned long long;
using ld=long double;
using i128=__int128;
template<class T>using vc=vector<T>;
template<class T>using vvc=vc<vc<T>>;
template<class T>using vvvc=vc<vvc<T>>;
template<class T>using vvvvc=vc<vvvc<T>>;
template<class T>using smpq=priority_queue<T,vc<T>,greater<T>>;
template<class T>using bipq=priority_queue<T>;
using vi=vc<int>;
using vvi=vvc<int>;
using vl=vc<ll>;
using vvl=vvc<ll>;
#define rep(i,n) for(ll i=0;i<(ll)(n);i++)
#define REP(i,j,n) for(ll i=(j);i<(ll)(n);i++)
#define DREP(i,n,m) for(ll i=(n);i>=(m);i--)
#define drep(i,n) for(ll i=(ll(n)-1);i>=0;i--)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define pb push_back
template<class T,class F>
bool chmin(T &x, F y){
    if(x>y){
        x=y;
        return true;
    }
    return false;
}
template<class T, class F>
bool chmax(T &x, F y){
    if(x<y){
        x=y;
        return true;
    }
    return false;
}
template<class T>
T sum(const vector<T>&v){
    return accumulate(all(v),T(0));
}
template<class T>
T min(const vector<T>&v){
    return *min_element(all(v));
}
template<class T>
T max(const vector<T>&v){
    return *max_element(all(v));
}
void YesNo(bool y){
    cout<<(y?"Yes":"No")<<endl;
}
void Yes(){
    cout<<"Yes"<<endl;
}
void No(){
    cout<<"No"<<endl;
}
template<class T>
void unique(vc<T>&a){
    a.erase(unique(all(a)),a.end());
}
vvi readgraph(int n,int m,int off = -1){
    vvi g(n);
    rep(i, m){
        int u,v;
        cin>>u>>v;
        u+=off,v+=off;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    return g;
}
vvi readtree(int n,int off=-1){
    return readgraph(n,n-1,off);
}
template<class T>
vc<T> presum(vc<T> &a){
    vc<T> ret(a.size()+1);
    rep(i,a.size())ret[i+1]=ret[i]+a[i];
    return ret;
}
template<class T, class F>
vc<T> &operator+=(vc<T> &a,F b){
    for (auto&v:a)v += b;
    return a;
}
template<class T, class F>
vc<T> &operator-=(vc<T>&a,F b){
    for (auto&v:a)v-=b;
    return a;
}
ostream&operator<<(ostream&os,i128 num) {
    if(num==0){
        os<<"0";
        return os;
    }
    if(num<0){
        os<<"-";
        num=-num;
    }
    string res;
    while(num){
        res+='0'+static_cast<int>(num%10);
        num/=10;
    }
    reverse(all(res));
    os<<res;
    return os;
}

istream&operator>>(istream& is,i128&num) {
    string s;
    is>>s;
    bool neg=0;
    num=0;
    if(s[0]=='-'){
        neg=1;
        s=s.substr(1);
    }
    for(auto&c:s){
        if (c>='0'&&c<='9'){
            num=num*10+(c-'0');
        }else{
            is.setstate(ios::failbit);
            return is;
        }
    }
    if(neg){
        num=-num;
    }
    return is;
}

void scan(int&a) { cin >> a; }
void scan(ll&a) { cin >> a; }
void scan(string&a) { cin >> a; }
void scan(char&a) { cin >> a; }
void scan(uint&a) { cin >> a; }
void scan(ull&a) { cin >> a; }
void scan(bool&a) { cin >> a; }
void scan(ld&a){ cin>> a; }
void scan(i128&a){ cin>> a; }
template<class T> void scan(vector<T>&a) { for(auto&x:a) scan(x); }
void read() {}
template<class Head, class... Tail> void read(Head&head, Tail&... tail) { scan(head); read(tail...); }
#define INT(...) int __VA_ARGS__; read(__VA_ARGS__);
#define LL(...) ll __VA_ARGS__; read(__VA_ARGS__);
#define ULL(...) ull __VA_ARGS__; read(__VA_ARGS__);
#define STR(...) string __VA_ARGS__; read(__VA_ARGS__);
#define CHR(...) char __VA_ARGS__; read(__VA_ARGS__);
#define DBL(...) double __VA_ARGS__; read(__VA_ARGS__);
#define LD(...) ld __VA_ARGS__; read(__VA_ARGS__);
#define I128(...) i128 __VA_ARGS__; read(__VA_ARGS__);
#define VC(type, name, ...) vector<type> name(__VA_ARGS__); read(name);
#define VVC(type, name, size, ...) vector<vector<type>> name(size, vector<type>(__VA_ARGS__)); read(name);

void print(int a) { cout << a; }
void print(ll a) { cout << a; }
void print(string a) { cout << a; }
void print(char a) { cout << a; }
void print(uint a) { cout << a; }
void print(bool a) { cout << a; }
void print(ull a) { cout << a; }
void print(double a) { cout << a; }
void print(ld a){ cout<< a; }
void print(i128 a){ cout<< a; }
template<class T> void print(vector<T>a) { for(int i=0;i<(int)a.size();i++){if(i)cout<<" ";print(a[i]);}cout<<endl;}
void PRT() { cout <<endl; return ; }
template<class T> void PRT(T a) { print(a); cout <<endl; return; }
template<class Head, class... Tail> void PRT(Head head, Tail ... tail) { print(head); cout << " "; PRT(tail...); return; }
struct ioset{
    ioset(){
        cin.tie(0)->sync_with_stdio(0);
        #ifdef t9unkubj
        cout<<fixed<<setprecision(6);
        #else
        cout<<fixed<<setprecision(20);
        #endif
    }
}ioset_______;
struct MY_TIMER{
    double start_time;
    MY_TIMER(){
        start_time=clock();
    }
    double out(){
        return (clock()-start_time)/double(CLOCKS_PER_SEC);
    }
}TIMER;
#endif
#include<bits/stdc++.h>
using namespace std;
struct bit_vector{
    using i8=uint8_t;
    using i16=uint16_t;
    using i32=uint32_t;
    using i64=uint64_t;
    constexpr static int l=512,s=16;// l=1000 s=25程度
    std::vector<i32>L;//大ブロックのbitの数 n/l個 
    std::vector<i16>S;//小ブロックのbitの数 n/s個
    std::vector<i8>B;//ビットベクトル n個
    std::vector<i16>B2;//小ブロック地点からのbit n/s
    void build(const std::vector<int>&b){
        for(auto&x:b)assert(x<2);
        i32 N=b.size();
        B=std::vector<i8>(N);
        for(int i=0;i<N;i++){
            B[i]=b[i];
        }
        L.reserve(N/l);
        S.reserve(N/s);
        B2.reserve(N/s);
        /*i16 log_n{};
        while(1<<(log_n)<=N)log_n++;
        l=(i32)log_n*log_n;
        s=(log_n+1)/2;*/

        int cnt=0;
        int diff=0;
        int now_bit=0;
        for(int i=0;i<N;i++){
            if(i%l==0){
                L.emplace_back(cnt),diff=0;
            }
            if(i%s==0){
                S.emplace_back(diff);
            }
            cnt+=B[i];
            diff+=B[i];
        }
        for(int i=N-1;i>=0;i--){
            now_bit<<=1;
            now_bit|=B[i];
            if(i%s==0)B2.emplace_back(now_bit),now_bit=0;
        }
        reverse(B2.begin(),B2.end());
    }
    i32 rank1(int i){//0 indexed [0,i)のrank1を返す
        if(i<=0)return 0;
        i32 pos_l=(i+l-1)/l;//[1,n/l]
        i32 pos_s=(i+s-1)/s;//[1,n/s]
        i32 bit_pattern=B2[pos_s-1];
        i16 bit_mask=i-(pos_s-1)*s;
        bit_mask=(1<<bit_mask)-1;
        bit_pattern&=bit_mask;
        return L[pos_l-1]+S[pos_s-1]+__builtin_popcount(bit_pattern);
    }
    i32 rank1(int l,int r){//[l,r)のrank1
        return rank1(r)-rank1(l);
    }
    i32 rank0(int i){//[0,i)
        return i-rank1(i);
    }
    i32 rank0(int l,int r){
        return rank0(r)-rank0(l);
    }
    i8 access(int i){//0 indexed
        return B[i];
    }
};
template<class T>
struct wavelet_matrix{
    using i8=uint8_t;
    using i16=uint16_t;
    using i32=uint32_t;
    using i64=uint64_t;
    int N;
    i16 LOG=0;

    std::vector<i32>zero_count;//各bitの境界,0が始まるindex
    std::vector<bit_vector>B;//各bitをbitvectorで保存したもの
    std::unordered_map<i64,i32>begin_time;
    T max_b;
    i64 RAND=0;
    void build(const vector<T>&b){
        std::random_device seed;
        while(!RAND)RAND=seed();
        if(b.size()==0)return;
        N=b.size();
        max_b=*std::max_element(b.begin(),b.end());
        while((1ll<<LOG)<=max_b)LOG++;
        zero_count.reserve(LOG),zero_count.resize(LOG);
        B.reserve(LOG),B.resize(LOG);
        std::vector<T>nb=b;
        for(int i=LOG-1;i>=0;i--){
            std::vector<T>fr,ba;
            for(int j=0;j<N;j++){
                if(~nb[j]>>i&1){
                    fr.emplace_back(nb[j]);
                }
            }
            for(int j=0;j<N;j++){
                if(nb[j]>>i&1){
                    ba.emplace_back(nb[j]);
                }
            }
            vector<int>tmp2(N);
            for(int j=0;j<N;j++){
                tmp2[j]=nb[j]>>i&1;
            }
            zero_count[i]=fr.size();
            B[i].build(tmp2);
            std::vector<T>tmp;
            for(auto&x:fr){
                tmp.emplace_back(x);
            }
            for(auto&x:ba){
                tmp.emplace_back(x);
            }
            nb=move(tmp);
        }
        for(int j=N-1;j>=0;j--){
            begin_time[nb[j]^RAND]=j;
        }
    }
    T access(int i){//0 indexed b[i]を復元する
        assert(B.size());
        T now=0;
        for(int j=LOG-1;j>=0;j--){
            i64 bit=B[j].access(i);
            now+=(bit<<j);
            if(bit){
                //i=B[j].rank0(N)+B[j].rank1(i+1)-1;
                i=zero_count[j]+B[j].rank1(i+1)-1;
            }
            else{ 
                i=B[j].rank0(i+1)-1;
            }
        }
        return now;
    }
    //verifyed with https://judge.yosupo.jp/submission/200516
    int rank(int i,T x){//0 indexed [0,i]までにxが何回出現したかを返す
        if(begin_time.find(x^RAND)==begin_time.end())return 0;
        if(i<0)return 0;
        for(int j=LOG-1;j>=0;j--){
            if(x>>j&1){
                //i=B[j].rank0(N)+B[j].rank1(i+1)-1;
                i=zero_count[j]+B[j].rank1(i+1)-1;
            }
            else{
                i=B[j].rank0(i+1)-1;
            }
        }
        return i-begin_time[x^RAND]+1;
    }
    int rank(int l,int r,int x){//[l,r) rank x
        return rank(r-1,x)-rank(l-1,x);
    }
    //
    //NO veryfied!!!!!!!!!!!!!!!!!!
    int select(int i,T x){//i番目にx(0 indexed)が出現する場所を返す //NO veryfied!!!!!!!!!!!!!!!!!!
        int now=begin_time[x^RAND]+i;
        for(int i=0;i<LOG;i++){
            if(x>>i&1){
                //now=now-B[i].rank0(N-1)-1;
                now=now-zero_count[i]-1;
            }
            else{
                now=B[i].rank0(now)-1;
            }
        }
        return now;
    }
    //NO veryfied!!!!!!!!!!!!!!!!!!
    //
    //verifyed with https://judge.yosupo.jp/submission/200539
    T quantile(int l,int r,int x){//[l,r)の中でx番目(0 indexed)に小さい値を返す(sortしてx番目のものを返すともいえる)
        T res=0;
        for(int i=LOG-1;i>=0;i--){
            int l0=B[i].rank0(l,r),l1=B[i].rank1(l,r);
            if(x<l0){
                int t1=B[i].rank0(0,l);
                l=t1,r=t1+l0;
            }
            else{
                int t1=B[i].rank1(0,l);
                //int t3=B[i].rank0(0,N);
                int t3=zero_count[i];
                l=(t3)+t1,r=(t3)+t1+l1;
                x-=l0;
                res|=(1ll<<i);
            }
        }
        return res;
    }
    //[0,x)
    //[l,r]
    int range_freq(int l,int r,T x){
        if(x>=(T(1)<<LOG)){
            return r-l;
        }
        int res=0;
        for(int i=LOG-1;i>=0;i--){
            bool f=(x>>i&1);
            i32 l0=B[i].rank0(l),r0=B[i].rank0(r);
            if(f){
                res+=r0-l0;
                l+=B[i].rank0(N)-l0;
                r+=B[i].rank0(N)-r0;
            }else{
                l=l0;
                r=r0;
            }
        }
        return res;
    }
    int range_freq(int l,int r,T sl,T sr){
        return range_freq(l,r,sr)-range_freq(l,r,sl);
    }
    //return max value s.t. (l<=i<r&&a[i]<x)
    T prev(int l,int r,T x){
        int cnt=range_freq(l,r,x);
        if(cnt==0)return -1;
        return quantile(l,r,cnt-1);
    }
    //return min value s.t. (l<=i<r&&a[i]>x)
    T next(int l,int r,T x){
        int cnt=range_freq(l,r,x);
        if(cnt==r-l)return -1;
        return quantile(l,r,cnt);
    }
};
void solve(){
    INT(n)
    VC(int,as,n);
    rep(i,n)as[i]+=(int)1e6;
    wavelet_matrix<int>wm;
    wm.build(as);
    INT(q);
    while(q--){
        INT(l,r,d);
        ++r;
        d+=(int)1e6;
        int ans=2e6;
        if(wm.rank(d,l-1)<wm.rank(d,r-1)){
            ans=0;
        }else{
            int suc=wm.next(l,r,d);
            if(~suc)chmin(ans,abs(suc-d));
            int pre=wm.prev(l,r,d);
            if(~pre)chmin(ans,abs(pre-d));
        }
        cout<<ans<<"\n";
    }
}
signed main(){
    int t=1;
    //cin>>t;
    while(t--)solve();
}
accuracy: 1
time_ms: 180
memory_kb: 10476
final_rank: 12

code_snippet: #ifndef ELSIE_LOCAL_H
#define ELSIE_LOCAL_H
#ifndef ELSIE_MISC_HEADER
#define ELSIE_MISC_HEADER
#if __has_include(<atcoder/modint>)
#include "atcoder/modint"
using namespace atcoder;
using mint=modint998244353;
using mint1=modint1000000007;
#endif
#include <limits>
#include <new>
#include <initializer_list>
#include <compare>
#include <concepts>
#include <utility>
#include <bitset>
#include <tuple>
#include <type_traits>
#include <functional>
#include <chrono>
#include <array>
#include <deque>
#include <list>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iterator>
#include <ranges>
#include <algorithm>
#include <bit>
#include <random>
#include <numeric>
#include <numbers>
#include <iostream>
#include <ios>
#include <streambuf>
#include <iomanip>
#include <sstream>
#include <regex>
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdarg>
#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
using namespace std;
using namespace chrono;
using std::cin;
using std::cout;
using sstream=stringstream;
#endif
#ifndef ELSIE_MISC_DEFINE
#define ELSIE_MISC_DEFINE
#define RET return
#define fi first
#define se second
#define endl '\n'
#define sn(i,c) " \n"[i==c]
#define rsv(n) reserve(n)
#define pf(a) push_front(a)
#define pb(a) push_back(a)
#define eb(...) emplace_back(__VA_ARGS__)
#define ppf() pop_front()
#define ppb() pop_back()
#define pp() pop()
#define ins(a) insert(a)
#define emp(...) emplace(__VA_ARGS__)
#define ers(a) erase(a)
#define cont(a) contains(a)
#define mp(f,s) make_pair(f,s)
#define A(a) begin(a),end(a)
#define I(a,i) begin(a),begin(a)+(i)
#define _SEL4(_1,_2,_3,_4,name,...) name
#define _SEL3(_1,_2,_3,name,...) name
#define _REP4(i,s,n,st) for(long i=(s);i<(n);i+=(st))
#define _REP3(i,s,n) _REP4(i,s,n,1)
#define _REP2(i,n) _REP3(i,0,n)
#define _REP1(n) _REP2(_,n)
#define _RREP4(i,n,t,s) for(long i=(n);i>=(t);i-=(s))
#define _RREP3(i,n,t) _RREP4(i,n,t,1)
#define _RREP2(i,n) _RREP3(i,n,0)
#define _ITER2(x,a) for(auto&&x:a)
#define _ITER3(x,y,a) for(auto&&[x,y]:a)
#define _CTER2(x,a) for(const auto&x:a)
#define _CTER3(x,y,a) for(const auto&[x,y]:a)
#define rep(...) _SEL4(__VA_ARGS__,_REP4,_REP3,_REP2,_REP1)(__VA_ARGS__)
#define rrep(...) _SEL4(__VA_ARGS__,_RREP4,_RREP3,_RREP2,_REP1)(__VA_ARGS__)
#define iter(...) _SEL3(__VA_ARGS__,_ITER3,_ITER2)(__VA_ARGS__)
#define cter(...) _SEL3(__VA_ARGS__,_CTER3,_CTER2)(__VA_ARGS__)
#endif
#ifndef ELSIE_MISC_CONST
#define ELSIE_MISC_CONST
#define NL cout<<'\n'
#define npi numbers::pi
constexpr int64_t inf=1ll<<60,minf=-inf;
constexpr int32_t inf32=1ll<<30,minf32=-inf32;
constexpr char sep='\n';
constexpr array<pair<int32_t,int32_t>,8>dc={{{1,0},{0,1},{-1,0},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}}};
#define yes cout<<"Yes\n"
#define no cout<<"No\n"
#define yn(c) (c)?yes:no
#endif
#if __cplusplus > 202002L
#ifndef ELSIE_MISC_FUNC
#define ELSIE_MISC_FUNC

namespace vies=std::views;
#define DR(i) views::drop(i)
#define TK(i) views::take(i)
#define RV views::reverse
#define IOTA vies::iota

#define rev(a) reverse(A(a))
#define minel(a) min_element(A(a))
#define maxel(a) max_element(A(a))
#define acm(a) accumulate(A(a),0ll)
#define nxpm(a) next_permutation(A(a))
#define Sort(a) sort(A(a))
#define uni(a) Sort(a);a.erase(unique(A(a)),a.end())
#define swapcase(a) a=(isalpha(a)?a^32:a)

template<class T,class U>inline void chmax(T&a,const U&b){if(a<b)a=b;}
template<class T,class U>inline void chmin(T&a,const U&b){if(a>b)a=b;}


#define _BISECT4(_1,_2,_3,_4,name,...) name
#define _LB_BEX(b,e,x) lower_bound(b,e,x)
#define _LB_BEXG(b,e,x,g) lower_bound(b,e,x,g)
#define _UB_BEX(b,e,x) upper_bound(b,e,x)
#define _UB_BEXG(b,e,x,g) upper_bound(b,e,x,g)
#define lb(...) _BISECT4(__VA_ARGS__,_LB_BEXG,_LB_BEX)(__VA_ARGS__)
#define ub(...) _BISECT4(__VA_ARGS__,_UB_BEXG,_UB_BEX)(__VA_ARGS__)

#define TP template<class T,class U,typename cp=less<U>>
template<class T,class U>concept LUBI= same_as<T,vector<U>>||same_as<T,deque<U>>||is_array_v<T>;
#define RL requires LUBI<T,U>

TP size_t lbi(const T&v,const U&x,cp cmp=cp())RL{RET lb(A(v),x,cmp)-begin(v);}
TP size_t ubi(const T&v,const U&x,cp cmp=cp())RL{RET ub(A(v),x,cmp)-begin(v);}
TP size_t lbi(size_t i,const T&v,const U&x,cp cmp=cp())RL{RET lb(i+A(v),x,cmp)-begin(v);}
TP size_t ubi(size_t i,const T&v,const U&x,cp cmp=cp())RL{RET ub(i+A(v),x,cmp)-begin(v);}
TP size_t lbi(const T&v,size_t i,const U&x,cp cmp=cp())RL{RET lb(I(v,i),x,cmp)-begin(v);}
TP size_t ubi(const T&v,size_t i,const U&x,cp cmp=cp())RL{RET ub(I(v,i),x,cmp)-begin(v);}
TP size_t lbi(size_t i,const T&v,size_t e,const U&x,cp cmp=cp())RL{RET lb(i+I(v,e),x,cmp)-begin(v);}
TP size_t ubi(size_t i,const T&v,size_t e,const U&x,cp cmp=cp())RL{RET ub(i+I(v,e),x,cmp)-begin(v);}

#undef TP
#undef RL
#define TP template<integral T>
#define MT make_unsigned_t<T>

TP constexpr int32_t pcnt(T p){return popcount(MT(p));}
TP constexpr int32_t lsb(T p){return countr_zero(MT(p));}
TP constexpr int32_t msb(T p){return sizeof(T)*8-1-countl_zero(MT(p));}

template<int32_t N,integral T>
void putbit(T s){
    char buf[N+1]={0};
    for(char*itr=buf+N-1;itr>=buf;itr--,s>>=1)
        *itr='0'+(s&1);
    cout<<buf<<sep;
}
#undef TP
#undef MT
#endif
#ifndef ELSIE_STD_IO
#define ELSIE_STD_IO

#define INT(...) int __VA_ARGS__;in(__VA_ARGS__)
#define CHR(...) char __VA_ARGS__;in(__VA_ARGS__)
#define STR(...) str __VA_ARGS__;in(__VA_ARGS__)
#define VI(a,n) vi a(n);in(a)
#define VIT(a,n) vit a(n);in(a)
#define VS(a,n) vs a(n);in(a)
#define UV(u,v) INT(u,v);--u,--v
#define UVW(u,v,w) INT(u,v,w);--u,--v
#ifdef LOCAL
#define dput(...) dos=&cerr;out(__VA_ARGS__);dos=&cout
#else
#define dput(...)
#endif

template<class T>concept Lint=is_integral_v<T>&&sizeof(T)>8;
template<class T>concept Itrabl=requires(const T&x){x.begin();x.end();}&&!std::is_same_v<T,string>;
template<class T>concept IItrabl=Itrabl<T>&&Itrabl<typename T::value_type>;
template<class T>concept ModInt=requires(const T&x){x.val();};
template<class T>concept NLobj=Itrabl<T>||std::is_same_v<T,string>;

istream&operator<<(istream&is,__float128&x){double y;is>>y;x=y;return is;}
ostream&operator<<(ostream&os,const __float128&x){return os<<static_cast<double>(x);}

template<Lint T>ostream&operator<<(ostream&dst,T val){
    ostream::sentry s(dst);
    if(!s)return dst;
    char _O128[64];
    char*d=end(_O128);
    bool vsign=val<0;
    __uint128_t v=val;
    if(vsign&&val!=numeric_limits<T>::min())v=1+~(__uint128_t)val;
    do{
        *(--d)="0123456789"[v%10];
        v/=10;
    }while(v!=0);
    if(vsign)*(--d)='-';
    size_t len=end(_O128)-d;
    if(dst.rdbuf()->sputn(d,len)!=len)dst.setstate(ios_base::badbit);
    return dst;
}

template<Lint T>istream&operator>>(istream&src,T&val) {
    string s;src>>s;
    bool is_neg=numeric_limits<T>::is_signed&&s.size()>0&&s[0]=='-';
    for(val=0;const auto&x:s|views::drop(is_neg))val=10*val+x-'0';
    if(is_neg)val*=-1;
    return src;
}

template<ModInt T>istream&operator>>(istream&is,T&v){int64_t x;is>>x;v=x;return is;}
template<class T,class U>istream&operator>>(istream&is,pair<T,U>&v){return is>>v.first>>v.second;}
template<Itrabl T>istream&operator>>(istream&is,T&v){for(auto&&x:v)is>>x;return is;}

template<class T>void in(T&a){cin>>a;}
template<class T,class... Ts>void in(T&a,Ts&... b){in(a);in(b...);}

template<class T,class U>vector<pair<T,U>>zip(size_t n,size_t m){
    vector<pair<T,U>>r(min(n,m));
    iter(x,y,r)in(x);
    iter(x,y,r)in(y);
    return move(r);
}
template<class T,class U>vector<pair<T,U>>zip(size_t n){return move(zip<T,U>(n,n));}

template<ModInt T>ostream&operator<<(ostream&os,const T&v){return os<<v.val(); }
template<class T,class U>ostream&operator<<(ostream&os,const pair<T,U>&v){return os<<'('<<v.first<<','<<v.second<<')';}
template<Itrabl T>ostream&operator<<(ostream&os,const T&v){int cnt=0;cter(x,v)os<<x<<(++cnt<v.size()?" ":"");return os;}
template<IItrabl T>ostream&operator<<(ostream&os,const T&v){int cnt=0;cter(x,v)os<<x<<(++cnt<v.size()?"\n":"");return os;}
inline ostream*dos=&cout;
inline int32_t OFLG; // 0:first, 1:notNLobj, 2:NLobj
template<class T>void _out(const T&a){if(OFLG)(*dos)<<"0 \n"[OFLG]<<a;else(*dos)<<a;OFLG=1;}
template<NLobj T>void _out(const T&a){(*dos)<<(OFLG?"\n":"")<<a;OFLG=2;}
template<class T,class...Ts>void _out(const T&a,const Ts&... b){_out(a);_out(b...);}
template<class... Ts>void out(const Ts&... v){OFLG=0;_out(v...);(*dos)<<sep;}
#endif
#endif
#endif
#ifndef ELSIE_STATIC_WAVELET
#define ELSIE_STATIC_WAVELET
#ifndef ELSIE_STATIC_BIT_VECTOR
#define ELSIE_STATIC_BIT_VECTOR
namespace elsie{

class static_bit_vector{
    using u32=std::uint32_t;
    using u64=std::uint64_t;
    constexpr static u32 bsz=64;
    bool fixed;
    size_t sz;
    std::vector<u32>cnt;
    std::vector<u64>bit;
    u32 ceil(u64 a,u64 b){return(a+b-1)/b;}
    public:
    static_bit_vector():fixed(false),bit(0),cnt(0),sz(0){}
    static_bit_vector(size_t N):fixed(false),sz(N),bit(ceil(N,bsz),0),cnt(ceil(N,bsz)+1,0){}
    static_bit_vector(const static_bit_vector&)=default;
    bool get(size_t idx)const{return(bit[idx>>6]&u64(1)<<(idx&0x3F))!=0;}
    void set(size_t idx){
        assert(!fixed);
        bit[idx>>6]|=u64(1)<<(idx&0x3F);
    }
    void reset(size_t idx){
        assert(!fixed);
        bit[idx>>6]&=~(u64(1)<<(idx&0x3F));
    }
    void fix(){
        for(u32 i=1;i<cnt.size();++i)
            cnt[i]=cnt[i-1]+std::popcount(bit[i-1]);
        fixed=true;
    }
    // [0,idx)
    template<bool one=true>
    size_t rank(size_t idx)const{
        assert(fixed&&idx<=sz);
        size_t r=cnt[idx>>6]+std::popcount(bit[idx>>6]&((u64(1)<<(idx&0x3F))-1));
        if constexpr(one)
            return r;
        else return idx-r;
    }
    // [l,r)
    template<bool one=true>
    size_t rank(size_t l,size_t r)const{ return rank<one>(r)-rank<one>(l); }
    // k is 1-based index
    template<bool one=true>
    size_t select(size_t k)const{
        assert(fixed&&k);
        if(k>sz)return sz;
        int64_t ng=k-2,ok=sz;
        while(ng+1<ok){
            int64_t m=(ng+ok)>>1;
            if(rank<one>(m+1)>=k)ok=m;
            else ng=m;
        }
        return ok;
    }
    template<bool one=true>
    size_t select(size_t l,size_t k)const{
        assert(k);
        return select<one>(rank<one>(l)+k);
    }
    const static_bit_vector&operator=(const static_bit_vector&v){
        sz=v.sz;
        fixed=v.fixed;
        cnt=v.cnt;
        bit=v.bit;
        return*this;
    }
    const static_bit_vector&operator=(static_bit_vector&&v){
        sz=v.sz;
        fixed=v.fixed;
        bit=std::move(v.bit);
        cnt=std::move(v.cnt);
        return*this;
    }
};
}// namespace elsie
#endif // include guard
namespace elsie{
using namespace std;

template<unsigned_integral type>
class wavelet{
    private:
    template<class T> using vc=vector<T>;
    bool fixed;
    size_t lg,sz;
    vc<type>data;
    vc<static_bit_vector>bv;
    public:
    wavelet():sz(0),fixed(0),data(0),bv(1){}
    wavelet(size_t N):sz(N),fixed(0),data(N),bv(0){}
    wavelet(vector<type>&&v):sz(v.size()),fixed(0),data(v),bv(0){}
    wavelet(const vector<type>&v):sz(v.size()),fixed(0),data(v),bv(0){}

    void set(size_t idx,type v){
        assert(!fixed&&idx<sz);
        data[idx]=v;
    }

    void fix(){
        assert(!fixed);
        if(sz==0){
            sz=1;
            data.resize(1,0);
        }
        fixed=1;
        lg=sizeof(type)*8-countl_zero(*max_element(data.begin(),data.end()));
        bv.resize(lg,static_bit_vector(sz));
        size_t s[2];
        array<vc<type>,2>b{vc<type>(sz),vc<type>(sz)};
        for(int32_t i=lg-1;i>=0;--i){
            s[0]=s[1]=0;
            type filter=type(1)<<i;
            for(size_t j=0;j<sz;++j){
                bool p=data[j]&filter;
                b[p][s[p]++]=data[j];
                if(p)bv[i].set(j);
            }
            for(size_t p=0,q=0;p<2;q+=s[p++])
                for(size_t j=0;j<s[p];++j)
                    data[j+q]=b[p][j];
            bv[i].fix();
        }
    }

    type get(size_t idx)const{
        type r=0;
        for(int32_t i=lg-1;i>=0;--i){
            if(bv[i].get(idx)){
                r|=type(1)<<i;
                idx=bv[i].rank<0>(sz)+bv[i].rank<1>(idx);
            }else idx=bv[i].rank<0>(idx);
        }
        return r;
    }
    size_t range_freq(size_t l,size_t r,type upper)const{
        if(upper>=(type(1)<<lg))return r-l;
        size_t ret=0;
        for(int32_t h=lg-1;h>=0;--h){
            uint32_t L0=bv[h].rank<0>(l),R0=bv[h].rank<0>(r);
            if(upper>>h&1){
                size_t zeros=bv[h].rank<0>(sz);
                ret+=R0-L0;
                l+=zeros-L0;
                r+=zeros-R0;
            }else l=L0,r=R0;
        }
        return ret;
    }
    size_t range_freq(size_t l,size_t r,type lower,type upper)const{
        return range_freq(l,r,upper)-range_freq(l,r,lower);
    }
    // [0,idx)に現れるvの数
    size_t rank(size_t l,size_t r,type v)const{
        if(v==numeric_limits<type>::max())
            return sz-range_freq(l,r,v);
        else return range_freq(l,r,v,v+1);
    }
    // ord is 0-based index
    size_t select(size_t idx,type v)const{
        size_t mx=rank(0,sz,v);
        if(idx>=mx) return sz;
        size_t pos=0;
        for(int32_t h=lg-1;h>=0;--h){
            if(v>>h&1) pos=bv[h].rank<0>(sz)+bv[h].rank<1>(pos);
            else pos=bv[h].rank<0>(pos);
        }
        pos+=idx;
        for(int32_t h=0;h<lg;++h){
            if(v>>h&1) pos=bv[h].select<1>(pos-bv[h].rank<0>(sz));
            else bv[h].select<0>(pos);
        }
        return pos;
    }
    type less(size_t l,size_t r,size_t ord)const{
        type ret=0;
        for(int32_t h=lg-1;h>=0;--h){
            uint32_t L0=bv[h].rank<0>(l),R0=bv[h].rank<0>(r);
            if(ord<R0-L0) l=L0,r=R0;
            else{
                uint32_t zeros=bv[h].rank<0>(sz);
                ord-=R0-L0;
                ret|=type(1)<<h;
                l+=zeros-L0,r+=zeros-R0;
            }
        }
        return ret;
    }
    type greater(size_t l,size_t r,size_t ord)const{ return less(l,r,r-l-ord-1); }
    // i \in [l,r), x \in [0,upper), x=data[i]
    type prev(size_t l,size_t r,type upper)const{
        size_t cnt=range_freq(l,r,upper);
        return cnt==0?type(-1):less(l,r,cnt-1);
    }
    // i \in [l,r), x \in [lower,max), x=data[i]
    type next(size_t l,size_t r,type lower)const{
        size_t cnt=range_freq(l,r,lower);
        return cnt==r-l?type(-1):less(l,r,cnt);
    }
};

template<signed_integral type>
class wavelet_s{
    private:
    using utype=make_unsigned_t<type>;
    utype pot;
    bool fixed;
    size_t sz;
    public:
    wavelet<utype>wv;
    vector<type>data;
    inline utype raise(type x)const{ return((x<0&&utype(-x)>=pot)?0:x+pot); }
    public:
    wavelet_s():pot(0),sz(0),fixed(0),data(0),wv(){}
    wavelet_s(size_t N,utype potential):pot(potential+1),sz(N),fixed(0),data(N,0),wv(N){}
    wavelet_s(vector<type>&&v,utype potential):pot(potential),sz(v.size()),fixed(0),data(v),wv(sz){}
    wavelet_s(const vector<type>&v,utype potential):pot(potential),sz(v.size()),fixed(0),data(v),wv(sz){}
    void set(size_t idx,type v){
        assert(!fixed&&idx<data.size());
        data[idx]=v;
    }
    void fix(){
        for(size_t i=0;i<data.size();++i)
            wv.set(i,data[i]+pot);
        wv.fix();
    }
    type get(size_t idx)const{ return (type)wv.get(idx)-(type)pot; }
    size_t range_freq(size_t l,size_t r,type upper)const{ return wv.range_freq(l,r,raise(upper)); }
    size_t range_freq(size_t l,size_t r,type lower,type upper)const{return wv.range_freq(l,r,raise(lower),raise(upper));}
    size_t rank(size_t l,size_t r,type v)const{ return wv.rank(l,r,raise(v)); }
    size_t select(size_t idx,type v)const{ return wv.select(idx,raise(v)); }
    type less(size_t l,size_t r,size_t ord)const{ return wv.less(l,r,ord)-pot; }
    type greater(size_t l,size_t r,size_t ord)const{ return wv.greater(l,r,ord)-pot; }
    type prev(size_t l,size_t r,type upper)const{ return wv.prev(l,r,raise(upper))-pot; }
    type next(size_t l,size_t r,type lower)const{ return wv.next(l,r,raise(lower))-pot; }
};
} // namespace elsie
#endif // include guard
#ifndef ELSIE_ALIAS
#define ELSIE_ALIAS

template<class f>using vc=vector<f>;
template<class f>using vv=vc<vc<f>>;
template<class f>using v3=vv<vc<f>>;
template<class f>using v4=vv<vv<f>>;

template<class f>using gr=greater<f>;
template<class f>using pq=priority_queue<f>;
template<class f>using pqg=priority_queue<f, vc<f>, gr<f>>;
#define uset unordered_set
#define umap unordered_map
using it=int32_t;
using i8=int8_t;   using u8=uint8_t;
using i16=int16_t; using u16=uint16_t;
using i32=int32_t; using u32=uint32_t;
using i64=int64_t; using u64=uint64_t;
using i128=__int128_t; using u128=__uint128_t;
using intw=__int128_t; using uintw=__uint128_t;
using f32=float;
using f64=double;
using f128=__float128;
using vi=vc<i64>;
using vit=vc<it>;
using vb=vc<bool>;
using pi=pair<i64,i64>;
using pit=pair<it,it>;
using str=string;
using vs=vc<str>;
using pqgp=pqg<pi>;
#define int i64
#define itn i64
#define LL long long
#endif

void slv(){
    INT(n);
    VIT(a,n);
    elsie::wavelet_s<i32> wv(a,1e6+1);
    wv.fix();
    INT(q);
    rep(q){
        INT(l,r,d);
        ++r;
        out(min(abs(wv.prev(l,r,d)-d),abs(wv.next(l,r,d)-d)));
    }
}

signed main(){
    cin.tie(0)->sync_with_stdio(0);
    cout<<fixed<<setprecision(15);
    slv();
}
accuracy: 1
time_ms: 80
memory_kb: 5760
final_rank: 1

code_snippet: // AOJ #1549
// Hard Beans 2025.2.1

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

#define gc() getchar_unlocked()
#define pc(c) putchar_unlocked(c)

int Cin() {  // 整数の入力
	int n = 0, c = gc();
	if (c == '-') {	c = gc();
		do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
		return -n;
	}
	do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
	return n;
}

void Cout(int n) { // 非負整数の表示（出力）
	char b[30];
	if (!n) pc('0');
	else {
		//		if (n < 0) pc('-'), n = -n;
		int i = 0; while (n) b[i++] = n % 10 + '0', n /= 10;
		while (i--) pc(b[i]);
	}
	pc('\n');
}

// ----- 持続セグメント木 (Persistent Segment Tree) の実装 -----
// 各ノードは、区間 [start, end] における出現個数を保持します。
struct Node {
    int left, right, count;
};
 
// N <= 10^5, 離散化後の値の個数 M <= 10^5, 各更新で O(log M) ノードが生成されるので
// おおよそ 2e6～2.5e6 個のノードが必要になります。安全のため 3000000 個確保。
static const int MAX_NODE = 3000000;
Node seg[MAX_NODE];
int nodeCount = 0;
 
// update: 以前のバージョン prev から [start, end] 区間の pos 番目の値の出現数を 1 増加させた新ノードを返す
int update(int prev, int start, int end, int pos) {
    int curr = ++nodeCount;
    seg[curr] = seg[prev];
    seg[curr].count = seg[prev].count + 1;
    if(start == end) return curr;
    int mid = (start + end) / 2;
    if(pos <= mid)
        seg[curr].left = update(seg[prev].left, start, mid, pos);
    else
        seg[curr].right = update(seg[prev].right, mid+1, end, pos);
    return curr;
}
 
// queryCount: 差分木 (バージョン u と v の差) において、離散化インデックス [L, R] に入る個数を返す
int queryCount(int u, int v, int start, int end, int L, int R) {
    if(R < start || end < L) return 0;
    if(L <= start && end <= R)
        return seg[u].count - seg[v].count;
    int mid = (start + end) / 2;
    return queryCount(seg[u].left, seg[v].left, start, mid, L, R) +
           queryCount(seg[u].right, seg[v].right, mid+1, end, L, R);
}
 
// kth: 差分木 (u と v の差) から k 番目の最小の要素の離散化インデックスを返す
int kth(int u, int v, int start, int end, int k) {
    if(start == end) return start;
    int mid = (start + end) / 2;
    int cntLeft = seg[ seg[u].left ].count - seg[ seg[v].left ].count;
    if(k <= cntLeft)
        return kth(seg[u].left, seg[v].left, start, mid, k);
    else
        return kth(seg[u].right, seg[v].right, mid+1, end, k - cntLeft);
}
 
int main(){
    int N = Cin();
    vector<int> beans(N);
    for (int i = 0; i < N; i++) beans[i] = Cin();
    
    vector<int> sorted = beans;
    sort(sorted.begin(), sorted.end());
    sorted.erase(unique(sorted.begin(), sorted.end()), sorted.end());
    int M = sorted.size();
 
    vector<int> root(N+1, 0);
    seg[0].left = seg[0].right = seg[0].count = 0;
    for (int i = 0; i < N; i++){
        int pos = lower_bound(sorted.begin(), sorted.end(), beans[i]) - sorted.begin();
        root[i+1] = update(root[i], 0, M-1, pos);
    }
    
    int Q = Cin();
    while(Q--){
        int l = Cin(), r = Cin(), D = Cin();

        int total = r - l + 1;

        int pos = lower_bound(sorted.begin(), sorted.end(), D) - sorted.begin();
        int rnk = (pos > 0) ? queryCount(root[r+1], root[l], 0, M-1, 0, pos-1) : 0;
 
        int ans = INT_MAX;
        if(rnk < total) {
            int idx = kth(root[r+1], root[l], 0, M-1, rnk+1);
            int candidate = sorted[idx];
            ans = min(ans, abs(candidate - D));
        }
        if(rnk > 0) {
            int idx = kth(root[r+1], root[l], 0, M-1, rnk);
            int candidate = sorted[idx];
            ans = min(ans, abs(candidate - D));
        }
        Cout(ans);
    }
    return 0;
}
accuracy: 1
time_ms: 110
memory_kb: 26696
final_rank: 14

code_snippet: // AOJ #1549
// Hard Beans 2025.2.1

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

#define gc() getchar_unlocked()
#define pc(c) putchar_unlocked(c)

int Cin() {  // 整数の入力
	int n = 0, c = gc();
	if (c == '-') {	c = gc();
		do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
		return -n;
	}
	do n = 10*n + (c & 0xf), c = gc(); while (c >= '0');
	return n;
}

void Cout(int n) { // 非負整数の表示（出力）
	char b[30];
	if (!n) pc('0');
	else {
		//		if (n < 0) pc('-'), n = -n;
		int i = 0; while (n) b[i++] = n % 10 + '0', n /= 10;
		while (i--) pc(b[i]);
	}
	pc('\n');
}

int main(){
    int N = Cin(); 
    vector<int> beans(N);
    for (int i = 0; i < N; i++) beans[i] = Cin();
    
    int segSize = 4 * N;
    vector<vector<int>> seg(segSize);
    
    function<void(int, int, int)> build = [&](int idx, int l, int r){
        if(l == r){
            seg[idx].push_back(beans[l]);
            return;
        }
        int mid = (l + r) / 2;
        build(idx * 2, l, mid);
        build(idx * 2 + 1, mid + 1, r);
        seg[idx].resize(seg[idx * 2].size() + seg[idx * 2 + 1].size());
        merge(seg[idx * 2].begin(), seg[idx * 2].end(), 
              seg[idx * 2 + 1].begin(), seg[idx * 2 + 1].end(), 
              seg[idx].begin());
    };
    
    build(1, 0, N - 1);
    int Q = Cin();
    function<void(int, int, int, int, int, int, int&)> query = 
        [&](int idx, int segL, int segR, int qL, int qR, int D, int &best) {
        if (segR < qL || qR < segL) return;
        if (qL <= segL && segR <= qR) {
            const vector<int>& vec = seg[idx];
            auto it = lower_bound(vec.begin(), vec.end(), D);
            if (it != vec.end()){
                best = min(best, abs(*it - D));
            }
            if (it != vec.begin()){
                best = min(best, abs(*(it - 1) - D));
            }
            return;
        }
        int mid = (segL + segR) / 2;
        query(idx * 2, segL, mid, qL, qR, D, best);
        query(idx * 2 + 1, mid + 1, segR, qL, qR, D, best);
    };
    
    for (int i = 0; i < Q; i++){
        int l = Cin(), r = Cin(), D = Cin();
        int ans = INT_MAX;
        query(1, 0, N - 1, l, r, D, ans);
        Cout(ans);
    }
    return 0;
}
accuracy: 1
time_ms: 130
memory_kb: 24308
final_rank: 13

code_snippet: #pragma region Macros
#include <bits/stdc++.h>

using namespace std;

using lint = long long;
using ull = unsigned long long;
using ld = long double;
using int128 = __int128_t;
#define all(x) (x).begin(), (x).end()
#define EPS 1e-8
#define uniqv(v) v.erase(unique(all(v)), v.end())
#define OVERLOAD_REP(_1, _2, _3, name, ...) name
#define REP1(i, n) for (auto i = std::decay_t<decltype(n)>{}; (i) != (n); ++(i))
#define REP2(i, l, r) for (auto i = (l); (i) != (r); ++(i))
#define rep(...) OVERLOAD_REP(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)
#define log(x) cout << x << endl
#define logfixed(x) cout << fixed << setprecision(10) << x << endl;
#define logy(bool)             \
    if (bool) {                \
        cout << "Yes" << endl; \
    } else {                   \
        cout << "No" << endl;  \
    }

ostream &operator<<(ostream &dest, __int128_t value) {
    ostream::sentry s(dest);
    if (s) {
        __uint128_t tmp = value < 0 ? -value : value;
        char buffer[128];
        char *d = end(buffer);
        do {
            --d;
            *d = "0123456789"[tmp % 10];
            tmp /= 10;
        } while (tmp != 0);
        if (value < 0) {
            --d;
            *d = '-';
        }
        int len = end(buffer) - d;
        if (dest.rdbuf()->sputn(d, len) != len) {
            dest.setstate(ios_base::badbit);
        }
    }
    return dest;
}

template <typename T>
ostream &operator<<(ostream &os, const vector<T> &v) {
    for (int i = 0; i < (int)v.size(); i++) {
        os << v[i] << (i + 1 != (int)v.size() ? " " : "");
    }
    return os;
}

template <typename T>
ostream &operator<<(ostream &os, const set<T> &set_var) {
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end()) os << " ";
        itr--;
    }
    return os;
}

template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << itr->first << " -> " << itr->second << "\n";
    }
    return os;
}

template <typename T, typename U>
ostream &operator<<(ostream &os, const pair<T, U> &pair_var) {
    os << "(" << pair_var.first << ", " << pair_var.second << ")";
    return os;
}

void out() { cout << '\n'; }
template <class T, class... Ts>
void out(const T &a, const Ts &...b) {
    cout << a;
    (cout << ... << (cout << ' ', b));
    cout << '\n';
}

template <typename T>
istream &operator>>(istream &is, vector<T> &v) {
    for (T &in : v) is >> in;
    return is;
}

inline void in(void) { return; }
template <typename First, typename... Rest>
void in(First &first, Rest &...rest) {
    cin >> first;
    in(rest...);
    return;
}

template <typename T>
bool chmax(T &a, const T &b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
template <typename T>
bool chmin(T &a, const T &b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}

vector<lint> dx8 = {1, 1, 0, -1, -1, -1, 0, 1};
vector<lint> dy8 = {0, 1, 1, 1, 0, -1, -1, -1};
vector<lint> dx4 = {1, 0, -1, 0};
vector<lint> dy4 = {0, 1, 0, -1};

#pragma endregion

struct BitVector {
    unsigned sz;
    unsigned blocksize;
    vector<unsigned> bit, sum;

    BitVector() {}

    BitVector(unsigned siz) {
        sz = siz;
        blocksize = (sz + 31) >> 5;
        bit.assign(blocksize, 0U);
        sum.assign(blocksize, 0U);
    }

    inline void set(int k) { bit[k >> 5] |= 1U << (k & 31); }

    inline void build() {
        sum[0] = 0U;
        for (int i = 1; i < blocksize; i++) {
            sum[i] = sum[i - 1] + __builtin_popcount(bit[i - 1]);
        }
    }

    inline bool access(unsigned k) {
        return (bool((bit[k >> 5] >> (k & 31)) & 1));
    }

    inline int rank(int k) {
        return (sum[k >> 5] + __builtin_popcount(bit[k >> 5] & ((1U << (k & 31)) - 1)));
    }
};

template <class T>
class WaveletMatrix {
   private:
    unsigned n;
    unsigned bitsize;
    vector<BitVector> b;
    vector<unsigned> zero;
    vector<T> cmp;
    T MI, MA;

    inline unsigned compress(const T &x) {
        return lower_bound(cmp.begin(), cmp.end(), x) - begin(cmp);
    }

   public:
    // コンストラクタ
    WaveletMatrix() {}
    WaveletMatrix(const vector<T> &v) {
        MI = numeric_limits<T>::min();
        MA = numeric_limits<T>::max();
        n = v.size();
        cmp = v;
        sort(cmp.begin(), cmp.end());
        cmp.erase(unique(cmp.begin(), cmp.end()), cmp.end());
        vector<unsigned> compressed(n);
        vector<unsigned> tmpc(n);
        unsigned size_mx = v.size();
        for (unsigned i = 0; i < n; i++) {
            compressed[i] = compress(v[i]);
        }
        bitsize = bit_width(cmp.size());
        b.resize(bitsize);
        zero.assign(bitsize, 0);
        int cur = 0;

        for (unsigned i = 0; i < bitsize; i++) {
            b[i] = BitVector(n + 1);
            cur = 0;
            for (unsigned j = 0; j < n; j++) {
                if (compressed[j] & (1U << (bitsize - i - 1))) {
                    b[i].set(j);
                } else {
                    zero[i]++;
                    tmpc[cur] = compressed[j];
                    cur++;
                }
            }
            b[i].build();

            for (unsigned j = 0; j < n; j++) {
                if (compressed[j] & (1U << (bitsize - i - 1))) {
                    tmpc[cur] = compressed[j];
                    cur++;
                }
            }
            swap(tmpc, compressed);
        }
    }

    // get v[k]
    T access(unsigned k) {
        unsigned res = 0;
        unsigned cur = k;
        for (unsigned i = 0; i < bitsize; i++) {
            if (b[i].access(cur)) {
                res |= (1U << (bitsize - i - 1));
                cur = zero[i] + b[i].rank(cur);
            } else {
                cur -= b[i].rank(cur);
            }
        }
        return cmp[res];
    }

    // v[l,r) の中でk番目(1-origin)に小さい値を返す
    T kth_smallest(unsigned l, unsigned r, unsigned k) {
        unsigned res = 0;
        unsigned rank1_l, rank1_r, num0;
        for (unsigned i = 0; i < bitsize; i++) {
            rank1_l = b[i].rank(l);
            rank1_r = b[i].rank(r);
            num0 = r - l - (rank1_r - rank1_l);
            if (num0 < k) {
                res |= (1U << (bitsize - i - 1));
                l = zero[i] + rank1_l;
                r = zero[i] + rank1_r;
                k -= num0;
            } else {
                l -= rank1_l;
                r -= rank1_r;
            }
        }
        return cmp[res];
    }

    // v[l,r) の中でk番目(1-origin)に大きい値を返す
    T kth_largest(unsigned l, unsigned r, unsigned k) {
        return kth_smallest(l, r, r - l - k + 1);
    }

    // v[l,r) の中で[mink,maxk)に入る値の個数を返す
    unsigned range_freq(int vl, int vr, T mink, T maxk) {
        int D = compress(mink);
        int U = compress(maxk);
        unsigned res = 0;
        auto dfs = [&](auto &rec, int d, int L, int R, int A, int B) -> void {
            if (U <= A or B <= D) return;
            if (D <= A and B <= U) {
                res += (R - L);
                return;
            }
            if (d == bitsize) {
                if (D <= A and A < U) {
                    res += (R - L);
                }
                return;
            }
            int C = (A + B) / 2;
            int rank0_l = L - b[d].rank(L);
            int rank0_r = R - b[d].rank(R);
            int rank1_l = b[d].rank(L) + zero[d];
            int rank1_r = b[d].rank(R) + zero[d];
            rec(rec, d + 1, rank0_l, rank0_r, A, C);
            rec(rec, d + 1, rank1_l, rank1_r, C, B);
        };
        dfs(dfs, 0, vl, vr, 0, 1 << bitsize);
        return res;
    }

    // v[l,r)の中でvalを超えない最大の値を返す
    T prev_value(unsigned l, unsigned r, T val) {
        int num = range_freq(l, r, MI, val);
        if (num == 0) {
            return MA;
        } else {
            return kth_smallest(l, r, num);
        }
    }

    // v[l,r)の中でvalより大きい最小の値を返す
    T next_value(unsigned l, unsigned r, T val) {
        int num = range_freq(l, r, MI, val + 1);
        if (num == r - l) {
            return MI;
        } else {
            return kth_smallest(l, r, num + 1);
        }
    }

    bool contains(unsigned l, unsigned r, T val) {
        return range_freq(l, r, val, val + 1) > 0;
    }
};
int main() {
    cin.tie(0)->sync_with_stdio(0);
    int n;
    in(n);
    vector<int> a(n);
    in(a);
    WaveletMatrix<int> wm(a);

    int q;
    in(q);
    rep(i, q) {
        int l, r, d;
        in(l, r, d);
        r++;
        if (wm.contains(l, r, d)) {
            cout << 0 << endl;
        } else {
            lint nex = wm.next_value(l, r, d);
            lint prev = wm.prev_value(l, r, d);
            out(min(abs(nex - d), abs(prev - d)));
        }
    }
}
accuracy: 1
time_ms: 120
memory_kb: 5376
final_rank: 4

code_snippet: #include <bits/stdc++.h>

using namespace std;

using PI = pair<int, int>;

int find(const vector<PI>& b, int x) {
    int left = -1;
    int right = (int)b.size();

    while (abs(right - left) > 1) {
        int mid = (right + left) / 2;
        if (b[mid].first < x) {
            left = mid;
        } else {
            right = mid;
        }
    }
    return right;
}
int main() {
    std::ios::sync_with_stdio(0);
    std::cin.tie(0);
    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; ++i) cin >> a[i];
    vector<PI> beans(n);
    for (int i = 0; i < n; ++i) {
        PI b;
        b.first = a[i];
        b.second = i;
        beans[i] = b;
    }
    sort(beans.begin(), beans.end());

    int q;
    cin >> q;
    while (q--) {
        int l, r, d;
        cin >> l >> r >> d;
        int p = find(beans, d);
        bool left = false;
        bool right = false;
        int i = p - 1;
        int j = p;
        while (i >= 0) {
            if (l <= beans[i].second && beans[i].second <= r) {
                left = true;
                break;
            }
            --i;
        }
        while (j < n) {
            if (l <= beans[j].second && beans[j].second <= r) {
                right = true;
                break;
            }
            ++j;
        }
        int ans;
        if (left && right) {
            ans = min(abs(beans[i].first - d), abs(beans[j].first - d));
        } else if (left && !right) {
            ans = abs(beans[i].first - d);
        } else if (!left && right) {
            ans = abs(beans[j].first - d);
        }
        cout << ans << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 120
memory_kb: 4400
final_rank: 3

code_snippet: #include <bits/stdc++.h>



using namespace std;

//make -f ../makefile SRC=
/*
Merge sort tree ?
*/

//------------------------------------------------------------------------------
bool DEBUG = false;
const int INF = 1000000000;

typedef vector<vector<int> > Segtree;

//------------------------------------------------------------------------------
int brute_force
(
    int N, const vector<int>& values,
    int start, int end, int index
)
{
    int K = end - start + 1;
    vector<int> S(K);
    for (int k=0; k<K; ++k) S[k] = values[k+start];
    sort(S.begin(), S.end());
    return S[index];
}

//------------------------------------------------------------------------------
vector<int> merge(const vector<int>& A, const vector<int>& B)
{
    vector<int> L;
    int i = 0;
    int j = 0;
    while (true)
    {
        if (i >= A.size())
        {
            L.insert(L.end(), B.begin()+j, B.end());
            break;
        }

        if (j >= B.size())
        {
            L.insert(L.end(), A.begin()+i, A.end());
            break;
        }

        if (A[i] <= B[j]) { L.push_back(A[i]); i += 1; }
        else { L.push_back(B[j]); j += 1; }
    }

    return L;
}

//------------------------------------------------------------------------------
void build(int N, const vector<int>& values, int node, int left, int right, Segtree& segtree)
{
    if (left == right)
    {
        segtree[node] = { values[left] };
        return;
    }

    int mid = (left + right) / 2;
    build(N, values, 2*node+1, left, mid, segtree);
    build(N, values, 2*node+2, mid+1, right, segtree);

    vector<int> A = segtree[2*node+1];
    vector<int> B = segtree[2*node+2];
    segtree[node] = merge(A, B);
}


int query
(
    const Segtree& segtree, int node, int left, int right,
    int start, int end, int value
)
{
    if (start > right || end < left) return INF;
    if (start <= left && end >= right)
    {
        auto it = lower_bound(segtree[node].begin(), segtree[node].end(), value);
        if (it == segtree[node].end()) return value - segtree[node].back();
        else if (*it == value) return 0;

        int diff = *it - value;
        if (it != segtree[node].begin())
        {
            it--;
            diff = min(diff, value-*it);
        }
        return diff;
    }
    int mid = (left + right)/2;
    int v1 = query(segtree, 2*node+1, left, mid, start, end, value);
    int v2 = query(segtree, 2*node+2, mid+1, right, start, end, value);
    return min(v1,v2);
}

int query
(
    int N, const Segtree& segtree,
    int start, int end, int D
)
{
    return query(segtree, 0, 0, N-1, start, end, D);
}
//------------------------------------------------------------------------------
void testcases()
{
    srand(time(0));
    int N = 20;
    vector<int> values(N);
    for (int i=0; i<N; ++i)
    {
        int v = rand()%50+1;
        values[i] = v;
    }
    printf("values: "); for (int v=0; v<N; ++v) printf("%d ",values[v]); printf("\n");

    Segtree segtree(N*4);
    build(N, values, 0, 0, N-1, segtree);

    int Q = 20;
    int x1, x2, k;
    for (int q=0; q<Q; ++q)
    {
        x1 = rand() % N;
        x2 = rand() % N;
        if (x2 < x1) swap(x1, x2);
        k = rand() % (x2-x1+1);
        int y = query(N, segtree, x1, x2, k);
        int y0 = brute_force(N, values, x1, x2, k);
        if (y == y0) continue;
        printf("%d,%d,%d: y=%d, y0=%d\n", x1, x2, k, y, y0);
    }
}

//------------------------------------------------------------------------------
void test()
{
    vector<int> values = {21,46,21,49,48,19,47,39,12,19,17,2,15,22,2,1,15,28,42,11};
    int N = values.size();
    Segtree segtree(N*4);
    build(N, values, 0, 0, N-1, segtree);

    int x1 = 0;
    int x2 = 17;
    int k = 15;
    printf("47 => %d\n", query(segtree, 0, 0, N-1, x1, x2, 47));
    printf("48 => %d\n", query(segtree, 0, 0, N-1, x1, x2, 48));

}

//------------------------------------------------------------------------------
int main()
{
    //testcases(); return 0;
    //DEBUG = true;
    //test(); return 0;
    //--------------------------------------------------------------------------
    int N, Q, v, x1, x2, d, num;
    num = scanf("%d ", &N);
    vector<int> values(N);
    for (int i=0; i<N; ++i)
    {
        num = scanf("%d ", &v);
        values[i] = v;
    }

    Segtree segtree(N*4);
    build(N, values, 0, 0, N-1, segtree);
    //printf("segtree built\n");

    //--------------------------------------------------------------------------
    num = scanf("%d ", &Q);
    //printf("Q=%d\n", Q);
    for (int q=0; q<Q; ++q)
    {
        num = scanf("%d %d %d ", &x1, &x2, &d);
        //printf("x1=%d, x2=%d, k=%d\n", x1, x2, d);
        int res = query(N, segtree, x1, x2, d);
        printf("%d\n", res);
    }
    //int res = query(N, segtree, 1, 4, 2);
    //printf("res=%d\n", res);
    //--------------------------------------------------------------------------
    return 0;
}
//------------------------------------------------------------------------------
accuracy: 1
time_ms: 150
memory_kb: 26712
final_rank: 15

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define db double
#define pii pair<int,int>
#define pli pair<ll,int>
#define pil pair<int,ll>
#define pll pair<ll,ll>
#define ti3 tuple<int,int,int>
#define int128 __int128_t
#define pii128 pair<int128,int128>
const int inf = 1 << 30;
const ll linf = (ll)4e18 + 10;;
const db EPS = 1e-10;
const db pi = acos(-1);
template<class T> bool chmin(T& x, T y){
    if(x > y) {
        x = y;
        return true;
    } else return false;
}
template<class T> bool chmax(T& x, T y){
    if(x < y) {
        x = y;
        return true;
    } else return false;
}

// overload macro
#define CAT( A, B ) A ## B
#define SELECT( NAME, NUM ) CAT( NAME, NUM )

#define GET_COUNT( _1, _2, _3, _4, _5, _6 /* ad nauseam */, COUNT, ... ) COUNT
#define VA_SIZE( ... ) GET_COUNT( __VA_ARGS__, 6, 5, 4, 3, 2, 1 )

#define VA_SELECT( NAME, ... ) SELECT( NAME, VA_SIZE(__VA_ARGS__) )(__VA_ARGS__)

// rep(overload)
#define rep( ... ) VA_SELECT(rep, __VA_ARGS__)
#define rep2(i, n) for (int i = 0; i < int(n); i++)
#define rep3(i, a, b) for (int i = a; i < int(b); i++)
#define rep4(i, a, b, c) for (int i = a; i < int(b); i += c)

// repll(overload)
#define repll( ... ) VA_SELECT(repll, __VA_ARGS__)
#define repll2(i, n) for (ll i = 0; i < (ll)(n); i++)
#define repll3(i, a, b) for (ll i = a; i < (ll)(b); i++)
#define repll4(i, a, b, c) for (ll i = a; i < (ll)(b); i += c)

// rrep(overload)
#define rrep( ... ) VA_SELECT(rrep, __VA_ARGS__)
#define rrep2(i, n) for (int i = n - 1; i >= 0; i--)
#define rrep3(i, a, b) for (int i = b - 1; i >= a; i--)
#define rrep4(i, a, b, c) for (int i = b - 1; i >= a; i -= c)

// rrepll(overload)
#define rrepll( ... ) VA_SELECT(rrepll, __VA_ARGS__)
#define rrepll2(i, n) for (ll i = (ll)(n) - 1; i >= 0ll; i--)
#define rrepll3(i, a, b) for (ll i = b - 1; i >= (ll)(a); i--)
#define rrepll4(i, a, b, c) for (ll i = b - 1; i >= (ll)(a); i -= c)

// for_earh
#define fore(e, v) for (auto&& e : v)

// vector
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()


struct bit_vector {
    int n;
    const int w = 64;
    vector<uint64_t> b;
    vector<int> cnt;
    bit_vector(int _n = 0) : n(_n), b(_n / w + 1), cnt(_n / w + 1) {}

    int access(int i) {
        return b[i / w] >> (i % w) & 1;
    }

    void set(int i) {
        b[i / w] |= 1ll << (i % w);
    }

    void build() {
        for (int i = 1; i < (int)cnt.size(); i++) {
            cnt[i] = cnt[i - 1] + __builtin_popcountll(b[i - 1]);
        }
    }

    int rank0(int i) {
        return i - rank1(i);
    }

    int rank1(int i) {
        return cnt[i / w] + __builtin_popcountll(b[i / w] & ((1ull << (i % w)) - 1));
    }
};

template<class T>
struct wavelet_matrix {
    int lg;
    vector<bit_vector> bv;
    vector<int> zeros;

    wavelet_matrix(vector<T> a) {
        for (auto u : a) lg = max(lg, u);
        lg = log2(lg) + 1;
        bv = vector(lg, bit_vector(a.size()));
        zeros.resize(lg);
        vector<T> crt = a, nxt(a.size());
        for (int i = lg - 1; i >= 0; i--) {
            int ones = a.size() - 1;
            for (int j = 0; j < a.size(); j++) {
                if (crt[j] >> i & 1) {
                    bv[i].set(j);
                    nxt[ones--] = crt[j];
                } else {
                    nxt[zeros[i]++] = crt[j];
                }
            }
            bv[i].build();
            reverse(nxt.begin() + ones + 1, nxt.end());
            swap(crt, nxt);
        }
    }

    T access(int x) {
        T ret = 0;
        for (int i = lg - 1; i >= 0; i--) {
            if (bv[i].access(x)) {
                ret |= (T)1 << i;
                x = zeros[i] + bv[i].rank1(i);
            } else {
                x = bv[i].rank0(i);
            }
        }
    }

    T kth_min(int l, int r, int k) {
        T ret = 0;
        for (int i = lg - 1; i >= 0; i--) {
            int l0 = bv[i].rank0(l), r0 = bv[i].rank0(r);
            if (k < r0 - l0) {
                l = l0;
                r = r0;
            } else {
                k -= r0 - l0;
                ret |= (T)1 << i;
                l += zeros[i] - l0;
                r += zeros[i] - r0;
            }
        }
        return ret;
    }

    T kth_max(int l, int r, int k) {
        return kth_min(l, r, r - l - k - 1);
    }

    T count_lt_k(int l, int r, T k) {
        int ret = 0;
        for (int i = lg - 1; i >= 0; i--) {
            int l0 = bv[i].rank0(l), r0 = bv[i].rank0(r);
            if (k >> i & 1) {
                ret += r0 - l0;
                l += zeros[i] - l0;
                r += zeros[i] - r0;
            } else {
                l = l0;
                r = r0;
            }
        }
        return ret;
    }

    T count_k(int l, int r, T k) {
        for (int i = lg - 1; i >= 0; i--) {
            int l0 = bv[i].rank0(l), r0 = bv[i].rank0(r);
            if (k >> i & 1) {
                l += zeros[i] - l0;
                r += zeros[i] - r0;
            } else {
                l = l0;
                r = r0;
            }
        }
        return r - l;
    }

    T count_gt_k(int l, int r, T k) {
        int ret = 0;
        for (int i = lg - 1; i >= 0; i--) {
            int l0 = bv[i].rank0(l), r0 = bv[i].rank0(r);
            if (k >> i & 1) {
                l += zeros[i] - l0;
                r += zeros[i] - r0;
            } else {
                ret += r - l - r0 + l0;
                l = l0;
                r = r0;
            }
        }
        return ret;
    }

    T range_freq(int l, int r, T lower, T upper) {
        return count_lt_k(l, r, upper) - count_lt_k(l, r, lower);
    }

    T next_value(int l, int r, T k) {
        int cnt = count_lt_k(l, r, k);
        if (r - l == cnt) return -1;
        else return kth_min(l, r, cnt);
    }

    T prev_value(int l, int r, T k) {
        int cnt = count_gt_k(l, r, k);
        if (r - l == cnt) return -1;
        else return kth_max(l, r, cnt);
    }
};

int N, Q;
int main() {
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout << fixed << setprecision(20);
    cin >> N;
    vector<int> A(N);
    rep (i, N) cin >> A[i], A[i] += 1000000;
    A.push_back(2000000);
    wavelet_matrix wm(A);
    cin >> Q;
    rep (i, Q) {
        int l, r, x;
        cin >> l >> r >> x;
        r++;
        x += 1000000;
        int ans = inf;
        int pre = wm.prev_value(l, r, x);
        if (pre > 0) chmin(ans, x - pre);
        int nxt = wm.next_value(l, r, x);
        if (nxt > 0) chmin(ans, nxt - x);
        cout << ans << '\n';
    }
}
accuracy: 1
time_ms: 170
memory_kb: 5392
final_rank: 7

code_snippet: #include <iostream>
#include <string>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <set>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <climits>
#include <time.h>
#include <assert.h>
#include <numeric>
#include <functional>
#include <random>
#include <iterator>
#include <bitset>
#include<valarray>
#include<fstream>
#include<unordered_map>
#include<unordered_set>
#include <filesystem>
#include <optional>
//#include<compare>
//#include <ranges>
//#define AIZU
//#define ATCODER

#ifdef ATCODER

#include<atcoder/all>
using namespace atcoder;
#endif
using namespace std;
typedef long long ll;

#define FOR(i, min, max) for (int i = (min); i < (max); ++i) 
#define FORE(i, min, max) for (int i = (min); i <= (max); ++i)
#define DFOR(i,max,min) for(int i=(max);i>(min);--i)
#define DFORE(i,max,min) for(int i=(max);i>=(min);--i)
#define REP(i, n) for (int i = 0; i < (n); ++i)
#define REPE(i, n) for (int i = 0; i <= (n); ++i)
#define DREP(i, n) for (int i = (n); i >=0; --i) 
#define REPV(vec, i) for (int i = 0; i < (int)(vec.size()); ++i) 
#define V(type) vector<type> 
#define VV(type) vector<vector<type>>
#define VVV(type) vector<vector<vector<type>>>
#define VVVV(type) vector<vector<vector<vector<type>>>>
#define VVVVV(type) vector<vector<vector<vector<vector<type>>>>>
#define VI(type,i,n) V(type)(i,n)
#define VVI(type,i,j,n) VV(type)(i,VI(type,j,n))
#define VVVI(type,i,j,k,n) VVV(type)(i,VVI(type,j,k,n))
#define VVVVI(type,i,j,k,l,n) VVVV(type)(i,VVVI(type,j,k,l,n))
#define VVVVVI(type,i,j,k,l,m,n) VVVVV(type)(i,VVVVI(type,j,k,l,m,n))
#define ALL(v) v.begin(),v.end()


template <typename Type>
void show(vector<Type> v, string sep = " ") {
	REP(i, v.size()) {
		cerr << v[i] << sep;
	}
	cerr << endl;
}
template <typename Type>
void show(VV(Type) v, string sep = " ") {
	REP(i, v.size()) {
		REP(j, v[i].size()) {
			cerr << v[i][j] << sep;
		}
		cerr << endl;
	}
	cerr << endl;
}
template<typename T> T maxc(T& a, const T& b) { return (a = std::max(a, b)); }
template<typename T> T minc(T& a, const T& b) { return (a = std::min(a, b)); }

const std::string WHITESPACE = " \n\r\t\f\v";
string getS(string filename) {
	ifstream ifs(filename);
	if (!ifs)return "";
	string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
	return str;
}
auto split(std::string str, const std::string cut) {
	std::vector<decltype(str)> data;
	for (auto pos = str.find(cut); pos != std::string::npos; pos = str.find(cut)) {
		data.push_back(str.substr(0, pos));
		str = str.substr(pos + cut.size());
	}
	if (!str.empty())data.push_back(str);
	return data;
}
std::string ltrim(const std::string& s)
{
	size_t start = s.find_first_not_of(WHITESPACE);
	return (start == std::string::npos) ? "" : s.substr(start);
}

std::string rtrim(const std::string& s)
{
	size_t end = s.find_last_not_of(WHITESPACE);
	return (end == std::string::npos) ? "" : s.substr(0, end + 1);
}
std::string trim(const std::string& s) {
	return rtrim(ltrim(s));
}
bool ismatch(string trues, string anss) {
	vector<string> smp0 = split(trues, "\n");
	vector<string> smp1 = split(anss, "\n");
	vector<string> sm0;
	vector<string> sm1;
	for (string s : smp0) {
		string st = trim(s);
		if (st != "") {
			sm0.push_back(st);
		}
	}
	for (string s : smp1) {
		string st = trim(s);
		if (st != "") {
			sm1.push_back(st);
		}
	}
	if (sm0.size() != sm1.size())return false;
	for (int i = 0; i < sm0.size(); i++) {
		if (sm0[i] != sm1[i]) {
			return false;
		}
	}
	return true;
}

template<typename T>
vector<pair<int, T>> enumerate(vector<T>& v) {
	vector<pair<int, T>> ret(v.size());
	REP(i, v.size()) {
		ret[i] = { i,v[i] };
	}
	return ret;
}
template<typename T0, typename T1>
vector<pair<T0, T1>> zip(vector<T0>& v0, vector<T1>& v1) {
	int n = min(v0.size(), v1.size());
	vector<pair<T0, T1>> ret(n);
	REP(i, n) {
		ret[i] = { v0[i],v1[i] };
	}
	return ret;
}
void setbit(ll &i, int j) {
	i=i | (1LL << j);
}
void resetbit(ll &i, int j) {
	i=i & ~(1 << j);
}
bool isset(ll i, int j) {
	return (i & (1LL << j)) != 0;
}
void setbit(int& i, int j) {
	i = i | (1LL << j);
}
void resetbit(int& i, int j) {
	i = i & ~(1 << j);
}
bool isset(int i, int j) {
	return (i & (1LL << j)) != 0;
}

int bitCount(int i) {
	i = i - ((i >> 1) & 0x55555555);
	i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
	i = (i + (i >> 4)) & 0x0f0f0f0f;
	i = i + (i >> 8);
	i = i + (i >> 16);
	return i & 0x3f;
}
int bitCount(ll i) {
	int ret = 0;
	while (i != 0) {
		if (i & 1)ret++;
		i = i >> 1;
	}
	return ret;

}
void setbitxor(int &i, int j) {
	i=(i ^ (1 << j));
}
void setbitxor(ll &i, int j) {
	i = (i ^ (1LL << j));
}
int next_combination(int sub) {
	int x = sub & -sub, y = sub + x;
	return (((sub & ~y) / x) >> 1) | y;
}

template<typename T>
bool candiv(T a, T b) {
	return a % b == 0;
}
template<typename T>
T llceil(T a, T b) {
	if (a % b == 0) {
		return a / b;
	}
	if (a >= 0) { return (a / b) + 1; }
	else {
		return -((-a) / b);

	}
}
template<typename T>
T llfloor(T a, T b) {
	if (a % b == 0) {
		return a / b;
	}
	if (a >= 0) { return (a / b); }
	else {
		return -((-a) / b) - 1;

	}
}
template<typename T>
bool isDuplicate(vector<T> a) {
	sort(ALL(a));
	return unique(ALL(a)) != a.end();
}
template<typename T>
bool isSameContents(vector<T> a, vector<T> b) {
	sort(ALL(a));
	sort(ALL(b));
	return a == b;
}
ll llpow(ll x, ll n) {
	long long ret = 1;
	while (n > 0) {
		if (n & 1) ret *= x;  // n の最下位bitが 1 ならば x^(2^i) をかける
		x *= x;
		n >>= 1;  // n を1bit 左にずらす
	}
	return ret;
}
ll llpowmod(ll x, ll n, ll m) {
	long long ret = 1;
	while (n > 0) {
		if (n & 1) {
			ret *= x;  // n の最下位bitが 1 ならば x^(2^i) をかける
			ret %= m;
		}
		x *= x;
		x %= m;
		n >>= 1;  // n を1bit 左にずらす
	}
	return ret;
}

//wavelet
//
enum {
	NOTFOUND = 0xFFFFFFFFFFFFFFFFLLU
};

class SuccinctBitVector {
private:
	const uint64_t size;    // ビットベクトルのサイズ
	static const uint64_t blockBitNum = 16;
	static const uint64_t LEVEL_L = 512;
	static const uint64_t LEVEL_S = 16;

	std::vector<uint64_t> L;   // 大ブロック
	std::vector<uint16_t> S;   // 小ブロック
	std::vector<uint16_t> B;   // ビットベクトル

	uint64_t numOne = 0;       // 1bitの数

public:
	explicit SuccinctBitVector(const uint64_t n) : size(n) {
		const uint64_t s = (n + blockBitNum - 1) / blockBitNum + 1;   // ceil(n, blockSize)
		this->B.assign(s, 0);
		this->L.assign(n / LEVEL_L + 1, 0);
		this->S.assign(n / LEVEL_S + 1, 0);
	}

	// B[pos] = bit
	void setBit(const uint64_t bit, const uint64_t pos) {
		assert(bit == 0 or bit == 1);
		assert(pos < this->size);

		const uint64_t blockPos = pos / blockBitNum;
		const uint64_t offset = pos % blockBitNum;
		if (bit == 1) { B.at(blockPos) |= (1LLU << offset); }
		else { B.at(blockPos) &= (~(1LLU << offset)); }
	}

	// B[pos]
	uint64_t access(const uint64_t pos) {
		assert(pos < this->size);
		const uint64_t blockPos = pos / blockBitNum;
		const uint64_t offset = pos % blockBitNum;
		return ((B.at(blockPos) >> offset) & 1);
	}

	void build() {
		uint64_t num = 0;
		for (uint64_t i = 0; i <= size; i++) {
			if (i % LEVEL_L == 0) {
				L.at(i / LEVEL_L) = num;
			}
			if (i % LEVEL_S == 0) {
				S.at(i / LEVEL_S) = (uint16_t)(num - L.at(i / LEVEL_L));
			}
			if (i != size and i % blockBitNum == 0) {
				num += this->popCount(this->B.at(i / blockBitNum));
			}
		}
		this->numOne = num;
	}

	// B[0, pos)のbitの数
	uint64_t rank(const uint64_t bit, const uint64_t pos) {
		assert(bit == 0 or bit == 1);
		assert(pos <= this->size);

		if (bit) {
			return L[pos / LEVEL_L] + S[pos / LEVEL_S] + popCount(B[pos / blockBitNum] & ((1 << (pos % blockBitNum)) - 1));
		}
		else {
			return pos - rank(1, pos);
		}
	}

	// rank番目のbitの位置 + 1(rankは1-origin)
	uint64_t select(const uint64_t bit, const uint64_t rank) {
		assert(bit == 0 or bit == 1);
		assert(rank > 0);
		if (bit == 0 and rank > this->size - this->numOne) { return NOTFOUND; }
		if (bit == 1 and rank > this->numOne) { return NOTFOUND; }

		// 大ブロックL内を検索
		uint64_t large_idx = 0;
		{
			uint64_t left = 0;
			uint64_t right = L.size();
			while (right - left > 1) {
				uint64_t mid = (left + right) / 2;
				uint64_t r = L.at(mid);
				r = (bit) ? r : mid * LEVEL_L - L.at(mid);

				if (r < rank) {
					left = mid;
					large_idx = mid;
				}
				else {
					right = mid;
				}
			}
		}

		// 小ブロックS内を検索
		uint64_t small_idx = (large_idx * LEVEL_L) / LEVEL_S;
		{
			uint64_t left = (large_idx * LEVEL_L) / LEVEL_S;
			uint64_t right = std::min(((large_idx + 1) * LEVEL_L) / LEVEL_S, (uint64_t)S.size());
			while (right - left > 1) {
				uint64_t mid = (left + right) / 2;
				uint64_t r = L.at(large_idx) + S.at(mid);
				r = (bit) ? r : mid * LEVEL_S - r;

				if (r < rank) {
					left = mid;
					small_idx = mid;
				}
				else {
					right = mid;
				}
			}
		}

		// Bをブロック単位で順番に探索
		uint64_t rank_pos = 0;
		{
			const uint64_t begin_block_idx = (small_idx * LEVEL_S) / blockBitNum;
			uint64_t total_bit = L.at(large_idx) + S.at(small_idx);
			if (bit == 0) {
				total_bit = small_idx * LEVEL_S - total_bit;
			}
			for (uint64_t i = 0;; ++i) {
				uint64_t b = popCount(B.at(begin_block_idx + i));
				if (bit == 0) {
					b = blockBitNum - b;
				}
				if (total_bit + b >= rank) {
					uint64_t block = (bit) ? B.at(begin_block_idx + i) : ~B.at(begin_block_idx + i);
					rank_pos = (begin_block_idx + i) * blockBitNum + selectInBlock(block, rank - total_bit);
					break;
				}
				total_bit += b;
			}
		}

		return rank_pos + 1;
	}

	uint64_t getNumOne() const {
		return numOne;
	}

	void debug() {
		std::cout << "LEVEL_L(" << L.size() << ")" << std::endl;
		for (uint64_t i = 0; i < L.size(); ++i) {
			std::cout << L.at(i) << ", ";
		}
		std::cout << std::endl;
		std::cout << "LEVEL_S(" << S.size() << ")" << std::endl;
		for (uint64_t i = 0; i < S.size(); ++i) {
			std::cout << S.at(i) << ", ";
		}
		std::cout << std::endl;
	}

private:
	uint64_t popCount(uint64_t x) {
		x = (x & 0x5555555555555555ULL) + ((x >> 1) & 0x5555555555555555ULL);
		x = (x & 0x3333333333333333ULL) + ((x >> 2) & 0x3333333333333333ULL);
		x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0fULL;
		x = x + (x >> 8);
		x = x + (x >> 16);
		x = x + (x >> 32);
		return x & 0x7FLLU;
	}

	uint64_t selectInBlock(uint64_t x, uint64_t rank) {
		uint64_t x1 = x - ((x & 0xAAAAAAAAAAAAAAAALLU) >> 1);
		uint64_t x2 = (x1 & 0x3333333333333333LLU) + ((x1 >> 2) & 0x3333333333333333LLU);
		uint64_t x3 = (x2 + (x2 >> 4)) & 0x0F0F0F0F0F0F0F0FLLU;

		uint64_t pos = 0;
		for (;; pos += 8) {
			uint64_t rank_next = (x3 >> pos) & 0xFFLLU;
			if (rank <= rank_next) break;
			rank -= rank_next;
		}

		uint64_t v2 = (x2 >> pos) & 0xFLLU;
		if (rank > v2) {
			rank -= v2;
			pos += 4;
		}

		uint64_t v1 = (x1 >> pos) & 0x3LLU;
		if (rank > v1) {
			rank -= v1;
			pos += 2;
		}

		uint64_t v0 = (x >> pos) & 0x1LLU;
		if (v0 < rank) {
			rank -= v0;
			pos += 1;
		}

		return pos;
	}
};
class WaveletMatrix {
private:
    std::vector<SuccinctBitVector> bit_arrays;
    std::vector<uint64_t> begin_one;                    // 各bitに着目したときの1の開始位置
    std::map<uint64_t, uint64_t> begin_alphabet;        // 最後のソートされた配列で各文字の開始位置
    std::vector<std::vector<uint64_t>> cumulative_sum;  // 各bitに着目したときの累積和

    uint64_t size;                                 // 与えられた配列のサイズ
    uint64_t maximum_element;                      // 文字数
    uint64_t bit_size;                             // 文字を表すのに必要なbit数

public:
    WaveletMatrix(const std::vector<uint64_t>& array) {
        assert(array.size() > 0);
        size = array.size();
        maximum_element = *max_element(array.begin(), array.end()) + 1;
        bit_size = get_num_of_bit(maximum_element);
        if (bit_size == 0) {
            bit_size = 1;
        }

        for (uint64_t i = 0; i < bit_size; ++i) {
            SuccinctBitVector sv(size);
            bit_arrays.push_back(sv);
        }
        this->begin_one.resize(bit_size);
        this->cumulative_sum.resize(bit_size + 1, std::vector<uint64_t>(size + 1, 0));

        for (uint64_t j = 0; j < array.size(); ++j) {
            this->cumulative_sum.at(0).at(j + 1) = this->cumulative_sum.at(0).at(j) + array[j];
        }

        std::vector<uint64_t> v(array);
        for (uint64_t i = 0; i < bit_size; ++i) {

            std::vector<uint64_t> temp;
            // 0をtempにいれてく
            for (uint64_t j = 0; j < v.size(); ++j) {
                uint64_t c = v.at(j);
                uint64_t bit = (c >> (bit_size - i - 1)) & 1;  //　上からi番目のbit
                if (bit == 0) {
                    temp.push_back(c);
                    bit_arrays.at(i).setBit(0, j);
                }
            }

            this->begin_one.at(i) = temp.size();

            // 1をtempにいれてく
            for (uint64_t j = 0; j < v.size(); ++j) {
                uint64_t c = v.at(j);
                uint64_t bit = (c >> (bit_size - i - 1)) & 1;  //　上からi番目のbit
                if (bit == 1) {
                    temp.push_back(c);
                    bit_arrays.at(i).setBit(1, j);
                }
            }

            for (uint64_t j = 0; j < temp.size(); ++j) {
                this->cumulative_sum.at(i + 1).at(j + 1) = this->cumulative_sum.at(i + 1).at(j) + temp.at(j);
            }

            bit_arrays.at(i).build();
            v = temp;
        }

        // ソートされた配列内での各文字の位置を取得
        for (int i = (int)v.size() - 1; i >= 0; --i) {
            this->begin_alphabet[v.at(i)] = i;
        }
    }

    // v[pos]
    uint64_t access(uint64_t pos) {
        if (pos >= this->size) { return NOTFOUND; }

        uint64_t c = 0;
        for (uint64_t i = 0; i < bit_arrays.size(); ++i) {
            uint64_t bit = bit_arrays.at(i).access(pos);   // もとの数値のi番目のbit
            c = (c <<= 1) | bit;
            pos = bit_arrays.at(i).rank(bit, pos);
            if (bit) {
                pos += this->begin_one.at(i);
            }
        }
        return c;
    }



    // T[begin_pos, end_pos)でx <= c < yを満たす最大のcを返す
    uint64_t prevValue(const uint64_t begin_pos, const uint64_t end_pos, const uint64_t x, uint64_t y) {
        assert(end_pos <= size);
        const uint64_t num = end_pos - begin_pos;

        if (x >= y or y == 0) {
            return NOTFOUND;
        }
        if (y > maximum_element) {
            y = maximum_element;
        }

        if (begin_pos >= end_pos) {
            return NOTFOUND;
        }
        if (x >= maximum_element || end_pos == 0) {
            return NOTFOUND;
        }

        y--; // x <= c <= yにする

        std::stack<std::tuple<uint64_t, uint64_t, uint64_t, uint64_t, bool>> s;   // (begin, end, depth, c, tight)
        s.emplace(std::make_tuple(begin_pos, end_pos, 0, 0, true));

        while (not s.empty()) {
            uint64_t b, e, depth, c;
            bool tight;
            std::tie(b, e, depth, c, tight) = s.top(); s.pop();

            if (depth == bit_size) {
                if (c >= x) {
                    return c;
                }
                continue;
            }

            const uint64_t bit = (y >> (bit_size - depth - 1)) & 1;

            const uint64_t rank0_begin = this->bit_arrays.at(depth).rank(0, b);
            const uint64_t rank0_end = this->bit_arrays.at(depth).rank(0, e);
            const uint64_t rank1_begin = b - rank0_begin;
            const uint64_t rank1_end = e - rank0_end;

            // d番目のbitが0のものを使う
            const uint64_t b0 = rank0_begin;
            const uint64_t e0 = rank0_end;
            if (b0 != e0) { // 範囲がつぶれてない
                const uint64_t c0 = ((c << 1) | 0);
                s.emplace(std::make_tuple(b0, e0, depth + 1, c0, tight and bit == 0));
            }

            // d番目のbitが1のものを使う
            const uint64_t b1 = this->begin_one.at(depth) + rank1_begin;
            const uint64_t e1 = this->begin_one.at(depth) + rank1_end;
            if (b1 != e1) {
                if (not tight or bit == 1) {
                    const auto c1 = ((c << 1) | 1);
                    s.emplace(std::make_tuple(b1, e1, depth + 1, c1, tight));
                }
            }
        }

        return NOTFOUND;
    }

    // T[begin_pos, end_pos)でx <= c < yを満たす最小のcを返す
    uint64_t nextValue(const uint64_t begin_pos, const uint64_t end_pos, const uint64_t x, const uint64_t y) {
        assert(end_pos <= size);
        const uint64_t num = end_pos - begin_pos;

        if (x >= y or y == 0) {
            return NOTFOUND;
        }

        if (begin_pos >= end_pos) {
            return NOTFOUND;
        }
        if (x >= maximum_element || end_pos == 0) {
            return NOTFOUND;
        }

        std::stack<std::tuple<uint64_t, uint64_t, uint64_t, uint64_t, bool>> s;   // (begin, end, depth, c, tight)
        s.emplace(std::make_tuple(begin_pos, end_pos, 0, 0, true));

        while (not s.empty()) {
            uint64_t b, e, depth, c;
            bool tight;
            std::tie(b, e, depth, c, tight) = s.top(); s.pop();

            if (depth == bit_size) {
                if (c < y) {
                    return c;
                }
                continue;
            }

            const uint64_t bit = (x >> (bit_size - depth - 1)) & 1;

            const uint64_t rank0_begin = this->bit_arrays.at(depth).rank(0, b);
            const uint64_t rank0_end = this->bit_arrays.at(depth).rank(0, e);
            const uint64_t rank1_begin = b - rank0_begin;
            const uint64_t rank1_end = e - rank0_end;

            // d番目のbitが1のものを使う
            const uint64_t b1 = this->begin_one.at(depth) + rank1_begin;
            const uint64_t e1 = this->begin_one.at(depth) + rank1_end;
            if (b1 != e1) {
                const auto c1 = ((c << 1) | 1);
                s.emplace(std::make_tuple(b1, e1, depth + 1, c1, tight and bit == 1));
            }

            // d番目のbitが0のものを使う
            const uint64_t b0 = rank0_begin;
            const uint64_t e0 = rank0_end;
            if (b0 != e0) {
                if (not tight or bit == 0) {
                    const uint64_t c0 = ((c << 1) | 0);
                    s.emplace(std::make_tuple(b0, e0, depth + 1, c0, tight));
                }
            }
        }

        return NOTFOUND;
    }

    // T[s1, e1)とT[s2, e2)に共通して出現する要素を求める
    std::vector<std::tuple<uint64_t, uint64_t, uint64_t>> intersect(uint64_t _s1, uint64_t _e1, uint64_t _s2, uint64_t _e2) {
        assert(_s1 < _e1);
        assert(_s2 < _e2);

        std::vector<std::tuple<uint64_t, uint64_t, uint64_t>> intersection;

        std::queue<std::tuple<uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t>> que; // s1, e1, s2, e2, depth, value
        que.push(std::make_tuple(_s1, _e1, _s2, _e2, 0, 0));
        while (not que.empty()) {
            auto e = que.front(); que.pop();
            uint64_t s1, e1, s2, e2, depth, value;
            std::tie(s1, e1, s2, e2, depth, value) = e;

            if (depth >= this->bit_size) {
                intersection.emplace_back(std::make_tuple(value, e1 - s1, e2 - s2));
                continue;
            }

            // 0
            uint64_t s1_0 = this->bit_arrays.at(depth).rank(0, s1);
            uint64_t e1_0 = this->bit_arrays.at(depth).rank(0, e1);
            uint64_t s2_0 = this->bit_arrays.at(depth).rank(0, s2);
            uint64_t e2_0 = this->bit_arrays.at(depth).rank(0, e2);

            if (s1_0 != e1_0 and s2_0 != e2_0) {
                que.push(std::make_tuple(s1_0, e1_0, s2_0, e2_0, depth + 1, value));
            }

            // 1
            uint64_t s1_1 = this->begin_one.at(depth) + this->bit_arrays.at(depth).rank(1, s1);
            uint64_t e1_1 = this->begin_one.at(depth) + this->bit_arrays.at(depth).rank(1, e1);
            uint64_t s2_1 = this->begin_one.at(depth) + this->bit_arrays.at(depth).rank(1, s2);
            uint64_t e2_1 = this->begin_one.at(depth) + this->bit_arrays.at(depth).rank(1, e2);

            if (s1_1 != e1_1 and s2_1 != e2_1) {
                que.push(std::make_tuple(s1_1, e1_1, s2_1, e2_1, depth + 1, value | (1ULL <<( bit_size - depth - 1))));
            }
        }

        return intersection;
    };

private:
    uint64_t get_num_of_bit(uint64_t x) {
        if (x == 0) return 0;
        x--;
        uint64_t bit_num = 0;
        while (x >> bit_num) {
            ++bit_num;
        }
        return bit_num;
    }

    uint64_t rangeSum(const uint64_t begin, const uint64_t end, const uint64_t depth, const uint64_t c, const uint64_t x, const uint64_t y) {
        if (begin == end) {
            return 0;
        }

        if (depth == bit_size) {
            if (x <= c and c < y) {
                return c * (end - begin);   // 値 * 頻度
            }
            return 0;
        }

        const uint64_t next_c = ((uint64_t)1 << (bit_size - depth - 1)) | c;                   // 上からdepth番目のbitを立てる
        const uint64_t all_one_c = (((uint64_t)1 << (bit_size - depth - 1)) - 1) | next_c;     // depth以降のbitをたてる(これ以降全部1を選んだときの値)
        if (all_one_c < x or y <= c) {
            return 0;
        }

        // [begin, pos)のすべての要素は[x, y)
        if (x <= c and all_one_c < y) {
            return this->cumulative_sum.at(depth).at(end) - this->cumulative_sum.at(depth).at(begin);
        }

        const uint64_t rank0_begin = this->bit_arrays.at(depth).rank(0, begin);
        const uint64_t rank0_end = this->bit_arrays.at(depth).rank(0, end);
        const uint64_t rank1_begin = begin - rank0_begin;
        const uint64_t rank1_end = end - rank0_end;

        return rangeSum(rank0_begin, rank0_end, depth + 1, c, x, y) +
            rangeSum(this->begin_one.at(depth) + rank1_begin, this->begin_one[depth] + rank1_end, depth + 1, next_c, x, y);
    }
};

#ifdef ATCODER
typedef modint1000000007 mint0;
typedef modint998244353 mint;
#endif
string CONTEST = "typical90";
string PROBLEM = "typical90_cc";//問題に合わせて変える

class Answer{
public:
	char problemc;
#ifdef TESTLOCAL
	void answertest(istream& cin, ostream& cout) {

	}
#endif
	void answer(istream& cin, ostream& cout) {
		int N;
		cin >> N;
		vector<uint64_t> A(N);
		REP(i, N) {
			cin >> A[i];
		}
        WaveletMatrix wm(A);
		int Q;
		cin >> Q;
		for (int i = 0; i < Q; i++) {
			uint64_t L, R, D;
			cin >> L >> R >> D;
			R++;
			uint64_t ans = numeric_limits<uint64_t>::max();
            auto a1 = wm.prevValue(L, R, 0, D);
            if (a1 != NOTFOUND) {
                ans = min(ans, D - a1);
            }
            auto a2 = wm.nextValue(L, R, D, 1000100);
            if(a2!=NOTFOUND){
                ans = min(ans, a2 - D);
            }
            cout << ans << endl;
		}
	}

};

bool test(char c) {
	string inputdir = "input\\";
	string outputdir = "output\\";
	string fs = getS(inputdir + c + ".txt");
	if (fs != "") {
		string os = getS(outputdir + c + ".txt");
		ostringstream oss;
		istringstream iss(fs);
		Answer A;
		A.problemc = c;
		A.answer(iss, oss);
		if (ismatch(os, oss.str())) {
			cerr << (char)(c + 1) << ":ok" << endl;
		}
		else {
			cerr << (char)(c + 1) << ":ng" << endl;
			cerr << "true:" << endl;
			cerr << os << endl;
			cerr << "ans:" << endl;
			cerr << oss.str() << endl;
		}
		return true;
	}
	else {
		return false;
	}

}
void testall() {
	for (char c = '0'; c < '9'; c++) {
		if (!test(c))break;
	}
}
void createRandom(ostringstream& cout) {
	int N = 6;
	cout << N << endl;
	//vector<int> p = { 6,4,5,5,6,6 };
	vector<int> p = {};
	REP(i, N) {
		p.push_back((rand() % (N - i)) + i + 1);
	}
	for (auto a : p) {
		cout << a << " ";
	}
	cout << endl;
}
#ifdef TESTLOCAL
void testLocal() {
	int MAX_NUM = 100;
	int show = max(1, MAX_NUM / 10);
	REP(i, MAX_NUM) {
		ostringstream os;
		createRandom(os);
		ostringstream ostest;
		istringstream istest(os.str());
		ostringstream osa;
		istringstream isa(os.str());
		Answer At('0');
		Answer A('0');
		A.answer(isa, osa);
		At.answertest(istest, ostest);
		if (ismatch(osa.str(), ostest.str())) {
			if (i % show == 0 || i == MAX_NUM - 1) {
				cout << i << ":ok" << endl;
			}
		}
		else {
			cout << i << ":ng" << endl;
			cout << "in:" << endl;
			cout << os.str() << endl;
			cout << "true->" << endl;
			cout << ostest.str() << endl;
			cout << "false->" << endl;
			cout << osa.str() << endl;
			return;
		}
	}

}
#endif
int main() {
	cin.tie(nullptr);//出力後に必ずendl or flushすれば問題ない。
	ios::sync_with_stdio(false);//scanf printfと混ぜなければ問題ない。

#ifdef ATCODER
#ifdef _LOCAL
#ifdef TESTLOCAL
	testLocal();
#else
	if (!std::filesystem::is_regular_file(PROBLEM + "_AC")) {
		string command = "problemget.bat " + CONTEST + " " + PROBLEM;
		system(command.c_str());
	}
	testall();
#endif
#else
	Answer A;
	A.answer(cin, cout);
#endif
#else
#ifdef AIZU
#ifdef _LOCAL
	if (!std::filesystem::is_regular_file(CONTEST + "_AC")) {//問題を取得したら一旦抜ける。
		string command = "problemgetaizu.bat " + CONTEST;
		system(command.c_str());
	}
	testall();
#else
	Answer A;
	A.answer(cin, cout);
#endif
#else
	Answer A;
	A.answer(cin, cout);
#endif
#endif
#ifdef _LOCAL
	cin.get();
#endif
	return 0;
}
accuracy: 1
time_ms: 240
memory_kb: 27532
final_rank: 18

code_snippet: #pragma region Macros

#pragma GCC optimize("O3,unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,fma,abm,mmx,avx,avx2")

#include <bits/extc++.h>
#include <immintrin.h>
// #include <atcoder/all>
// using namespace atcoder;
using namespace std;
using namespace __gnu_pbds;

// #include <boost/multiprecision/cpp_dec_float.hpp>
// #include <boost/multiprecision/cpp_int.hpp>
// namespace mp = boost::multiprecision;
// using Bint = mp::cpp_int;
// using Bdouble = mp::number<mp::cpp_dec_float<256>>;

#define pb emplace_back
#define int ll
#define endl '\n'

#define sqrt __builtin_sqrt
#define cbrt __builtin_cbrt
#define hypot __builtin_hypot

using ll = long long;
using ld = long double;
const ld PI = acosl(-1);
const int INF = 1 << 30;
const ll INFL = 1LL << 61;
const int MOD = 998244353;
// const int MOD = 1000000007;

const ld EPS = 1e-10;
const bool equals(ld a, ld b) { return fabs((a) - (b)) < EPS; }

const vector<int> dx = {0, 1, 0, -1, 1, 1, -1, -1}; // → ↓ ← ↑ ↘ ↙ ↖ ↗
const vector<int> dy = {1, 0, -1, 0, 1, -1, -1, 1};

struct Edge {
    int from, to;
    ll cost;
    Edge(int to, ll cost) : to(to), cost(cost) {}
    Edge(int from, int to, ll cost) : from(from), to(to), cost(cost) {}
};

chrono::system_clock::time_point  start, now;
__attribute__((constructor))
void constructor() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout << fixed << setprecision(10);
    start = chrono::system_clock::now();
}

__int128_t POW(__int128_t x, int n) {
    __int128_t ret = 1;
    assert(n >= 0);
    if (x == 1 or n == 0) ret = 1;
    else if (x == -1 && n % 2 == 0) ret = 1; 
    else if (x == -1) ret = -1; 
    else if (n % 2 == 0) {
        assert(x < INFL);
        ret = POW(x * x, n / 2);
    } else {
        assert(x < INFL);
        ret = x * POW(x, n - 1);
    }
    return ret;
}
int per(int x, int y) { // x = qy + r (0 <= r < y) を満たすq
    assert(y != 0);
    if (x >= 0 && y > 0) return x / y;
    if (x >= 0 && y < 0) return x / y - (x % y < 0);
    if (x < 0 && y < 0) return x / y + (x % y < 0);
    return x / y - (x % y < 0); //  (x < 0 && y > 0) 
}
// int perl(ld x, ld y) { // perld(4.5, 2.1) = 2  // TODO
//     if (-EPS < x && x < 0 or 0 < x && x < EPS) x = 0;
//     if (-EPS < y && y < 0 or 0 < x && x < EPS) y = 0;
//     assert(!equals(y, 0));
//     if (x >= 0 && y > 0) return floor(x / y)+EPS;
//     if (x >= 0 && y < 0) return floor(x / y) - (x - floor(x/y)*y < -EPS);
//     if (x < 0 && y < 0) return floor(x / y) + (x - floor(x/y)*y < -EPS);
//     return floor(x / y) - (x - floor(x/y)*y < -EPS); //  (x < 0 && y > 0) 
// }
int mod(int x, int y) { // x = qy + r (0 <= r < y) を満たすr
    assert(y != 0);
    if (x >= 0) return x % y;
    __int128_t ret = x % y; // (x < 0)
    ret += (__int128_t)abs(y) * INFL;
    ret %= abs(y);
    return ret;
}
// ld modl(ld x, ld y) { // TODO
//     assert(!equals(y, 0));
//     if (x >= -EPS) return (x - floor(x/y)*y);
//     ld ret = x - floor(x/y)*y; // (x < 0)
//     ret += abs(y) * INFL; // TODO : オーバーフローする?
//     ret = x - floor(x/abs(y))*abs(y);
//     return ret;
// }
// int floor(int x, int y) { // TODO
//     assert(y != 0);
//     if (b < 0) a = -a, b = -b;
//     return a >= 0 ? a / b : (a + 1) / b - 1;
// }
// int ceil(int x, int y) { // TODO
// assert(y != 0);
//     if (b < 0) a = -a, b = -b;
//     return a > 0 ? (a - 1) / b + 1 : a / b;
// }
// int floorl(ld x, ld y) { return 0; } // TODO
// int ceill(ld x, ld y) { return 0; } // TODO
// int gauss(int x, int y) {
//     assert(y != 0);
//     return x / y;
// } // 整数部分(未verify)
// int gauss(ld x, ld y) { return 0; } // TODO

pair<int, int> max(const pair<int, int> &a, const pair<int, int> &b) {
    if (a.first > b.first or a.first == b.first && a.second > b.second) {
        return a;
    }
    return b;
}
pair<int, int> min(const pair<int, int> &a, const pair<int, int> &b) {
    if (a.first < b.first or a.first == b.first && a.second < b.second) {
        return a;
    }
    return b;
}

template <class T> bool chmax(T &a, const T& b) {
    if (a < b) { a = b; return true; }
    return false;
}
template <class T> bool chmin(T &a, const T& b) {
    if (a > b) { a = b; return true; }
    return false;
}
template <class T> T mid(T a, T b, T c) {
    return a + b + c - max({a, b, c}) - min({a, b, c});
}
template <class T> void sort(T &a, T &b, T &c, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b);
        if (a > c) swap(a, c);
        if (b > c) swap(b, c);
    } else {
        if (c > b) swap(c, b);
        if (c > a) swap(c, a);
        if (b > a) swap(b, a);
    }
}
template <class T> void sort(T &a, T &b, T &c, T &d, bool rev = false) {
    if (rev == false) { 
        if (a > b) swap(a, b); if (a > c) swap(a, c);  if (a > d) swap(a, d);
        if (b > c) swap(b, c); if (b > d) swap(b, d);
        if (c > d) swap(c, d);
    } else {
        if (d > c) swap(d, c); if (d > b) swap(d, b); if (d > a) swap(d, a);
        if (c > b) swap(c, b); if (c > a) swap(c, a);
        if (b > a) swap(b, a);
    }
}

int countl_zero(int x) { return __builtin_clzll(x); }
int countl_one(int x) {
    int ret = 0; while (x % 2) { x /= 2; ret++; }
    return ret;
}
int countr_zero(int x) { return __builtin_ctzll(x); }
int countr_one(int x) {
    int ret = 0, k = 63 - __builtin_clzll(x);
    while (k != -1 && (x & (1LL << k))) { k--; ret++; }
    return ret;
}
int popcount(int x) { return __builtin_popcountll(x); }
int unpopcount(int x) { return 64 - __builtin_clzll(x) - __builtin_popcountll(x); }

int top_bit(int x) { return 63 - __builtin_clzll(x);} // 2^kの位
int bot_bit(int x) { return __builtin_ctz(x);} // 2^kの位
int MSB(int x) { return 1 << (63 - __builtin_clzll(x)); } // mask
int LSB(int x) { return (x & -x); } // mask

int bit_width(int x) { return 64 - __builtin_clzll(x); } // 桁数
int ceil_log2(int x) { return 63 - __builtin_clzll(x); }
int bit_floor(int x) { return 1 << (63 - __builtin_clzll(x)); }
int floor_log2(int x) { return 64 - __builtin_clzll(x-1); }
int bit_ceil(int x) { return 1 << (64 - __builtin_clzll(x-1)) - (x==1); }

int hamming(int a, int b) { return popcount(a ^ b); }
int compcnt(int x) { return (popcount(x^(x >> 1)) + (x&1)) / 2; }

class UnionFind {
public:
	UnionFind() = default;
    UnionFind(int N) : par(N), sz(N, 1) {
        iota(par.begin(), par.end(), 0);
    }

	int root(int x) {
		if (par[x] == x) return x;
		return (par[x] = root(par[x]));
	}

	bool unite(int x, int y) {
		int rx = root(x);
		int ry = root(y);

        if (rx == ry) return false;
		if (sz[rx] < sz[ry]) swap(rx, ry);

		sz[rx] += sz[ry];
		par[ry] = rx;

        return true;
	}

	bool issame(int x, int y) { return (root(x) == root(y)); }
	int size(int x) { return sz[root(x)]; }

    vector<vector<int>> groups(int N) {
        vector<vector<int>> G(N);
        for (int x = 0; x < N; x++) {
            G[root(x)].push_back(x);
        }
		G.erase(
            remove_if(G.begin(), G.end(),
                [&](const vector<int>& V) { return V.empty(); }),
                    G.end());
        return G;
    }
private:
	vector<int> par;
	vector<int> sz;
};

template<int mod> class Modint{
public:
    int val = 0;
    Modint(int x = 0) { while (x < 0) x += mod; val = x % mod; }
    Modint(const Modint &r) { val = r.val; }

    Modint operator -() { return Modint(-val); } // 単項
    Modint operator +(const Modint &r) { return Modint(*this) += r; }
    Modint operator +(const int &q) { Modint r(q); return Modint(*this) += r; }
    Modint operator -(const Modint &r) { return Modint(*this) -= r; }
    Modint operator -(const int &q) { Modint r(q); return Modint(*this) -= r; }
    Modint operator *(const Modint &r) { return Modint(*this) *= r; }
    Modint operator *(const int &q) { Modint r(q); return Modint(*this) *= r; }
    Modint operator /(const Modint &r) { return Modint(*this) /= r; }
    Modint operator /(const int &q) { Modint r(q); return Modint(*this) /= r; }
    
    Modint& operator ++() { val++; if (val >= mod) val -= mod; return *this; } // 前置
    Modint operator ++(signed) { ++*this; return *this; } // 後置
    Modint& operator --() { val--; if (val < 0) val += mod; return *this; }
    Modint operator --(signed) { --*this; return *this; }
    Modint &operator +=(const Modint &r) { val += r.val; if (val >= mod) val -= mod; return *this; }
    Modint &operator +=(const int &q) { Modint r(q); val += r.val; if (val >= mod) val -= mod; return *this; }
    Modint &operator -=(const Modint &r) { if (val < r.val) val += mod; val -= r.val; return *this; }
    Modint &operator -=(const int &q) { Modint r(q);  if (val < r.val) val += mod; val -= r.val; return *this; }
    Modint &operator *=(const Modint &r) { val = val * r.val % mod; return *this; }
    Modint &operator *=(const int &q) { Modint r(q); val = val * r.val % mod; return *this; }
    Modint &operator /=(const Modint &r) {
        int a = r.val, b = mod, u = 1, v = 0;
        while (b) {int t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v);}
        val = val * u % mod; if (val < 0) val += mod;
        return *this;
    }
    Modint &operator /=(const int &q) {
        Modint r(q); int a = r.val, b = mod, u = 1, v = 0;
        while (b) {int t = a / b; a -= t * b; swap(a, b); u -= t * v; swap(u, v);}
        val = val * u % mod; if (val < 0) val += mod;
        return *this;
    }

    bool operator ==(const Modint& r) { return this -> val == r.val; }
    bool operator <(const Modint& r) { return this -> val < r.val; }
    bool operator >(const Modint& r) { return this -> val > r.val; }
    bool operator !=(const Modint& r) { return this -> val != r.val; }
};

using mint = Modint<MOD>;
// using Mint = modint998244353;

istream &operator >>(istream &is, mint& x) {
    int t; is >> t;
    x = t;
    return (is);
}
ostream &operator <<(ostream &os, const mint& x) {
    return os << x.val;
}
mint modpow(const mint &x, int n) {
    assert(n >= 0); // TODO: n <= -1
    if (n == 0) return 1;
    mint t = modpow(x, n / 2);
    t = t * t;
    if (n & 1) t = t * x;
    return t;
}

int modpow(__int128_t x, int n, int mod) {
    assert(n >= 0 && mod > 0); // TODO: n <= -1
    __int128_t ret = 1;
    while (n > 0) {
        if (n % 2 == 1) ret = ret * x % mod;
        x = x * x % mod;
        n /= 2;
    }
    return ret;
}

int modinv(__int128_t x, int mod) {
    assert(mod > 0 && x > 0);
    if (x == 1) return 1;
    return mod - modinv(mod % x, mod) * (mod / x) % mod;
}

istream &operator >>(istream &is, __int128_t& x) {
    string S; is >> S;
    __int128_t ret = 0;
    int f = 1;
    if (S[0] == '-') f = -1; 
    for (int i = 0; i < S.length(); i++)
        if ('0' <= S[i] && S[i] <= '9')
            ret = ret * 10 + S[i] - '0';
    x = ret * f;
    return (is);
}
ostream &operator <<(ostream &os, __int128_t x) {
    ostream::sentry s(os);
    if (s) {
        __uint128_t tmp = x < 0 ? -x : x;
        char buffer[128];
        char *d = end(buffer);

        do {
            --d;
            *d = "0123456789"[tmp % 10];
            tmp /= 10;
        } while (tmp != 0);

        if (x < 0) {
            --d;
            *d = '-';
        }
        int len = end(buffer) - d;

        if (os.rdbuf()->sputn(d, len) != len) {
            os.setstate(ios_base::badbit);
        }
    }
    return os;
}

__int128_t stoll(string &S) {
    __int128_t ret = 0;
    int f = 1;
    if (S[0] == '-') f = -1; 
    for (int i = 0; i < S.length(); i++)
        if ('0' <= S[i] && S[i] <= '9')
            ret = ret * 10 + S[i] - '0';
    return ret * f;
}
__int128_t gcd(__int128_t a, __int128_t b) {
    return b ? gcd(b, a % b) : a;
}
__int128_t lcm(__int128_t a, __int128_t b) {
    return a / gcd(a, b) * b;
    // lcmが__int128_tに収まる必要あり
}

string to_string(ld x, int k) { // xの小数第k位までをstring化する
    assert(k >= 0);
    stringstream ss;
    ss << setprecision(k + 2) << x;
    string s = ss.str();
    if (s.find('.') == string::npos) s += '.';
    int pos = s.find('.');
    for (int i = 0; k >= (int)s.size() - 1 - pos; i++) s += '0';
    s.pop_back();
    if (s.back() == '.') s.pop_back();
    return s;

    // stringstream ss; // 第k+1位を四捨五入して第k位まで返す
    // ss << setprecision(k + 1) << x;
    // string s = ss.str();
    // if (s.find('.') == string::npos) s += '.';
    // int pos = s.find('.');
    // for (int i = 0; k > (int)s.size() - 1 - pos; i++) s += '0';
    // if (s.back() == '.') s.pop_back();
    // return s;
}

string to_string(__int128_t x) {
    string ret = "";
    if (x < 0) {
        ret += "-";
        x *= -1;
    }
    while (x) {
        ret += (char)('0' + x % 10);
        x /= 10;
    }
    reverse(ret.begin(), ret.end());
    return ret;
}
string to_string(char c) {
    string s = "";
    s += c;
    return s;
}

struct SXor128 {
    uint64_t x = 88172645463325252LL;
    unsigned Int() {
        x = x ^ (x << 7);
        return x = x ^ (x >> 9);
    }
    unsigned Int(unsigned mod) {
        x = x ^ (x << 7);
        x = x ^ (x >> 9);
        return x % mod;
    }
    unsigned Int(unsigned l, unsigned r) {
        x = x ^ (x << 7);
        x = x ^ (x >> 9);
        return x % (r - l + 1) + l;
    }
    double Double() {
        return double(Int()) / UINT_MAX;
    }
} rnd;

struct custom_hash {
    static uint64_t splitmix64(uint64_t x) {
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};

template<class T> size_t HashCombine(const size_t seed,const T &v){
    return seed^(hash<T>()(v)+0x9e3779b9+(seed<<6)+(seed>>2));
}
template<class T,class S> struct hash<pair<T,S>>{
    size_t operator()(const pair<T,S> &keyval) const noexcept {
        return HashCombine(hash<T>()(keyval.first), keyval.second);
    }
};
template<class T> struct hash<vector<T>>{
    size_t operator()(const vector<T> &keyval) const noexcept {
        size_t s=0;
        for (auto&& v: keyval) s=HashCombine(s,v);
        return s;
    }
};
template<int N> struct HashTupleCore{
    template<class Tuple> size_t operator()(const Tuple &keyval) const noexcept{
        size_t s=HashTupleCore<N-1>()(keyval);
        return HashCombine(s,get<N-1>(keyval));
    }
};
template <> struct HashTupleCore<0>{
    template<class Tuple> size_t operator()(const Tuple &keyval) const noexcept{ return 0; }
};
template<class... Args> struct hash<tuple<Args...>>{
    size_t operator()(const tuple<Args...> &keyval) const noexcept {
        return HashTupleCore<tuple_size<tuple<Args...>>::value>()(keyval);
    }
};

vector<mint> _fac, _finv, _inv;
void COMinit(int N) {
    _fac.resize(N + 1);
    _finv.resize(N + 1);
    _inv.resize(N + 1);
    _fac[0] = _fac[1] = 1;
    _finv[0] = _finv[1] = 1;
    _inv[1] = 1;
    for (int i = 2; i <= N; i++) {
        _fac[i] = _fac[i-1] * mint(i);
        _inv[i] = -_inv[MOD % i] * mint(MOD / i);
        _finv[i] = _finv[i - 1] * _inv[i];
    }
}

mint FAC(int N) {
    if (N < 0) return 0;
    return _fac[N];
}
mint COM(int N, int K) {
    if (N < K) return 0;
    if (N < 0 or K < 0) return 0;
    return _fac[N] * _finv[K] * _finv[N - K];
}
mint PERM(int N, int K) {
    if (N < K) return 0;
    if (N < 0 or K < 0) return 0;
    return _fac[N] *  _finv[N - K];
}
mint NHK(int N, int K) {
    if (N == 0 && K == 0)  return 1;
    return COM(N + K - 1, K);
}

#pragma endregion

struct bit_vector {
    using u32 = uint32_t;
    using i64 = int64_t;
    using u64 = uint64_t;

    static constexpr u32 w = 64;
    vector<u64> block;
    vector<u32> count;
    u32 n, zeros;

    inline u32 get(u32 i) const { return u32(block[i / w] >> (i % w)) & 1u; }
    inline void set(u32 i) { block[i / w] |= 1LL << (i % w); }

    bit_vector() {}
    bit_vector(int _n) { init(_n); }
    __attribute__((optimize("O3", "unroll-loops"))) void init(int _n) {
        n = zeros = _n;
        block.resize(n / w + 1, 0);
        count.resize(block.size(), 0);
    }

    __attribute__((target("popcnt"))) void build() {
        for (u32 i = 1; i < block.size(); i++)
        count[i] = count[i - 1] + _mm_popcnt_u64(block[i - 1]);
        zeros = rank0(n);
    }

    inline u32 rank0(u32 i) const { return i - rank1(i); }
    __attribute__((target("bmi2,popcnt"))) inline u32 rank1(u32 i) const {
        return count[i / w] + _mm_popcnt_u64(_bzhi_u64(block[i / w], i % w));
    }
};

template <typename T>
struct WaveletMatrix {
    using u32 = uint32_t;
    using i64 = int64_t;
    using u64 = uint64_t;

    int n, lg;
    vector<T> A;
    vector<bit_vector> bv;

    WaveletMatrix(u32 _n) : n(max<u32>(_n, 1)), A(n) {}
    WaveletMatrix(const vector<T>& _a) : n(_a.size()), A(_a) { build(); }

    __attribute__((optimize("O3"))) void build() {
        lg = __lg(max<T>(*max_element(begin(A), end(A)), 1)) + 1;
        bv.assign(lg, n);
        vector<T> cur = A, nxt(n);
        for (int h = lg - 1; h >= 0; h--) {
            for (int i = 0; i < n; i++) {
                if ((cur[i] >> h) & 1) bv[h].set(i);
            }
            bv[h].build();
            array<decltype(begin(nxt)), 2> it{begin(nxt), begin(nxt) + bv[h].zeros};
            for (int i = 0; i < n; i++) *it[bv[h].get(i)]++ = cur[i];
            swap(cur, nxt);
        }
        return;
    }

    void set(u32 i, const T& x) { 
        assert(x >= 0);
        A[i] = x; 
    }

    inline pair<u32, u32> succ0(int l, int r, int h) const {
        return make_pair(bv[h].rank0(l), bv[h].rank0(r));
    }

    inline pair<u32, u32> succ1(int l, int r, int h) const {
        u32 l0 = bv[h].rank0(l);
        u32 r0 = bv[h].rank0(r);
        u32 zeros = bv[h].zeros;
        return make_pair(l + zeros - l0, r + zeros - r0);
    }

    // return A[k]
    T access(u32 k) const {
        T ret = 0;
        for (int h = lg - 1; h >= 0; h--) {
            u32 f = bv[h].get(k);
            ret |= f ? T(1) << h : 0;
            k = f ? bv[h].rank1(k) + bv[h].zeros : bv[h].rank0(k);
        }
        return ret;
    }

    // k-th (0-indexed) smallest number in A[l, r)
    T kth_smallest(u32 l, u32 r, u32 k) const {
        T res = 0;
        for (int h = lg - 1; h >= 0; h--) {
            u32 l0 = bv[h].rank0(l), r0 = bv[h].rank0(r);
            if (k < r0 - l0)
                l = l0, r = r0;
            else {
                k -= r0 - l0;
                res |= (T)1 << h;
                l += bv[h].zeros - l0;
                r += bv[h].zeros - r0;
            }
        }
        return res;
    }

    // k-th (0-indexed) largest number in A[l, r)
    T kth_largest(int l, int r, int k) {
        return kth_smallest(l, r, r - l - k - 1);
    }

    // range_freq i s.t. (l <= i < r) && (v[i] < upper)
    int range_freq(int l, int r, T upper) {
        if (upper >= (T(1) << lg)) return r - l;
        int ret = 0;
        for (int h = lg - 1; h >= 0; h--) {
            bool f = (upper >> h) & 1;
            u32 l0 = bv[h].rank0(l), r0 = bv[h].rank0(r);
            if (f) {
                ret += r0 - l0;
                l += bv[h].zeros - l0;
                r += bv[h].zeros - r0;
            } else {
                l = l0;
                r = r0;
            }
        }
        return ret;
    }

    int count(int l, int r, T x) {
        return range_freq(l, r, x + 1) - range_freq(l, r, x);
    }

    int count(int l, int r, T lower, T upper) {
        return range_freq(l, r, upper) - range_freq(l, r, lower);
    }

    // max v[i] s.t. (l <= i < r) && (v[i] < upper)
    T prev_value(int l, int r, T upper) {
        int cnt = range_freq(l, r, upper);
        return cnt == 0 ? T(-1) : kth_smallest(l, r, cnt - 1);
    }

    // min v[i] s.t. (l <= i < r) && (lower <= v[i])
    T next_value(int l, int r, T lower) {
        int cnt = range_freq(l, r, lower);
        return cnt == r - l ? T(-1) : kth_smallest(l, r, cnt);
    }
};

signed main() {
    int N;
    cin >> N;
    vector<int> A(N);
    for (int i = 0; i < N; i++) {
        cin >> A[i];
        if (A[i] < 0) A[i] = INF + A[i];
    }
    WaveletMatrix<int> WM(A); // 長さNの数列による初期化を行う

    int Q;
    cin >> Q;
    for (int q = 0; q < Q; q++) {
        int l, r, x;
        cin >> l >> r >> x;
        int a = WM.next_value(l, r + 1, x);
        int b = WM.prev_value(l, r + 1, x);
        int c = WM.next_value(l, r + 1, INF);
        int d = WM.prev_value(l, r + 1, INF);

        int ans = INFL;
        if (a != -1) ans = min(ans, max(x, a) - min(x, a));
        if (b != -1) ans = min(ans, max(x, b) - min(x, b));
        if (c != -1) ans = min(ans, max(x, c) - min(x, c));
        if (d != -1) ans = min(ans, max(x, d) - min(x, d));

        cout << ans << endl;
    }
}
accuracy: 1
time_ms: 110
memory_kb: 6624
final_rank: 5

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

#line 2 "data-structure-2d/wavelet-matrix.hpp"

#include <immintrin.h>

struct bit_vector {
  using u32 = uint32_t;
  using i64 = int64_t;
  using u64 = uint64_t;

  static constexpr u32 w = 64;
  vector<u64> block;
  vector<u32> count;
  u32 n, zeros;

  inline u32 get(u32 i) const { return u32(block[i / w] >> (i % w)) & 1u; }
  inline void set(u32 i) { block[i / w] |= 1LL << (i % w); }

  bit_vector() {}
  bit_vector(int _n) { init(_n); }
  __attribute__((optimize("O3", "unroll-loops"))) void init(int _n) {
    n = zeros = _n;
    block.resize(n / w + 1, 0);
    count.resize(block.size(), 0);
  }

  __attribute__((target("popcnt"))) void build() {
    for (u32 i = 1; i < block.size(); ++i)
      count[i] = count[i - 1] + _mm_popcnt_u64(block[i - 1]);
    zeros = rank0(n);
  }

  inline u32 rank0(u32 i) const { return i - rank1(i); }
  __attribute__((target("bmi2,popcnt"))) inline u32 rank1(u32 i) const {
    return count[i / w] + _mm_popcnt_u64(_bzhi_u64(block[i / w], i % w));
  }
};

template <typename T>
struct WaveletMatrix {
  using u32 = uint32_t;
  using i64 = int64_t;
  using u64 = uint64_t;

  int n, lg;
  vector<T> a;
  vector<bit_vector> bv;

  WaveletMatrix(u32 _n) : n(max<u32>(_n, 1)), a(n) {}
  WaveletMatrix(const vector<T>& _a) : n(_a.size()), a(_a) { build(); }

  __attribute__((optimize("O3"))) void build() {
    lg = __lg(max<T>(*max_element(begin(a), end(a)), 1)) + 1;
    bv.assign(lg, n);
    vector<T> cur = a, nxt(n);
    for (int h = lg - 1; h >= 0; --h) {
      for (int i = 0; i < n; ++i)
        if ((cur[i] >> h) & 1) bv[h].set(i);
      bv[h].build();
      array<decltype(begin(nxt)), 2> it{begin(nxt), begin(nxt) + bv[h].zeros};
      for (int i = 0; i < n; ++i) *it[bv[h].get(i)]++ = cur[i];
      swap(cur, nxt);
    }
    return;
  }

  void set(u32 i, const T& x) { 
    assert(x >= 0);
    a[i] = x; 
  }

  inline pair<u32, u32> succ0(int l, int r, int h) const {
    return make_pair(bv[h].rank0(l), bv[h].rank0(r));
  }

  inline pair<u32, u32> succ1(int l, int r, int h) const {
    u32 l0 = bv[h].rank0(l);
    u32 r0 = bv[h].rank0(r);
    u32 zeros = bv[h].zeros;
    return make_pair(l + zeros - l0, r + zeros - r0);
  }

  // return a[k]
  T access(u32 k) const {
    T ret = 0;
    for (int h = lg - 1; h >= 0; --h) {
      u32 f = bv[h].get(k);
      ret |= f ? T(1) << h : 0;
      k = f ? bv[h].rank1(k) + bv[h].zeros : bv[h].rank0(k);
    }
    return ret;
  }

  // k-th (0-indexed) smallest number in a[l, r)
  T kth_smallest(u32 l, u32 r, u32 k) const {
    T res = 0;
    for (int h = lg - 1; h >= 0; --h) {
      u32 l0 = bv[h].rank0(l), r0 = bv[h].rank0(r);
      if (k < r0 - l0)
        l = l0, r = r0;
      else {
        k -= r0 - l0;
        res |= (T)1 << h;
        l += bv[h].zeros - l0;
        r += bv[h].zeros - r0;
      }
    }
    return res;
  }

  // k-th (0-indexed) largest number in a[l, r)
  T kth_largest(int l, int r, int k) {
    return kth_smallest(l, r, r - l - k - 1);
  }

  // count i s.t. (l <= i < r) && (v[i] < upper)
  int range_freq(int l, int r, T upper) {
    if (upper >= (T(1) << lg)) return r - l;
    int ret = 0;
    for (int h = lg - 1; h >= 0; --h) {
      bool f = (upper >> h) & 1;
      u32 l0 = bv[h].rank0(l), r0 = bv[h].rank0(r);
      if (f) {
        ret += r0 - l0;
        l += bv[h].zeros - l0;
        r += bv[h].zeros - r0;
      } else {
        l = l0;
        r = r0;
      }
    }
    return ret;
  }

  int range_freq(int l, int r, T lower, T upper) {
    return range_freq(l, r, upper) - range_freq(l, r, lower);
  }

  // max v[i] s.t. (l <= i < r) && (v[i] < upper)
  T prev_value(int l, int r, T upper) {
    int cnt = range_freq(l, r, upper);
    return cnt == 0 ? T(-1) : kth_smallest(l, r, cnt - 1);
  }

  // min v[i] s.t. (l <= i < r) && (lower <= v[i])
  T next_value(int l, int r, T lower) {
    int cnt = range_freq(l, r, lower);
    return cnt == r - l ? T(-1) : kth_smallest(l, r, cnt);
  }
};

/*
 * @brief Wavelet Matrix
 * @docs docs/data-structure-2d/wavelet-matrix.md
 */

int N,Q;
int A[100005];
WaveletMatrix<int> W(100005);

int main(){
  cin>>N;
  for(int i=0;i<N;i++){
    cin>>A[i];
    W.set(i,A[i]);
  }
  W.build();
  cin>>Q;
  while(Q--){
    int l,r,d; cin>>l>>r>>d;
    int p=W.prev_value(l,r+1,d),n=W.next_value(l,r+1,d);
    if(p==-1)cout<<n-d<<endl;
    else if(n==-1)cout<<d-p<<endl;
    else cout<<min(d-p,n-d)<<endl;
  }
}
accuracy: 1
time_ms: 210
memory_kb: 4956
final_rank: 11

code_snippet: /* -*- coding: utf-8 -*-
 *
 * 1549.cc: Problem I: Hard Beans
 */

#include<cstdio>
#include<vector>
#include<algorithm>
#include<utility>
#include<tuple>
 
using namespace std;

/* constant */

const int MAX_N = 100000;
const int MAX_QN = 100000;
const int INF = 1 << 30;

/* typedef */

typedef pair<int,int> pii;
typedef tuple<int,int,int,int> quadi;

template <typename T>
struct SegTreeOp {
  int e2;
  vector<T> nodes;
  T defv, (*fop)(T,T);
  SegTreeOp() {}

  void init(int n, T _defv, T (*_fop)(T,T)) {
    defv = _defv, fop = _fop;
    for (e2 = 1; e2 < n; e2 <<= 1);
    nodes.assign(e2 * 2, defv);
  }

  T &geti(int i) { return nodes[e2 - 1 + i]; }
  void seti(int i, T v) { geti(i) = v; }

  void setall() {
    for (int j = e2 - 2; j >= 0; j--)
      nodes[j] = fop(nodes[j * 2 + 1], nodes[j * 2 + 2]);
  }

  void set(int i, T v) {
    int j = e2 - 1 + i;
    nodes[j] = v;
    while (j > 0) {
      j = (j - 1) / 2;
      nodes[j] = fop(nodes[j * 2 + 1], nodes[j * 2 + 2]);
    }
  }

  T op_range(int r0, int r1, int k, int i0, int i1) {
    if (r1 <= i0 || i1 <= r0) return defv;
    if (r0 <= i0 && i1 <= r1) return nodes[k];

    int im = (i0 + i1) / 2;
    T v0 = op_range(r0, r1, k * 2 + 1, i0, im);
    T v1 = op_range(r0, r1, k * 2 + 2, im, i1);
    return fop(v0, v1);
  }
  T op_range(int r0, int r1) { return op_range(r0, r1, 0, 0, e2); }
};


/* global variables */

int as[MAX_N], res[MAX_QN];
pii ais[MAX_N];
quadi qs[MAX_QN];
SegTreeOp<int> st0, st1;

/* subroutines */

int op_min(int a, int b) { return min(a, b); }
int op_max(int a, int b) { return max(a, b); }

/* main */

int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) scanf("%d", as + i);

  for (int i = 0; i < n; i++) ais[i] = pii(as[i], i);
  sort(ais, ais + n);

  int qn;
  scanf("%d", &qn);
  for (int i = 0; i < qn; i++) {
    int l, r, d;
    scanf("%d%d%d", &l, &r, &d), r++;
    qs[i] = { d, l, r, i };
  }
  sort(qs, qs + qn);

  st0.init(n, INF, op_min);
  st1.init(n, -INF, op_max);
  for (int i = 0; i < n; i++) st0.seti(i, as[i]);
  st0.setall();

  for (int i = 0, k = 0; i < qn; i++) {
    auto [dj, lj, rj, j] = qs[i];

    while (k < n && ais[k].first < dj) {
      auto [ak, ik] = ais[k++];
      st0.set(ik, INF);
      st1.set(ik, ak);
    }

    int v0 = st0.op_range(lj, rj);
    int v1 = st1.op_range(lj, rj);
    res[j] = min(v0 - dj, dj - v1);
  }

  for (int i = 0; i < qn; i++) printf("%d\n", res[i]);
  return 0;
}
accuracy: 1
time_ms: 80
memory_kb: 7904
final_rank: 2

code_snippet: //
// Wavelet Matrix (Preprocess: O(N log N), Query: O(log N))
//
// verified:
//   Yosupu Judge - Range Kth Smallest (for k_th_smallest)
//     https://judge.yosupo.jp/problem/range_kth_smallest
//
//   Yosupu Judge - Static Range Frequency (for rank)
//     https://judge.yosupo.jp/problem/static_range_frequency
//
//   Yosupu Judge - Rectangle Sum (for BIT on WM)
//     https://judge.yosupo.jp/problem/rectangle_sum
//
//   Yosupu Judge - Point Add Rectangle Sum (for BIT on WM)
//     https://judge.yosupo.jp/problem/point_add_rectangle_sum
//
//   AtCoder ABC 234 D - Prefix K-th Max (for k_th_largest)
//     https://atcoder.jp/contests/abc234/tasks/abc234_d
//
//   AtCoder ABC 281 E - Least Elements (for top_k_sum)
//     https://atcoder.jp/contests/abc281/tasks/abc281_e
//
//   AtCoder ABC 324 E - G - Generate Arrays (for range_freq)
//     https://atcoder.jp/contests/abc324/tasks/abc324_g
//
//   AOJ 1549 Hard Beans (for prev_value, next_value)
//     https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1549
//
//   AOJ 2426 Treasure Hunt (for BIT on WM) 未 verify
//     https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2426
//


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


// Bit Vector (for 64-bit non-negative integer)
struct BitVector {
    // block: bit vector
    // count: the number of 1 within each block
    unsigned int n, zeros;
    vector<unsigned long long> block;
    vector<unsigned int> count;
    
    // constructor
    BitVector() {}
    BitVector(const unsigned int num) {
        resize(num);
    }
    void resize(const unsigned int num) {
        n = num;
        block.assign(((num + 1) >> 6) + 1, 0);
        count.assign(block.size(), 0);
    }
    
    // set val(0 or 1) onto i-th bit, get i-th bit of val(0 or 1)
    void set(const unsigned int i, const unsigned long long val = 1LL) {
        assert((i >> 6) < block.size());
        block[i >> 6] |= (val << (i & 63));
    }
    unsigned int get(const unsigned int i) const {
        assert((i >> 6) < block.size());
        return (const unsigned int)(block[i >> 6] >> (i & 63)) & 1;
    }
    void build() {
        for (unsigned int i = 1; i < block.size(); i++) {
            count[i] = count[i - 1] + __builtin_popcountll(block[i - 1]);
        }
        zeros = rank0(n);
    }
    
    // the number of 1 in [0, i)
    unsigned int rank1(const unsigned int i) const {
        assert((i >> 6) < count.size());
        assert((i >> 6) < block.size());
        return count[i >> 6] +
        __builtin_popcountll(block[i >> 6] & ((1ULL << (i & 63)) - 1ULL));
    }
    // the number of 1 in [i, j)
    unsigned int rank1(const unsigned int i, const unsigned int j) const {
        return rank1(j) - rank1(i);
    }
    // the number of 0 in [0, i)
    unsigned int rank0(const unsigned int i) const {
        return i - rank1(i);
    }
    // the number of 0 in [i, j)
    unsigned int rank0(const unsigned int i, const unsigned int j) const {
        return rank0(j) - rank0(i);
    }
    // the number of 0 in [0, n)
    unsigned int rank0() const {
        return zeros;
    }
};

// Wavelet Matrix (must vec[i] >= 0)
template<class T> struct WaveletMatrix {
    // inner data
    unsigned int n, height;
    vector<T> v;
    vector<BitVector> bv;
    vector<vector<long long>> sum;

    // constructor (sigma: the number of characters)
    WaveletMatrix() : n(0) {}
    WaveletMatrix(unsigned int n) : n(n), v(n) {}
    WaveletMatrix(const vector<T> &vec) : n(vec.size()), v(vec) {
        build();
    }
    void add(const T &val) {
        assert(v >= 0);
        v.push_back(v);
        n = v.size();
    }
    void set(unsigned int i, const T &val) {
        assert(i >= 0 && i < n && val >= 0);
        v[i] = val;
    }
    void build() {
        assert(n == (int)v.size());
        T mv = 1;
        for (int i = 0; i < n; ++i) mv = max(mv, v[i]);
        for (height = 1; mv != 0; mv >>= 1) ++height;
        vector<int> left(n), right(n), ord(n);
        iota(ord.begin(), ord.end(), 0);
        bv.assign(height, BitVector(n));
        sum.assign(height + 1, vector<long long>(n + 1, 0));
        for (int h = height - 1; h >= 0; --h) {
            int l = 0, r = 0;
            for (int i = 0; i < n; ++i) {
                if ((v[ord[i]] >> h) & 1) {
                    bv[h].set(i);
                    right[r++] = ord[i];
                } else {
                    left[l++] = ord[i];
                }
            }
            bv[h].build();
            ord.swap(left);
            for (int i = 0; i < r; ++i) ord[i + l] = right[i];
            for (int i = 0; i < n; ++i) sum[h][i + 1] = sum[h][i] + v[ord[i]];
        }
    }
    
    // access v[k]
    T access(int i) {
        T res = 0;
        for (int h = height - 1; h >= 0; --h) {
            int i0 = bv[h].rank0(i);
            if (bv[h].get(i)) {
                i += bv[h].rank0() - i0;
                res |= T(1) << h;
            } else {
                i = i0;
            }
        }
        return res;
    }
    T operator [] (int i) {
        return access(i);
    }
    
    // count "i" s.t. v[i] = val, i \in [l, r)
    int rank(int l, int r, const T &val) {
        assert(0 <= l && l <= r && r <= n);
        for (int h = height - 1; h >= 0; --h) {
            int l0 = bv[h].rank0(l), r0 = bv[h].rank0(r);
            if ((val >> h) & 1) {
                l += bv[h].rank0() - l0;
                r += bv[h].rank0() - r0;
            } else {
                l = l0;
                r = r0;
            }
        }
        return r - l;
    }
    
    // count "i" s.t. v[i] \in [lower, upper), i \in [l, r)
    int range_freq(int l, int r, const T &upper) {
        assert(0 <= l && l <= r && r <= n);
        int res = 0;
        for (int h = height - 1; h >= 0; --h) {
            int l0 = bv[h].rank0(l), r0 = bv[h].rank0(r);
            if ((upper >> h) & 1) {
                l += bv[h].rank0() - l0;
                r += bv[h].rank0() - r0;
                res += r0 - l0;
            } else {
                l = l0;
                r = r0;
            }
        }
        return res;
    }
    int range_freq(int l, int r, const T &lower, const T &upper) {
        return range_freq(l, r, upper) - range_freq(l, r, lower);
    }
    
    // the k-th (0-indexed) smallest value in [l, r)
    T k_th_smallest(int l, int r, int k) {
        assert(0 <= l && l <= r && r <= n);
        T res = 0;
        for (int h = height - 1; h >= 0; --h) {
            int l0 = bv[h].rank0(l), r0 = bv[h].rank0(r);
            if (r0 - l0 <= k) {
                l += bv[h].rank0() - l0;
                r += bv[h].rank0() - r0;
                k -= r0 - l0;
                res |= T(1) << h;
            } else {
                l = l0;
                r = r0;
            }
        }
        return res;
    }
    
    // the k-th (0-indexed) largest value in [l, r)
    T k_th_largest(int l, int r, int k) {
        assert(0 <= l && l <= r && r <= n);
       return k_th_smallest(l, r, r - l - k - 1);
    }
    
    // the sum of the top-k sum in [l, r)
    T top_k_sum(int l, int r, int k) {
        assert(0 <= l && l <= r && r <= n);
        if (l == r) return 0;
        T res = 0, val = 0;
        for (int h = height - 1; h >= 0; --h) {
            int l0 = bv[h].rank0(l), r0 = bv[h].rank0(r);
            if (r0 - l0 <= k) {
                l += bv[h].rank0() - l0;
                r += bv[h].rank0() - r0;
                k -= r0 - l0;
                val |= T(1) << h;
                res += sum[h][r0] - sum[h][l0];
            } else {
                l = l0;
                r = r0;
            }
        }
        res += val * k;
        return res;
    }
    
    // the max value (< val) in [l, r)
    T prev_value(int l, int r, T val) {
        assert(0 <= l && l <= r && r <= n);
        int num = range_freq(l, r, 0, val);
        if (num == 0) return T(-1);
        else return k_th_smallest(l, r, num - 1);
    }
    
    // the min value (>= val) in [l, r)
    T next_value(int l, int r, T val) {
        assert(0 <= l && l <= r && r <= n);
        int num = range_freq(l, r, 0, val);
        if (num == r - l) return T(-1);
        else return k_th_smallest(l, r, num);
    }
};


// 2D queries
template<class POS, class VAL> struct BITonWaveletMatrix {
    // inner data
    struct BIT {
        VAL UNITY_SUM = 0;
        int N;
        vector<VAL> dat;
        
        // [0, n)
        BIT() {}
        BIT(int n, VAL unity = 0) : UNITY_SUM(unity), N(n), dat(n, unity) { }
        void init(int n) {
            N = n;
            dat.assign(n, UNITY_SUM);
        }
        
        // a is 0-indexed
        void add(int a, VAL x) {
            for (int i = a; i < (int)dat.size(); i |= i + 1)
                dat[i] = dat[i] + x;
        }
        
        // [0, a), a is 0-indexed
        VAL sum(int a) {
            VAL res = UNITY_SUM;
            for (int i = a - 1; i >= 0; i = (i & (i + 1)) - 1)
                res = res + dat[i];
            return res;
        }
        
        // [a, b), a and b are 0-indexed
        VAL sum(int a, int b) {
            return sum(b) - sum(a);
        }
        
        // debug
        void print() {
            for (int i = 0; i < (int)dat.size(); ++i)
                cout << sum(i, i + 1) << ",";
            cout << endl;
        }
    };
    
    using Point = pair<POS, POS>;
    int n, height;
    vector<BitVector> bv;
    vector<Point> ps;
    vector<POS> ys;
    vector<BIT> bit;

    // constructor (sigma: the number of characters)
    // add_point() cannot be used after build()
    BITonWaveletMatrix() {}
    BITonWaveletMatrix(const vector<Point> &vec) {
        for (auto [x, y] : vec) add_point(x, y);
        build();
    }
    void add_point(POS x, POS y) {
        ps.emplace_back(x, y);
        ys.emplace_back(y);
    }
    int xid(POS x) const {
        return lower_bound(ps.begin(), ps.end(), Point(x, 0)) - ps.begin();
    }
    int yid(POS y) const {
        return lower_bound(ys.begin(), ys.end(), y) - ys.begin();
    }
    void build() {
        sort(ps.begin(), ps.end());
        ps.erase(unique(ps.begin(), ps.end()), ps.end());
        n = (int)ps.size();
        sort(ys.begin(), ys.end());
        ys.erase(unique(ys.begin(), ys.end()), ys.end());
        vector<int> v(n), left(n), right(n), ord(n);
        int mv = 1;
        for (int i = 0; i < n; ++i) {
            v[i] = yid(ps[i].second);
            mv = max(mv, v[i]);
        }
        for (height = 1; mv != 0; mv >>= 1) ++height;
        iota(ord.begin(), ord.end(), 0);
        bv.resize(height, BitVector(n));
        bit.assign(height + 1, BIT(n));
        for (int h = height - 1; h >= 0; --h) {
            int l = 0, r = 0;
            for (int i = 0; i < n; ++i) {
                if ((v[ord[i]] >> h) & 1) {
                    bv[h].set(i);
                    right[r++] = ord[i];
                } else {
                    left[l++] = ord[i];
                }
            }
            bv[h].build();
            ord.swap(left);
            for (int i = 0; i < r; ++i) ord[i + l] = right[i];
        }
    }
    
    // add
    void add(const POS x, const POS y, const VAL val) {
        int i = lower_bound(ps.begin(), ps.end(), Point(x, y)) - ps.begin();
        int j = yid(y);
        for (int h = height - 1; h >= 0; --h) {
            int i0 = bv[h].rank0(i);
            if ((j >> h) & 1) {
                i += bv[h].rank0() - i0;
            } else {
                i = i0;
            }
            bit[h].add(i, val);
        }
    }
    
    // sum
    VAL inner_sum(int l, int r, const POS upper) {
        assert(0 <= l && r <= n);
        VAL res = 0;
        for (int h = height - 1; h >= 0; --h) {
            int l0 = bv[h].rank0(l), r0 = bv[h].rank0(r);
            if ((upper >> h) & 1) {
                l += bv[h].rank0() - l0;
                r += bv[h].rank0() - r0;
                res += bit[h].sum(l0, r0);
            } else {
                l = l0;
                r = r0;
            }
        }
        return res;
    }
    VAL sum(const POS lx, const POS rx, const POS ly, const POS ry) {
        int l = xid(lx), r = xid(rx);
        return inner_sum(l, r, yid(ry)) - inner_sum(l, r, yid(ly));
    }
};



/*/////////////////////////////*/
// Examples
/*/////////////////////////////*/

void YosupoRangeKthSmallest() {
    int N, Q;
    cin >> N >> Q;
    vector<int> a(N);
    for (int i = 0; i < N; ++i) cin >> a[i];
    
    WaveletMatrix<int> wm(a);
    for (int q = 0; q < Q; ++q) {
        int l, r, k;
        cin >> l >> r >> k;
        cout << wm.k_th_smallest(l, r, k) << endl;
    }
}

void YosupoStaticRangeFrequency() {
    int N, Q;
    cin >> N >> Q;
    vector<int> a(N);
    for (int i = 0; i < N; ++i) cin >> a[i];
    
    WaveletMatrix<int> wm(a);
    for (int q = 0; q < Q; ++q) {
        int l, r, x;
        cin >> l >> r >> x;
        cout << wm.rank(l, r, x) << endl;
    }
}

void YosupoRectangleSum() {
    BITonWaveletMatrix<int, long long> wm;
    
    int N, Q;
    cin >> N >> Q;
    vector<int> ix(N), iy(N), iw(N), lx(Q), ly(Q), rx(Q), ry(Q);
    for (int i = 0; i < N; ++i) {
        cin >> ix[i] >> iy[i] >> iw[i];
        wm.add_point(ix[i], iy[i]);
    }
    
    wm.build();
    
    for (int i = 0; i < N; ++i) {
        wm.add(ix[i], iy[i], iw[i]);
    }
    for (int q = 0; q < Q; ++q) {
        cin >> lx[q] >> ly[q] >> rx[q] >> ry[q];
        cout << wm.sum(lx[q], rx[q], ly[q], ry[q]) << endl;
    }
}

void YosupoJudgePointAddRectangleSum() {
    BITonWaveletMatrix<int, long long> wm;
    
    int N, Q;
    cin >> N >> Q;
    vector<int> ix(N), iy(N), iw(N), type(Q), lx(Q), ly(Q), rx(Q), ry(Q);
    for (int i = 0; i < N; ++i) {
        cin >> ix[i] >> iy[i] >> iw[i];
        wm.add_point(ix[i], iy[i]);
    }
    for (int q = 0; q < Q; ++q) {
        cin >> type[q];
        if (type[q] == 0) {
            cin >> lx[q] >> ly[q] >> rx[q];
            wm.add_point(lx[q], ly[q]);
        }
        else cin >> lx[q] >> ly[q] >> rx[q] >> ry[q];
    }
    
    wm.build();
    for (int i = 0; i < N; ++i) {
        wm.add(ix[i], iy[i], iw[i]);
    }
    for (int q = 0; q < Q; ++q) {
        if (type[q] == 0) {
            wm.add(lx[q], ly[q], rx[q]);
        } else {
            cout << wm.sum(lx[q], rx[q], ly[q], ry[q]) << endl;
        }
    }
}

void ABC_234_D() {
    int N, K;
    cin >> N >> K;
    vector<int> P(N);
    for (int i = 0; i < N; ++i) cin >> P[i];
    
    WaveletMatrix wm(P);
    for (int i = K; i <= N; ++i) {
        cout << wm.k_th_largest(0, i, K - 1) << endl;
    }
}

void ABC_281_E() {
    int N, M, K;
    cin >> N >> M >> K;
    vector<long long> A(N);
    for (int i = 0; i < N; ++i) cin >> A[i];
    
    WaveletMatrix wm(A);
    for (int i = 0; i < N - M + 1; ++i) {
        cout << wm.top_k_sum(i, i + M, K) << " ";
    }
    cout << endl;
}

void ABC_324_G() {
    int N, Q;
    cin >> N;
    vector<int> A(N);
    for (int i = 0; i < N; ++i) cin >> A[i];
    
    WaveletMatrix<int> wm(A);

    cin >> Q;
    vector<int> left(Q+1, 0), right(Q+1, N), lower(Q+1, 1), upper(Q+1, N+1);
    for (int q = 0; q < Q; ++q) {
        int t, s, v;
        cin >> t >> s >> v;
        if (t == 1) {
            // [left, x) 内部の lower 以上 upper 未満の値が v 個以上である最小の x を求める
            int low = left[s] - 1, high = N + 1;
            while (high - low > 1) {
                int mid = (low + high) / 2;
                if (wm.range_freq(left[s], mid, lower[s], upper[s]) >= v) high = mid;
                else low = mid;
            }
            
            // [left, high) と [high, right) とに分割する
            high = min(high, right[s]);
            left[q+1] = high;
            right[q+1] = right[s];
            lower[q+1] = lower[s];
            upper[q+1] = upper[s];
            right[s] = high;
        } else {
            // 値が v 未満と v 以上に分ける
            ++v;
            v = max(v, lower[s]);
            v = min(v, upper[s]);
            left[q+1] = left[s];
            right[q+1] = right[s];
            lower[q+1] = v;
            upper[q+1] = upper[s];
            upper[s] = v;
        }
        cout << wm.range_freq(left[q+1], right[q+1], lower[q+1], upper[q+1]) << endl;
    }
}

void AOJ_1549() {
    int N, Q;
    cin >> N;
    const int GETA = 1100000;
    vector<int> a(N);
    for (int i = 0; i < N; ++i) {
        cin >> a[i];
        a[i] += GETA;
    }
    
    WaveletMatrix<int> wm(a);
    cin >> Q;
    while (Q--) {
        int l, r, d;
        cin >> l >> r >> d;
        ++r;
        d += GETA;
        
        int nex = wm.next_value(l, r, d);
        int pre = wm.prev_value(l, r, d);
        int res = GETA*2;
        if (nex != -1) res = min(res, nex - d);
        if (pre != -1) res = min(res, d - pre);
        cout << res << endl;
    }
}

void AOJ_2426() {
    BITonWaveletMatrix<long long, long long> wm;
    
    int N, M;
    cin >> N >> M;
    vector<long long> x(N), y(N), lx(M), ly(M), rx(M), ry(M);
    for (int i = 0; i < N; ++i) {
        cin >> x[i] >> y[i];
        wm.add_point(x[i], y[i]);
    }
    for (int i = 0; i < M; ++i) {
        cin >> lx[i] >> ly[i] >> rx[i] >> ry[i];
    }
    
    wm.build();
    
    for (int i = 0; i < N; ++i) {
        wm.add(x[i], y[i], 1);
    }
    for (int i = 0; i < M; ++i) {
        cout << wm.sum(lx[i], rx[i], ly[i], ry[i]) << endl;
    }
}


int main() {
    //YosupoRangeKthSmallest();
    //YosupoStaticRangeFrequency();
    //YosupoRectangleSum();
    //YosupoJudgePointAddRectangleSum();
    //ABC_234_D();
    //ABC_281_E();
    //ABC_324_G();
    AOJ_1549();
    //AOJ_2426();
}
accuracy: 1
time_ms: 300
memory_kb: 25060
final_rank: 19

code_snippet: //
// Wavelet Matrix (Preprocess: O(N log N), Query: O(log N))
//
// verified:
//   AtCoder ABC 234 D - Prefix K-th Max (for k_th_largest)
//     https://atcoder.jp/contests/abc234/tasks/abc234_d
//
//   AtCoder ABC 281 E - Least Elements (for top_k_sum)
//     https://atcoder.jp/contests/abc281/tasks/abc281_e
//
//   AtCoder ABC 324 E - G - Generate Arrays (for range_freq)
//     https://atcoder.jp/contests/abc324/tasks/abc324_g
//
//   AOJ 1549 Hard Beans (for prev_value, next_value)
//     https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1549
//
//   AOJ 2426 Treasure Hunt (for 2D queries)
//     https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2426
//


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


// Bit Vector
struct BitVector {
    // block: bit vector
    // count: the number of 1 within each block
    unsigned int n, zeros;
    vector<unsigned long long> block;
    vector<unsigned int> count;
    
    // constructor
    BitVector() {}
    BitVector(const unsigned int num) {
        resize(num);
    }
    void resize(const unsigned int num) {
        n = num;
        block.resize(((num + 1) >> 6) + 1, 0);
        count.resize(block.size(), 0);
    }
    
    // set val(0 or 1) onto i-th bit, get i-th bit of val(0 or 1)
    void set(const unsigned int i, const unsigned long long val) {
        block[i >> 6] |= (val << (i & 63));
    }
    unsigned int get(const unsigned int i) const {
        return (const unsigned int)(block[i >> 6] >> (i & 63)) & 1;
    }
    void build() {
        for (unsigned int i = 1; i < block.size(); i++) {
            count[i] = count[i - 1] + __builtin_popcountll(block[i - 1]);
        }
        zeros = rank0(n);
    }
    
    // the number of 1 in [0, i)
    unsigned int rank1(const unsigned int i) const {
        return count[i >> 6] +
        __builtin_popcountll(block[i >> 6] & ((1ULL << (i & 63)) - 1ULL));
    }
    // the number of 1 in [i, j)
    unsigned int rank1(const unsigned int i, const unsigned int j) const {
        return rank1(j) - rank1(i);
    }
    // the number of 0 in [0, i)
    unsigned int rank0(const unsigned int i) const {
        return i - rank1(i);
    }
    // the number of 0 in [i, j)
    unsigned int rank0(const unsigned int i, const unsigned int j) const {
        return rank0(j) - rank0(i);
    }
};

// Wavelet Matrix (must vec[i] >= 0)
template<class T> struct WaveletMatrix {
    // inner data
    int height;
    vector<BitVector> bv;
    vector<vector<long long>> sum;

    // constructor (sigma: the number of characters)
    WaveletMatrix() {}
    WaveletMatrix(vector<T> vec) :
        WaveletMatrix(vec, *max_element(vec.begin(), vec.end()) + 1) {}
    WaveletMatrix(vector<T> vec, T sigma) {
        init(vec, sigma);
    }
    void init(vector<T> &vec, T sigma) {
        height = (sigma == 1) ? 1 : (64 - __builtin_clzll(sigma - 1));
        bv.resize(height);
        vector<T> A = vec;
        sum.resize(height + 1);
        for (int h = 0; h < height; ++h) {
            bv[h].resize(vec.size());
            for (int j = 0; j < vec.size(); ++j) {
                bv[h].set(j, get(vec[j], height - h - 1));
            }
            bv[h].build();
            stable_partition(vec.begin(), vec.end(), [&](int c) {
                return !get(c, height - h - 1);
            });
        }
        for (int h = 0; h <= height; ++h) {
            sum[h].resize((int)A.size() + 1);
            for (int j = 1; j <= (int)A.size(); ++j) {
                sum[h][j] = sum[h][j - 1] + A[j - 1];
            }
            if (h == height) break;
            stable_partition(A.begin(), A.end(), [&](int c) {
                return !get(c, height - h - 1);
            });
        }
    }
    
    // the i-th bit of "val" (0 or 1)
    int get(const T val, const int i) {
        return val >> i & 1;
    }
    
    // the number of "val" in [l, r)
    int rank(const T val, const int l, const int r) {
        return rank(val, r) - rank(val, l);
    }
    
    // the number of "val" in [0, i)
    int rank(T val, int i) {
        int p = 0;
        for (int h = 0; h < height; ++h) {
            int p0 = bv[h].rank0(p), i0 = bv[h].rank0(i);
            if (get(val, height - h - 1)) {
                p += bv[h].zeros - p0;
                i += bv[h].zeros - i0;
            } else {
                p = p0;
                i = i0;
            }
        }
        return i - p;
    }
    
    // the k-th (0-indexed) smallest value in [l, r)
    T k_th_smallest(int k, int l, int r) {
        T res = 0;
        for (int h = 0; h < height; ++h) {
            int l0 = bv[h].rank0(l), r0 = bv[h].rank0(r);
            if (r0 - l0 > k) {
                l = l0;
                r = r0;
            } else {
                l += bv[h].zeros - l0;
                r += bv[h].zeros - r0;
                k -= r0 - l0;
                res |= (1LL << (height - h - 1));
            }
        }
        return res;
    }
    
    // the k-th (0-indexed) largest value in [l, r)
    T k_th_largest(int k, int l, int r) {
       return k_th_smallest(r - l - k - 1, l, r);
    }
    
    // the sum of the top-k sum in [l, r)
    T top_k_sum(int k, int l, int r) {
        if (l == r) return 0;
        T res = 0, val = 0;
        for (int h = 0; h < height; ++h) {
            int l0 = bv[h].rank0(l), r0 = bv[h].rank0(r);
            if (r0 - l0 > k) {
                l = l0;
                r = r0;
            } else {
                l += bv[h].zeros - l0;
                r += bv[h].zeros - r0;
                k -= r0 - l0;
                val |= (1LL << (height - h - 1));
                res += sum[h + 1][r0] - sum[h + 1][l0];
            }
        }
        res += (long long)val * k;
        return res;
    }
    
    // the number of value between [loewr, upper) in [l, r)
    int range_freq(const int i, const int j, const T lower, const T upper,
                   const int l, const int r, const int h) {
        if (i == j || r <= lower || upper <= l) return 0;
        int mid = (l + r) >> 1;
        if (lower <= l && r <= upper) {
            return j - i;
        } else {
            int i0 = bv[h].rank0(i), j0 = bv[h].rank0(j);
            T left = range_freq(i0, j0, lower, upper, l, mid, h + 1);
            T right = range_freq(i + bv[h].zeros - i0, j + bv[h].zeros - j0,
                                 lower, upper, mid, r, h + 1);
            return left + right;
        }
    }
    int range_freq(const int l, const int r, const T lower, const T upper) {
        return range_freq(l, r, lower, upper, 0, 1LL << height, 0);
    }
    
    // the minmum value between [lower, upper) in [l, r)
    T range_min(const int i, const int j, const T lower, const T upper,
                  const int l, const int r, const int h, const T val) {
        if (i == j || r <= lower || upper <= l) return -1;
        if (r - l == 1) return val;
        int mid = (l + r) >> 1;
        int i0 = bv[h].rank0(i), j0 = bv[h].rank0(j);
        T res = range_min(i0, j0, lower, upper, l, mid, h + 1, val);
        if (res < 0) {
            return range_min(i + bv[h].zeros - i0, j + bv[h].zeros - j0,
                             lower, upper, mid, r, h + 1, val + (1LL << (height - h - 1)));
        } else return res;
    }
    T range_min(int l, int r, T lower, T upper) {
        return range_min(l, r, lower, upper, 0, 1LL << height, 0, 0);
    }
    
    // the max value (< val) in [l, r)
    T prev_value(int l, int r, T val) {
        int num = range_freq(l, r, 0, val);
        if (num == 0) return T(-1);
        else return k_th_smallest(num - 1, l, r);
    }
    
    // the min value (>= val) in [l, r)
    T next_value(int l, int r, T val) {
        int num = range_freq(l, r, 0, val);
        if (num == r - l) return T(-1);
        else return k_th_smallest(num, l, r);
    }
};

// 2D range count
template<class POS, class VAL> struct BITonWaveletMatrix {
    // inner data
    struct BIT {
        VAL UNITY_SUM = 0;
        vector<VAL> dat;
        
        // [0, n)
        BIT(int n, VAL unity = 0) : UNITY_SUM(unity), dat(n, unity) { }
        void init(int n) {
            dat.assign(n, UNITY_SUM);
        }
        
        // a is 0-indexed
        void add(int a, VAL x) {
            for (int i = a; i < (int)dat.size(); i |= i + 1)
                dat[i] = dat[i] + x;
        }
        
        // [0, a), a is 0-indexed
        VAL sum(int a) {
            VAL res = UNITY_SUM;
            for (int i = a - 1; i >= 0; i = (i & (i + 1)) - 1)
                res = res + dat[i];
            return res;
        }
        
        // [a, b), a and b are 0-indexed
        VAL sum(int a, int b) {
            return sum(b) - sum(a);
        }
        
        // debug
        void print() {
            for (int i = 0; i < (int)dat.size(); ++i)
                cout << sum(i, i + 1) << ",";
            cout << endl;
        }
    };
    
    using Point = pair<POS, POS>;
    int n, height;
    vector<BitVector> bv;
    vector<Point> ps;
    vector<POS> ys;
    vector<int> pos;
    vector<BIT> bit;

    // constructor (sigma: the number of characters)
    // add_point() cannot be used after init()
    BITonWaveletMatrix() {}
    BITonWaveletMatrix(vector<Point> vec) {
        for (auto [x, y] : vec) add_point(x, y);
        init();
    }
    void add_point(POS x, POS y) {
        ps.emplace_back(x, y);
        ys.emplace_back(y);
    }
    int xid(POS x) const {
        return lower_bound(ps.begin(), ps.end(), make_pair(x, Point(0, 0)),
                           [](const Point& a, const Point& b) { return a.first < b.first; }) -
        ps.begin();
    }
    int yid(POS y) const {
        return lower_bound(ys.begin(), ys.end(), y) - ys.begin();
    }
    void init() {
        sort(ps.begin(), ps.end());
        ps.erase(unique(ps.begin(), ps.end()), ps.end());
        n = (int)ps.size();
        sort(ys.begin(), ys.end());
        ys.erase(unique(ys.begin(), ys.end()), ys.end());
        vector<int> vec(n);
        for (int i = 0; i < n; ++i) vec[i] = yid(ps[i].second);
        POS sigma = *max_element(vec.begin(), vec.end()) + 1;
        height = (sigma == 1) ? 1 : (64 - __builtin_clzll(sigma - 1));
        bv.resize(height), pos.resize(height), bit.resize(height, BIT(n));
        for (int i = 0; i < height; ++i) {
            bv[i].resize(vec.size());
            for (int j = 0; j < vec.size(); ++j) {
                bv[i].set(j, get(vec[j], height - i - 1));
            }
            bv[i].build();
            auto it = stable_partition(vec.begin(), vec.end(), [&](int c) {
                return !get(c, height - i - 1);
            });
            pos[i] = it - vec.begin();
        }
    }
    
    // the i-th bit of "y" (0 or 1)
    int get(const POS y, const int i) {
        return y >> i & 1;
    }
    
    // the number of "y" in [l, r)
    int rank(const POS y, const int l, const int r) {
        return rank(y, r) - rank(y, l);
    }
    
    // the number of "y" in [0, i)
    int rank(const POS y, int i) {
        int p = 0;
        for (int j = 0; j < height; ++j) {
            if (get(y, height - j - 1)) {
                p = pos[j] + bv[j].rank1(p);
                i = pos[j] + bv[j].rank1(i);
            } else {
                p = bv[j].rank0(p);
                i = bv[j].rank0(i);
            }
        }
        return i - p;
    }
    
    /*
    // add
    void add(const POS x, const POS y, const VAL val) {
        int l = lower_bound(ps.begin(), ps.end(), Point(x, y)) - ps.begin();
        for (int i = height - 1; i >= 0; --i) {
            int l0 = bv[i].rank0(l);
            if (bv[i].get(l)) {
                l = pos[i] + bv[i].rank1(l);
            } else {
                l = l0;
            }
            bit[i].add(i, val);
        }
    }
     */
    
    // sum
    VAL inner_sum(int l, int r, const POS upper) const {
        VAL res = 0;
        for (int i = height; i >= 1; --i) {
            int l0 = bv[i].rank0(l), r0 = bv[i].rank0(r);
            if ((upper >> i) & 1) {
                res += bit[i].sum(l0, r0);
                l += bv[i].zeros - l0;
                r += bv[i].zeros - r0;
            } else {
                l = l0;
                r = r0;
            }
        }
    }
    
    VAL sum(const POS lx, const POS rx, const POS ly, const POS ry) const {
        lx = xid(lx), rx = xid(rx), ly = xid(ly), ry = yid(ry);
        
    }
    
    /*
    // the k-th (0-indexed) smallest value in [l, r)
    T k_th_smallest(int k, int l, int r) {
        T res = 0;
        for (int i = 0; i < height; ++i) {
            const int j = bv[i].rank0(l, r);
            if (j > k){
                l = bv[i].rank0(l);
                r = bv[i].rank0(r);
            } else {
                l = pos[i] + bv[i].rank1(l);
                r = pos[i] + bv[i].rank1(r);
                k -= j;
                res |= (1LL << (height - i - 1));
            }
        }
        return res;
    }
    
    // the k-th (0-indexed) largest value in [l, r)
    T k_th_largest(int k, int l, int r) {
       return k_th_smallest(r - l - k - 1, l, r);
    }
    
    // the number of value between [loewr, upper) in [l, r)
    int range_freq(const int i, const int j, const T lower, const T upper,
                   const int l, const int r, const int x) {
        if (i == j || r <= lower || upper <= l) return 0;
        int mid = (l + r) >> 1;
        if (lower <= l && r <= upper) {
            return j - i;
        } else {
            T left = range_freq(bv[x].rank0(i), bv[x].rank0(j), lower, upper, l, mid, x + 1);
            T right = range_freq(pos[x] + bv[x].rank1(i), pos[x] + bv[x].rank1(j),
                                 lower, upper, mid, r, x + 1);
            return left + right;
        }
    }
    int range_freq(const int l, const int r, const T lower, const T upper) {
        return range_freq(l, r, lower, upper, 0, 1LL << height, 0);
    }
    
    // the minmum value between [lower, upper) in [l, r)
    T range_min(const int i, const int j, const T lower, const T upper,
                  const int l, const int r, const int x, const T val) {
        if (i == j || r <= lower || upper <= l) return -1;
        if (r - l == 1) return val;
        int mid = (l + r) >> 1;
        T res = range_min(bv[x].rank0(i), bv[x].rank0(j), lower, upper, l, mid, x + 1, val);
        if (res < 0) {
            return range_min(pos[x] + bv[x].rank1(i), pos[x] + bv[x].rank1(j),
                             lower, upper, mid, r, x + 1, val + (1LL << (height - x - 1)));
        } else return res;
    }
    T range_min(int l, int r, T lower, T upper) {
        return range_min(l, r, lower, upper, 0, 1LL << height, 0, 0);
    }
    
    // the max value (< val) in [l, r)
    T prev_value(int l, int r, T val) {
        int num = range_freq(l, r, 0, val);
        if (num == 0) return T(-1);
        else return k_th_smallest(num - 1, l, r);
    }
    
    // the min value (>= val) in [l, r)
    T next_value(int l, int r, T val) {
        int num = range_freq(l, r, 0, val);
        if (num == r - l) return T(-1);
        else return k_th_smallest(num, l, r);
    }
     */
};

/*
template<class T> struct OrthogonalRangeCount {
    // inner data
    using ptt = pair<T, T>;
    const int sz;
    vector<T> X, Y;
    WaveletMatrix<T> wm;
    
    // constructor
    OrthogonalRangeCount(vector<ptt> candidate) : sz((int)candidate.size()), X(sz), Y(sz) {
        sort(candidate.begin(), candidate.end());
        vector<int> vec(sz);
        for (int i = 0; i < sz; ++i) {
            X[i] = candidate[i].first, Y[i] = candidate[i].second;
        }
        sort(Y.begin(), Y.end());
        Y.erase(unique(Y.begin(), Y.end()), Y.end());
        for (int i = 0; i < sz; ++i) {
            vec[i] = lower_bound(Y.begin(), Y.end(), candidate[i].second) - Y.begin();
        }
        wm.init(vec, Y.size());
    }
    
    // the number of points in [lx, rx) × [ly, ry)
    int query(const T lx, const T ly, const T rx, const T ry){
        const int lxid = lower_bound(X.begin(), X.end(), lx) - X.begin();
        const int rxid = lower_bound(X.begin(), X.end(), rx) - X.begin();
        const int lyid = lower_bound(Y.begin(), Y.end(), ly) - Y.begin();
        const int ryid = lower_bound(Y.begin(), Y.end(), ry) - Y.begin();
        if (lxid >= rxid || lyid >= ryid) return 0;
        return wm.range_freq(lxid, rxid, lyid, ryid);
    }
};
 */



/*/////////////////////////////*/
// Examples
/*/////////////////////////////*/

void ABC_234_D() {
    int N, K;
    cin >> N >> K;
    vector<int> P(N);
    for (int i = 0; i < N; ++i) cin >> P[i];
    
    WaveletMatrix wm(P);
    for (int i = K; i <= N; ++i) {
        cout << wm.k_th_largest(K - 1, 0, i) << endl;
    }
}

void ABC_281_E() {
    int N, M, K;
    cin >> N >> M >> K;
    vector<long long> A(N);
    for (int i = 0; i < N; ++i) cin >> A[i];
    
    WaveletMatrix wm(A);
    for (int i = 0; i < N - M + 1; ++i) {
        cout << wm.top_k_sum(K, i, i + M) << " ";
    }
    cout << endl;
}

void ABC_324_G() {
    int N, Q;
    cin >> N;
    vector<int> A(N);
    for (int i = 0; i < N; ++i) cin >> A[i];
    
    WaveletMatrix<int> wm(A);
    cin >> Q;
    vector<int> left(Q+1, 0), right(Q+1, N), lower(Q+1, 1), upper(Q+1, N+1);
    for (int q = 0; q < Q; ++q) {
        int t, s, v;
        cin >> t >> s >> v;
        if (t == 1) {
            // [left, x) 内部の lower 以上 upper 未満の値が v 個以上である最小の x を求める
            int low = left[s] - 1, high = N + 1;
            while (high - low > 1) {
                int mid = (low + high) / 2;
                if (wm.range_freq(left[s], mid, lower[s], upper[s]) >= v) high = mid;
                else low = mid;
            }
            
            // [left, high) と [high, right) とに分割する
            high = min(high, right[s]);
            left[q+1] = high;
            right[q+1] = right[s];
            lower[q+1] = lower[s];
            upper[q+1] = upper[s];
            right[s] = high;
        } else {
            // 値が v 未満と v 以上に分ける
            ++v;
            v = max(v, lower[s]);
            v = min(v, upper[s]);
            left[q+1] = left[s];
            right[q+1] = right[s];
            lower[q+1] = v;
            upper[q+1] = upper[s];
            upper[s] = v;
        }
        cout << wm.range_freq(left[q+1], right[q+1], lower[q+1], upper[q+1]) << endl;
    }
}

void AOJ_1549() {
    int N, Q;
    cin >> N;
    const int GETA = 1100000;
    vector<int> a(N);
    for (int i = 0; i < N; ++i) {
        cin >> a[i];
        a[i] += GETA;
    }
    
    WaveletMatrix<int> wm(a);
    cin >> Q;
    while (Q--) {
        int l, r, d;
        cin >> l >> r >> d;
        ++r;
        d += GETA;
        
        int nex = wm.next_value(l, r, d);
        int pre = wm.prev_value(l, r, d);
        int res = GETA*2;
        if (nex != -1) res = min(res, nex - d);
        if (pre != -1) res = min(res, d - pre);
        cout << res << endl;
    }
}

void AOJ_2426() {
    BITonWaveletMatrix<long long, long long> wm;
    
    int N, M;
    cin >> N >> M;
    vector<long long> x(N), y(N), lx(M), ly(M), rx(M), ry(M);
    for (int i = 0; i < N; ++i) {
        cin >> x[i] >> y[i];
        wm.add_point(x[i], y[i]);
    }
    for (int i = 0; i < M; ++i) {
        cin >> lx[i] >> ly[i] >> rx[i] >> ry[i];
        ++rx[i], ++ry[i];
        wm.add_point(lx[i], ly[i]);
        wm.add_point(rx[i], ry[i]);
    }
    
    
}


int main() {
    //ABC_234_D();
    //ABC_281_E();
    //ABC_324_G();
    AOJ_1549();
    //AOJ_2426();
}
accuracy: 1
time_ms: 250
memory_kb: 23592
final_rank: 16

code_snippet: //
// Wavelet Matrix (Preprocess: O(N log N), Query: O(log N))
//
// verified:
//   AtCoder ABC 234 D - Prefix K-th Max (for k_th_largest)
//     https://atcoder.jp/contests/abc281/tasks/abc281_e
//
//   AtCoder ABC 281 E - Least Elements (for top_k_sum)
//     https://atcoder.jp/contests/abc281/tasks/abc281_e
//
//   AtCoder ABC 324 E - G - Generate Arrays (for range_freq)
//     https://atcoder.jp/contests/abc324/tasks/abc324_g
//
//   AOJ 1549 Hard Beans (for prev_value, next_value)
//     https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1549
//


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


// Bit Vector
struct BitRank {
    // block: bit vector
    // count: the number of 1 within each block
    vector<unsigned long long> block;
    vector<unsigned int> count;
    
    // constructor
    BitRank() {}
    void resize(const unsigned int num) {
        block.resize(((num + 1) >> 6) + 1, 0);
        count.resize(block.size(), 0);
    }
    
    // set val(0 or 1) onto i-th bit
    void set(const unsigned int i, const unsigned long long val) {
        block[i >> 6] |= (val << (i & 63));
    }
    void build() {
        for (unsigned int i = 1; i < block.size(); i++) {
            count[i] = count[i - 1] + __builtin_popcountll(block[i - 1]);
        }
    }
    
    // the number of 1 in [0, i)
    unsigned int rank1(const unsigned int i) const {
        return count[i >> 6] +
        __builtin_popcountll(block[i >> 6] & ((1ULL << (i & 63)) - 1ULL));
    }
    // the number of 1 in [i, j)
    unsigned int rank1(const unsigned int i, const unsigned int j) const {
        return rank1(j) - rank1(i);
    }
    // the number of 0 in [0, i)
    unsigned int rank0(const unsigned int i) const {
        return i - rank1(i);
    }
    // the number of 0 in [i, j)
    unsigned int rank0(const unsigned int i, const unsigned int j) const {
        return rank0(j) - rank0(i);
    }
};

// Wavelet Matrix
template<class T> struct WaveletMatrix {
    // inner data
    int height;
    vector<BitRank> bv;
    vector<int> pos;
    vector<vector<long long>> rui;

    // constructor (sigma: the number of characters)
    WaveletMatrix() {}
    WaveletMatrix(vector<T> vec) :
        WaveletMatrix(vec, *max_element(vec.begin(), vec.end()) + 1) {}
    WaveletMatrix(vector<T> vec, T sigma) {
        init(vec, sigma);
    }
    void init(vector<T> &vec, T sigma) {
        height = (sigma == 1) ? 1 : (64 - __builtin_clzll(sigma - 1));
        bv.resize(height), pos.resize(height);
        vector<T> A = vec;
        rui.resize(height + 1);
        for (int i = 0; i < height; ++i) {
            bv[i].resize(vec.size());
            for (int j = 0; j < vec.size(); ++j) {
                bv[i].set(j, get(vec[j], height - i - 1));
            }
            bv[i].build();
            auto it = stable_partition(vec.begin(), vec.end(), [&](int c) {
                return !get(c, height - i - 1);
            });
            pos[i] = it - vec.begin();
        }
        for (int i = 0; i <= height; ++i) {
            rui[i].resize((int)A.size() + 1);
            for (int j = 1; j <= (int)A.size(); ++j) {
                rui[i][j] = rui[i][j - 1] + A[j - 1];
            }
            if (i == height) break;
            stable_partition(A.begin(), A.end(), [&](int c) {
                return !get(c, height - i - 1);
            });
        }
    }
    
    // the i-th bit of "val" (0 or 1)
    int get(const T val, const int i) {
        return val >> i & 1;
    }
    
    // the number of "val" in [l, r)
    int rank(const T val, const int l, const int r) {
        return rank(val, r) - rank(val, l);
    }
    
    // the number of "val" in [0, i)
    int rank(T val, int i) {
        int p = 0;
        for (int j = 0; j < height; ++j) {
            if (get(val, height - j - 1)) {
                p = pos[j] + bv[j].rank1(p);
                i = pos[j] + bv[j].rank1(i);
            } else {
                p = bv[j].rank0(p);
                i = bv[j].rank0(i);
            }
        }
        return i - p;
    }
    
    // the k-th (0-indexed) smallest value in [l, r)
    T k_th_smallest(int k, int l, int r) {
        T res = 0;
        for (int i = 0; i < height; ++i) {
            const int j = bv[i].rank0(l, r);
            if (j > k){
                l = bv[i].rank0(l);
                r = bv[i].rank0(r);
            } else {
                l = pos[i] + bv[i].rank1(l);
                r = pos[i] + bv[i].rank1(r);
                k -= j;
                res |= (1LL << (height - i - 1));
            }
        }
        return res;
    }
    
    // the k-th (0-indexed) largest value in [l, r)
    T k_th_largest(int k, int l, int r) {
       return k_th_smallest(r - l - k - 1, l, r);
    }
    
    // the sum of the top-k sum in [l, r)
    T top_k_sum(int k, int l, int r) {
        if (l == r) return 0;
        T res = 0, val = 0;
        for (int i = 0; i < height; ++i) {
            const int j = bv[i].rank0(l, r);
            if (j > k) {
                l = bv[i].rank0(l);
                r = bv[i].rank0(r);
            } else {
                int l2 = bv[i].rank0(l);
                int r2 = bv[i].rank0(r);
                res += rui[i + 1][r2] - rui[i + 1][l2];
                l = pos[i] + bv[i].rank1(l);
                r = pos[i] + bv[i].rank1(r);
                k -= j;
                val |= (1LL << (height - i - 1));
            }
        }
        res += (long long)val * k;
        return res;
    }
    
    // the number of value between [loewr, upper) in [l, r)
    int range_freq(const int i, const int j, const T lower, const T upper,
                   const int l, const int r, const int x) {
        if (i == j || r <= lower || upper <= l) return 0;
        int mid = (l + r) >> 1;
        if (lower <= l && r <= upper) {
            return j - i;
        } else {
            T left = range_freq(bv[x].rank0(i), bv[x].rank0(j), lower, upper, l, mid, x + 1);
            T right = range_freq(pos[x] + bv[x].rank1(i), pos[x] + bv[x].rank1(j),
                                 lower, upper, mid, r, x + 1);
            return left + right;
        }
    }
    int range_freq(const int l, const int r, const T lower, const T upper) {
        return range_freq(l, r, lower, upper, 0, 1LL << height, 0);
    }
    
    // the minmum value between [lower, upper) in [l, r)
    T range_min(const int i, const int j, const T lower, const T upper,
                  const int l, const int r, const int x, const T val) {
        if (i == j || r <= lower || upper <= l) return -1;
        if (r - l == 1) return val;
        int mid = (l + r) >> 1;
        T res = range_min(bv[x].rank0(i), bv[x].rank0(j), lower, upper, l, mid, x + 1, val);
        if (res < 0) {
            return range_min(pos[x] + bv[x].rank1(i), pos[x] + bv[x].rank1(j),
                             lower, upper, mid, r, x + 1, val + (1LL << (height - x - 1)));
        } else return res;
    }
    T range_min(int l, int r, T lower, T upper) {
        return range_min(l, r, lower, upper, 0, 1LL << height, 0, 0);
    }
    
    // the max value (< val) in [l, r)
    T prev_value(int l, int r, T val) {
        int num = range_freq(l, r, 0, val);
        if (num == 0) return T(-1);
        else return k_th_smallest(num - 1, l, r);
    }
    
    // the min value (>= val) in [l, r)
    T next_value(int l, int r, T val) {
        int num = range_freq(l, r, 0, val);
        if (num == r - l) return T(-1);
        else return k_th_smallest(num, l, r);
    }
};

// 2D range count
template<class T> struct OrthogonalRangeCount {
    // inner data
    using ptt = pair<T, T>;
    const int sz;
    vector<T> X, Y;
    WaveletMatrix<T> wm;
    
    // constructor
    OrthogonalRangeCount(vector<ptt> candidate) : sz((int)candidate.size()), X(sz), Y(sz) {
        sort(candidate.begin(), candidate.end());
        vector<int> vec(sz);
        for (int i = 0; i < sz; ++i) {
            X[i] = candidate[i].first, Y[i] = candidate[i].second;
        }
        sort(Y.begin(), Y.end());
        Y.erase(unique(Y.begin(), Y.end()), Y.end());
        for (int i = 0; i < sz; ++i) {
            vec[i] = lower_bound(Y.begin(), Y.end(), candidate[i].second) - Y.begin();
        }
        wm.init(vec, Y.size());
    }
    
    // the number of points in [lx, rx) × [ly, ry)
    int query(const T lx, const T ly, const T rx, const T ry){
        const int lxid = lower_bound(X.begin(), X.end(), lx) - X.begin();
        const int rxid = lower_bound(X.begin(), X.end(), rx) - X.begin();
        const int lyid = lower_bound(Y.begin(), Y.end(), ly) - Y.begin();
        const int ryid = lower_bound(Y.begin(), Y.end(), ry) - Y.begin();
        if (lxid >= rxid || lyid >= ryid) return 0;
        return wm.range_freq(lxid, rxid, lyid, ryid);
    }
};



/*/////////////////////////////*/
// Examples
/*/////////////////////////////*/

void ABC_234_D() {
    int N, K;
    cin >> N >> K;
    vector<int> P(N);
    for (int i = 0; i < N; ++i) cin >> P[i];
    
    WaveletMatrix wm(P);
    for (int i = K; i <= N; ++i) {
        cout << wm.k_th_largest(K - 1, 0, i) << endl;
    }
}

void ABC_281_E() {
    int N, M, K;
    cin >> N >> M >> K;
    vector<long long> A(N);
    for (int i = 0; i < N; ++i) cin >> A[i];
    
    WaveletMatrix wm(A);
    for (int i = 0; i < N - M + 1; ++i) {
        cout << wm.top_k_sum(K, i, i + M) << " ";
    }
    cout << endl;
}

void ABC_324_G() {
    int N, Q;
    cin >> N;
    vector<int> A(N);
    for (int i = 0; i < N; ++i) cin >> A[i];
    
    WaveletMatrix<int> wm(A);
    cin >> Q;
    vector<int> left(Q+1, 0), right(Q+1, N), lower(Q+1, 1), upper(Q+1, N+1);
    for (int q = 0; q < Q; ++q) {
        int t, s, v;
        cin >> t >> s >> v;
        if (t == 1) {
            // [left, x) 内部の lower 以上 upper 未満の値が v 個以上である最小の x を求める
            int low = left[s] - 1, high = N + 1;
            while (high - low > 1) {
                int mid = (low + high) / 2;
                if (wm.range_freq(left[s], mid, lower[s], upper[s]) >= v) high = mid;
                else low = mid;
            }
            
            // [left, high) と [high, right) とに分割する
            high = min(high, right[s]);
            left[q+1] = high;
            right[q+1] = right[s];
            lower[q+1] = lower[s];
            upper[q+1] = upper[s];
            right[s] = high;
        } else {
            // 値が v 未満と v 以上に分ける
            ++v;
            v = max(v, lower[s]);
            v = min(v, upper[s]);
            left[q+1] = left[s];
            right[q+1] = right[s];
            lower[q+1] = v;
            upper[q+1] = upper[s];
            upper[s] = v;
        }
        cout << wm.range_freq(left[q+1], right[q+1], lower[q+1], upper[q+1]) << endl;
    }
}

void AOJ_1549() {
    int N, Q;
    cin >> N;
    const int GETA = 1100000;
    vector<int> a(N);
    for (int i = 0; i < N; ++i) {
        cin >> a[i];
        a[i] += GETA;
    }
    
    WaveletMatrix<int> wm(a);
    cin >> Q;
    while (Q--) {
        int l, r, d;
        cin >> l >> r >> d;
        ++r;
        d += GETA;
        
        int nex = wm.next_value(l, r, d);
        int pre = wm.prev_value(l, r, d);
        int res = GETA*2;
        if (nex != -1) res = min(res, nex - d);
        if (pre != -1) res = min(res, d - pre);
        
        //cout << nex << ", " << pre << endl;
        cout << res << endl;
    }
}


int main() {
    //ABC_234_D();
    //ABC_281_E();
    //ABC_324_G();
    AOJ_1549();
}
accuracy: 1
time_ms: 260
memory_kb: 23576
final_rank: 17

code_snippet: #line 1 "combined.cpp"
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/problems/1549"
#line 1 "/Users/siro53/kyo-pro/compro_library/template/template.cpp"
#pragma region Macros
#include <bits/stdc++.h>
using namespace std;
template <class T> inline bool chmax(T &a, T b) {
    if(a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <class T> inline bool chmin(T &a, T b) {
    if(a > b) {
        a = b;
        return 1;
    }
    return 0;
}
#ifdef DEBUG
template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {
    os << '{';
    for(int i = 0; i < (int)v.size(); i++) {
        if(i) { os << ','; }
        os << v[i];
    }
    os << '}';
    return os;
}
void debugg() { cerr << endl; }
template <class T, class... Args>
void debugg(const T &x, const Args &... args) {
    cerr << " " << x;
    debugg(args...);
}
#define debug(...)                                                             \
    cerr << __LINE__ << " [" << #__VA_ARGS__ << "]: ", debugg(__VA_ARGS__)
#define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl
#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif

struct Setup {
    Setup() {
        cin.tie(0);
        ios::sync_with_stdio(false);
        cout << fixed << setprecision(15);
    }
} __Setup;

using ll = long long;
#define OVERLOAD3(_1, _2, _3, name, ...) name
#define ALL(v) (v).begin(), (v).end()
#define RALL(v) (v).rbegin(), (v).rend()
#define REP1(i, n) for(int i = 0; i < int(n); i++)
#define REP2(i, a, b) for(int i = (a); i < int(b); i++)
#define REP(...) OVERLOAD3(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define REVERSE(v) reverse(ALL(v))
#define SZ(v) ((int)(v).size())
const int INF = 1 << 30;
const ll LLINF = 1LL << 60;
constexpr int MOD = 1000000007;
constexpr int MOD2 = 998244353;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

void Case(int i) { cout << "Case #" << i << ": "; }
int popcount(int x) { return __builtin_popcount(x); }
ll popcount(ll x) { return __builtin_popcountll(x); }
#pragma endregion Macros
#line 2 "/Users/siro53/kyo-pro/compro_library/data-structure/wavelet-matrix.hpp"

#line 5 "/Users/siro53/kyo-pro/compro_library/data-structure/wavelet-matrix.hpp"

#line 2 "/Users/siro53/kyo-pro/compro_library/data-structure/compact-bitvector.hpp"

#line 5 "/Users/siro53/kyo-pro/compro_library/data-structure/compact-bitvector.hpp"

class CompactBitVector {
  private:
    using u32 = unsigned int;
    using u64 = unsigned long long;

  public:
    explicit CompactBitVector() = default;
    explicit CompactBitVector(int n) : N(n), sz((N + 63) >> 6) {
        bv.assign(sz, 0);
        sum.assign(sz + 1, 0);
    }
    inline void set(int i, int b) {
        if(b) bv[i >> 6] |= (1ULL << (i & 63));
        else bv[i >> 6] &= ~(1ULL << (i & 63));
    }
    inline int access(int i) const { return (bv[i >> 6] >> (i & 63) & 1); }
    void build() {
        sum[0] = 0U;
        for(int i = 0; i < sz; i++) sum[i + 1] = sum[i] + (u32)__builtin_popcountll(bv[i]);
    }
    // [0, i)
    u32 rank(int i, int b) const {
        assert(i >= 0);
        u32 res = sum[i >> 6] + __builtin_popcountll(bv[i >> 6] & ((1ULL << (i & 63)) - 1));
        if(b == 0) res = i - res;
        return res;
    }
    int select(int i, int b) const {
        if(b and sum.back() > i) return -1;
        if(!b and N - sum.back() > i) return -1;
        int ok = N, ng = -1;
        while(ok - ng > 1) {
            int mid = (ok + ng) / 2;
            (rank(i, b) >= mid ? ok : ng) = mid;
        }
        return ok;
    }
    inline int operator[](const int i) const { return access(i); }

  private:
    int N, sz;
    std::vector<u64> bv;
    std::vector<u32> sum;
};
#line 7 "/Users/siro53/kyo-pro/compro_library/data-structure/wavelet-matrix.hpp"

template <typename T, int BITLEN = 31> 
class WaveletMatrix {
public:
    explicit WaveletMatrix() = default;
    explicit WaveletMatrix(vector<int> v): N((int)v.size()), B(BITLEN, CompactBitVector(N)), zero_num(BITLEN, 0) {
        for(int k = BITLEN - 1; k >= 0; k--) {
            std::vector<T> zeros, ones;
            for(int i = 0; i < N; i++) {
                if(v[i] >> k & 1) {
                    ones.emplace_back(v[i]);
                    B[k].set(i, 1);
                } else {
                    zeros.emplace_back(v[i]);
                }
            }
            B[k].build();
            zero_num[k] = (int)zeros.size();
            for(int i = 0; i < N; i++) {
                if(i < (int)zeros.size()) v[i] = zeros[i];
                else v[i] = ones[i - (int)zeros.size()];
            }
        }
    }
    T access(int pos) const {
        T res = 0; 
        for(int k = BITLEN - 1; k >= 0; k--) {
            int b = B[k][pos];
            res |= (T(b) << k);
            pos = B[k].rank(pos, b) + zero_num[k] * b;
        }
        return pos;
    }
    // [0, i) の範囲内に値 x が何個出現したか. O(log(σ))
    int rank(int i, T x) {
        int l = 0, r = i;
        for(int k = BITLEN - 1; k >= 0; k--) {
            int b = (x >> k & 1);
            l = B[k].rank(l, b) + zero_num[k] * b;
            r = B[k].rank(r, b) + zero_num[k] * b;
        }
        return (r - l);
    };
    // 左から i 個目の値 x の index. O(log(N)log(σ))
    int select(int i, T x) {
        int pos = 0;
        for(int k = BITLEN - 1; k >= 0; k--) {
            int b = (x >> k) & 1;
            pos = B[k].rank(pos, b) + zero_num[k] * b;
        }
        pos += i;
        for(int k = 0; k < BITLEN; k++) {
            if(x >> k & 1) {
                pos = B[k].select(pos - zero_num[k], 1);
            } else {
                pos = B[k].select(pos, 0);
            }
        }
        return pos;
    }
    // [l, r) の中で i 番目に小さい値を返す (i は 0-indexed)
    T quantile(int l, int r, int i) {
        assert(0 <= i and i < r - l);
        T res = 0;
        for(int k = BITLEN - 1; k >= 0; k--) {
            int zero_cnt = B[k].rank(r, 0) - B[k].rank(l, 0);
            int b = (zero_cnt <= i);
            if(b) {
                res |= (T(1) << k);
                i -= zero_cnt;
            }
            l = B[k].rank(l, b) + zero_num[k] * b;
            r = B[k].rank(r, b) + zero_num[k] * b;
        }
        return res;
    }
    // [l, r) の中で x < xr を満たす x の個数の総和を返す
    int rangefreq(int l, int r, T xr) {
        int res = 0;
        for(int k = BITLEN - 1; k >= 0; k--) {
            int b = (xr >> k & 1);
            if(b) res += B[k].rank(r, 0) - B[k].rank(l, 0);
            l = B[k].rank(l, b) + zero_num[k] * b;
            r = B[k].rank(r, b) + zero_num[k] * b;
        }
        return res;
    }
    // [l, r) の中で xl <= x < xr を満たす x の個数の総和を返す
    int rangefreq(int l, int r, T xl, T xr) {
        return (rangefreq(l, r, xr) - rangefreq(l, r, xl));
    }
    // [l, r) の中で x < xr を満たす x のうち最大値を返す
    // そのような x が存在しないならば -1 を返す
    T prev_value(int l, int r, T xr) {
        int num = rangefreq(l, r, xr);
        return (num == 0 ? -1 : quantile(l, r, num - 1));
    }
    // [l, r) の中で xl <= x を満たす x のうち最小値を返す
    // そのような x が存在しないならば -1 を返す
    T next_value(int l, int r, T xl) {
        int num = rangefreq(l, r, xl);
        return (num == r - l ? -1 : quantile(l, r, num));
    }
    T operator[](const int i) const { return access(i); }
private:
    int N;
    std::vector<CompactBitVector> B;
    std::vector<int> zero_num;
};
#line 4 "combined.cpp"

int main() {
    const int OFFSET = 1000000;
    int N;
    cin >> N;
    vector<int> a(N);
    REP(i, N) {
        cin >> a[i];
        a[i] += OFFSET;
    }
    WaveletMatrix<int> wm(a);
    int Q;
    cin >> Q;
    REP(_, Q) {
        int l, r, D;
        cin >> l >> r >> D;
        r++;
        D += OFFSET;
        int res = INF;
        int x = wm.prev_value(l, r, D);
        if(x != -1) chmin(res, abs(x - D));
        x = wm.next_value(l, r, D);
        if(x != -1) chmin(res, abs(x - D));
        cout << res << '\n';
    }
}
accuracy: 1
time_ms: 190
memory_kb: 5324
final_rank: 10

code_snippet: #line 1 "combined.cpp"
#pragma region Macros
#include <bits/stdc++.h>
using namespace std;
template <class T> inline bool chmax(T &a, T b) {
    if(a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <class T> inline bool chmin(T &a, T b) {
    if(a > b) {
        a = b;
        return 1;
    }
    return 0;
}
#ifdef DEBUG
template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << '(' << p.first << ',' << p.second << ')';
    return os;
}
template <class T> ostream &operator<<(ostream &os, const vector<T> &v) {
    os << '{';
    for(int i = 0; i < (int)v.size(); i++) {
        if(i) { os << ','; }
        os << v[i];
    }
    os << '}';
    return os;
}
void debugg() { cerr << endl; }
template <class T, class... Args>
void debugg(const T &x, const Args &... args) {
    cerr << " " << x;
    debugg(args...);
}
#define debug(...)                                                             \
    cerr << __LINE__ << " [" << #__VA_ARGS__ << "]: ", debugg(__VA_ARGS__)
#define dump(x) cerr << __LINE__ << " " << #x << " = " << (x) << endl
#else
#define debug(...) (void(0))
#define dump(x) (void(0))
#endif

struct Setup {
    Setup() {
        cin.tie(0);
        ios::sync_with_stdio(false);
        cout << fixed << setprecision(15);
    }
} __Setup;

using ll = long long;
#define OVERLOAD3(_1, _2, _3, name, ...) name
#define ALL(v) (v).begin(), (v).end()
#define RALL(v) (v).rbegin(), (v).rend()
#define REP1(i, n) for(int i = 0; i < int(n); i++)
#define REP2(i, a, b) for(int i = (a); i < int(b); i++)
#define REP(...) OVERLOAD3(__VA_ARGS__, REP2, REP1)(__VA_ARGS__)
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define REVERSE(v) reverse(ALL(v))
#define SZ(v) ((int)(v).size())
const int INF = 1 << 30;
const ll LLINF = 1LL << 60;
constexpr int MOD = 1000000007;
constexpr int MOD2 = 998244353;
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};

void Case(int i) { cout << "Case #" << i << ": "; }
int popcount(int x) { return __builtin_popcount(x); }
ll popcount(ll x) { return __builtin_popcountll(x); }
#pragma endregion Macros

#line 2 "/Users/siro53/kyo-pro/compro_library/data-structure/wavlet_matrix.hpp"

#line 5 "/Users/siro53/kyo-pro/compro_library/data-structure/wavlet_matrix.hpp"

#line 2 "/Users/siro53/kyo-pro/compro_library/data-structure/compact_bitvector.hpp"

#line 5 "/Users/siro53/kyo-pro/compro_library/data-structure/compact_bitvector.hpp"

class CompactBitVector {
  private:
    using u32 = unsigned int;
    using u64 = unsigned long long;

  public:
    explicit CompactBitVector() = default;
    explicit CompactBitVector(int n) : N(n), sz((N + 63) >> 6) {
        bv.assign(sz, 0);
        sum.assign(sz + 1, 0);
    }
    inline void set(int i, int b) {
        if(b) bv[i >> 6] |= (1ULL << (i & 63));
        else bv[i >> 6] &= ~(1ULL << (i & 63));
    }
    inline int access(int i) const { return (bv[i >> 6] >> (i & 63) & 1); }
    void build() {
        sum[0] = 0U;
        for(int i = 0; i < sz; i++) sum[i + 1] = sum[i] + (u32)__builtin_popcountll(bv[i]);
    }
    // [0, i)
    u32 rank(int i, int b) const {
        assert(i >= 0);
        u32 res = sum[i >> 6] + __builtin_popcountll(bv[i >> 6] & ((1ULL << (i & 63)) - 1));
        if(b == 0) res = i - res;
        return res;
    }
    int select(int i, int b) const {
        if(b and sum.back() > i) return -1;
        if(!b and N - sum.back() > i) return -1;
        int ok = N, ng = -1;
        while(ok - ng > 1) {
            int mid = (ok + ng) / 2;
            (rank(i, b) >= mid ? ok : ng) = mid;
        }
        return ok;
    }
    inline int operator[](const int i) const { return access(i); }

  private:
    int N, sz;
    std::vector<u64> bv;
    std::vector<u32> sum;
};
#line 7 "/Users/siro53/kyo-pro/compro_library/data-structure/wavlet_matrix.hpp"

template <typename T, int BITLEN = 31> 
class WaveletMatrix {
public:
    explicit WaveletMatrix() = default;
    explicit WaveletMatrix(vector<int> v): N((int)v.size()), B(BITLEN, CompactBitVector(N)), zero_num(BITLEN, 0) {
        for(int k = BITLEN - 1; k >= 0; k--) {
            std::vector<T> zeros, ones;
            for(int i = 0; i < N; i++) {
                if(v[i] >> k & 1) {
                    ones.emplace_back(v[i]);
                    B[k].set(i, 1);
                } else {
                    zeros.emplace_back(v[i]);
                }
            }
            B[k].build();
            zero_num[k] = (int)zeros.size();
            for(int i = 0; i < N; i++) {
                if(i < (int)zeros.size()) v[i] = zeros[i];
                else v[i] = ones[i - (int)zeros.size()];
            }
        }
    }
    T access(int pos) const {
        T res = 0; 
        for(int k = BITLEN - 1; k >= 0; k--) {
            int b = B[k][pos];
            res |= (T(b) << k);
            pos = B[k].rank(pos, b) + zero_num[k] * b;
        }
        return pos;
    }
    // [0, i) の範囲内に値 x が何個出現したか. O(log(σ))
    int rank(int i, T x) {
        int l = 0, r = i;
        for(int k = BITLEN - 1; k >= 0; k--) {
            int b = (x >> k & 1);
            l = B[k].rank(l, b) + zero_num[k] * b;
            r = B[k].rank(r, b) + zero_num[k] * b;
                // std::cerr << k << ' ' << l << ' ' << r << std::endl;
        }
        return (r - l);
    };
    // 左から i 個目の値 x の index. O(log(N)log(σ))
    int select(int i, T x) {
        int pos = 0;
        for(int k = BITLEN - 1; k >= 0; k--) {
            int b = (x >> k) & 1;
            pos = B[k].rank(pos, b) + zero_num[k] * b;
        }
        pos += i;
        for(int k = 0; k < BITLEN; k++) {
            if(x >> k & 1) {
                pos = B[k].select(pos - zero_num[k], 1);
            } else {
                pos = B[k].select(pos, 0);
            }
        }
        return pos;
    }
    // [l, r) の中で i 番目に小さい値を返す (i は 0-indexed)
    T quantile(int l, int r, int i) {
        assert(0 <= i and i < r - l);
        T res = 0;
        for(int k = BITLEN - 1; k >= 0; k--) {
            int zero_cnt = B[k].rank(r, 0) - B[k].rank(l, 0);
            int b = (zero_cnt <= i);
            if(b) {
                res |= (T(1) << k);
                i -= zero_cnt;
            }
            l = B[k].rank(l, b) + zero_num[k] * b;
            r = B[k].rank(r, b) + zero_num[k] * b;
        }
        return res;
    }
    // [l, r) の中で x < xr を満たす x の個数の総和を返す
    int rangefreq(int l, int r, T xr) {
        int res = 0;
        for(int k = BITLEN - 1; k >= 0; k--) {
            int b = (xr >> k & 1);
            if(b) res += B[k].rank(r, 0) - B[k].rank(l, 0);
            l = B[k].rank(l, b) + zero_num[k] * b;
            r = B[k].rank(r, b) + zero_num[k] * b;
        }
        return res;
    }
    // [l, r) の中で xl <= x < xr を満たす x の個数の総和を返す
    int rangefreq(int l, int r, T xl, T xr) {
        return (rangefreq(l, r, xr) - rangefreq(l, r, xl));
    }
    // [l, r) の中で x < xr を満たす x のうち最大値を返す
    // そのような x が存在しないならば -1 を返す
    T prev_value(int l, int r, T xr) {
        int num = rangefreq(l, r, xr);
        return (num == 0 ? -1 : quantile(l, r, num - 1));
    }
    // [l, r) の中で xl <= x を満たす x のうち最小値を返す
    // そのような x が存在しないならば -1 を返す
    T next_value(int l, int r, T xl) {
        int num = rangefreq(l, r, xl);
        return (num == r - l ? -1 : quantile(l, r, num));
    }
    T operator[](const int i) const { return access(i); }
private:
    int N;
    std::vector<CompactBitVector> B;
    std::vector<int> zero_num;
};
#line 78 "combined.cpp"

int main() {
    int N;
    cin >> N;
    vector<int> a(N);
    REP(i, N) cin >> a[i];
    WaveletMatrix<int, 21> wm(a);
    int Q;
    cin >> Q;
    REP(_, Q) {
        int l, r, D;
        cin >> l >> r >> D;
        r++;
        int x1 = wm.prev_value(l, r, D);
        int x2 = wm.next_value(l, r, D);
        assert(x1 != -1 or x2 != -1);
        if(x1 == -1) cout << abs(x2 - D) << '\n';
        else if(x2 == -1) cout << abs(x1 - D) << '\n';
        else cout << (abs(x1 - D) < abs(x2 - D) ? abs(x1 - D) : abs(x2 - D)) << '\n';
    }
}
accuracy: 1
time_ms: 140
memory_kb: 5300
final_rank: 6