Problem:
F: Disordered Data Detection / 異常検知
物語
宮守あかねは武蔵野ソフトウェアに務めるエンジニアである．今日は顧客から受けた不具合報告に頭を悩ませている．「変な話，この前作ってもらったソフトの挙動がぷるんぷるんしてるんでぇ，そちらでチェックしてもらえますか？保守するのもおたくらの仕事でしょ？」いつも無理難題ばかり押し付けてくるこの顧客だが，今回ばかりはこちらに非がある．なぜなら，いつも適当な仕事ばかりのジローがテストに通っていないコードをそのまま放置して製品に組み込んだことを告白したからである．普通の人間ならジローに殴りかかりそうなものだが，もはやいつものことだ，あかねは怒りを通り越し，すでに悟りを開きつつある．なにはともあれ，バグを取り除かなければならない．まずはデータログを解析し，異常が出ている箇所を検知することでバグの原因を探ろう．
今，
D
日分のログがあり，各データは1つの整数である．
l
日目から
r
日目までのデータについて，
l
日目のデータと
r
日目のデータの間に収まらず，大きくかけ離れたデータは異常の可能性が高いと考えられる．よって，指定された期間を入力とし，上記のような外れ値を検知するコードを書くことにした．
顧客が提示したデバッグ期限は3時間後．万策尽きたかのような状況だが，あかねは何度もこのような状況を乗り越えてきた．お気に入りのドーナツを頬張り気合を入れて，どんどんデバッグ，どーんと行こう！
問題
長さ
D
の整数列
x_1, . . . ,  x_D
がある．この数列に対し
Q
回のクエリが与えられる．
i
番目のクエリは3つの整数
l_i
,
r_i
,
e_i
からなる．
i
番目のクエリに対し，
a_i = min\{x_{l_i},x_{r_i}\}
,
b_i = max\{x_{l_i},x_{r_i}\}
としたとき，
x_j < a_i − e_i
もしくは
b_i+e_i < x_j
を満たすような
l_i ≤ j ≤ r_i
の個数を答えよ．
入力形式
入力は以下の形式からなる．
D
x_1
x_2
. . .
x_D
Q
l_1
r_1
e_1
. . .
l_Q
r_Q
e_Q
入力の1行目は数列の長さを表す1つの整数
D
(
1 ≤ D ≤ 100{,}000
) からなる．2行目では，数列
X
を表す
D
個の整数がそれぞれ空白1つを区切りとして与えられる．
i
番目の整数
x_i
は
−10^8 ≤ x_i ≤ 10^8
を満たす．
3行目はクエリの個数を表す1つの整数
Q
(
1≤ Q ≤ 100{,}000
) からなる．続く
Q
行のうち
j
番目の行では，
j
番目のクエリを表す3つの整数
l_j
,
r_j
,
e_j
が空白1つを区切りとして与えられる．
j
番目のクエリについて，
1 ≤ l_j ≤ r_j ≤ D
,
0 ≤ e_j ≤ 10^8
を満たす．
出力形式
Q
個のクエリに対する答えを，クエリが与えられた順にそれぞれ1行ごとに出力せよ．
入力例1
7
4 1 10 5 7 7 3
5
2 5 0
3 6 1
3 6 2
1 7 2
1 7 5
出力例1
1
1
0
3
1
入力例2
9
8 3 0 2 5 2 5 2 1
3
1 3 5
2 5 0
3 9 0
出力例2
0
2
5
入力例3
9
10 10 10 7 2 10 10 1 5
13
3 3 6
3 4 5
3 5 4
3 6 3
3 7 2
3 8 1
3 9 0
4 9 1
5 9 2
6 9 3
7 9 4
8 9 5
9 9 6
出力例3
0
0
0
1
2
0
2
4
2
1
0
0
0

Submitted solutions:

code_snippet: #line 1 "test/aoj/2674.test.cpp"
// clang-format off
// competitive-verifier: PROBLEM https://onlinejudge.u-aizu.ac.jp/challenges/search/titles/2674
// clang-format on
#line 2 "other/fastio.hpp"
// ref: https://maspypy.com/library-checker-many-a-b , Nyaanさん
#line 2 "other/type-utils.hpp"
#include <bits/stdc++.h>
using ll = long long;
using u32 = unsigned int;
using u64 = unsigned long long;
using i128 = __int128;
using u128 = unsigned __int128;
using vi = std::vector<int>;
using vii = std::vector<std::vector<int>>;
using pii = std::pair<int, int>;
using vl = std::vector<ll>;
using vll = std::vector<vl>;
using pll = std::pair<ll, ll>;

template <class T>
concept extended_integral =
    std::integral<T> || std::same_as<std::remove_cv_t<T>, i128> ||
    std::same_as<std::remove_cv_t<T>, u128>;
template <class T>
concept extended_signed_integral =
    std::signed_integral<T> || std::same_as<std::remove_cv_t<T>, i128>;
template <class T>
concept extended_unsigned_integral =
    std::unsigned_integral<T> || std::same_as<std::remove_cv_t<T>, u128>;

template <class T>
concept Streamable =
    requires(std::ostream &os, T &x) { os << x; } || extended_integral<T>;
template <class mint>
concept is_modint = requires(mint &x) {
    { x.val() } -> std::convertible_to<int>;
};
#line 4 "other/fastio.hpp"
namespace fastio {
constexpr int SZ = 1 << 17;
constexpr int offset = 64;
constexpr int mod = 10000;
char in_buf[SZ];
int in_left{}, in_right{};
char out_buf[SZ];
char out_tmp[offset];
int out_right{};
struct Pre {
    char num[4 * mod]{};
    constexpr Pre() {
        for(int i = 0; i < mod; ++i) {
            for(int n = i, j = 3; j >= 0; --j, n /= 10)
                num[4 * i + j] = '0' + n % 10;
        }
    }
    constexpr const char *operator[](int i) const { return &num[4 * i]; }
} constexpr pre;
void load() {
    memmove(in_buf, in_buf + in_left, in_right - in_left);
    in_right += -in_left + std::fread(in_buf + in_right - in_left, 1,
                                      SZ - (in_right - in_left), stdin);
    in_left = 0;
    if(in_right < SZ)
        in_buf[in_right++] = '\n';
}
void read(char &c) {
    do {
        if(in_left == in_right)
            load();
        c = in_buf[in_left++];
    } while(isspace(c));
}
void read(std::string &s) {
    s.clear();
    char c;
    do {
        if(in_left == in_right)
            load();
        c = in_buf[in_left++];
    } while(isspace(c));
    do {
        s += c;
        if(in_left == in_right)
            load();
        c = in_buf[in_left++];
    } while(!isspace(c));
}
template <extended_integral T> void read(T &x) {
    if(in_right - in_left < offset)
        load();
    char c;
    do
        c = in_buf[in_left++];
    while(c < '-'); // \n:10 space:32 -:45 '0':48
    bool minus{};
    if constexpr(extended_signed_integral<T>) {
        if(c == '-') {
            c = in_buf[in_left++];
            minus = true;
        }
    }
    x = 0;
    while(c >= '0') {
        x = 10 * x + (c & 15);
        c = in_buf[in_left++];
    }
    if constexpr(extended_signed_integral<T>) {
        if(minus)
            x = -x;
    }
}
void flush() { fwrite(out_buf, 1, std::exchange(out_right, 0), stdout); }
void write_range(const char *c, int n) {
    int pos{};
    while(pos < n) {
        if(out_right == SZ)
            flush();
        int len = std::min(n - pos, SZ - out_right);
        memcpy(out_buf + out_right, c + pos, len);
        out_right += len;
        pos += len;
    }
}

void write(char c) {
    if(SZ == out_right)
        flush();
    out_buf[out_right++] = c;
}
void write(const char *c) { write_range(c, strlen(c)); }
void write(const std::string &s) { write_range(s.data(), s.size()); }
template <std::floating_point T> void write(T x) {
    int n = std::snprintf(out_tmp, sizeof(out_tmp), "%.16g", x);
    write_range(out_tmp, n);
}
void write(bool x) { write(x ? '1' : '0'); }
template <extended_integral T> void write(T x) {
    if(x == 0) {
        write('0');
    }
    if constexpr(extended_signed_integral<T>) {
        if(x < 0) {
            write('-');
            x = -x;
        }
    }
    if(SZ - out_right < offset)
        flush();
    int cur = offset;
    for(; x >= 1000; x /= mod) {
        cur -= 4;
        memcpy(out_tmp + cur, pre[x % mod], 4);
    }
    if(x >= 100) {
        cur -= 3;
        memcpy(out_tmp + cur, pre[x % mod] + 1, 3);
    } else if(x >= 10) {
        cur -= 2;
        memcpy(out_tmp + cur, pre[x % mod] + 2, 2);
    } else if(x >= 1) {
        cur -= 1;
        memcpy(out_tmp + cur, pre[x % mod] + 3, 1);
    }
    write_range(out_tmp + cur, offset - cur);
}
struct Dummy {
    // プログラム終了時に出力
    ~Dummy() { flush(); }
} dummy;
} // namespace fastio
using fastio::write;
#line 4 "template.hpp"
// #pragma GCC target("avx2")
// #pragma GCC optimize("O3")
// #pragma GCC optimize("unroll-loops")
#line 8 "template.hpp"
using namespace std;
#ifdef LOCAL
#include <debug.hpp>
#else
#define debug(...)
#endif
template <Streamable T> void print_one(const T &value) { fastio::write(value); }
template <is_modint T> void print_one(const T &value) {
    print_one(value.val());
}
void print() { print_one('\n'); }
template <class T, class... Ts> void print(const T &a, const Ts &...b) {
    print_one(a);
    ((print_one(' '), print_one(b)), ...);
    print();
}
template <ranges::range Iterable>
    requires(!Streamable<Iterable>)
void print(const Iterable &v) {
    for(auto it = v.begin(); it != v.end(); ++it) {
        if(it != v.begin())
            print_one(' ');
        print_one(*it);
    }
    print();
}
#define all(v) begin(v), end(v)
template <class T> void UNIQUE(T &v) {
    ranges::sort(v);
    v.erase(unique(all(v)), end(v));
}
template <typename T> inline bool chmax(T &a, T b) {
    return ((a < b) ? (a = b, true) : (false));
}
template <typename T> inline bool chmin(T &a, T b) {
    return ((a > b) ? (a = b, true) : (false));
}
// https://trap.jp/post/1224/
template <class... T> constexpr auto min(T... a) {
    return min(initializer_list<common_type_t<T...>>{a...});
}
template <class... T> constexpr auto max(T... a) {
    return max(initializer_list<common_type_t<T...>>{a...});
}
void input() {}
template <class Head, class... Tail> void input(Head &head, Tail &...tail) {
#ifdef LOCAL
    cin >> head;
#else
    fastio::read(head);
#endif
    input(tail...);
}
template <class T> void input(vector<T> &a) {
    for(T &x : a)
        input(x);
}
#define INT(...)                                                               \
    int __VA_ARGS__;                                                           \
    input(__VA_ARGS__)
#define LL(...)                                                                \
    long long __VA_ARGS__;                                                     \
    input(__VA_ARGS__)
#define STR(...)                                                               \
    string __VA_ARGS__;                                                        \
    input(__VA_ARGS__)
#define REP1_0(n, c) REP1_1(n, c)
#define REP1_1(n, c)                                                           \
    for(ll REP_COUNTER_##c = 0; REP_COUNTER_##c < (ll)(n); REP_COUNTER_##c++)
#define REP1(n) REP1_0(n, __COUNTER__)
#define REP2(i, a) for(ll i = 0; i < (ll)(a); i++)
#define REP3(i, a, b) for(ll i = (ll)(a); i < (ll)(b); i++)
#define REP4(i, a, b, c) for(ll i = (ll)(a); i < (ll)(b); i += (ll)(c))
#define overload4(a, b, c, d, e, ...) e
#define rep(...) overload4(__VA_ARGS__, REP4, REP3, REP2, REP1)(__VA_ARGS__)
ll inf = 3e18;
vl dx = {1, -1, 0, 0};
vl dy = {0, 0, 1, -1};
template <class T> constexpr T floor(T x, T y) noexcept {
    return x / y - ((x ^ y) < 0 and x % y);
}
template <class T> constexpr T ceil(T x, T y) noexcept {
    return x / y + ((x ^ y) >= 0 and x % y);
}
// yの符号に関わらず非負で定義 \bmod:texコマンド
template <class T> constexpr T bmod(T x, T y) noexcept {
    T m = x % y;
    return (m < 0) ? m + (y > 0 ? y : -y) : m;
}
template <std::signed_integral T> constexpr int bit_width(T x) noexcept {
    return std::bit_width((uint64_t)x);
}
template <std::signed_integral T> constexpr int popcount(T x) noexcept {
    return std::popcount((uint64_t)x);
}
constexpr bool kth_bit(auto n, auto k) { return (n >> k) & 1; }
#line 3 "data-structure/bit-vector.hpp"
/**
 * @brief ビットベクトル
 * ref: https://judge.yosupo.jp/submission/208512
 */
struct BitVector {
    int n;
    vector<u32> bit, sum;
    BitVector() = default;
    explicit BitVector(int n)
        : n(n), bit((n + 31) >> 5, 0), sum(bit.size() + 1, 0) {}
    void set(int i) { bit[i >> 5] |= 1U << (i & 31); }
    void reset(int i) { bit[i >> 5] &= ~(1U << (i & 31)); }
    void build() {
        for(int i = 0; i < ssize(bit); ++i) {
            sum[i + 1] = sum[i] + popcount(bit[i]);
        }
    }
    u32 rank1(int r) const {
        return sum[r >> 5] + popcount(bit[r >> 5] & ((1U << (r & 31)) - 1));
    }
    u32 rank1(int l, int r) const { return rank1(r) - rank1(l); }
    u32 rank0(int r) const { return r - rank1(r); }
    u32 rank0(int l, int r) const { return rank0(r) - rank0(l); }
    u32 rank(bool f, int r) const { return f ? rank1(r) : rank0(r); }
    u32 rank(bool f, int l, int r) const {
        return f ? rank1(l, r) : rank0(l, r);
    }
    pair<u32, u32> succ(bool f, int l, int r) const {
        return f ? make_pair(n - sum.back() + rank1(l),
                             n - sum.back() + rank1(r))
                 : make_pair(rank0(l), rank0(r));
    }
};
#line 4 "data-structure/wavelet-matrix.hpp"
/**
 * @brief ウェーブレット行列
 * ref: https://judge.yosupo.jp/submission/208512
 */
template <class T, bool COMPRESS = true> struct WaveletMatrix {
    int n, lg;
    vector<BitVector> b;
    vector<T> memo;
    WaveletMatrix() = default;
    explicit WaveletMatrix(const vector<T> &a) : n(a.size()) { build(a); }

  private:
    void build0(vector<T> a) {
        vector<T> lv(n), rv(n);
        for(int i = 0; i < lg; ++i) {
            int l{}, r{};
            for(int j = 0; j < n; ++j) {
                if(kth_bit(a[j], lg - 1 - i)) {
                    b[i].set(j);
                    rv[r++] = a[j];
                } else
                    lv[l++] = a[j];
            }
            b[i].build();
            swap(a, lv);
            copy(begin(rv), begin(rv) + r, begin(a) + l);
        }
    }
    void build(const vector<T> &a) {
        if constexpr(COMPRESS) {
            memo.reserve(n);
            vector<int> ord(n), _a(n);
            iota(all(ord), 0);
            ranges::stable_sort(ord, {}, [&](int i) { return a[i]; });
            int val = -1;
            for(auto i : ord) {
                if(memo.empty() or memo.back() != a[i]) {
                    memo.emplace_back(a[i]);
                    val++;
                }
                _a[i] = val;
            }
            lg = bit_width(val + 1);
            b = vector(lg, BitVector(n));
            build0(std::move(_a));
        } else {
            n = a.size();
            lg = n ? bit_width(ranges::max(a) + 1) : 0;
            b = vector(lg, BitVector(n));
            build0(a);
        }
    }

  public:
    T kth_smallest(int l, int r, int k) const {
        T res{};
        for(int i = 0; i < lg; ++i) {
            bool f = b[i].rank0(l, r) <= (u32)k;
            if(f) {
                k -= b[i].rank0(l, r);
                res |= T(1) << (lg - 1 - i);
            }
            tie(l, r) = b[i].succ(f, l, r);
        }
        if constexpr(COMPRESS)
            return memo[res];
        else
            return res;
    }
    // #{i : l<=i<r and a[i]<upper}
    T count(int l, int r, T upper) const {
        if constexpr(COMPRESS) {
            upper = ranges::lower_bound(memo, upper) - begin(memo);
        }
        T res{};
        for(int i = 0; i < lg; ++i) {
            bool f = kth_bit(upper, lg - 1 - i);
            if(f)
                res += b[i].rank0(l, r);
            tie(l, r) = b[i].succ(f, l, r);
        }
        return res;
    }
    // #{i : l<=i<r and lower<=a[i]<upper}
    T count(int l, int r, T lower, T upper) const {
        return count(l, r, upper) - count(l, r, lower);
    }
    // #{i : l<=i<r and a[i]==x}
    T freq(int l, int r, T x) const { return count(l, r, x, x + 1); }
};
#line 6 "test/aoj/2674.test.cpp"
int main() {
    INT(d);
    vector<int> a(d);
    input(a);
    for(int &ai : a) {
        ai += 100'000'000;
    }
    WaveletMatrix<int, true> wm(a);
    INT(q);
    rep(q) {
        INT(l, r, e);
        --l;
        auto [mini, maxi] = minmax(a[l], a[r - 1]);
        int ans = r - l - wm.count(l, r, max(0, mini - e), maxi + e + 1);
        print(ans);
    }
}
accuracy: 1
time_ms: 50
memory_kb: 6252
final_rank: 1

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)
    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);
    }
};
void solve(){
    INT(d);
    VC(ll,x,d);
    rep(i,d)x[i]+=5e8;
    wavelet_matrix<ll>wm;
    wm.build(x);
    INT(q);
    while(q--){
        INT(l,r,e);
        --l,--r;
        cout<<r-l+1-wm.range_freq(l,r+1,min(x[l],x[r])-e,max(x[l],x[r])+e+1)<<"\n";
    }
}
signed main(){
    int t=1;
    //cin>>t;
    while(t--)solve();
}
accuracy: 1
time_ms: 160
memory_kb: 12872
final_rank: 10

code_snippet: #line 1 "test/verify/yosupo-line-add-get-min-2.test.cpp"
// competitive-verifier: PROBLEM https://judge.yosupo.jp/problem/line_add_get_min

#line 1 "template/template.hpp"
#include <bits/stdc++.h>
#if __has_include(<atcoder/all>)
#include <atcoder/all>
#endif

using namespace std;

using int64 = long long;

const int64 infll = (1LL << 62) - 1;
const int inf = (1 << 30) - 1;

struct IoSetup {
  IoSetup() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(10);
    cerr << fixed << setprecision(10);
  }
} iosetup;

template<typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> &p) {
  os << p.first << " " << p.second;
  return os;
}

template<typename T1, typename T2>
istream &operator>>(istream &is, pair<T1, T2> &p) {
  is >> p.first >> p.second;
  return is;
}

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 != v.size() ? " " : "");
  }
  return os;
}

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

template<typename T1, typename T2>
inline bool chmax(T1 &a, T2 b) {
  return a < b && (a = b, true);
}

template<typename T1, typename T2>
inline bool chmin(T1 &a, T2 b) {
  return a > b && (a = b, true);
}

template<typename T = int64>
vector<T> make_v(size_t a) {
  return vector<T>(a);
}

template<typename T, typename... Ts>
auto make_v(size_t a, Ts... ts) {
  return vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));
}

template<typename T, typename V>
typename enable_if<is_class<T>::value == 0>::type fill_v(T &t, const V &v) {
  t = v;
}

template<typename T, typename V>
typename enable_if<is_class<T>::value != 0>::type fill_v(T &t, const V &v) {
  for (auto &e : t) fill_v(e, v);
}

template<typename F>
struct FixPoint : F {
  explicit FixPoint(F &&f) : F(std::forward<F>(f)) {}

  template<typename... Args>
  decltype(auto) operator()(Args &&...args) const {
    return F::operator()(*this, std::forward<Args>(args)...);
  }
};

template<typename F>
inline decltype(auto) MFP(F &&f) {
  return FixPoint<F>{std::forward<F>(f)};
}

template< typename T >
struct SegmentTreeFractionalCascading {
 private:
  vector<vector<T> > seg;
  vector<vector<int> > LL, RR;
  int sz;

  int prod(int a, int b, int lower, int upper, int k, int l, int r) const {
    if (a >= r or b <= l) {
      return 0;
    } else if (a <= l and r <= b) {
      return upper - lower;
    } else {
      return prod(a, b, LL[k][lower], LL[k][upper], 2 * k + 1, l, (l + r) >> 1) +
          prod(a, b, RR[k][lower], RR[k][upper], 2 * k + 2, (l + r) >> 1, r);
    }
  }

 public:
  SegmentTreeFractionalCascading() = default;

  explicit SegmentTreeFractionalCascading(const vector<T> &v) {
    sz = 1;
    while (sz < v.size()) sz <<= 1;
    seg.resize(2 * sz - 1);
    LL.resize(2 * sz - 1);
    RR.resize(2 * sz - 1);
    for (int k = 0; k < v.size(); k++) {
      seg[k + sz - 1].emplace_back(v[k]);
    }
    for (int k = sz - 2; k >= 0; k--) {
      seg[k].resize(seg[2 * k + 1].size() + seg[2 * k + 2].size());
      LL[k].resize(seg[k].size() + 1);
      RR[k].resize(seg[k].size() + 1);
      merge(begin(seg[2 * k + 1]), end(seg[2 * k + 1]), begin(seg[2 * k + 2]),
            end(seg[2 * k + 2]), begin(seg[k]));
      int tail1 = 0, tail2 = 0;
      for (int i = 0; i < seg[k].size(); i++) {
        while (tail1 < seg[2 * k + 1].size() and seg[2 * k + 1][tail1] < seg[k][i])
          ++tail1;
        while (tail2 < seg[2 * k + 2].size() and seg[2 * k + 2][tail2] < seg[k][i])
          ++tail2;
        LL[k][i] = tail1, RR[k][i] = tail2;
      }
      LL[k][seg[k].size()] = (int) seg[2 * k + 1].size();
      RR[k][seg[k].size()] = (int) seg[2 * k + 2].size();
    }
  }

  int prod(int a, int b, T l, T r) const {
    l = int(lower_bound(seg[0].begin(), seg[0].end(), l) - seg[0].begin());
    r = int(lower_bound(seg[0].begin(), seg[0].end(), r) - seg[0].begin());
    return prod(a, b, l, r, 0, 0, sz);
  }
};

int main() {
  int N, Q;
  cin >> N;
  vector< int64 > X(N);
  for(int i = 0; i < N; i++) {
    cin >> X[i];
  }
  SegmentTreeFractionalCascading seg(X);
  cin >> Q;
  while(Q--) {
    int L, R, E;
    cin >> L >> R >> E;
    --L, --R;
    cout << (R - L + 1) - seg.prod(L, R + 1, min(X[L], X[R]) - E, max(X[L], X[R]) + E + 1) << "\n";
  }
}
accuracy: 1
time_ms: 200
memory_kb: 59408
final_rank: 18

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"

const int OFFSET = 300000000;

int main() {
    int D;
    cin >> D;
    vector<int> x(D);
    REP(i, D) {
        cin >> x[i];
        x[i] += OFFSET;
    }
    WaveletMatrix<int> wm(x);
    int Q;
    cin >> Q;
    REP(_, Q) {
        int l, r, e;
        cin >> l >> r >> e;
        l--;
        auto [a, b] = minmax(x[l], x[r-1]);
        int cnt = wm.rangefreq(l, r, a-e, b+e+1);
        cout << (r - l - cnt) << '\n';
    }
}
accuracy: 1
time_ms: 130
memory_kb: 5484
final_rank: 3

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"
const int OFFSET = 300000000;

int main() {
    int D;
    cin >> D;
    vector<int> x(D);
    REP(i, D) {
        cin >> x[i];
        x[i] += OFFSET;
    }
    WaveletMatrix<int> wm(x);
    int Q;
    cin >> Q;
    REP(_, Q) {
        int l, r, e;
        cin >> l >> r >> e;
        l--;
        auto [a, b] = minmax(x[l], x[r-1]);
        int cnt = wm.rangefreq(l, r, a-e, b+e+1);
        cout << (r - l - cnt) << '\n';
    }
}
accuracy: 1
time_ms: 130
memory_kb: 5484
final_rank: 3

code_snippet: #line 1 "main.cpp"
#define PROBLEM "https://onlinejudge.u-aizu.ac.jp/problems/2674"

#include <iostream>
#include <algorithm>
#line 1 "/home/anqooqie/.proconlib/tools/wavelet_matrix.hpp"



#include <cstdint>
#include <vector>
#line 7 "/home/anqooqie/.proconlib/tools/wavelet_matrix.hpp"
#include <iterator>
#include <array>
#include <utility>
#include <cassert>
#line 1 "/home/anqooqie/.proconlib/tools/bit_vector.hpp"



#line 6 "/home/anqooqie/.proconlib/tools/bit_vector.hpp"
#include <immintrin.h>

// Source: https://nyaannyaan.github.io/library/data-structure-2d/wavelet-matrix.hpp.html
// License: CC0 1.0 Universal
// Author: Nyaan

namespace tools {
  class bit_vector {
  private:
    using u32 = ::std::uint32_t;
    using i64 = ::std::int64_t;
    using u64 = ::std::uint64_t;

    static constexpr u32 w = 64;
    ::std::vector<u64> m_block;
    ::std::vector<u32> m_count;
    u32 m_size, m_zeros;

  public:
    bit_vector() {}
    explicit bit_vector(int _n) { init(_n); }
    __attribute__((optimize("O3", "unroll-loops"))) void init(int _n) {
      m_size = m_zeros = _n;
      m_block.resize(m_size / w + 1, 0);
      m_count.resize(m_block.size(), 0);
    }

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

    __attribute__((target("popcnt"))) void build() {
      for (u32 i = 1; i < m_block.size(); ++i)
        m_count[i] = m_count[i - 1] + _mm_popcnt_u64(m_block[i - 1]);
      m_zeros = rank0(m_size);
    }

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


#line 1 "/home/anqooqie/.proconlib/tools/floor_log2.hpp"



#include <type_traits>
#line 6 "/home/anqooqie/.proconlib/tools/floor_log2.hpp"
#include <limits>
#line 1 "/home/anqooqie/.proconlib/tools/popcount.hpp"



#line 8 "/home/anqooqie/.proconlib/tools/popcount.hpp"

namespace tools {

  template <typename T>
  T popcount(T x) {
    static_assert(::std::is_integral_v<T>);
    assert(x >= 0);
    if constexpr (::std::is_signed_v<T>) {
      return static_cast<T>(::tools::popcount<::std::make_unsigned_t<T>>(x));
    } else {
      const auto log2 = [](const int w) {
        if (w == 8) return 3;
        if (w == 16) return 4;
        if (w == 32) return 5;
        if (w == 64) return 6;
        return -1;
      };
      static_assert(log2(::std::numeric_limits<T>::digits) >= 0);

      if constexpr (::std::numeric_limits<T>::digits == 8) {
        x = (x & UINT8_C(0x55)) + (x >> 1 & UINT8_C(0x55));
        x = (x & UINT8_C(0x33)) + (x >> 2 & UINT8_C(0x33));
        x = (x & UINT8_C(0x0f)) + (x >> 4 & UINT8_C(0x0f));
      } else if constexpr (::std::numeric_limits<T>::digits == 16) {
        x = (x & UINT16_C(0x5555)) + (x >> 1 & UINT16_C(0x5555));
        x = (x & UINT16_C(0x3333)) + (x >> 2 & UINT16_C(0x3333));
        x = (x & UINT16_C(0x0f0f)) + (x >> 4 & UINT16_C(0x0f0f));
        x = (x & UINT16_C(0x00ff)) + (x >> 8 & UINT16_C(0x00ff));
      } else if constexpr (::std::numeric_limits<T>::digits == 32) {
        x = (x & UINT32_C(0x55555555)) + (x >> 1 & UINT32_C(0x55555555));
        x = (x & UINT32_C(0x33333333)) + (x >> 2 & UINT32_C(0x33333333));
        x = (x & UINT32_C(0x0f0f0f0f)) + (x >> 4 & UINT32_C(0x0f0f0f0f));
        x = (x & UINT32_C(0x00ff00ff)) + (x >> 8 & UINT32_C(0x00ff00ff));
        x = (x & UINT32_C(0x0000ffff)) + (x >> 16 & UINT32_C(0x0000ffff));
      } else if constexpr (::std::numeric_limits<T>::digits == 64) {
        x = (x & UINT64_C(0x5555555555555555)) + (x >> 1 & UINT64_C(0x5555555555555555));
        x = (x & UINT64_C(0x3333333333333333)) + (x >> 2 & UINT64_C(0x3333333333333333));
        x = (x & UINT64_C(0x0f0f0f0f0f0f0f0f)) + (x >> 4 & UINT64_C(0x0f0f0f0f0f0f0f0f));
        x = (x & UINT64_C(0x00ff00ff00ff00ff)) + (x >> 8 & UINT64_C(0x00ff00ff00ff00ff));
        x = (x & UINT64_C(0x0000ffff0000ffff)) + (x >> 16 & UINT64_C(0x0000ffff0000ffff));
        x = (x & UINT64_C(0x00000000ffffffff)) + (x >> 32 & UINT64_C(0x00000000ffffffff));
      }

      return x;
    }
  }
}


#line 8 "/home/anqooqie/.proconlib/tools/floor_log2.hpp"

namespace tools {

  template <typename T>
  T floor_log2(T x) {
    static_assert(::std::is_integral_v<T>);
    assert(x > 0);
    if constexpr (::std::is_signed_v<T>) {
      return static_cast<T>(::tools::floor_log2<::std::make_unsigned_t<T>>(x));
    } else {
      const auto log2 = [](const int w) {
        if (w == 8) return 3;
        if (w == 16) return 4;
        if (w == 32) return 5;
        if (w == 64) return 6;
        return -1;
      };
      static_assert(log2(::std::numeric_limits<T>::digits) >= 0);

      x |= (x >> 1);
      x |= (x >> 2);
      x |= (x >> 4);
      if constexpr (::std::numeric_limits<T>::digits > 8) x |= (x >> 8);
      if constexpr (::std::numeric_limits<T>::digits > 16) x |= (x >> 16);
      if constexpr (::std::numeric_limits<T>::digits > 32) x |= (x >> 32);
      return ::tools::popcount(x) - static_cast<T>(1);
    }
  }
}


#line 13 "/home/anqooqie/.proconlib/tools/wavelet_matrix.hpp"

// Source: https://nyaannyaan.github.io/library/data-structure-2d/wavelet-matrix.hpp.html
// License: CC0 1.0 Universal
// Author: Nyaan

namespace tools {
  template <typename T>
  class wavelet_matrix {
  private:
    using u32 = ::std::uint32_t;
    using i64 = ::std::int64_t;
    using u64 = ::std::uint64_t;

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

  public:
    wavelet_matrix() = default;
    explicit wavelet_matrix(u32 _n) : n(::std::max<u32>(_n, 1)), a(n) {}
    wavelet_matrix(const ::std::vector<T>& _a) : n(_a.size()), a(_a) { build(); }

    __attribute__((optimize("O3"))) void build() {
      assert(::std::all_of(::std::begin(a), ::std::end(a), [](const auto a_i) { return a_i >= 0; }));

      lg = ::tools::floor_log2(::std::max<T>(*::std::max_element(::std::begin(a), ::std::end(a)), 1)) + 1;
      bv.assign(lg, ::tools::bit_vector(n));
      ::std::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();
        ::std::array<decltype(::std::begin(nxt)), 2> it{::std::begin(nxt), ::std::begin(nxt) + bv[h].zeros()};
        for (int i = 0; i < n; ++i) *it[bv[h].get(i)]++ = cur[i];
        ::std::swap(cur, nxt);
      }
      return;
    }

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

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

    inline ::std::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 ::std::make_pair(l + zeros - l0, r + zeros - r0);
    }

  public:
    // return a[k]
    T access(u32 k) const {
      assert(k <= u32(n));

      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 {
      assert(l <= r && r <= u32(n));
      assert(k < r - l);

      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) {
      assert(l <= r && r <= n);
      assert(k < r - l);

      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) {
      assert(l <= r && r <= n);
      assert(upper >= 0);

      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) {
      assert(l <= r && r <= n);
      assert(0 <= lower && lower <= 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) {
      assert(l <= r && r <= n);
      assert(upper >= 0);

      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) {
      assert(l <= r && r <= n);
      assert(lower >= 0);

      int cnt = range_freq(l, r, lower);
      return cnt == r - l ? T(-1) : kth_smallest(l, r, cnt);
    }
  };
}


#line 6 "main.cpp"

int main() {
  std::cin.tie(nullptr);
  std::ios_base::sync_with_stdio(false);

  int D;
  std::cin >> D;
  tools::wavelet_matrix<int> x(D);
  for (int i = 0; i < D; ++i) {
    int x_i;
    std::cin >> x_i;
    x_i += 100000000;
    x.set(i, x_i);
  }
  x.build();

  int Q;
  std::cin >> Q;
  for (int q = 0; q < Q; ++q) {
    int l, r, e;
    std::cin >> l >> r >> e;
    --l;
    const auto [a, b] = std::minmax({x.access(l), x.access(r - 1)});
    std::cout << (r - l) - x.range_freq(l, r, std::max(0, a - e), b + e + 1) << "\n";
  }

  return 0;
}
accuracy: 1
time_ms: 150
memory_kb: 4940
final_rank: 2

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

#define rep(i, a, n) for (int i = (int)(a); i < (int)(n); i++)
#define rrep(i, a, n) for (int i = ((int)(n - 1)); i >= (int)(a); i--)

template<class IL, class IR, class DL, class DR, class O>
void mo_algorithm(const int &n, const std::vector<int> &l, const std::vector<int> &r, const IL &insert_left, const IR &insert_right, const DL &delete_left, const DR &delete_right, const O &out) {
    const int q = l.size();
    const int block =  n/std::max<int>(1, std::sqrt(n));
    std::vector<int> order(q, 0);
    iota(order.begin(), order.end(), 0);
    std::sort(order.begin(), order.end(), [&](int i, int j) {
        int bi = l[i]/block;
        int bj = l[j]/block;
        return bi != bj ? bi < bj : bi & 1 ? r[i] > r[j] : r[i] < r[j];
    });
    int nl = 0, nr = 0;
    for(auto i: order) {
        while(l[i] < nl) insert_left(--nl);
        while(nr < r[i]) insert_right(nr++);
        while(nl < l[i]) delete_left(nl++);
        while(r[i] < nr) delete_right(--nr);
        out(i);
    }
    return;
}

template<class Monoid, Monoid (*op)(Monoid, Monoid), Monoid (*e)()>
struct segtree {
private:
    int n;
    int size;
    std::vector<Monoid> data;
public:
    segtree(int _n) : n(_n), size(1) {
        while(size < _n) {
            size <<= 1;
        }
        data.assign(2*size, e());
        return;
    }

    segtree(const std::vector<Monoid> &v) : size(1) {
        n = (int)v.size();
        while(size < n) {
            size <<= 1;
        }
        data.assign(2*size, e());
        std::copy(v.begin(), v.end(), data.begin() + size);
        for(int i = size-1; i > 0; i--) {
            data[i] = op(data[i<<1|0], data[i<<1|1]);
        }
        return;
    }

    void set(int p, Monoid x) {
        assert(0 <= p && p < n);
        p += size;
        data[p] = x;
        while(p > 1) {
            p >>= 1;
            data[p] = op(data[p<<1|0], data[p<<1|1]);
        }
        return;
    }

    Monoid get(int p) const {
        assert(0 <= p && p < n);
        return data[p+size];
    }

    Monoid prod(int l, int r) const {
        assert(0 <= l && l <= r && r <= n);
        Monoid left = e(), right = e();
        l += size;
        r += size;
        while(l < r) {
            if(l & 1) left = op(left, data[l++]);
            if(r & 1) right = op(data[--r], right);
            l >>= 1;
            r >>= 1;
        }
        return op(left, right);
    }

    Monoid all_prod() const {
        return data[1];
    }

    Monoid operator [] (int p) const { return data[size+p]; }
};

template<class T>
struct compress {
private:
    std::vector<T> cp;
    bool flag = false;
public:
    compress() = default;

    compress(std::vector<T> cp) : cp(cp) {
        build();
    }

    void build() {
        std::sort(cp.begin(), cp.end());
        cp.erase(std::unique(cp.begin(), cp.end()), cp.end());
        flag = true;
    }

    void add(const T &val) {
        cp.emplace_back(val);
        flag = false;
    }

    int get(const T &val) {
        if(flag == false) build();
        return std::lower_bound(cp.begin(), cp.end(), val) - cp.begin();
    }

    int size() const {
        return cp.size();
    }

    T val(int idx) const {
        assert(0 <= idx && idx < (int)cp.size());
        return cp[idx];
    }
};

using i64 = std::int64_t;

i64 op(i64 a, i64 b) {
    return a + b;
}

i64 e() {
    return 0;
}

int main() {
    int d;
    std::cin >> d;
    std::vector<i64> x(d);
    compress<i64> cp;
    rep(i,0,d) {
        std::cin >> x[i];
        cp.add(x[i]);
    }
    cp.build();
    segtree<i64, op, e> seg(cp.size());
    int q;
    std::cin >> q;
    std::vector<int> ls(q), rs(q);
    std::vector<i64> ans(q), es(q);
    rep(i,0,q) {
        std::cin >> ls[i] >> rs[i] >> es[i];
        ls[i]--;
    }
    const auto insert = [&](int idx) -> void {
        int i = cp.get(x[idx]);
        seg.set(i, seg.get(i) + 1);
    };
    const auto remove = [&](int idx) -> void {
        int i = cp.get(x[idx]);
        seg.set(i, seg.get(i) - 1);
    };
    const auto out = [&](int i) -> void {
        int l = ls[i];
        int r = rs[i];
        i64 e = es[i];
        i64 a = std::min(x[l], x[r-1]);
        i64 b = std::max(x[l], x[r-1]);
        ans[i] = seg.all_prod() - seg.prod(cp.get(a - e), cp.get(b + e+1));
    };
    mo_algorithm(d, ls, rs, insert, insert, remove, remove, out);
    rep(i,0,q) {
        std::cout << ans[i] << '\n';
    }
}
accuracy: 1
time_ms: 2860
memory_kb: 9396
final_rank: 19

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

template <typename T>
int bisect_left(vector<T> &X, T v){
	return lower_bound(X.begin(), X.end(), v) - X.begin();
}
template <typename T>
int bisect_right(vector<T> &X, T v){
	return upper_bound(X.begin(), X.end(), v) - X.begin();
}

int main(){
	int n; cin >> n;
	vector<int> x(n);
	for (int i=0; i<n; i++){
		cin >> x[i];
	}

	int b = int(pow(n, 0.5) + 1);
	vector<vector<int>> dat(b, vector<int>(0));
	for (int i=0; i<b; i++){
		for (int j=min(n, i*b); j<min(n, (i+1)*b); j++){
			dat[i].push_back(x[j]);
		}
		sort(dat[i].begin(), dat[i].end());
	}

	int q; cin >> q;
	for (int num=0; num<q; num++){
		int l, r, e; cin >> l >> r >> e;
		l--;
		int mn = min(x[l], x[r-1]);
		int mx = max(x[l], x[r-1]);
		// x[j] < mn - e || mx + e < x[j]
		int tl = l+b-(l%b), tr = r-(r%b), ans = 0;
		for (int i=l; i<min(r, tl); i++){
			if (x[i]<mn-e || mx+e<x[i]) ans++;
		}
		for (int i=tl/b; i<tr/b; i++){
			ans += bisect_left(dat[i], mn-e);
			ans += (int)dat[i].size() - bisect_right(dat[i], mx+e); 
		}
		for (int i=max(tl,tr); i<r; i++){
			if (x[i]<mn-e || mx+e<x[i]) ans++;
		}
		cout << ans << "\n";
	}

}
accuracy: 1
time_ms: 1770
memory_kb: 4596
final_rank: 17

code_snippet: #include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
using std::cout;
using std::cin;
using std::endl;
using ll=long long;
using ld=long double;
ll ILL=2167167167167167167;
const int INF=2100000000;
const ll mod=998244353;
#define rep(i,a) for (int i=0;i<a;i++)
#define all(p) p.begin(),p.end()
template<class T> using _pq = priority_queue<T, vector<T>, greater<T>>;
template<class T> ll LB(vector<T> &v,T a){return lower_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> ll UB(vector<T> &v,T a){return upper_bound(v.begin(),v.end(),a)-v.begin();}
template<class T> bool chmin(T &a,const T &b){if(a>b){a=b;return 1;}else return 0;}
template<class T> bool chmax(T &a,const T &b){if(a<b){a=b;return 1;}else return 0;}
template<class T> void So(vector<T> &v) {sort(v.begin(),v.end());}
template<class T> void Sore(vector<T> &v) {sort(v.begin(),v.end(),[](T x,T y){return x>y;});}
void yneos(bool a){if(a) cout<<"Yes\n"; else cout<<"No\n";}
template<class T> void vec_out(vector<T> &p){for(int i=0;i<(int)(p.size());i++){if(i) cout<<" ";cout<<p[i];}cout<<"\n";}
template<class T> T min(vector<T> &a){assert(!a.empty());T ans=a[0];for(auto &x:a) chmin(ans,x);return ans;}
template<class T> T max(vector<T> &a){assert(!a.empty());T ans=a[0];for(auto &x:a) chmax(ans,x);return ans;}

namespace po167{
template <class T,T (*op)(T,T),T(*e)()>
struct segment_tree{
	int _n,size;
	std::vector<T> seg;
	int ceil_pow2(int a){
		int b=1;
		while(a>b){
			b<<=1;
		}
		return b;
	}
	void update(int k){seg[k]=op(seg[k*2],seg[k*2+1]);};
	segment_tree(int n) :_n(n){
		size=ceil_pow2(n);
		seg=std::vector<T>(size*2,e());
	}
	segment_tree(std::vector<T> &p) :_n((int) p.size()){
		size=ceil_pow2(_n);
		seg=std::vector<T>(size*2,e());
		for(int i=0;i<_n;i++) seg[i+size]=p[i];
		for(int i=size-1;i>0;i--) update(i);
	}
	void set(int ind,T val){
		assert(0<=ind&&ind<_n);
		ind+=size;
		seg[ind]=val;
		while(ind!=1){
			ind>>=1;
			update(ind);
		}
	}
    void addl(int ind,T val){
        set(ind,op(get(ind),val));
    }
    void addr(int ind,T val){
        set(ind,op(val,get(ind)));
    }
	T get(int ind){
		assert(0<=ind&&ind<_n);
		return seg[ind+size];
	}
	T query(int l,int r){
		assert(0<=l&&l<=r&&r<=_n);
		T l_val=e();
		T r_val=e();
		l+=size,r+=size;
		while(l<r){
			if(l&1) l_val=op(l_val,seg[l]),l+=1;
			if(r&1) r-=1,r_val=op(seg[r],r_val);
			r>>=1;
			l>>=1;
		}
		return op(l_val,r_val);
	}
	template <bool (*f)(T)> int max_right(int l) {
        return max_right(l, [](T x) { return f(x); });
    }
	template <class F> int max_right(int l, F f) {
		assert(0<=l&&l<=_n);
		assert(f(e()));
		if(f(query(l,_n))) return _n;
		T val=e();
		l+=size;
		while(true){
			while(l%2==0) l>>=1;
			if(!f(op(val,seg[l]))){
				while(l<size){
					l*=2;
					if(f(op(val,seg[l]))){
						val=op(val,seg[l]);
						l++;
					}
				}
				return l-size;
			}
			val=op(val,seg[l]);
			l++;
		}
	}
	template <bool (*f)(T)> int min_left(int r) {
        return min_left(r, [](T x) { return f(x); });
    }
    template <class F> int min_left(int r, F f) {
        assert(0 <= r && r <= _n);
        assert(f(e()));
        if (r == 0) return 0;
        r += size;
        T sm = e();
        do {
            r--;
            while (r > 1 && (r % 2)) r >>= 1;
            if (!f(op(seg[r], sm))) {
                while (r < size) {
                    r = (2 * r + 1);
                    if (f(op(seg[r], sm))) {
                        sm = op(seg[r], sm);
                        r--;
                    }
                }
                return r + 1 - size;
            }
            sm = op(seg[r], sm);
        } while ((r & -r) != r);
        return 0;
    }

};
}
using po167::segment_tree;


using F= int;
F op(F a,F b){return a+b;}
F e(){return 0;}
int target;
bool f(F x){
	return (x%target==0);
}


void solve();
// oddloop
int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	int t=1;
	//cin>>t;
	rep(i,t) solve();
}

void solve(){
	int D;
	cin>>D;
	vector<int> X(D);
	vector<pair<int,int>> p(D);
	segment_tree<F,op,e> seg(D);
	rep(i,D) cin>>X[i],p[i]={X[i],i};
	int Q;
	cin>>Q;
	vector<int> ans(Q,1);
	vector<pair<int,int>> order(2*Q);
	vector<int> L(Q),R(Q),E(Q);
	rep(i,Q){
		cin>>L[i]>>R[i]>>E[i];
		L[i]--;
		R[i]--;
		int a=min(X[L[i]],X[R[i]]);
		int b=max(X[L[i]],X[R[i]]);
		order[i]={a-E[i],i};
		order[i+Q]={b+E[i]+1,i};
	}
	So(order);
	So(p);
	int ind=0;
	rep(i,2*Q){
		while(ind!=D&&p[ind].first<order[i].first){
			seg.set(p[ind].second,1);
			ind++;
		}
		int a=order[i].second;
		if(ans[a]==1) ans[a]=-seg.query(L[a],R[a]+1);
		else ans[a]+=seg.query(L[a],R[a]+1);
	}
	rep(i,Q) cout<<R[i]-L[i]+1-ans[i]<<"\n";
}
accuracy: 1
time_ms: 60
memory_kb: 8236
final_rank: 6

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;

#define REP(i,n) for(int i=0;i<(n);i++)

template<typename T>
struct RangeTree{
  typedef vector<T> V;
  int n;
   
  vector<V> dat;

  static constexpr auto V_merge=[](const V&a,const V&b){
    V res;
    std::merge(a.begin(),a.end(),b.begin(),b.end(),std::back_inserter(res));
    return res;
  };
  
  RangeTree(){}; 
  RangeTree(int n_){
    n=1;
    while(n<n_) n<<=1;
    dat.assign(n<<1,V());
  }
  RangeTree(const V &v){
    int n_=v.size();
    n=1;
    while(n<n_)n<<=1;
    dat.assign(n<<1,V());
    for(int i=0;i<n_;i++)dat[n+i]=V(1,v[i]);
    for(int i=n-1;i;i--)dat[i]=V_merge(dat[2*i],dat[2*i+1]);
  }
  
  void set_val(int idx,T x){
    dat[idx+=n]=V(1,x);  
    while(idx>>=1)dat[idx]=V_merge(dat[2*idx],dat[2*idx+1]);
  }

  /*なんかコンパイル通らん
  template<typename R>
  R query(int a,int b,function<R(const V&)>Q,function<R(R,R)>merge,R e){
    R vl=e,vr=e;
    for(int l=a+n,r=b+n;l<r;l>>=1,r>>=1){
      if(l&1)vl=merge(vl,Q(dat[l++]));
      if(r&1)vr=merge(Q(dat[--r]),vr);
    }
    return merge(vl,vr);
  }
  */

  
  int query(int a,int b,function<int(const V&)>Q,function<int(int,int)>merge,int e){
    int vl=e,vr=e;
    for(int l=a+n,r=b+n;l<r;l>>=1,r>>=1){
      if(l&1)vl=merge(vl,Q(dat[l++]));
      if(r&1)vr=merge(Q(dat[--r]),vr);
    }
    return merge(vl,vr);
  }
  

};

int main(){
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n;cin>>n;
  vector<int> v(n);
  REP(i,n)cin>>v[i];
  RangeTree<int> rt(v);

  int q;cin>>q;
  REP(_,q){
    int l,r,e;cin>>l>>r>>e;l--;r--;
    int a=min(v[l],v[r])-e,b=max(v[l],v[r])+e;

    auto Q=[&](const vector<int>&ve)->int{
      int L=-1,R=ve.size();//[0,L]がa未満
      while(R-L>1){
        int M=(L+R)>>1;
        (ve[M]<a?L:R)=M;
      }
      int tmp=L+1;
      L=-1,R=ve.size();//[R,ve.size())がbより大きい
      while(R-L>1){
        int M=(L+R)>>1;
        (ve[M]>b?R:L)=M;
      }
      return tmp+(ve.size()-R);
    };
    auto merge=[](int a,int b){return a+b;};
    cout<<rt.query(l,r,Q,merge,0)<<endl;
  }
}
accuracy: 1
time_ms: 210
memory_kb: 21816
final_rank: 14

code_snippet: #pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
using namespace std;

#define REP(i,n) for(int i=0;i<(n);i++)

template<typename T>
struct RangeTree{
  typedef vector<T> V;
  int n;
   
  vector<V> dat;

  static constexpr auto V_merge=[](const V&a,const V&b){
    V res;
    std::merge(a.begin(),a.end(),b.begin(),b.end(),std::back_inserter(res));
    return res;
  };
  
  RangeTree(){}; 
  RangeTree(int n_){
    n=1;
    while(n<n_) n<<=1;
    dat.assign(n<<1,V());
  }
  RangeTree(const V &v){
    int n_=v.size();
    n=1;
    while(n<n_)n<<=1;
    dat.assign(n<<1,V());
    for(int i=0;i<n_;i++)dat[n+i]=V(1,v[i]);
    for(int i=n-1;i;i--)dat[i]=V_merge(dat[2*i],dat[2*i+1]);
  }
  
  void set_val(int idx,T x){
    dat[idx+=n]=V(1,x);  
    while(idx>>=1)dat[idx]=V_merge(dat[2*idx],dat[2*idx+1]);
  }
  
  /*
  [a,b)の範囲でのcheck結果の総和を返す Rmergeは結合法則満たす
  例えば Q(v)=v内のk以上の個数 , Rmerge(a,b)=a+b とか
  */
  int query(int a,int b,function<int(const V&)>Q,function<int(int,int)>merge,int e){
    int vl=e,vr=e;
    for(int l=a+n,r=b+n;l<r;l>>=1,r>>=1){
      if(l&1)vl=merge(vl,Q(dat[l++]));
      if(r&1)vr=merge(Q(dat[--r]),vr);
    }
    return merge(vl,vr);
  }
};

int main(){
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n;cin>>n;
  vector<int> v(n);
  REP(i,n)cin>>v[i];
  RangeTree<int> rt(v);

  int q;cin>>q;
  REP(_,q){
    int l,r,e;cin>>l>>r>>e;l--;r--;
    int a=min(v[l],v[r])-e,b=max(v[l],v[r])+e;

    auto Q=[&](const vector<int>&ve)->int{
      int L=-1,R=ve.size();//[0,L]がa未満
      while(R-L>1){
        int M=(L+R)>>1;
        (ve[M]<a?L:R)=M;
      }
      int tmp=L+1;
      L=-1,R=ve.size();//[R,ve.size())がbより大きい
      while(R-L>1){
        int M=(L+R)>>1;
        (ve[M]>b?R:L)=M;
      }
      return tmp+(ve.size()-R);
    };
    auto merge=[](int a,int b){return a+b;};
    cout<<rt.query(l,r,Q,merge,0)<<endl;
  }
}
accuracy: 1
time_ms: 220
memory_kb: 21780
final_rank: 15

code_snippet: #include <bits/stdc++.h>
//#include <atcoder/all>
//using namespace atcoder;
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
using namespace std;
 
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<string> VS;
typedef pair<int, int> PII;
typedef pair<int, int> pii;
typedef pair<long long, long long> PLL;
typedef pair<int, PII> TIII;
 
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
 
 
#define FOR(i, s, n) for (int i = s; i < (int)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define rep(i, a, b) for (int i = a; i < (b); ++i)
#define trav(a, x) for (auto &a : x)
#define all(x) x.begin(), x.end()
 
#define MOD 1000000007
 
template<class T1, class T2> inline bool chmax(T1 &a, T2 b) {if (a < b) {a = b; return true;} return false;}
template<class T1, class T2> inline bool chmin(T1 &a, T2 b) {if (a > b) {a = b; return true;} return false;}
const double EPS = 1e-8, PI = acos(-1);
const double pi = 3.141592653589793238462643383279;
//ここから編集    
typedef string::const_iterator State;
ll GCD(ll a, ll b){
  return (b==0)?a:GCD(b, a%b);
}
ll LCM(ll a, ll b){
  return a/GCD(a, b) * b;
}
template< int mod >
struct ModInt {
  int x;
 
  ModInt() : x(0) {}
 
  ModInt(int64_t y) : x(y >= 0 ? y % mod : (mod - (-y) % mod) % mod) {}
 
  ModInt &operator+=(const ModInt &p) {
    if((x += p.x) >= mod) x -= mod;
    return *this;
  }
 
  ModInt &operator-=(const ModInt &p) {
    if((x += mod - p.x) >= mod) x -= mod;
    return *this;
  }
 
  ModInt &operator*=(const ModInt &p) {
    x = (int) (1LL * x * p.x % mod);
    return *this;
  }
 
  ModInt &operator/=(const ModInt &p) {
    *this *= p.inverse();
    return *this;
  }
 
  ModInt operator-() const { return ModInt(-x); }
 
  ModInt operator+(const ModInt &p) const { return ModInt(*this) += p; }
 
  ModInt operator-(const ModInt &p) const { return ModInt(*this) -= p; }
 
  ModInt operator*(const ModInt &p) const { return ModInt(*this) *= p; }
 
  ModInt operator/(const ModInt &p) const { return ModInt(*this) /= p; }
 
  bool operator==(const ModInt &p) const { return x == p.x; }
 
  bool operator!=(const ModInt &p) const { return x != p.x; }
 
  ModInt inverse() const {
    int a = x, b = mod, u = 1, v = 0, t;
    while(b > 0) {
      t = a / b;
      swap(a -= t * b, b);
      swap(u -= t * v, v);
    }
    return ModInt(u);
  }
 
  ModInt pow(int64_t n) const {
    ModInt ret(1), mul(x);
    while(n > 0) {
      if(n & 1) ret *= mul;
      mul *= mul;
      n >>= 1;
    }
    return ret;
  }
 
  friend ostream &operator<<(ostream &os, const ModInt &p) {
    return os << p.x;
  }
 
  friend istream &operator>>(istream &is, ModInt &a) {
    int64_t t;
    is >> t;
    a = ModInt< mod >(t);
    return (is);
  }
 
  static int get_mod() { return mod; }
};
 
using modint = ModInt< 1000000007 >;
template< typename T >
struct Combination {
  vector< T > _fact, _rfact, _inv;
 
  Combination(int sz) : _fact(sz + 1), _rfact(sz + 1), _inv(sz + 1) {
    _fact[0] = _rfact[sz] = _inv[0] = 1;
    for(int i = 1; i <= sz; i++) _fact[i] = _fact[i - 1] * i;
    _rfact[sz] /= _fact[sz];
    for(int i = sz - 1; i >= 0; i--) _rfact[i] = _rfact[i + 1] * (i + 1);
    for(int i = 1; i <= sz; i++) _inv[i] = _rfact[i] * _fact[i - 1];
  }
 
  inline T fact(int k) const { return _fact[k]; }
 
  inline T rfact(int k) const { return _rfact[k]; }
 
  inline T inv(int k) const { return _inv[k]; }
 
  T P(int n, int r) const {
    if(r < 0 || n < r) return 0;
    return fact(n) * rfact(n - r);
  }
 
  T C(int p, int q) const {
    if(q < 0 || p < q) return 0;
    return fact(p) * rfact(q) * rfact(p - q);
  }
 
  T H(int n, int r) const {
    if(n < 0 || r < 0) return (0);
    return r == 0 ? 1 : C(n + r - 1, r);
  }
};
 
ll modpow(ll x, ll n, ll mod) {
  ll res = 1;
  x %= mod;
  if(x == 0) return 0;
  while(n) {
    if(n&1) res = (res * x) % mod;
    x = (x * x) % mod;
    n >>= 1;
  }
  return res;
} 
inline long long mod(long long a, long long m) {
    return (a % m + m) % m;
}
template<typename T> 
struct BIT{
  int N;
  std::vector<T> node;
  BIT(){}
  BIT(int n){
    N = n;
    node.resize(N+10);
  }
  void build(int n) {
    N = n;
    node.resize(N+10);
  }
  /* a: 1-indexed */
  void add(int a, T x){
    for(int i=a; i<(int)node.size(); i += i & -i) node[i] += x;
  }

  /* [1, a] */
  T sum(int a){
    T res = 0;
    for(int x=a; x>0; x -= x & -x) res += node[x];
    return res;
  }

  /* [l, r] */
  T rangesum(int l, int r){
    return sum(r) - sum(l-1);
  }

  /* 
    a1+a2+...+aw >= valとなるような最小のwを返す
    @verify https://codeforces.com/contest/992/problem/E
  */
  int lower_bound(T val) {
    if(val < 0) return 0;

    int res = 0;
    int n = 1; 
    while (n < N) n *= 2;

    T tv=0;
    for (int k = n; k > 0; k /= 2) {
      if(res + k < N && node[res + k] < val){
        val -= node[res+k];
        res += k;
      }
    }
    return res+1; 
  }
};
struct UnionFind{
  std::vector<int> par;
  std::vector<int> siz;

  UnionFind(int sz_): par(sz_), siz(sz_) {
    for(int i=0; i<sz_; ++i) par[i] = i, siz[i] = 1;
  }

  void init(int sz_){
    par.resize(sz_);
    siz.resize(sz_);
    for(int i=0; i<sz_; ++i) par[i] = i, siz[i] = 1;
  }

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

  bool merge(int x, int y){
    x = root(x), y = root(y);
    if(x == y) return false;
    if(siz[x] < siz[y]) std::swap(x, y);
    siz[x] += siz[y];
    par[y] = x;
    return true;
  }

  bool issame(int x, int y){
    return root(x) == root(y);
  }

  int size(int x){
    return siz[root(x)];
  }
};
struct RollingHash{

    using ull = unsigned long long;
    const ull mod = (1ULL << 61) - 1;
    const ull MASK30 = (1ULL << 30) - 1;
    const ull MASK31 = (1ULL << 31) - 1;

    const ull MASK61 = mod;

    ull base;
    int n;
    vector<ull> hash, pow;

    RollingHash(const string &s)
    {
        random_device rnd;
        mt19937_64 mt(rnd());
        base = 1001;
        
        n = (int)s.size();
        hash.assign(n+1, 0);
        pow.assign(n+1, 1);
        
        for(int i=0; i<n; i++){
            hash[i+1] = calc_mod(mul(hash[i], base) + s[i]);
            pow[i+1] = calc_mod(mul(pow[i], base));
        }
    }

    ull calc_mod(ull x){
        ull xu = x >> 61;
        ull xd = x & MASK61;
        ull res = xu + xd;
        if(res >= mod) res -= mod;
        return res;
    }

    ull mul(ull a, ull b){
        ull au = a >> 31;
        ull ad = a & MASK31;
        ull bu = b >> 31;
        ull bd = b & MASK31;
        ull mid = ad * bu + au * bd;
        ull midu = mid >> 30;
        ull midd = mid & MASK30;
        return calc_mod(au * bu * 2 + midu + (midd << 31) + ad * bd);
    }

    //[l,r)のハッシュ値
    inline ull get(int l, int r){
        ull res = calc_mod(hash[r] + mod*3-mul(hash[l], pow[r-l]));
        return res;
    }
    //string tのハッシュ値
    inline ull get(string t){
        ull res = 0;
        for(int i=0; i<t.size(); i++){
            res = calc_mod(mul(res, base)+t[i]);
        }
        return res;
    }
    //string s中のtの数をカウント
    inline int count(string t) {
        if(t.size() > n) return 0;
        auto hs = get(t);
        int res = 0;
        for(int i=0; i<n-t.size()+1; i++){
            if(get(i, i+t.size()) == hs) res++; 
        }
        return res;
    }

    /* 
        concat 
        @verify https://codeforces.com/problemset/problem/514/C
    */
    inline ull concat(ull h1, ull h2, int h2len){
      return calc_mod(h2 + mul(h1, pow[h2len]));
    }

    // LCPを求める S[a:] T[b:]
    inline int LCP(int a, int b){
        int len = min((int)hash.size()-a, (int)hash.size()-b);
        
        int lb = -1, ub = len;
        while(ub-lb>1){
            int mid = (lb+ub)/2;

            if(get(a, a+mid) == get(b, b+mid)) lb = mid;
            else ub = mid;
        }
        return lb;
    }
};
struct SegmentTree{
  int n0;
  vector<vector<int>> node;

  SegmentTree(vector<int> &v){
    int n = v.size();
    n0 = 1;
    while(n0 < n) n0 <<= 1;
    node.resize(2*n0-1);
    for(int i=0; i<n; i++) node[i+n0-1].push_back(v[i]);
    for(int i=n0-2; i>=0; i--) merge(all(node[i*2+1]), all(node[i*2+2]), back_inserter(node[i]));
  }

  /* 区間内のk番目に小さい要素を取得 */
  /* 区間内のx以上の最小の値を求める */

  int query(int a, int b, int lb, int ub, int k, int l, int r){
    if(b <= l || r <= a){
      return 0;
    }
    if(a <= l && r <= b){
      return upper_bound(all(node[k]), ub) - lower_bound(all(node[k]), lb);
    }
    int lv = query(a, b, lb, ub, k*2+1, l, (l+r)/2);
    int rv = query(a, b, lb, ub, k*2+2, (l+r)/2, r);

    return lv+rv;
  }


  int query(int l, int r, int lb, int ub){
    return query(l, r, lb, ub, 0, 0, n0);
  }
};
int main() {  
  cin.tie(0);
  ios::sync_with_stdio(false);
  cout << fixed << setprecision(12);

  int D; cin >> D;
  vector<int> v(D);
  REP(i,D) cin >> v[i];
  SegmentTree seg(v);
  int Q; cin >> Q;
  while(Q--) {
    int l, r, e; cin >> l >> r >> e;
    l--; r--;
    int a = min(v[l], v[r]);
    int b = max(v[l], v[r]);
    cout << r-l+1-seg.query(l, r+1, a-e, b+e) << '\n';
  }
  return 0;
}
accuracy: 1
time_ms: 180
memory_kb: 21700
final_rank: 13

code_snippet: // #pragma GCC optimize ("O3")
// #pragma GCC target("avx512f")
// #pragma GCC optimize("unroll-loops")
// #ifndef ONLINE_JUDGE
// #define _GLIBCXX_DEBUG
// #endif
#include<bits/stdc++.h>
// #include <boost/multiprecision/cpp_dec_float.hpp>
// #include <boost/multiprecision/cpp_int.hpp>
// #include <boost/rational.hpp>
// namespace mp = boost::multiprecision;
// using Bint=mp::cpp_int;
// using Real = mp::number<mp::cpp_dec_float<1024>>;
// #include<atcoder/all>
using namespace std;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define bit(n,k) (((ll)n>>(ll)k)&1) /*nのk bit目*/
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define eb emplace_back
// #define endl '\n'
#define SZ(x) ((int)(x).size())
#define all(x) (x).begin(),(x).end()
#define rall(x) (x).rbegin(),(x).rend()
#define debug(v) cout<<#v<<":";for(auto x:v){cout<<x<<' ';}cout<<endl;
#define PI 3.14159265359
const double eps = 1e-12;
const long long INF= (long long)1e18+20;
const int inf= 1010101010;
typedef long double D;      // 座標値の型。doubleかlong doubleを想定
typedef complex<D> Point;  // Point
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl>vvl;
typedef vector<vvl>vvvl;
typedef vector<vvvl>vvvvl;
typedef vector<vvvvl>vvvvvl;
typedef vector<int>vi;
typedef vector<vi>vvi;
typedef vector<vvi>vvvi;
typedef vector<vvvi>vvvvi;
typedef vector<vvvvi>vvvvvi;
typedef pair<ll,ll> P;
// typedef double D;    
template<class T> using minpq=priority_queue<T,vector<T>,greater<T>>;
const ll MOD=1000000007LL;
// const ll MOD=998244353LL;
const ll mod=MOD;
vl dx={0,0,1,-1,1,1,-1,-1};
vl dy={1,-1,0,0,-1,1,-1,1};


template<class T> vector<T> make_vec(size_t a) { return vector<T>(a); }
template<class T, class... Ts> auto make_vec(size_t a, Ts... ts) {
  return vector<decltype(make_vec<T>(ts...))>(a, make_vec<T>(ts...));
}

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(b<a){a=b;return true;}return false;}

//素因数分解O(√n)
map<ll,ll>prime_factor(ll n){
  map<ll,ll>res;
  for(ll i=2;i*i<=n;i++){
    while(n%i==0){
      res[i]++;
      n/=i;
    }
  }
  if(n!=1)res[n]=1;
  return res;
}

const ll MAX = 5000010;
long long fac[MAX], finv[MAX], inv[MAX];
//finvが階乗の逆元

// テーブルを作る前処理
void COMinit() {
    fac[0] = fac[1] = 1;
    finv[0] = finv[1] = 1;
    inv[1] = 1;
    for (ll i = 2; i < MAX; i++){
        fac[i] = fac[i - 1] * i % MOD;
        inv[i] = MOD - inv[MOD%i] * (MOD / i) % MOD;
        finv[i] = finv[i - 1] * inv[i] % MOD;
    }
}

// 二項係数計算
long long COM(ll n, ll k){
    if (n < k) return 0;
    if (n < 0 || k < 0) return 0;
    return fac[n] * (finv[k] * finv[n - k] % MOD) % MOD;
}

ll modpow(ll a, ll n,ll mod=MOD) {

    ll res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}

/*Eratosthenes()
ll N=2000010;
vl arr(N);
void Eratosthenes(){
	for(ll i = 0; i < N; i++){
		arr[i] = 1;
	}
        arr[1]=0;
	for(ll i = 2; i < sqrt(N); i++){
		if(arr[i]){
			for(ll j = 0; i * (j + 2) < N; j++){
				arr[i *(j + 2)] = 0;
			}
		}
	}
}*/
//素数判定O(√n)
bool is_prime(ll n){
  for(ll i=2;i*i<=n;i++){
    if(n%i==0)return false;
  }
  return n!=1;
}

//約数の列挙O(√n)
vector<ll>divisor(ll n){
  vector<ll>res;
  for(ll i=1;i*i<=n;i++){
    if(n%i==0){
      res.push_back(i);
      if(i != n/i) res.push_back(n/i);
    }
  }
  return res;
}


/* Trie 木： 文字の種類(char_size)、int型で0に対応する文字(base)
    insert(word): 単語 word を Trie 木に挿入する
    search(word): 単語 word が Trie 木にあるか判定する
    start_with(prefix):  prefix が一致する単語が Trie 木にあるか判定する
    count(): 挿入した単語の数を返す
    size(): Trie 木の頂点数を返す
    計算量：insert, search ともに O(M)（Mは単語の長さ）
*/
template <int char_size, int base>
struct Trie {
    struct Node {            // 頂点を表す構造体
        vector<int> next;    // 子の頂点番号を格納。存在しなければ-1
        vector<int> accept;  // 末端がこの頂点になる単語の word_id を保存
        int c;               // base からの間隔をint型で表現したもの
        int common;          // いくつの単語がこの頂点を共有しているか
        Node(int c_) : c(c_), common(0) {
            next.assign(char_size, -1);
        }
    };
    vector<Node> nodes;  // trie 木本体
    int root;
    Trie() : root(0) {
        nodes.push_back(Node(root));
    }
    // 単語の挿入
    void insert(const string &word, int word_id) {
        int node_id = 0;
        for (int i = 0; i < (int)word.size(); i++) {
            int c = (int)(word[i] - base);
            int &next_id = nodes[node_id].next[c];
            if (next_id == -1) {  // 次の頂点が存在しなければ追加
                next_id = (int)nodes.size();
                nodes.push_back(Node(c));
            }
            ++nodes[node_id].common;
            node_id = next_id;
        }
        ++nodes[node_id].common;
        nodes[node_id].accept.push_back(word_id);
    }
    void insert(const string &word) {
        insert(word, nodes[0].common);
    }
    // 単語とprefixの検索
    bool search(const string &word, bool prefix = false) {
        int node_id = 0;
        for (int i = 0; i < (int)word.size(); i++) {
            int c = (int)(word[i] - base);
            int &next_id = nodes[node_id].next[c];
            if (next_id == -1) {  // 次の頂点が存在しなければ終了
                return false;
            }
            node_id = next_id;
        }
        return (prefix) ? true : nodes[node_id].accept.size() > 0;
    }
    // prefix を持つ単語が存在するかの検索
    bool start_with(const string &prefix) {
        return search(prefix, true);
    }
    // 挿入した単語の数
    int count() const {
        return (nodes[0].common);
    }
    // Trie木のノード数
    int size() const {
        return ((int)nodes.size());
    }
};

// //Lowest Common Ancestor
// struct Edge{
//     int to;
//     Edge(int to):to(to){}
// };
 
// using Graph = vector<vector<Edge>>;
// class lca {
// public:
//     const int n = 0;
//     const int log2_n = 0;
//     vector<vector<int>> parent;
//     vector<int> depth;
 
//     lca() {}
   
//     //g:グラフ root:根
//     lca(const Graph &g, int root)
//         : n(g.size()), log2_n(log2(n) + 1), parent(log2_n, vector<int>(n)), depth(n) {
//         dfs(g, root, -1, 0);
//         for (int k = 0; k + 1 < log2_n; k++) {
//             for (int v = 0; v < (int)g.size(); v++) {
//                 if (parent[k][v] < 0)
//                     parent[k + 1][v] = -1;
//                 else
//                     parent[k + 1][v] = parent[k][parent[k][v]];
//             }
//         }
//     }
 
//     void dfs(const Graph &g, int v, int p, int d) {
//         parent[0][v] = p;
//         depth[v] = d;
//         for (auto &e : g[v]) {
//             if (e.to != p) dfs(g, e.to, v, d + 1);
//         }
//     }
//     //uとvのlcaを取得
//     int get(int u, int v) {
//         if (depth[u] > depth[v]) swap(u, v);
//         for (int k = 0; k < log2_n; k++) {
//             if ((depth[v] - depth[u]) >> k & 1) {
//                 v = parent[k][v];
//             }
//         }
//         if (u == v) return u;
//         for (int k = log2_n - 1; k >= 0; k--) {
//             if (parent[k][u] != parent[k][v]) {
//                 u = parent[k][u];
//                 v = parent[k][v];
//             }
//         }
//         return parent[0][u];
//     }
// 	int dep(int i) {
// 		return depth[i];
// 	}
//     int dist(int u,int v){
//         return depth[u]+depth[v]-depth[get(u,v)]*2;
//     }
// };

// union by size + path having
class UnionFind {
public:
    vector <ll> par; // 各元の親を表す配列
    vector <ll> siz; // 素集合のサイズを表す配列(1 で初期化)

    // Constructor
    UnionFind(ll sz_): par(sz_), siz(sz_, 1LL) {
        for (ll i = 0; i < sz_; ++i) par[i] = i; // 初期では親は自分自身
    }
    void init(ll sz_) {
        par.resize(sz_);
        siz.assign(sz_, 1LL);  // resize だとなぜか初期化されなかった
        for (ll i = 0; i < sz_; ++i) par[i] = i; // 初期では親は自分自身
    }

    // Member Function
    // Find
    ll root(ll x) { // 根の検索
        while (par[x] != x) {
            x = par[x] = par[par[x]]; // x の親の親を x の親とする
        }
        return x;
    }

    // Union(Unite, Merge)
    bool merge(ll x, ll y) {
        x = root(x);
        y = root(y);
        if (x == y) return false;
        // merge technique（データ構造をマージするテク．小を大にくっつける）
        if (siz[x] < siz[y]) swap(x, y);
        siz[x] += siz[y];
        par[y] = x;
        return true;
    }

    bool issame(ll x, ll y) { // 連結判定
        return root(x) == root(y);
    }

    ll size(ll x) { // 素集合のサイズ
        return siz[root(x)];
    }
};

// 0-indexed parmutation only
vvl cycle_partition(const vl &p){
    ll n=p.size();
    vvl ret;
    vector<bool> check(n,false);
    rep(i,n)if(!check[p[i]]){
        vl v;
        ll pos=p[i];
        v.pb(i);
        check[i]=true;
        while(pos!=i){
            v.pb(pos);
            check[pos]=true;
            pos=p[pos];
        }
        ret.pb(v);
    }
    return ret;
}

vl Z_algorithm(vl s){
    ll c=0,n=s.size();
    vl Z(n,0);
    for(ll i=1;i<n;i++){
        ll l=i-c;
        if(i+Z[l]<c+Z[c]){
            Z[i]=Z[l];
        }else{
            ll j=max(0LL,c+Z[c]-i);
            while(i+j<n && s[j]==s[i+j])j++;
            Z[i]=j;
            c=i;
        }
    }
    Z[0]=n;
    return Z;
}

//Manachar　修理中
// vl Manachar(string S){
//     ll c=0,n=S.size();
//     vl R(n,1);
//     for(ll i=0;i<n;i++){
//         ll l=c-(i-c);
//         if(i+R[l]<c+R[c]){
//             R[i]=R[l];
//         }else{
//             ll j=c+R[c]-i;
//             while(i-j>=0 && i+j<n && S[i-j] == S[i+j])j++;
//             R[i]=j;
//             c=i;
//         }
//     }
//     return R;
// }



template <typename T>
T pow(T a, long long n, T e = 1) {
    T ret = e;
    while (n) {
        if (n & 1) ret *= a;
        a *= a;
        n >>= 1;
    }
    return ret;
}
 
template <int mod>
struct ModInt {
    int x;
    ModInt() : x(0) {}
    ModInt(long long x_) {
        if ((x = x_ % mod + mod) >= mod) x -= mod;
    }
    ModInt& operator+=(ModInt rhs) {
        if ((x += rhs.x) >= mod) x -= mod;
        return *this;
    }
    ModInt& operator-=(ModInt rhs) {
        if ((x -= rhs.x) < 0) x += mod;
        return *this;
    }
    ModInt& operator*=(ModInt rhs) {
        x = (unsigned long long)x * rhs.x % mod;
        return *this;
    }
    ModInt& operator/=(ModInt rhs) {
        x = (unsigned long long)x * rhs.inv().x % mod;
        return *this;
    }
 
    ModInt operator-() const { return -x < 0 ? mod - x : -x; }
    ModInt operator+(ModInt rhs) const { return ModInt(*this) += rhs; }
    ModInt operator-(ModInt rhs) const { return ModInt(*this) -= rhs; }
    ModInt operator*(ModInt rhs) const { return ModInt(*this) *= rhs; }
    ModInt operator/(ModInt rhs) const { return ModInt(*this) /= rhs; }
    bool operator==(ModInt rhs) const { return x == rhs.x; }
    bool operator!=(ModInt rhs) const { return x != rhs.x; }
    ModInt inv() const { return pow(*this, mod - 2); }
 
    friend ostream& operator<<(ostream& s, ModInt<mod> a) {
        s << a.x;
        return s;
    }
    friend istream& operator>>(istream& s, ModInt<mod>& a) {
        s >> a.x;
        return s;
    }
};
 
using mint = ModInt<MOD>;
typedef vector<mint> vm;
typedef vector<vector<mint> >vvm;
typedef vector<vector<vector<mint> > >vvvm;

template <typename T>
struct segment_tree_beats{
	int N;
	vector<T> max1, max2, min1, min2, add, sum;
	vector<int> maxc, minc, len;
	void update_max(int i, T x){
		sum[i] += (x - max1[i]) * maxc[i];
		if (max1[i] == min1[i]){
			min1[i] = x;
		} else if (max1[i] == min2[i]){
			min2[i] = x;
		}
		max1[i] = x;
	}
	void update_min(int i, T x){
		sum[i] += (x - min1[i]) * minc[i];
		if (min1[i] == max1[i]){
			max1[i] = x;
		} else if (min1[i] == max2[i]){
			max2[i] = x;
		}
		min1[i] = x;
	}
	void update_add(int i, T x){
		max1[i] += x;
		if (max2[i] != -INF){
			max2[i] += x;
		}
		min1[i] += x;
		if (min2[i] != INF){
			min2[i] += x;
		}
		sum[i] += x * len[i];
		add[i] += x;
	}
	void push(int i){
		if (i >= N - 1){
			return;
		}
		int l = i * 2 + 1;
		int r = i * 2 + 2;
		if (add[i] != 0){
			update_add(l, add[i]);
			update_add(r, add[i]);
			add[i] = 0;
		}
		if (max1[i] < max1[l]){
			update_max(l, max1[i]);
		}
		if (min1[i] > min1[l]){
			update_min(l, min1[i]);
		}
		if (max1[i] < max1[r]){
			update_max(r, max1[i]);
		}
		if (min1[i] > min1[r]){
			update_min(r, min1[i]);
		}
	}
	void update(int i){
		int l = i * 2 + 1;
		int r = i * 2 + 2;
		sum[i] = sum[l] + sum[r];
		if (max1[l] > max1[r]){
			max1[i] = max1[l];
			max2[i] = max(max2[l], max1[r]);
			maxc[i] = maxc[l];
		} else if (max1[l] < max1[r]){
			max1[i] = max1[r];
			max2[i] = max(max1[l], max2[r]);
			maxc[i] = maxc[r];
		} else {
			max1[i] = max1[l];
			max2[i] = max(max2[l], max2[r]);
			maxc[i] = maxc[l] + maxc[r];
		}
		if (min1[l] < min1[r]){
			min1[i] = min1[l];
			min2[i] = min(min2[l], min1[r]);
			minc[i] = minc[l];
		} else if (min1[l] > min1[r]){
			min1[i] = min1[r];
			min2[i] = min(min1[l], min2[r]);
			minc[i] = minc[r];
		} else {
			min1[i] = min1[l];
			min2[i] = min(min2[l], min2[r]);
			minc[i] = minc[l] + minc[r];
		}
	}
	segment_tree_beats(vector<T> A){
		int n = A.size();
		N = 1;
		while (N < n){
			N *= 2;
		}
		max1 = vector<T>(N * 2 - 1, -INF);
		max2 = vector<T>(N * 2 - 1, -INF);
		min1 = vector<T>(N * 2 - 1, INF);
		min2 = vector<T>(N * 2 - 1, INF);
		add = vector<T>(N * 2 - 1, 0);
		sum = vector<T>(N * 2 - 1, 0);
		maxc = vector<int>(N * 2 - 1, 1);
		minc = vector<int>(N * 2 - 1, 1);
		len = vector<int>(N * 2 - 1, 1);
		for (int i = 0; i < n; i++){
			max1[N - 1 + i] = A[i];
			min1[N - 1 + i] = A[i];
			sum[N - 1 + i] = A[i];
		}
		for (int i = N - 2; i >= 0; i--){
			len[i] = len[i * 2 + 1] + len[i * 2 + 2];
			update(i);
		}
	}
	void range_chmin(int L, int R, T x, int i, int l, int r){
		if (r <= L || R <= l || x >= max1[i]){
			return;
		} else if (L <= l && r <= R && x > max2[i]){
			update_max(i, x);
			return;
		}
		push(i);
		int m = (l + r) / 2;
		range_chmin(L, R, x, i * 2 + 1, l, m);
		range_chmin(L, R, x, i * 2 + 2, m, r);
		update(i);
	}
	void range_chmax(int L, int R, T x, int i, int l, int r){
		if (r <= L || R <= l || x <= min1[i]){
			return;
		} else if (L <= l && r <= R && x < min2[i]){
			update_min(i, x);
			return;
		}
		push(i);
		int m = (l + r) / 2;
		range_chmax(L, R, x, i * 2 + 1, l, m);
		range_chmax(L, R, x, i * 2 + 2, m, r);
		update(i);
	}
	void range_add(int L, int R, T x, int i, int l, int r){
		if (r <= L || R <= l){
			return;
		} else if (L <= l && r <= R){
			update_add(i, x);
			return;
		}
		push(i);
		int m = (l + r) / 2;
		range_add(L, R, x, i * 2 + 1, l, m);
		range_add(L, R, x, i * 2 + 2, m, r);
		update(i);
	}
	T range_sum(int L, int R, int i, int l, int r){
		if (r <= L || R <= l){
			return 0;
		} else if (L <= l && r <= R){
			return sum[i];
		}
		push(i);
		int m = (l + r) / 2;
		return range_sum(L, R, i * 2 + 1, l, m) +	range_sum(L, R, i * 2 + 2, m, r);
	}
	void range_chmin(int L, int R, T x){
		range_chmin(L, R, x, 0, 0, N);
	}
	void range_chmax(int L, int R, T x){
		range_chmax(L, R, x, 0, 0, N);
	}
	void range_add(int L, int R, T x){
		range_add(L, R, x, 0, 0, N);
	}
	T range_sum(int L, int R){
		return range_sum(L, R, 0, 0, N);
	}
};

struct PartiallyPersistentUnionFind {
    vector<ll> par, last;
    vector<vector<P> > history;
    
    PartiallyPersistentUnionFind(ll n) : par(n, -1), last(n, -1), history(n) {
        for (auto &vec : history) vec.emplace_back(-1, -1);
    }
    void init(ll n) {
        par.assign(n, -1); last.assign(n, -1); history.assign(n, vector<P>());
        for (auto &vec : history) vec.emplace_back(-1, -1);
    }
    
    ll root(ll t, ll x) {
        if (last[x] == -1 || t < last[x]) return x;
        return root(t, par[x]);
    }
    
    bool issame(ll t, ll x, ll y) {
        return root(t, x) == root(t, y);
    }
    
    bool merge(ll t, ll x, ll y) {
        x = root(t, x); y = root(t, y);
        if (x == y) return false;
        if (par[x] > par[y]) swap(x, y); // merge technique
        par[x] += par[y];
        par[y] = x;
        last[y] = t;
        history[x].emplace_back(t, par[x]);
        return true;
    }
    
    ll size(ll t, ll x) {
        x = root(t, x);
        return -prev(lower_bound(history[x].begin(), history[x].end(), make_pair(t, 0LL)))->second;
    }
};

// matrix
// template<class T> struct Matrix {
//     vector<vector<T> > val;
//     Matrix(int n = 1, int m = 1, T v = 0) : val(n, vector<T>(m, v)) {}
//     void init(int n, int m, T v = 0) {val.assign(n, vector<T>(m, v));}
//     void resize(int n, int m) {
//         val.resize(n);
//         for (int i = 0; i < n; ++i) val[i].resize(m);
//     }
//     Matrix<T>& operator = (const Matrix<T> &A) {
//         val = A.val;
//         return *this;
//     }
//     size_t size() const {return val.size();}
//     vector<T>& operator [] (int i) {return val[i];}
//     const vector<T>& operator [] (int i) const {return val[i];}
//     friend ostream& operator << (ostream& s, const Matrix<T>& M) {
//         s << endl;
//         for (int i = 0; i < (int)M.size(); ++i) s << M[i] << endl;
//         return s;
//     }
// };

// template<class T> Matrix<T> operator * (const Matrix<T> &A, const Matrix<T> &B) {
//     Matrix<T> R(A.size(), B[0].size());
//     for (int i = 0; i < A.size(); ++i)
//         for (int j = 0; j < B[0].size(); ++j)
//             for (int k = 0; k < B.size(); ++k)
//                 R[i][j] += A[i][k] * B[k][j];
//     return R;
// }

// template<class T> Matrix<T> pow(const Matrix<T> &A, long long n) {
//     Matrix<T> R(A.size(), A.size());
//     auto B = A;
//     for (int i = 0; i < A.size(); ++i) R[i][i] = 1;
//     while (n > 0) {
//         if (n & 1) R = R * B;
//         B = B * B;
//         n >>= 1;
//     }
//     return R;
// }

// template<class T> vector<T> operator * (const Matrix<T> &A, const vector<T> &B) {
//     vector<T> v(A.size());
//     for (int i = 0; i < A.size(); ++i)
//         for (int k = 0; k < B.size(); ++k)
//             v[i] += A[i][k] * B[k];
//     return v;
// }

// template<class T> Matrix<T> operator + (const Matrix<T> &A, const Matrix<T> &B) {
//     Matrix<T> R(A.size(), A[0].size());
//     for (int i = 0; i < A.size(); ++i)
//         for (int j = 0; j < A[0].size(); ++j)
//             R[i][j] = A[i][j] + B[i][j];
//     return R;
// }

// template<class T> Matrix<T> operator - (const Matrix<T> &A, const Matrix<T> &B) {
//     Matrix<T> R(A.size(), A[0].size());
//     for (int i = 0; i < A.size(); ++i)
//         for (int j = 0; j < A[0].size(); ++j)
//             R[i][j] = A[i][j] - B[i][j];
//     return R;
// }

// const int MAX_ROW = 510; // to be set appropriately
// const int MAX_COL = 510; // to be set appropriately
// struct BitMatrix {
//     int H, W;
//     bitset<MAX_COL> val[MAX_ROW];
//     BitMatrix(int m = 1, int n = 1) : H(m), W(n) {}
//     inline bitset<MAX_COL>& operator [] (int i) {return val[i];}
// };

// int GaussJordan(BitMatrix &A, bool is_extended = false) {
//     int rank = 0;
//     for (int col = 0; col < A.W; ++col) {
//         if (is_extended && col == A.W - 1) break;
//         int pivot = -1;
//         for (int row = rank; row < A.H; ++row) {
//             if (A[row][col]) {
//                 pivot = row;
//                 break;
//             }
//         }
//         if (pivot == -1) continue;
//         swap(A[pivot], A[rank]);
//         for (int row = 0; row < A.H; ++row) {
//             if (row != rank && A[row][col]) A[row] ^= A[rank];
//         }
//         ++rank;
//     }
//     return rank;
// }

// int linear_equation(BitMatrix A, vector<int> b, vector<int> &res) {
//     int m = A.H, n = A.W;
//     BitMatrix M(m, n + 1);
//     for (int i = 0; i < m; ++i) {
//         for (int j = 0; j < n; ++j) M[i][j] = A[i][j];
//         M[i][n] = b[i];
//     }
//     int rank = GaussJordan(M, true);

//     // check if it has no solution
//     for (int row = rank; row < m; ++row) if (M[row][n]) return -1;

//     // answer
//     res.assign(n, 0);
//     for (int i = 0; i < rank; ++i) res[i] = M[i][n];
//     return rank;
// }


ll exp(ll n,ll r){
    if(r==0)return 1;
    return n*exp(n,r-1);
}

ll factorial(int n){
    if(n==0)return 1;
    return n*factorial(n-1);
}


void input_vvi(int n){
    vector<string>s(n);
    string ans;
    ans+="vector<vector<int>> dp={";
    rep(i,n){
        cin>>s[i];
        ans+="{";
        ans+=s[i];
        ans+="}";
        if(i!=n-1)ans+=",";
    }
    ans+="};";
    cout<<ans<<endl;
}

/**
 * @brief Rolling-Hash(ローリングハッシュ)
 * @see https://qiita.com/keymoon/items/11fac5627672a6d6a9f6
 * @docs docs/rolling-hash.md
 */
struct RollingHash {
  static const uint64_t mod = (1ull << 61ull) - 1;
  using uint128_t = __uint128_t;
  vector< uint64_t > power;
  const uint64_t base;

  static inline uint64_t add(uint64_t a, uint64_t b) {
    if((a += b) >= mod) a -= mod;
    return a;
  }

  static inline uint64_t mul(uint64_t a, uint64_t b) {
    uint128_t c = (uint128_t) a * b;
    return add(c >> 61, c & mod);
  }

  static inline uint64_t generate_base() {
    mt19937_64 mt(chrono::steady_clock::now().time_since_epoch().count());
    uniform_int_distribution< uint64_t > rand(1, RollingHash::mod - 1);
    return rand(mt);
  }

  inline void expand(size_t sz) {
    if(power.size() < sz + 1) {
      int pre_sz = (int) power.size();
      power.resize(sz + 1);
      for(int i = pre_sz - 1; i < sz; i++) {
        power[i + 1] = mul(power[i], base);
      }
    }
  }

  explicit RollingHash(uint64_t base = generate_base()) : base(base), power{1} {}

  vector< uint64_t > build(const string &s) const {
    int sz = s.size();
    vector< uint64_t > hashed(sz + 1);
    for(int i = 0; i < sz; i++) {
      hashed[i + 1] = add(mul(hashed[i], base), s[i]);
    }
    return hashed;
  }

  template< typename T >
  vector< uint64_t > build(const vector< T > &s) const {
    int sz = s.size();
    vector< uint64_t > hashed(sz + 1);
    for(int i = 0; i < sz; i++) {
      hashed[i + 1] = add(mul(hashed[i], base), s[i]);
    }
    return hashed;
  }

  uint64_t query(const vector< uint64_t > &s, int l, int r) {
    expand(r - l);
    return add(s[r], mod - mul(s[l], power[r - l]));
  }

  uint64_t combine(uint64_t h1, uint64_t h2, size_t h2len) {
    expand(h2len);
    return add(mul(h1, power[h2len]), h2);
  }

  int lcp(const vector< uint64_t > &a, int l1, int r1, const vector< uint64_t > &b, int l2, int r2) {
    int len = min(r1 - l1, r2 - l2);
    int low = 0, high = len + 1;
    while(high - low > 1) {
      int mid = (low + high) / 2;
      if(query(a, l1, l1 + mid) == query(b, l2, l2 + mid)) low = mid;
      else high = mid;
    }
    return low;
  }
};

struct SuccinctIndexableDictionary {
  size_t length;
  size_t blocks;
  vector< unsigned > bit, sum;

  SuccinctIndexableDictionary() = default;

  SuccinctIndexableDictionary(size_t length) : length(length), blocks((length + 31) >> 5) {
    bit.assign(blocks, 0U);
    sum.assign(blocks, 0U);
  }

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

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

  bool operator[](int k) {
    return (bool((bit[k >> 5] >> (k & 31)) & 1));
  }

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

  int rank(bool val, int k) {
    return (val ? rank(k) : k - rank(k));
  }
};

/*
 * @brief Wavelet-Matrix(ウェーブレット行列)
 * @docs docs/wavelet-matrix.md
 */
template< typename T, int MAXLOG >
struct WaveletMatrix {
  size_t length;
  SuccinctIndexableDictionary matrix[MAXLOG];
  int mid[MAXLOG];

  WaveletMatrix() = default;

  WaveletMatrix(vector< T > v) : length(v.size()) {
    vector< T > l(length), r(length);
    for(int level = MAXLOG - 1; level >= 0; level--) {
      matrix[level] = SuccinctIndexableDictionary(length + 1);
      int left = 0, right = 0;
      for(int i = 0; i < length; i++) {
        if(((v[i] >> level) & 1)) {
          matrix[level].set(i);
          r[right++] = v[i];
        } else {
          l[left++] = v[i];
        }
      }
      mid[level] = left;
      matrix[level].build();
      v.swap(l);
      for(int i = 0; i < right; i++) {
        v[left + i] = r[i];
      }
    }
  }

  pair< int, int > succ(bool f, int l, int r, int level) {
    return {matrix[level].rank(f, l) + mid[level] * f, matrix[level].rank(f, r) + mid[level] * f};
  }

  // v[k]
  T access(int k) {
    T ret = 0;
    for(int level = MAXLOG - 1; level >= 0; level--) {
      bool f = matrix[level][k];
      if(f) ret |= T(1) << level;
      k = matrix[level].rank(f, k) + mid[level] * f;
    }
    return ret;
  }

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

  // count i s.t. (0 <= i < r) && v[i] == x
  int rank(const T &x, int r) {
    int l = 0;
    for(int level = MAXLOG - 1; level >= 0; level--) {
      tie(l, r) = succ((x >> level) & 1, l, r, level);
    }
    return r - l;
  }

  // k-th(0-indexed) smallest number in v[l,r)
  T kth_smallest(int l, int r, int k) {
    assert(0 <= k && k < r - l);
    T ret = 0;
    for(int level = MAXLOG - 1; level >= 0; level--) {
      int cnt = matrix[level].rank(false, r) - matrix[level].rank(false, l);
      bool f = cnt <= k;
      if(f) {
        ret |= T(1) << level;
        k -= cnt;
      }
      tie(l, r) = succ(f, l, r, level);
    }
    return ret;
  }

  // k-th(0-indexed) largest number in v[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) {
    int ret = 0;
    for(int level = MAXLOG - 1; level >= 0; level--) {
      bool f = ((upper >> level) & 1);
      if(f) ret += matrix[level].rank(false, r) - matrix[level].rank(false, l);
      tie(l, r) = succ(f, l, r, level);
    }
    return ret;
  }

  // count i s.t. (l <= i < r) && (lower <= v[i] < upper)
  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);
  }
};

template< typename T, int MAXLOG >
struct CompressedWaveletMatrix {
  WaveletMatrix< int, MAXLOG > mat;
  vector< T > ys;

  CompressedWaveletMatrix(const vector< T > &v) : ys(v) {
    sort(begin(ys), end(ys));
    ys.erase(unique(begin(ys), end(ys)), end(ys));
    vector< int > t(v.size());
    for(int i = 0; i < v.size(); i++) t[i] = get(v[i]);
    mat = WaveletMatrix< int, MAXLOG >(t);
  }

  inline int get(const T& x) {
    return lower_bound(begin(ys), end(ys), x) - begin(ys);
  }

  T access(int k) {
    return ys[mat.access(k)];
  }

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

  int rank(const T &x, int r) {
    auto pos = get(x);
    if(pos == ys.size() || ys[pos] != x) return 0;
    return mat.rank(pos, r);
  }

  T kth_smallest(int l, int r, int k) {
    return ys[mat.kth_smallest(l, r, k)];
  }

  T kth_largest(int l, int r, int k) {
    return ys[mat.kth_largest(l, r, k)];
  }

  int range_freq(int l, int r, T upper) {
    return mat.range_freq(l, r, get(upper));
  }

  int range_freq(int l, int r, T lower, T upper) {
    return mat.range_freq(l, r, get(lower), get(upper));
  }

  T prev_value(int l, int r, T upper) {
    auto ret = mat.prev_value(l, r, get(upper));
    return ret == -1 ? T(-1) : ys[ret];
  }

  T next_value(int l, int r, T lower) {
    auto ret = mat.next_value(l, r, get(lower));
    return ret == -1 ? T(-1) : ys[ret];
  }
};

int main(){
    ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    cout << fixed << setprecision(13);
    //CDEは制約を読もう！
    //主客転倒！二重和のときは一番内側の物が何回使われるか
    //√Nで分けるテク
    //絶対値は外して2通りの式にした後、変数ごとにまとめる
    //組み合わせが少ないそうなものはdfsで実行してみる（典型25）
    /*--------------------------------*/

    int n;cin>>n;
    vl x(n);
    rep(i,n)cin>>x[i],x[i]+=(ll)(5e8+eps);
    int q;cin>>q;
    CompressedWaveletMatrix<ll,17> wm (x);
    while(q--){
        int l,r,e;cin>>l>>r>>e;
        l--;
        ll mi=min(x[l],x[r-1]);
        ll ma=max(x[l],x[r-1]);
        cout<<wm.range_freq(l,r,0,mi-e)+wm.range_freq(l,r,ma+e+1,INF)<<endl;
    }
}
accuracy: 1
time_ms: 190
memory_kb: 6792
final_rank: 7

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <queue>
#include <string>
#include <map>
#include <set>
#include <stack>
#include <tuple>
#include <deque>
#include <array>
#include <numeric>
#include <bitset>
#include <iomanip>
#include <cassert>
#include <chrono>
#include <random>
#include <limits>
#include <iterator>
#include <functional>
#include <sstream>
#include <fstream>
#include <complex>
#include <cstring>
#include <unordered_map>
using namespace std;

using ll = long long;
using P = pair<int, int>;
constexpr int INF = 1001001001;
constexpr int mod = 1000000007;
// constexpr int mod = 998244353;

template<class T>
inline bool chmax(T& x, T y){
    if(x < y){
        x = y;
        return true;
    }
    return false;
}
template<class T>
inline bool chmin(T& x, T y){
    if(x > y){
        x = y;
        return true;
    }
    return false;
}

struct SuccinctIndexableDictionary {
    size_t length, blocks;
    vector<unsigned> bit, sum;

    SuccinctIndexableDictionary() = default;

    SuccinctIndexableDictionary(size_t length) : length(length), blocks((length + 31) >> 5) {
        bit.assign(blocks, 0U);
        sum.assign(blocks, 0U);
    }

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

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

    bool operator[](int k){
        return (bool((bit[k >> 5] >> (k & 31)) & 1));
    }

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

    // f : bit flag
    int rank(bool f, int k){
        return (f ? rank(k) : k - rank(k));
    }
};

template<typename T, int MAXLOG>
struct WaveletMatrix {
    size_t length;
    SuccinctIndexableDictionary matrix[MAXLOG];
    int mid[MAXLOG];

    WaveletMatrix() = default;

    WaveletMatrix(vector<T> v) : length(v.size()) {
        vector<T> zero(length), one(length);
        for(int level = MAXLOG - 1; level >= 0; --level){
            matrix[level] = SuccinctIndexableDictionary(length + 1);
            int left = 0, right = 0;
            for(int i = 0; i < length; ++i){
                if(((v[i] >> level & 1))){
                    matrix[level].set(i);
                    one[right++] = v[i];
                }
                else{
                    zero[left++] = v[i];
                }
            }
            mid[level] = left;
            matrix[level].build();
            v.swap(zero);
            for(int i = 0; i < right; ++i){
                v[left + i] = one[i];
            }
        }
    }

    pair<int, int> succ(bool f, int l, int r, int level){
        return {matrix[level].rank(f, l) + mid[level] * f, matrix[level].rank(f, r) + mid[level] * f};
    }

    T access(int k){
        T ret = 0;
        for(int level = MAXLOG - 1; level >= 0; --level){
            bool f = matrix[level][k];
            if(f)   ret |= T(1) << level;
            k = matrix[level].rank(f, k) + mid[level] * f;
        }
        return ret;
    }

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

    int rank(const T& x, int r){
        int l = 0;
        for(int level = MAXLOG - 1; level >= 0; --level){
            tie(l, r) = succ((x >> level) & 1, l, r, level);
        }
        return r - l;
    }

    T kth_smallest(int l, int r, int k){
        assert(0 <= k && k < r - l);
        T ret = 0;
        for(int level = MAXLOG - 1; level >= 0; --level){
            int cnt = matrix[level].rank(false, r) - matrix[level].rank(false, l);
            bool f = cnt <= k;
            if(f){
                ret |= T(1) << level;
                k -= cnt;
            }
            tie(l, r) = succ(f, l, r, level);
        }
        return ret;
    }

    T kth_largest(int l, int r, int k){
        return kth_smallest(l, r, r - l - k - 1);
    }

    int range_freq(int l, int r, T upper){
        int ret = 0;
        for(int level = MAXLOG - 1; level >= 0; --level){
            bool f = ((upper >> level) & 1);
            if(f)   ret += matrix[level].rank(false, r) - matrix[level].rank(false, l);
            tie(l, r) = succ(f, l, r, level);
        }
        return ret;
    }

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

    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);
    }

    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);
    }
};

template<typename T, int MAXLOG>
struct CompressedWaveletMatrix {
    WaveletMatrix<int, MAXLOG> mat;
    vector<T> ys;

    CompressedWaveletMatrix(const vector<T>& v) : ys(v) {
        sort(begin(ys), end(ys));
        ys.erase(unique(ys.begin(), ys.end()), ys.end());
        vector<int> t(v.size());
        for(int i = 0; i < (int)v.size(); ++i)  t[i] = get(v[i]);
        mat = WaveletMatrix<int, MAXLOG>(t);
    }

    inline int get(const T& x){
        return lower_bound(begin(ys), end(ys), x) - begin(ys);
    }

    T access(int k){
        return ys[mat.access(k)];
    }

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

    int rank(const T& x, int r){
        auto pos = get(x);
        if(pos == ys.size() || ys[pos] != x)    return 0;
        return mat.rank(pos, r);
    }

    T kth_smallest(int l, int r, int k){
        return ys[mat.kth_smallest(l, r, k)];
    }

    T kth_largest(int l, int r, int k){
        return ys[mat.kth_largest(l, r, k)];
    }

    int range_freq(int l, int r, T upper){
        return mat.range_freq(l, r, get(upper));
    }

    int range_freq(int l, int r, T lower, T upper){
        return mat.range_freq(l, r, get(lower), get(upper));
    }

    T prev_value(int l, int r, T upper){
        auto ret = mat.prev_value(l, r, get(upper));
        return ret == -1 ? T(-1) : ys[ret];
    }

    T next_value(int l, int r, T lower){
        auto ret = mat.next_value(l, r, get(lower));
        return ret == -1 ? T(-1) : ys[ret];
    }
};

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int D, Q;
    cin >> D;
    vector<int> x(D);
    for(int i = 0; i < D; ++i)  cin >> x[i];
    CompressedWaveletMatrix<int, 30> cwm(x);

    cin >> Q;
    for(int i = 0; i < Q; ++i){
        int l, r, e;
        cin >> l >> r >> e;
        --l, --r;
        int lb = min(x[l], x[r]), ub = max(x[l], x[r]);
        lb -= e, ub += e;
        ++r;
        cout << r - l - cwm.range_freq(l, r, lb, ub + 1) << '\n';
    }

    return 0;
}
accuracy: 1
time_ms: 120
memory_kb: 6256
final_rank: 5

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

using namespace std;

using int64 = long long;
const int mod = 1e9 + 7;

const int64 infll = (1LL << 62) - 1;
const int inf = (1 << 30) - 1;

struct IoSetup {
  IoSetup() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(10);
    cerr << fixed << setprecision(10);
  }
} iosetup;


template< typename T1, typename T2 >
ostream &operator<<(ostream &os, const pair< T1, T2 > &p) {
  os << p.first << " " << p.second;
  return os;
}

template< typename T1, typename T2 >
istream &operator>>(istream &is, pair< T1, T2 > &p) {
  is >> p.first >> p.second;
  return is;
}

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 != v.size() ? " " : "");
  }
  return os;
}

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

template< typename T1, typename T2 >
inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }

template< typename T1, typename T2 >
inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); }

template< typename T = int64 >
vector< T > make_v(size_t a) {
  return vector< T >(a);
}

template< typename T, typename... Ts >
auto make_v(size_t a, Ts... ts) {
  return vector< decltype(make_v< T >(ts...)) >(a, make_v< T >(ts...));
}

template< typename T, typename V >
typename enable_if< is_class< T >::value == 0 >::type fill_v(T &t, const V &v) {
  t = v;
}

template< typename T, typename V >
typename enable_if< is_class< T >::value != 0 >::type fill_v(T &t, const V &v) {
  for(auto &e : t) fill_v(e, v);
}

template< typename F >
struct FixPoint : F {
  FixPoint(F &&f) : F(forward< F >(f)) {}

  template< typename... Args >
  decltype(auto) operator()(Args &&... args) const {
    return F::operator()(*this, forward< Args >(args)...);
  }
};

template< typename F >
inline decltype(auto) MFP(F &&f) {
  return FixPoint< F >{forward< F >(f)};
}

struct SuccinctIndexableDictionary {
  size_t length;
  size_t blocks;
  vector< unsigned > bit, sum;

  SuccinctIndexableDictionary() = default;

  SuccinctIndexableDictionary(size_t length) : length(length), blocks((length + 31) >> 5) {
    bit.assign(blocks, 0U);
    sum.assign(blocks, 0U);
  }

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

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

  bool operator[](int k) {
    return (bool((bit[k >> 5] >> (k & 31)) & 1));
  }

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

  int rank(bool val, int k) {
    return (val ? rank(k) : k - rank(k));
  }
};


template< typename T, int MAXLOG >
struct WaveletTree {

  struct Node {
    SuccinctIndexableDictionary sid;
    Node *ch[2];

    Node() = default;

    Node(size_t length) : sid(length + 1), ch{nullptr} {}

  };

  Node *root;

  Node *build(vector< T > &v, vector< T > &rbuff, int bit, int l, int r) {
    if(l >= r || bit == -1) return nullptr;
    Node *node = new Node(r - l);
    int left = 0, right = 0;
    for(int k = l; k < r; k++) {
      if(((v[k] >> bit) & 1)) {
        rbuff[right++] = v[k];
        node->sid.set(k - l);
      } else {
        v[l + left++] = v[k];
      }
    }
    for(int k = 0; k < right; k++) {
      v[l + left + k] = rbuff[k];
    }
    node->sid.build();
    node->ch[0] = build(v, rbuff, bit - 1, l, l + left);
    node->ch[1] = build(v, rbuff, bit - 1, l + left, r);
    return node;
  }

  WaveletTree() = default;

  WaveletTree(vector< T > v) {
    vector< T > rbuff(v.size());
    root = build(v, rbuff, MAXLOG - 1, 0, v.size());
  }

  int rank(Node *t, int l, int r, const T &x, int level) {
    if(l >= r || t == nullptr) return 0;
    if(level == -1) return r - l;
    bool f = (x >> level) & 1;
    l = t->sid.rank(f, l), r = t->sid.rank(f, r);
    return rank(t->ch[f], l, r, x, level - 1);
  }

  int rank(const T &x, int r) {
    return rank(root, 0, r, x, MAXLOG - 1);
  }

  T kth_smallest(Node *t, int l, int r, int k, int level) {
    if(l >= r || t == nullptr) return 0;
    int cnt = t->sid.rank(false, r) - t->sid.rank(false, l);
    bool f = cnt <= k;
    l = t->sid.rank(f, l), r = t->sid.rank(f, r);
    if(f) return kth_smallest(t->ch[f], l, r, k - cnt, level - 1) | ((T(1) << level));
    return kth_smallest(t->ch[f], l, r, k, level - 1);
  }

  // k-th(0-indexed) smallest number in v[l,r)
  T kth_smallest(int l, int r, int k) {
    assert(0 <= k && k < r - l);
    return kth_smallest(root, l, r, k, MAXLOG - 1);
  }

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

  int range_freq(Node *t, int l, int r, T upper, int level) {
    if(t == nullptr || l >= r) return 0;
    bool f = ((upper >> level) & 1);
    int ret = 0;
    if(f) ret += t->sid.rank(false, r) - t->sid.rank(false, l);
    l = t->sid.rank(f, l), r = t->sid.rank(f, r);
    return range_freq(t->ch[f], l, r, upper, level - 1) + ret;
  }

  // count i s.t. (l <= i < r) && (v[i] < upper)
  int range_freq(int l, int r, T upper) {
    return range_freq(root, l, r, upper, MAXLOG - 1);
  }

  // count i s.t. (l <= i < r) && (lower <= v[i] < upper)
  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);
  }
};

template< typename T, int MAXLOG >
struct CompressedWaveletTree {
  WaveletTree< int, MAXLOG > mat;
  vector< T > ys;

  CompressedWaveletTree(const vector< T > &v) : ys(v) {
    sort(begin(ys), end(ys));
    ys.erase(unique(begin(ys), end(ys)), end(ys));
    vector< int > t(v.size());
    for(int i = 0; i < v.size(); i++) t[i] = get(v[i]);
    mat = WaveletTree< int, MAXLOG >(t);
  }

  inline int get(const T &x) {
    return lower_bound(begin(ys), end(ys), x) - begin(ys);
  }

  int rank(const T &x, int r) {
    auto pos = get(x);
    if(pos == ys.size() || ys[pos] != x) return 0;
    return mat.rank(pos, r);
  }

  T kth_smallest(int l, int r, int k) {
    return ys[mat.kth_smallest(l, r, k)];
  }

  T kth_largest(int l, int r, int k) {
    return ys[mat.kth_largest(l, r, k)];
  }

  int range_freq(int l, int r, T upper) {
    return mat.range_freq(l, r, get(upper));
  }

  int range_freq(int l, int r, T lower, T upper) {
    return mat.range_freq(l, r, get(lower), get(upper));
  }

  T prev_value(int l, int r, T upper) {
    auto ret = mat.prev_value(l, r, get(upper));
    return ret == -1 ? T(-1) : ys[ret];
  }

  T next_value(int l, int r, T lower) {
    auto ret = mat.next_value(l, r, get(lower));
    return ret == -1 ? T(-1) : ys[ret];
  }
};


int main() {
  int N, Q;
  cin >> N;
  vector< int > X(N);
  for(int i = 0; i < N; i++) {
    cin >> X[i];
    X[i] += 5e8;
  }
  CompressedWaveletTree< int, 20 > matrix(X);
  cin >> Q;
  while(Q--) {
    int L, R, E;
    cin >> L >> R >> E;
    --L, --R;
    cout << (R - L + 1) - matrix.range_freq(L, R + 1, min(X[L], X[R]) - E, max(X[L], X[R]) + E + 1) << "\n";
  }
}
accuracy: 1
time_ms: 130
memory_kb: 20860
final_rank: 12

code_snippet: #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define rep(i,n) for (int i = 0; i < (n); ++i)
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
const ll INF=1LL<<60;
const int inf=(1<<30)-1;
const int mod=1e9+7;
int dx[8]={1,0,-1,0,-1,-1,1,1};
int dy[8]={0,1,0,-1,-1,1,-1,1};
template< typename T >
struct BIT {
  int N; int max_2beki;

  vector< T > data;
  // 初期化 1-indexedでデータを管理する 0で初期化
  BIT(int size){
      N = ++size;
      data.assign(N, 0);
      max_2beki = 1;
      while(max_2beki * 2 <= N) max_2beki *= 2;
  }

  // [0,k](閉区間)の総和 閉区間に注意！
  T sum(int k) {
    if(k < 0) return 0; // k<0のとき0を返す
    T ret = 0;
    for(++k; k > 0; k -= k & -k) ret += data[k];
    return (ret);
  }

  // [l,r](閉区間)の総和
  inline T sum(int l,int r){
    return sum(r) - sum(l-1);
  }

  // 一点取得 更新はできないことに注意
  inline T operator[](int k){
    return sum(k) - sum(k-1);
  }

  // data[k] += x;
  void add(int k, T x) {
    for(++k; k < N; k += k & -k) data[k] += x;
  }

  // imos法 [l,r]にxを加算
  void imos(int l,int r,T x){
    add(l , x); add(r + 1 , -x);
  }

  // lower_bound sum(i)がval以上となる最小のi
  int lower_bound(T w){
    if(w <= 0) return 0;
    int x = 0;
    for(int k = max_2beki; k > 0; k /= 2){
      if(x+k <= N - 1 && data[x + k] < w){
        w -= data[x + k];
        x += k;
      }
    }
    return x;
  }

  // upper_bound sum(i)がvalより大きくなる最小のi
  int upper_bound(T w){
    if(w < 0) return 0;
    int x = 0;
    for(int k = max_2beki; k > 0; k /= 2){
      if(x+k <= N - 1 && data[x + k] <= w){
        w -= data[x + k];
        x += k;
      }
    }
    return x;
  }

};
int main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    int d;cin >> d;
    vector<int> x(d);
    vector<pair<int,pair<int,int>>> p;
    rep(i,d){
        cin >> x[i];
        p.push_back({x[i],{0,i}});
    }
    int q;cin >> q;
    vector<int> l(q),r(q),e(q);
    rep(i,q){
        cin >> l[i] >> r[i] >> e[i];
        l[i]--,r[i]--;
        int a=min(x[l[i]],x[r[i]]),b=max(x[l[i]],x[r[i]]);
        p.push_back({a-e[i],{-1,i}});
        p.push_back({b+e[i],{1,i}});
    }
    sort(p.begin(),p.end());
    BIT<int> bit(d);
    vector<int> ans(q);
    for(auto x:p){
        int u=x.first,v=x.second.first,w=x.second.second;
        if(v==-1){
            ans[w]+=bit.sum(l[w],r[w]);
        }
        else if(v==0){
            bit.add(w,1);
        }
        else{
            ans[w]+=r[w]-l[w]+1-bit.sum(l[w],r[w]);
        }
    }
    for(int x:ans){
        cout << x << endl;
    }
}
accuracy: 1
time_ms: 130
memory_kb: 10472
final_rank: 8

code_snippet: #include <vector>
#include <climits>
#include <functional>

template <typename T>
struct SegmentTree{
private:
  using F = std::function<T(T,T)>;
  int n;
  F f;
  T ti;
  std::vector<T> dat;
public:
  SegmentTree(){};
  SegmentTree(F f,T ti) : f(f),ti(ti) {}
  void build(int n_){
    n = n_;
    dat.assign(2*n,ti);
  }
  void build(const std::vector<T> &v){
    int n_ = v.size();
    build(n_);
    for(int i = 0; i < n; ++i) dat[n+i]=v[i];
    for(int i = n-1; i >= 0; --i)
      dat[i]=f(dat[2*i+0],dat[2*i+1]);
  }
  void set_val(int k,T x){
    dat[k+=n] = x;
    while(k > 0){
      k = k/2;
      dat[k]=f(dat[2*k+0],dat[2*k+1]);
    }
  }
  int query(int a,int b, int lb, int ub){
    if(a == b) return 0;
    int ret = 0;
    auto g = [](T v, int lb, int ub){
               return upper_bound(v.begin(), v.end(), ub) - lower_bound(v.begin(), v.end(), lb);
             };
    for(int l = a+n, r = b+n; l < r; l >>= 1, r >>= 1){
      if(l&1) ret += g(dat[l++],lb,ub);//vl = f(vl,dat[l++]);
      if(r&1) ret += g(dat[--r],lb,ub);//vr = f(dat[--r],vr);
    }
    return ret;
  }
};


#include <algorithm>
#include <iostream>
using namespace std;

int main(){
  using T = vector<int>;
  function<T(T,T)> f = [](T a, T b){
                         int n = a.size();
                         a.insert(a.end(),b.begin(),b.end());
                         inplace_merge(a.begin(),a.begin()+n,a.end());
                         return a;
                       };
  T ti = {};
  
  int D;
  cin >> D;
  vector<T> X(D);
  for(int i = 0; i < D; ++i){
    int x;
    cin >> x;
    X[i].emplace_back(x);
  }
  SegmentTree<T> st(f,ti);
  st.build(X);

  int Q;
  cin >> Q;
  while(Q--){
    int l, r, e;
    cin >> l >> r >> e;
    --l,--r;
    int a = min(X[l][0],X[r][0]);
    int b = max(X[l][0],X[r][0]);
    ++r;
    cout << r-l-st.query(l,r,a-e,b+e) << endl;
  }
}
accuracy: 1
time_ms: 2150
memory_kb: 25644
final_rank: 20

code_snippet: // #define _GLIBCXX_DEBUG // for STL debug (optional)
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <cstring>
#include <deque>
#include <list>
#include <queue>
#include <stack>
#include <vector>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <complex>
#include <cmath>
#include <limits>
#include <cfloat>
#include <climits>
#include <ctime>
#include <cassert>
#include <numeric>
#include <fstream>
#include <functional>
#include <bitset>
using namespace std;
using ll = long long int;
using int64 = long long int;
#define call_from_test

template<typename T> void chmax(T &a, T b) {a = max(a, b);}
template<typename T> void chmin(T &a, T b) {a = min(a, b);}
template<typename T> void chadd(T &a, T b) {a = a + b;}
 
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
const int INF = 1LL << 29;
const ll LONGINF = 1LL << 60;
const ll MOD = 1000000007LL;

const ll ofs = 1LL << 30;

// #pragma once

// @title 簡潔ビットベクトル (compact bit vector)
// 簡潔ビットベクトル (数列の長さを N とする)
// n_big <- log^2(N)   (N = 2^32 としたとき、n_big = 32^2 = 1024 = 2^10)
// n_sml <- log(N) / 2 (N = 2^32 としたとき、n_sml = 32/2 = 16 = 2^4)
// n_blk <- n_big を n_sml で割ったもの
// ln_big, ln_sml には、それぞれ log(n_big), log(n_sml) をいれる

template <typename value_type = int,
          uint64_t ln_big = 10, uint64_t ln_sml = 4>
struct CompactBitVector {
private:
    size_t n, n_big, n_sml, n_blk, ln_blk;
    vector<value_type> big, sml, bit;
    
    int popcount(value_type b) const {
        return __builtin_popcountll(b); // GCC builtin function
    }
    void build(vector<value_type> vec);

public:
    // 構築: O(N)
    CompactBitVector();
    CompactBitVector(vector<value_type> vec);
    CompactBitVector(vector<value_type> vec, int k);
    // 数列のサイズ: O(1)
    size_t size() const;
    // 全体の 1 の個数: O(1)
    int count() const;
    // k 番目の値: O(1)
    int value(size_t k) const;
    // [0, k] に存在する 1 の個数: O(1)
    int rank(size_t k) const;
    // [l, r) に存在する 1 の個数: O(1)
    int rank(size_t l, size_t r) const;
    // 1 / 0 の個数 が r を超える、インデックス k 未満最小の要素を返す: O(log N)
    int select1(int r, int k) const;
    int select0(int r, int k) const;
    // k 番目の次に存在する 1 / 0 は何か: O(log N)
    int select1_nxt(size_t k) const;
    int select0_nxt(size_t k) const;
    // k 番目の前に存在する 1 / 0 は何か: O(log N)
    int select1_pre(size_t k) const;
    int select0_pre(size_t k) const;
    // ビットベクトルの k 番目にアクセス
    int at(size_t k) const;
    int operator[](size_t k) const;

    // 出力するだけ
    void show() const {
        cerr << "# big ";
        for(size_t i=0; i<big.size(); i++) {
            cerr << big[i] << " ";
        }
        cerr << endl;
        cerr << "# sml ";
        for(size_t i=0; i<sml.size(); i++) {
            cerr << sml[i] << " ";
        }
        cerr << endl;
        cerr << "# bit ";
        for(size_t i=0; i<bit.size(); i++) {
            cerr << bit[i] << " ";
        }
        cerr << endl;
    }
};

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
void CompactBitVector<value_type, ln_big, ln_sml>::build(vector<value_type> vec) {
    big.resize(((n + n_big - 1) >> ln_big) + 1); // O(N / log^2 N) memory
    sml.resize(big.size() << ln_blk); // O(N / log N) memory
    bit.resize(big.size() << ln_blk); // O(N / log N) memory
    for(size_t i=0; i<n; i++) {
        size_t b = i >> ln_big;
        big[b+1] += vec[i];
        size_t s = i >> ln_sml, m = i & (n_sml - 1);
        sml[s] += vec[i];
        bit[s] |= (static_cast<value_type>(vec[i]) << m);
    }

    // accumulate
    for(size_t i=1; i<big.size(); i++) big[i] += big[i-1];
    for(size_t i=0; i<big.size(); i++) {
        for(size_t j=1; j<n_blk; j++) {
            sml[(i << ln_blk) + j] += sml[(i << ln_blk) + j - 1];
        }
    }
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
CompactBitVector<value_type, ln_big, ln_sml>::CompactBitVector() {}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
CompactBitVector<value_type, ln_big, ln_sml>::CompactBitVector(vector<value_type> vec)
    : n(vec.size()), n_big(1ULL << ln_big), n_sml(1ULL << ln_sml),
      n_blk(n_big >> ln_sml), ln_blk(ln_big - ln_sml) {
    build(vec);
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
CompactBitVector<value_type, ln_big, ln_sml>::CompactBitVector(vector<value_type> vec, int k)
    : n(vec.size()), n_big(1ULL << ln_big), n_sml(1ULL << ln_sml),
      n_blk(n_big >> ln_sml), ln_blk(ln_big - ln_sml) {
    vector<value_type> n_vec;
    for(auto e : vec) n_vec.emplace_back(e >> k & 1);
    build(n_vec);
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
size_t CompactBitVector<value_type, ln_big, ln_sml>::size() const {
    return n;
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::count() const {
    return rank(n-1);
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::value(size_t k) const {
    if(k >= n) return 0;
    size_t m = k & (n_sml - 1);
    return bit[k >> ln_sml] >> m & 1;
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::rank(size_t k) const {
    if(k >= n) return 0; // for range query
    size_t m = k & (n_sml - 1), mask = (1ULL << n_sml) - (1ULL << (m+1));
    return big[k >> ln_big] + sml[k >> ln_sml] - popcount(bit[k >> ln_sml] & mask);
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::rank(size_t l, size_t r) const {
    if(l >= r) return 0;
    return rank(r-1) - rank(l-1);
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::select1(int r, int k) const {
    int ub = n+1, lb = -1;
    while(ub - lb > 1) {
        int mid = (ub + lb) / 2;
        if(rank(mid) > r) ub = mid;
        else lb = mid;
    }
    return (ub < k) ? ub : -1;
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::select0(int r, int k) const {
    int ub = n+1, lb = -1;
    while(ub - lb > 1) {
        int mid = (ub + lb) / 2;
        if(mid + 1 - rank(mid) > r) ub = mid;
        else lb = mid;
    }
    return (ub < k) ? ub : -1;
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::select1_nxt(size_t k) const {
    return select1(rank(k), n);
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::select0_nxt(size_t k) const {
    return select0(rank(k), n);
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::select1_pre(size_t k) const {
    return select1(rank(k) - 1 - value(k), k);
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::select0_pre(size_t k) const {
    return select0(rank(k) - 1 - value(k), k);
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::at(size_t k) const {
    return bit[k >> ln_sml] >> (k & (n_sml - 1)) & 1;
}

template <typename value_type, uint64_t ln_big, uint64_t ln_sml>
int CompactBitVector<value_type, ln_big, ln_sml>::operator[](size_t k) const {
    return at(k);
}

// #pragma once

// @title Wavelet 行列 (wavelet matrix)
#define DOCS "./docs/strc_024_static_wavelet_matrix.md"

#ifndef call_from_test
#include "strc_023_compact_bitvector.cpp"
#endif

// ウェーブレット行列 (Wavelet Matrix)
// w は ビット幅, 30 bit で表現できる整数なら 30
template <uint64_t word_size = 30, typename value_type = int,
          uint64_t ln_big = 10, uint64_t ln_sml = 4>
struct WaveletMatrix {
private:
    using BitVector = CompactBitVector<value_type, ln_big, ln_sml>;
    array<BitVector, word_size> vecs;

    // 要素数
    int n;
    // k ビット目を基準に安定ソート
    vector<value_type> sort_kth_bit(const vector<value_type>& vec, int k) const;

    // [l, r) の範囲内にある x と等しい要素は最下段のどの範囲に相当？
    // select するときに利用
    pair<int, int> rank_range(int l, int r, value_type x) const;    

public:
    // クエリは特に注釈がない限り 0-indexed
    // 構築: O(N w)
    WaveletMatrix(vector<value_type> vec);

    // k 番目の値を復元: O(w)
    // <verified> ITP1_6_A (Reversing Numbers)
    value_type at(int k) const;
    value_type operator[](int k) const;

    // [l, r) の範囲内に以下が何個存在するか: O(w)
    // ・x より小さい要素
    // ・x と等しい要素
    // ・x より大きい要素
    tuple<int, int, int> rank_tuple(int l, int r, value_type x) const;
    tuple<int, int, int> rank_tuple(value_type x) const;
    
    // [l, r) の範囲内で k 番目 (1-indexed) に小さい要素が何か: O(w)
    // <verified> AOJ ALDS1_6_A (Count Sort)
    value_type quantile(int l, int r, value_type mi, value_type ma, int k) const;
    value_type quantile(int l, int r, int k) const;
    value_type quantile(int k) const;

    // [l, r) の範囲内の m 未満 / m を超える 要素はいくつか: O(w)
    // <verified> AOJ ALDS1_5_D (The Number of Inversions)
    int freq_less(int l, int r, value_type m) const;
    int freq_less(value_type m) const;
    int freq_greater(int l, int r, value_type m) const;
    int freq_greater(value_type m) const;
    
    // [l, r) の範囲内に x \in [mi, ma] を満たす x がいくつ出てきたか: O(w)
    // [mi, ma] は閉区間！！
    // <verified> AOJ 1549 (Hard Beans)
    // <verified> AOJ 2426 (Treasure Hunt)
    int freq(int l, int r, value_type mi, value_type ma) const;
    int freq(int l, int r, value_type x) const;
    int freq(value_type mi, value_type ma) const;
    
    // [l, r) の範囲内にある要素の最小値 (quantile 再利用): O(w)
    // <verified> AOJ DSL_3_D (Sliding Minimum Elements)
    value_type min_value(int l, int r, value_type mi, value_type ma) const;
    value_type min_value(int l, int r) const;
    value_type min_value() const;

    // [l, r) の範囲内にある要素の最大値 (quantile 再利用): O(w)
    value_type max_value(int l, int r, value_type mi, value_type ma) const;
    value_type max_value(int l, int r) const;
    value_type max_value() const;

    // [l, r) の範囲内にある k 番目 (1-indexed) の x の位置: O(w log N)
    int select(int l, int r, int k, value_type x) const;
    int select(int k, value_type x) const;

    // k 番目の要素と値が等しいもので、k 番目の直後 / 直前の要素 idx: O(w log N)
    int next_idx(int k) const;
    int prev_idx(int k) const;

    // [l, r) の範囲内にある、x 未満 / x を超える要素のうち 最大 / 最小 であるもの: O(w)
    // <verified> AOJ 1549 (Hard Beans)
    value_type next_val(int l, int r, value_type x) const;
    value_type prev_val(int l, int r, value_type x) const;
};

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
vector<value_type> WaveletMatrix<word_size, value_type, ln_big, ln_sml>::sort_kth_bit(const vector<value_type>& vec, int k) const {
    vector<value_type> v0, v1;
    v0.reserve(vec.size()), v1.reserve(vec.size());
    for(size_t i=0; i<vec.size(); i++) {
        ((vec[i] >> k & 1) ? v1 : v0).emplace_back(vec[i]);
    }
    v0.insert(v0.end(), v1.begin(), v1.end());
    return v0;
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
pair<int, int> WaveletMatrix<word_size, value_type, ln_big, ln_sml>::rank_range(int l, int r, value_type x) const {
    for(size_t i=0; i<word_size; i++) {
        int all1 = vecs[i].rank(n-1), all0 = n - all1;
        int cnt1 = vecs[i].rank(r-1) - vecs[i].rank(l-1), cnt0 = r - l - cnt1;
        if(x >> (word_size - i - 1) & 1) {
            l = all0 + vecs[i].rank(l-1), r = l + cnt1;
        }
        else {
            l = l - vecs[i].rank(l-1), r = l + cnt0;
        }
    }
    return make_pair(l, r);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
WaveletMatrix<word_size, value_type, ln_big, ln_sml>::WaveletMatrix(vector<value_type> vec) : n(vec.size()) {
    vecs[0] = BitVector(vec, word_size - 1);
    for(size_t i=1; i<word_size; i++) {
        vec = sort_kth_bit(vec, word_size - i);
        vecs[i] = BitVector(vec, word_size - i - 1);
    }
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::at(int k) const {
    int b = k; value_type res = 0;
    for(size_t i=0; i<word_size; i++) {
        int all1 = vecs[i].rank(n-1), all0 = n - all1;
        int cnt1 = vecs[i].rank(b), cnt0 = b + 1 - cnt1;
        if(vecs[i][b] == 1) {
            res |= (1ULL << (word_size - 1 - i));
            b = all0 + cnt1 - 1;
        }
        else {
            b = cnt0 - 1;
        }
    }
    return res;
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::operator[](int k) const {
    return at(k);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
tuple<int, int, int> WaveletMatrix<word_size, value_type, ln_big, ln_sml>::rank_tuple(int l, int r, value_type x) const {
    int small = 0, equal = 0, big = 0;
    for(size_t i=0; i<word_size; i++) {
        int all1 = vecs[i].rank(n-1), all0 = n - all1;
        int cnt1 = vecs[i].rank(r-1) - vecs[i].rank(l-1), cnt0 = r - l - cnt1;
        if(x >> (word_size - i - 1) & 1) {
            small += cnt0;
            l = all0 + vecs[i].rank(l-1), r = l + cnt1;
        }
        else {
            big += cnt1;
            l = l - vecs[i].rank(l-1), r = l + cnt0;
        }
    }
    equal = r - l;
    return make_tuple(small, equal, big);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
tuple<int, int, int> WaveletMatrix<word_size, value_type, ln_big, ln_sml>::rank_tuple(value_type x) const {
    return rank_tuple(0, n, x);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::quantile(int l, int r, value_type mi, value_type ma, int k) const {
    int cnt_less = freq_less(l, r, mi), cnt_greater = freq_greater(l, r, ma);
    if(r - l - cnt_less - cnt_greater < k) return -1;
    return quantile(l, r, k + cnt_less);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::quantile(int l, int r, int k) const {
    if(r - l < k) return -1;
    value_type res = 0;
    for(size_t i=0; i<word_size; i++) {
        int all1 = vecs[i].rank(n-1), all0 = n - all1;
        int cnt1 = vecs[i].rank(r-1) - vecs[i].rank(l-1), cnt0 = r - l - cnt1;
        if(cnt0 >= k) {
            l = l - vecs[i].rank(l-1), r = l + cnt0;
        }
        else {
            k -= cnt0;
            res |= 1ULL << (word_size - 1 - i);
            l = all0 + vecs[i].rank(l-1), r = l + cnt1;
        }
    }
    return res;
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::quantile(int k) const {
    return quantile(0, n, k);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
int WaveletMatrix<word_size, value_type, ln_big, ln_sml>::freq_less(int l, int r, value_type m) const {
    int res = 0;
    for(size_t i=0; i<word_size; i++) {
        int all1 = vecs[i].rank(n-1), all0 = n - all1;
        int cnt1 = vecs[i].rank(r-1) - vecs[i].rank(l-1), cnt0 = r - l - cnt1;
        if(m >> (word_size - 1 - i) & 1) {
            res += cnt0;
            l = all0 + vecs[i].rank(l-1), r = l + cnt1;
        }
        else {
            l = l - vecs[i].rank(l-1), r = l + cnt0;
        }
    }
    return res;
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
int WaveletMatrix<word_size, value_type, ln_big, ln_sml>::freq_less(value_type m) const {
    return freq_less(0, n, m);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
int WaveletMatrix<word_size, value_type, ln_big, ln_sml>::freq_greater(int l, int r, value_type m) const {
    int res = 0;
    for(size_t i=0; i<word_size; i++) {
        int all1 = vecs[i].rank(n-1), all0 = n - all1;
        int cnt1 = vecs[i].rank(r-1) - vecs[i].rank(l-1), cnt0 = r - l - cnt1;
        if(m >> (word_size - 1 - i) & 1) {
            l = all0 + vecs[i].rank(l-1), r = l + cnt1;
        }
        else {
            res += cnt1;
            l = l - vecs[i].rank(l-1), r = l + cnt0;
        }
    }
    return res;
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
int WaveletMatrix<word_size, value_type, ln_big, ln_sml>::freq_greater(value_type m) const {
    return freq_greater(0, n, m);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
int WaveletMatrix<word_size, value_type, ln_big, ln_sml>::freq(int l, int r, value_type mi, value_type ma) const {
    return r - l - freq_less(l, r, mi) - freq_greater(l, r, ma);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
int WaveletMatrix<word_size, value_type, ln_big, ln_sml>::freq(int l, int r, value_type x) const {
    return freq(l, r, x, x);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
int WaveletMatrix<word_size, value_type, ln_big, ln_sml>::freq(value_type mi, value_type ma) const {
    return freq(0, n, mi, ma);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::min_value(int l, int r, value_type mi, value_type ma) const {
    return quantile(l, r, mi, ma, 1);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::min_value(int l, int r) const {
    return quantile(l, r, 1);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::min_value() const {
    return min_value(0, n);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::max_value(int l, int r, value_type mi, value_type ma) const {
    return quantile(l, r, mi, ma, freq(l, r, mi, ma));
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::max_value(int l, int r) const {
    return quantile(l, r, r - l);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::max_value() const {
    return max_value(0, n);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
int WaveletMatrix<word_size, value_type, ln_big, ln_sml>::select(int l, int r, int k, value_type x) const {
    if(k <= 0) return -1;
    tie(l, r) = rank_range(l, r, x);
    if(r - l < k) return -1;

    int pos = l + k - 1;
    for(size_t i=0; i<word_size; i++) {
        int b = x >> i & 1;
        int cnt1 = vecs[word_size - 1 - i].rank(n-1), cnt0 = n - cnt1;
        if(b == 0) {
            int m = pos;
            pos = vecs[word_size - 1 - i].select0(m, n);
        }
        else {
            int m = pos - cnt0;
            pos = vecs[word_size - 1 - i].select1(m, n);
        }
    }
    return pos;
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
int WaveletMatrix<word_size, value_type, ln_big, ln_sml>::select(int k, value_type x) const {
    return select(0, n, k, x);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
int WaveletMatrix<word_size, value_type, ln_big, ln_sml>::next_idx(int k) const {
    int m = freq(0, k+1, at(k));
    return select(m+1, at(k));
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
int WaveletMatrix<word_size, value_type, ln_big, ln_sml>::prev_idx(int k) const {
    int m = freq(0, k+1, at(k));
    return select(m-1, at(k));
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::next_val(int l, int r, value_type x) const {
    int k = r - l - freq_greater(l, r, x) + 1;
    return quantile(l, r, k);
}

template <uint64_t word_size, typename value_type,
          uint64_t ln_big, uint64_t ln_sml>
value_type WaveletMatrix<word_size, value_type, ln_big, ln_sml>::prev_val(int l, int r, value_type x) const {
    return quantile(l, r, freq_less(l, r, x));
}

int main() {
    int N; scanf("%d", &N);
    vector<ll> A(N);
    for(int i=0; i<N; i++) {
        scanf("%lld", &A[i]);
        A[i] += ofs;
    }

    WaveletMatrix<35, ll> wm(A);
    int Q; scanf("%d", &Q);
    while(Q--) {
        ll l, r, e; scanf("%lld%lld%lld", &l, &r, &e);
        l--; r--;
        ll X = min(A[l], A[r]), Y = max(A[l], A[r]);
        ll ans = wm.freq_less(l, r+1, X-e) + wm.freq_greater(l, r+1, Y+e);
        printf("%lld\n", ans);
    }
    return 0;
}
accuracy: 1
time_ms: 220
memory_kb: 10748
final_rank: 9

code_snippet: #include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1000000 + 5;

int ans, a[N], b[N], rt[N * 20], ls[N * 20], rs[N * 20], sum[N * 20];
 
int n, k, tot, sz, ql, qr, x, q;
 
void Build(int& o, int l, int r){
    o = ++ tot;
    sum[o] = 0;
    if(l == r) return;
    int m = (l + r) >> 1;
    Build(ls[o], l, m);
    Build(rs[o], m + 1, r);
}
 
void update(int& o, int l, int r, int last, int p){
    o = ++ tot;
    ls[o] = ls[last];
    rs[o] = rs[last];
    sum[o] = sum[last] + 1;
    if(l == r) return;
    int m = (l + r) >> 1;
    if(p <= m)  update(ls[o], l, m, ls[last], p);
    else update(rs[o], m + 1, r, rs[last], p);
}
 
void query(int ss, int tt, int l, int r, int x, int y){
    if(x <= l && r <= y)  
	{
		ans += sum[tt] - sum[ss];
		return;
	}
    int m = (l + r) >> 1;
    if(x <= m) query(ls[ss], ls[tt], l, m, x, y);
    if (y > m) query(rs[ss], rs[tt], m + 1, r, x, y);
}
void work(){
    scanf("%d%d%d", &ql, &qr, &x);
    int l = lower_bound(b + 1, b + sz + 2, min(b[a[ql]], b[a[qr]]) - x) - b - 1;
    int r = lower_bound(b + 1, b + sz + 2, max(b[a[ql]], b[a[qr]]) + x + 1) - b;
    ans = 0;
	if (l >= 1)
		query(rt[ql - 1], rt[qr], 1, sz, 1, l);
	if (r <= sz) 
		query(rt[ql - 1], rt[qr], 1, sz, r, sz); 
    printf("%d\n", ans);
}
 
int main(){
    scanf("%d", &n);
    for(int i = 1; i <= n; i++) scanf("%d", a + i), b[i] = a[i];
    scanf("%d", &q);
    sort(b + 1, b + n + 1);
    sz = unique(b + 1, b + n + 1) - (b + 1);
    b[sz + 1] = 1e9;
    tot = 0;
    Build(rt[0], 1, sz);
    //for(int i = 0; i <= 4 * n; i ++)printf("%d,rt =  %d,ls =  %d, rs = %d, sum = %d\n", i, rt[i], ls[i], rs[i], sum[i]);
    for(int i = 1; i <= n; i++)a[i] = lower_bound(b + 1, b + sz + 1, a[i]) - b;
    for(int i = 1; i <= n; i++)update(rt[i], 1, sz, rt[i - 1], a[i]);
    //for(int i = 0; i <= 5 * n; i++)printf("%d,rt =  %d,ls =  %d, rs = %d, sum = %d\n", i, rt[i], ls[i], rs[i], sum[i]);
    while(q--)work();
    return 0;
}
accuracy: 1
time_ms: 160
memory_kb: 27028
final_rank: 16

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

using namespace std;

using int64 = long long;
const int mod = 1e9 + 7;
// const int mod = 998244353;

const int64 infll = (1LL << 62) - 1;
const int inf = (1 << 30) - 1;

struct IoSetup {
  IoSetup() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(10);
    cerr << fixed << setprecision(10);
  }
} iosetup;


template< typename T1, typename T2 >
ostream &operator<<(ostream &os, const pair< T1, T2 > &p) {
  os << p.first << " " << p.second;
  return os;
}

template< typename T1, typename T2 >
istream &operator>>(istream &is, pair< T1, T2 > &p) {
  is >> p.first >> p.second;
  return is;
}

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 != v.size() ? " " : "");
  }
  return os;
}

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

template< typename T1, typename T2 >
inline bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }

template< typename T1, typename T2 >
inline bool chmin(T1 &a, T2 b) { return a > b && (a = b, true); }

template< typename T = int64 >
vector< T > make_v(size_t a) {
  return vector< T >(a);
}

template< typename T, typename... Ts >
auto make_v(size_t a, Ts... ts) {
  return vector< decltype(make_v< T >(ts...)) >(a, make_v< T >(ts...));
}

template< typename T, typename V >
typename enable_if< is_class< T >::value == 0 >::type fill_v(T &t, const V &v) {
  t = v;
}

template< typename T, typename V >
typename enable_if< is_class< T >::value != 0 >::type fill_v(T &t, const V &v) {
  for(auto &e : t) fill_v(e, v);
}

template< typename F >
struct FixPoint : F {
  FixPoint(F &&f) : F(forward< F >(f)) {}

  template< typename... Args >
  decltype(auto) operator()(Args &&... args) const {
    return F::operator()(*this, forward< Args >(args)...);
  }
};

template< typename F >
inline decltype(auto) MFP(F &&f) {
  return FixPoint< F >{forward< F >(f)};
}

struct SuccinctIndexableDictionary {
  size_t length;
  size_t blocks;
  vector< unsigned > bit, sum;

  SuccinctIndexableDictionary() = default;

  SuccinctIndexableDictionary(size_t length) : length(length), blocks((length + 31) >> 5) {
    bit.assign(blocks, 0U);
    sum.assign(blocks, 0U);
  }

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

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

  bool operator[](int k) {
    return (bool((bit[k >> 5] >> (k & 31)) & 1));
  }

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

  int rank(bool val, int k) {
    return (val ? rank(k) : k - rank(k));
  }
};

template< typename T, int MAXLOG >
struct WaveletTree {

  struct Node {
    SuccinctIndexableDictionary sid;
    Node *ch[2];

    Node() = default;

    Node(size_t length) : sid(length + 1), ch{nullptr} {}

  };

  Node *root;

  Node *build(vector< T > &v, vector< T > &rbuff, int bit, int l, int r) {
    if(l >= r || bit == -1) return nullptr;
    Node *node = new Node(r - l);
    int left = 0, right = 0;
    for(int k = l; k < r; k++) {
      if(((v[k] >> bit) & 1)) {
        rbuff[right++] = v[k];
        node->sid.set(k - l);
      } else {
        v[l + left++] = v[k];
      }
    }
    for(int k = 0; k < right; k++) {
      v[l + left + k] = rbuff[k];
    }
    node->sid.build();
    node->ch[0] = build(v, rbuff, bit - 1, l, l + left);
    node->ch[1] = build(v, rbuff, bit - 1, l + left, r);
    return node;
  }

  WaveletTree() = default;

  WaveletTree(vector< T > v) {
    vector< T > rbuff(v.size());
    root = build(v, rbuff, MAXLOG - 1, 0, v.size());
  }

  T kth_smallest(Node *t, int l, int r, int k, int level) {
    if(l >= r || t == nullptr) return 0;
    int cnt = t->sid.rank(false, r) - t->sid.rank(false, l);
    bool f = cnt <= k;
    l = t->sid.rank(f, l), r = t->sid.rank(f, r);
    if(f) return kth_smallest(t->ch[f], l, r, k - cnt, level - 1) | ((T(1) << level));
    return kth_smallest(t->ch[f], l, r, k, level - 1);
  }

  // k-th(0-indexed) smallest number in v[l,r)
  T kth_smallest(int l, int r, int k) {
    assert(0 <= k && k < r - l);
    return kth_smallest(root, l, r, k, MAXLOG - 1);
  }

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

  int range_freq(Node *t, int l, int r, T upper, int level) {
    if(t == nullptr || l >= r) return 0;
    bool f = ((upper >> level) & 1);
    int ret = 0;
    if(f) ret += t->sid.rank(false, r) - t->sid.rank(false, l);
    l = t->sid.rank(f, l), r = t->sid.rank(f, r);
    return range_freq(t->ch[f], l, r, upper, level - 1) + ret;
  }

  // count i s.t. (l <= i < r) && (v[i] < upper)
  int range_freq(int l, int r, T upper) {
    return range_freq(root, l, r, upper, MAXLOG - 1);
  }

  // count i s.t. (l <= i < r) && (lower <= v[i] < upper)
  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);
  }
};

template< typename T, int MAXLOG >
struct CompressedWaveletTree {
  WaveletTree< int, MAXLOG > mat;
  vector< T > ys;

  CompressedWaveletTree(const vector< T > &v) : ys(v) {
    sort(begin(ys), end(ys));
    ys.erase(unique(begin(ys), end(ys)), end(ys));
    vector< int > t(v.size());
    for(int i = 0; i < v.size(); i++) t[i] = get(v[i]);
    mat = WaveletTree< int, MAXLOG >(t);
  }

  inline int get(const T &x) {
    return lower_bound(begin(ys), end(ys), x) - begin(ys);
  }

  T access(int k) {
    return ys[mat.access(k)];
  }

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

  int rank(const T &x, int r) {
    auto pos = get(x);
    if(pos == ys.size() || ys[pos] != x) return 0;
    return mat.rank(pos, r);
  }

  T kth_smallest(int l, int r, int k) {
    return ys[mat.kth_smallest(l, r, k)];
  }

  T kth_largest(int l, int r, int k) {
    return ys[mat.kth_largest(l, r, k)];
  }

  int range_freq(int l, int r, T upper) {
    return mat.range_freq(l, r, get(upper));
  }

  int range_freq(int l, int r, T lower, T upper) {
    return mat.range_freq(l, r, get(lower), get(upper));
  }

  T prev_value(int l, int r, T upper) {
    auto ret = mat.prev_value(l, r, get(upper));
    return ret == -1 ? T(-1) : ys[ret];
  }

  T next_value(int l, int r, T lower) {
    auto ret = mat.next_value(l, r, get(lower));
    return ret == -1 ? T(-1) : ys[ret];
  }
};


int main() {
  int N, Q;
  cin >> N;
  vector< int > X(N);
  for(int i = 0; i < N; i++) {
    cin >> X[i];
    X[i] += 5e8;
  }
  CompressedWaveletTree< int, 18 > matrix(X);
  cin >> Q;
  while(Q--) {
    int L, R, E;
    cin >> L >> R >> E;
    --L, --R;
    cout << (R - L + 1) - matrix.range_freq(L, R + 1, min(X[L], X[R]) - E, max(X[L], X[R]) + E + 1) << "\n";
  }
}
accuracy: 1
time_ms: 130
memory_kb: 20840
final_rank: 11