Problem:
Score : 800 points

Problem Statement

There are N points on a number line, i-th of which is placed on coordinate X_i.
These points are numbered in the increasing order of coordinates.
In other words, for all i (1 \leq i \leq N-1), X_i < X_{i+1} holds.
In addition to that, an integer K is given.

Process Q queries.

In the i-th query, two integers L_i and R_i are given.
Here, a set s of points is said to be a good set if it satisfies all of the following conditions.
Note that the definition of good sets varies over queries.

Each point in s is one of X_{L_i},X_{L_i+1},\ldots,X_{R_i}.

For any two distinct points in s, the distance between them is greater than or equal to K.

The size of s is maximum among all sets that satisfy the aforementioned conditions.

For each query, find the size of the union of all good sets.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq K \leq 10^9

0 \leq X_1 < X_2 < \cdots < X_N \leq 10^9

1 \leq Q \leq 2 \times 10^5

1 \leq L_i \leq R_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
X_1 X_2 \cdots X_N
Q
L_1 R_1
L_2 R_2
\vdots
L_Q R_Q

Output

For each query, print the size of the union of all good sets in a line.

Sample Input 1

5 3
1 2 4 7 8
2
1 5
1 2

Sample Output 1

4
2

In the first query, you can have at most 3 points in a good set.
There exist two good sets: \{1,4,7\} and \{1,4,8\}.
Therefore, the size of the union of all good sets is |\{1,4,7,8\}|=4.

In the second query, you can have at most 1 point in a good set.
There exist two good sets: \{1\} and \{2\}.
Therefore, the size of the union of all good sets is |\{1,2\}|=2.

Sample Input 2

15 220492538
4452279 12864090 23146757 31318558 133073771 141315707 263239555 350278176 401243954 418305779 450172439 560311491 625900495 626194585 891960194
5
6 14
1 8
1 13
7 12
4 12

Sample Output 2

4
6
11
2
3

Solution in Rust (1.42.0) (judge verdict: Accepted)

// template {{{
#![allow(clippy::many_single_char_names)]

#[allow(dead_code)]
mod ngtio {
    use ::std::collections::VecDeque;

    pub struct Buffer {
        buf: VecDeque<String>,
    }

    impl Buffer {
        pub fn new() -> Self {
            Self {
                buf: VecDeque::new(),
            }
        }

        fn load(&mut self) {
            while self.buf.is_empty() {
                let mut s = String::new();
                let length = ::std::io::stdin().read_line(&mut s).unwrap();
                if length == 0 {
                    break;
                }
                self.buf.extend(s.split_whitespace().map(|s| s.to_owned()));
            }
        }

        pub fn string(&mut self) -> String {
            self.load();
            self.buf
                .pop_front()
                .unwrap_or_else(|| panic!("入力が終了したのですが。"))
        }

        pub fn string_char_vec(&mut self) -> Vec<char> {
            let s = self.string();
            s.chars().collect::<Vec<_>>()
        }

        pub fn string_char_vec_trusted_len(&mut self, len: usize) -> Vec<char> {
            let s = self.string();
            let s = s.chars().collect::<Vec<_>>();
            assert_eq!(s.len(), len, "あら、思ったのと長さ違いますね……");
            s
        }

        pub fn char(&mut self) -> char {
            let string = self.string();
            let mut chars = string.chars();
            let res = chars.next().unwrap();
            assert!(
                chars.next().is_none(),
                "char で受け取りたいのも山々なのですが、さては 2 文字以上ありますね？"
            );
            res
        }

        pub fn read<T: ::std::str::FromStr>(&mut self) -> T
        where
            <T as ::std::str::FromStr>::Err: ::std::fmt::Debug,
        {
            self.string()
                .parse::<T>()
                .expect("Failed to parse the input.")
        }

        pub fn read_vec<T: ::std::str::FromStr>(&mut self, len: usize) -> Vec<T>
        where
            <T as ::std::str::FromStr>::Err: ::std::fmt::Debug,
        {
            (0..len).map(|_| self.read::<T>()).collect()
        }
    }

    macro_rules! define_primitive_reader {
        ($($ty:tt,)*) => {
            impl Buffer {
                $(
#[inline]
                    pub fn $ty(&mut self) -> $ty {
                        self.read::<$ty>()
                    }
                )*
            }
        }
    }

    define_primitive_reader! {
        u8, u16, u32, u64, usize,
        i8, i16, i32, i64, isize,
    }

    impl Default for Buffer {
        fn default() -> Self {
            Self::new()
        }
    }
}

#[allow(unused_imports)]
use std::{collections, iter, mem, ops};
// }}}

use type_traits::{wrappers::Add, Assoc};

#[derive(Debug, Clone, PartialEq)]
struct Doubling<T: Assoc> {
    table: Vec<Vec<(usize, T)>>,
}
impl<T: Assoc> Doubling<T> {
    fn new(a: &[(usize, T)]) -> Self {
        let mut table = vec![a.to_vec()];
        for _ in 0..a.len().next_power_of_two().trailing_zeros() {
            let prv = table.last().unwrap();
            let mut crr = prv.clone();
            for i in 0..a.len() {
                let j = prv[i].0;
                crr[i] = (prv[j].0, prv[i].1.clone().op(prv[j].1.clone()));
            }
            table.push(crr);
        }
        Self { table }
    }
    // (距離, 終着点, 累積)
    fn find(
        &self,
        start: usize,
        init: T,
        mut pred: impl FnMut(usize, &T) -> bool,
    ) -> (usize, usize, T) {
        if !pred(start, &init) {
            let mut d = 0;
            let mut i = start;
            let mut value = init;
            let mut k = 1usize << (self.table.len() - 1);

            for row in self.table.iter().rev() {
                let next_i = row[i].0;
                let next_value = value.clone().op(row[i].1.clone());
                if !pred(next_i, &next_value) {
                    i = next_i;
                    value = next_value;
                    d += k;
                }
                k /= 2;
            }
            assert!(!pred(i, &value));
            (
                d,
                self.table[0][i].0,
                value.clone().op(self.table[0][i].1.clone()),
            )
        } else {
            (0, start, init)
        }
    }
}

fn main() {
    let mut buf = ngtio::Buffer::new();
    let n = buf.usize();
    let k = buf.i64();
    let a = iter::once(std::i64::MIN / 2)
        .chain(iter::repeat_with(|| buf.i64()).take(n))
        .chain(iter::once(std::i64::MAX / 2))
        .collect::<Vec<_>>();
    let n = a.len();

    let prev = {
        let mut prev = vec![(0, Add(0)); n];
        let mut i = n - 1;
        for j in (1..n).rev() {
            while a[j] - a[i] < k {
                i -= 1;
            }
            prev[j] = (i, Add(j));
        }
        Doubling::new(&prev)
    };
    let next = {
        let mut next = vec![(n - 1, Add(0)); n];
        let mut j = 0;
        for i in 0..n - 1 {
            while a[j] - a[i] < k {
                j += 1;
            }
            next[i] = (j, Add(i));
        }
        Doubling::new(&next)
    };

    for _ in 0..buf.usize() {
        let l = buf.usize();
        let r = buf.usize();
        let (d0, _, Add(min)) = next.find(l, Add(0), |i, _| r < i);
        let (d1, _, Add(max)) = prev.find(r, Add(0), |i, _| i < l);
        assert_eq!(d0, d1);
        let ans = d0 + max - min + 1;
        println!("{}", ans);
    }
}
// type_traits {{{
#[allow(dead_code)]
mod type_traits {
    #![warn(missing_docs)]

    use std::{cmp, fmt, ops};

    mod primitive {
        use super::{One, Zero};

        macro_rules! int {
            ($($T:ty,)*) => {
                $(
                    impl Zero for $T {
                        fn zero() -> $T {
                            0
                        }
                        fn times(self, n: u64) -> $T {
                            self * n as $T
                        }
                        fn times_assign(&mut self, n: u64) {
                            *self *= n as $T
                        }
                        fn from_u64(n: u64) -> $T {
                            n as $T
                        }
                    }
                    impl One for $T {
                        fn one() -> $T {
                            1
                        }
                    }
                )*
            }
        }

        int! {
            u8, u16, u32, u64, u128, usize,
            i8, i16, i32, i64, i128, isize,
        }
    }

    pub mod wrappers {
        use super::{Assoc, Element, Identity, One, Zero};
        use std::ops;

        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
        pub struct Add<T>(pub T);
        impl<T> Assoc for Add<T>
        where
            T: ops::Add<Output = T> + Element,
        {
            fn op(self, rhs: Self) -> Self {
                Add(self.0 + rhs.0)
            }
        }
        impl<T> Identity for Add<T>
        where
            T: Zero,
        {
            fn identity() -> Self {
                Add(T::zero())
            }
        }

        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
        pub struct Mul<T>(pub T);

        impl<T> Assoc for Mul<T>
        where
            T: ops::Mul<Output = T> + Element,
        {
            fn op(self, rhs: Self) -> Self {
                Mul(self.0 * rhs.0)
            }
        }
        impl<T> Identity for Mul<T>
        where
            T: One,
        {
            fn identity() -> Self {
                Mul(T::one())
            }
        }

        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
        pub struct Affine<T> {
            pub a: T,
            pub b: T,
        }

        impl<T> Assoc for Affine<T>
        where
            T: ops::Add<Output = T> + Element,
            T: ops::Mul<Output = T> + Element,
        {
            fn op(self, rhs: Self) -> Self {
                Self {
                    a: self.a.clone() * rhs.a,
                    b: self.b + self.a * rhs.b,
                }
            }
        }
        impl<T> Identity for Affine<T>
        where
            T: Zero + One,
        {
            fn identity() -> Self {
                Self {
                    a: T::one(),
                    b: T::zero(),
                }
            }
        }

        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct Cat(pub String);

        impl Assoc for Cat {
            fn op(self, rhs: Self) -> Self {
                Cat(self.0.chars().chain(rhs.0.chars()).collect())
            }
        }
        impl Identity for Cat {
            fn identity() -> Self {
                Cat(String::new())
            }
        }
    }

    pub trait Element: Sized + Clone + PartialEq + fmt::Debug {}
    impl<T: Sized + Clone + PartialEq + fmt::Debug> Element for T {}

    pub trait Assoc: Element {
        fn op(self, rhs: Self) -> Self;

        fn op_from_left(&mut self, left: &Self) {
            *self = Self::op(left.clone(), self.clone());
        }

        fn op_from_right(&mut self, right: &Self) {
            *self = Self::op(self.clone(), right.clone());
        }
    }

    pub trait Identity: Assoc {
        fn identity() -> Self;
    }

    pub trait Zero: ops::Add<Output = Self> + ops::AddAssign + Element {
        fn zero() -> Self;

        fn is_zero(&self) -> bool
        where
            Self: cmp::PartialEq,
        {
            self == &Self::zero()
        }

        fn times(self, n: u64) -> Self;

        fn times_assign(&mut self, n: u64);

        fn from_u64(x: u64) -> Self;
    }

    pub trait One: ops::Mul<Output = Self> + ops::MulAssign + Element {
        fn one() -> Self;

        fn is_one(&self) -> bool
        where
            Self: cmp::PartialEq,
        {
            self == &Self::one()
        }
    }

    pub trait Ring: Zero + One + ops::Neg + ops::Sub<Output = Self> + ops::SubAssign {}
    impl<T: Zero + One + ops::Neg + ops::Sub<Output = Self> + ops::SubAssign> Ring for T {}

    #[macro_export]
    macro_rules! define_constant {
        ($(#[$attr:meta])? $vis:vis type $wrapper_type:ident: $value_type:ty = $value:expr;) => {
            $(#[$attr])?
            #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
            $vis struct $wrapper_type {}

            impl Constant for $wrapper_type {
                type Output = $value_type;
                const VALUE: Self::Output = $value;
            }
        };
    }

    pub trait Constant: Copy {
        type Output: Copy;

        const VALUE: Self::Output;
    }
}
// }}}