Problem:
Score : 400 points

Problem Statement

You are given a sequence A_1, A_2, ..., A_N and an integer K.

Print the maximum possible length of a sequence B that satisfies the following conditions:

B is a (not necessarily continuous) subsequence of A.

For each pair of adjacents elements of B, the absolute difference of the elements is at most K.

Constraints

1 \leq N \leq 300,000

0 \leq A_i \leq 300,000

0 \leq K \leq 300,000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1
A_2
:
A_N

Output

Print the answer.

Sample Input 1

10 3
1
5
4
3
8
6
9
7
2
4

Sample Output 1

7

For example, B = (1, 4, 3, 6, 9, 7, 4) satisfies the conditions.

It is a subsequence of A = (1, 5, 4, 3, 8, 6, 9, 7, 2, 4).

All of the absolute differences between two adjacent elements (|1-4|, |4-3|, |3-6|, |6-9|, |9-7|, |7-4|) are at most K = 3.

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

#[allow(unused_imports)]
use ngtio::prelude::*;

use type_traits::{Assoc, Element};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Max<T>(pub T);
impl<T> Assoc for Max<T>
where
    T: Ord + Element,
{
    fn op(self, rhs: Self) -> Self {
        Max(self.0.max(rhs.0))
    }
}

use segtree::Segtree;

const LIM: usize = 300_000;

fn main() {
    let mut buf = ngtio::with_stdin();
    let n = buf.usize();
    let k = buf.usize();
    let mut seg = std::iter::repeat(0)
        .take(LIM + 1)
        .map(Max)
        .collect::<Segtree<_>>();

    for _ in 0..n {
        let x = buf.usize();
        let l = x.saturating_sub(k);
        let r = (x + k).min(LIM);
        let value = Max(seg.fold(l..=r).unwrap().0 + 1);
        seg.set(x, value);
    }
    let ans = seg.fold(..).unwrap().0;
    println!("{}", ans);
}

// type_traits {{{
#[allow(dead_code)]
mod type_traits {
    #![warn(missing_docs)]

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

    mod primitive {
        use super::{
            binary::{Add, Mul},
            Commut, One, OpN, Zero,
        };

        macro_rules! zero {
            (int) => {
                0
            };
            (float) => {
                0.
            };
        }
        macro_rules! one {
            (int) => {
                1
            };
            (float) => {
                1.
            };
        }
        macro_rules! num {
            (@kind $kind:ident @type $T:ty) => {
                impl Zero for $T {
                    fn zero() -> $T {
                        zero!($kind)
                    }
                }
                impl One for $T {
                    fn one() -> $T {
                        one!($kind)
                    }
                }
                impl Commut for Add<$T> {}
                impl OpN for Add<$T> {
                    fn op_n(self, n: u64) -> Self {
                        Add(self.0 * n as $T)
                    }
                }
                impl Commut for Mul<$T> {}
            };
        }

        macro_rules! int {
            ($($T:ty,)*) => {
                $( num! { @kind int @type $T } )*
            };
        }

        macro_rules! float {
            ($($T:ty,)*) => {
                $( num! { @kind float @type $T } )*
            };
        }

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

        float! {
            f32, f64,
        }
    }

    pub mod binary {
        use super::{Assoc, Commut, Element, Identity, One, OpN, Peek, Zero};
        use std::ops;

        macro_rules! triv_wrapper {
            ($name:ident<$T:ident>) => {
                impl<$T> Peek for $name<$T>
                where
                    $T: Element,
                {
                    type Inner = $T;
                    fn peek(&self) -> $T {
                        self.0.clone()
                    }
                }
            };
        }

        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct Len<T> {
            pub len: u64,
            pub base: T,
        }
        impl<T> Len<T> {
            pub fn single(base: T) -> Self {
                Len { len: 1, base }
            }
        }
        impl<T: Assoc> Assoc for Len<T> {
            fn op(self, rhs: Self) -> Self {
                Len {
                    len: self.len + rhs.len,
                    base: self.base.op(rhs.base),
                }
            }
        }

        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct Pair<T, U>(pub T, pub U);
        impl<T: Assoc, U: Assoc> Assoc for Pair<T, U> {
            fn op(self, rhs: Self) -> Self {
                Pair(self.0.op(rhs.0), self.1.op(rhs.1))
            }
        }
        impl<T: Identity, U: Identity> Identity for Pair<T, U> {
            fn identity() -> Self {
                Pair(T::identity(), U::identity())
            }
        }
        impl<T: Commut, U: Commut> Commut for Pair<T, U> {}
        impl<T: OpN, U: OpN> OpN for Pair<T, U> {
            fn op_n(self, n: u64) -> Self {
                let Pair(t, u) = self;
                Self(t.op_n(n), u.op_n(n))
            }
        }

        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
        pub struct BitXor<T>(pub T);
        triv_wrapper! { BitXor<T> }
        impl<T> Assoc for BitXor<T>
        where
            T: ops::BitXor<Output = T> + Element,
        {
            fn op(self, rhs: Self) -> Self {
                BitXor(self.0 ^ rhs.0)
            }
        }
        impl<T> Identity for BitXor<T>
        where
            T: ops::BitXor<Output = T> + Zero,
        {
            fn identity() -> Self {
                BitXor(T::zero())
            }
        }
        impl<T: ops::BitXor<Output = T> + Element> Commut for BitXor<T> {}
        impl<T: ops::BitXor<Output = T> + Zero> OpN for BitXor<T> {
            fn op_n(self, n: u64) -> Self {
                if n % 2 == 0 {
                    Self::identity()
                } else {
                    self
                }
            }
        }

        #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
        pub struct Add<T>(pub T);
        triv_wrapper! { Add<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);
        triv_wrapper! { Mul<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, Default)]
        pub struct InvertionNumber {
            pub zero: u64,
            pub one: u64,
            pub invertion: u64,
        }
        impl Peek for InvertionNumber {
            type Inner = bool;
            fn peek(&self) -> bool {
                self.try_get_bool()
                    .expect("ビットでないものを peek するのはいけません！")
            }
        }

        impl Assoc for InvertionNumber {
            fn op(self, rhs: Self) -> Self {
                InvertionNumber {
                    zero: self.zero + rhs.zero,
                    one: self.one + rhs.one,
                    invertion: self.invertion + self.one * rhs.zero + rhs.invertion,
                }
            }
        }
        impl Identity for InvertionNumber {
            fn identity() -> Self {
                InvertionNumber::new()
            }
        }
        impl InvertionNumber {
            pub fn new() -> Self {
                InvertionNumber {
                    zero: 0,
                    one: 0,
                    invertion: 0,
                }
            }
            pub fn try_get_u8(&self) -> Option<u8> {
                self.try_get_bool().map(|b| if b { 1 } else { 0 })
            }
            pub fn try_get_bool(&self) -> Option<bool> {
                if *self == Self::bit_zero() {
                    Some(false)
                } else if *self == Self::bit_one() {
                    Some(true)
                } else {
                    None
                }
            }
            pub fn count_zeros(&self) -> u64 {
                self.zero
            }
            pub fn count_ones(&self) -> u64 {
                self.one
            }
            pub fn inversion_number(&self) -> u64 {
                self.invertion
            }
            pub fn bit_zero() -> Self {
                InvertionNumber {
                    zero: 1,
                    one: 0,
                    invertion: 0,
                }
            }
            pub fn bit_one() -> Self {
                InvertionNumber {
                    zero: 0,
                    one: 1,
                    invertion: 0,
                }
            }
            pub fn from_bool(b: bool) -> Self {
                if b {
                    Self::bit_one()
                } else {
                    Self::bit_zero()
                }
            }
            pub fn from_u8(x: u8) -> Self {
                match x {
                    0 => Self::bit_zero(),
                    1 => Self::bit_one(),
                    _ => panic!("0 でも 1 でもないものを渡すとパニックです。"),
                }
            }
        }

        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub struct Affine<T> {
            pub a: T,
            pub b: T,
        }
        impl<T: Element> Peek for Affine<T> {
            type Inner = (T, T);
            fn peek(&self) -> (T, T) {
                (self.a.clone(), self.b.clone())
            }
        }
        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 Peek for Cat {
            type Inner = String;
            fn peek(&self) -> String {
                self.0.clone()
            }
        }
        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 mod actions {
        use super::{binary::Len, Action, Commut, OpN};

        #[derive(Debug, Clone, PartialEq, Copy)]
        pub struct Update<T>(pub T);

        impl<T: OpN> Action for Update<T> {
            type Space = Len<T>;
            fn acted(self, x: Self::Space) -> Self::Space {
                Len {
                    len: x.len,
                    base: self.0.op_n(x.len),
                }
            }
        }

        #[derive(Debug, Clone, PartialEq, Copy)]
        pub struct Adjoint<T>(pub T);

        impl<T: OpN + Commut> Action for Adjoint<T> {
            type Space = Len<T>;
            fn acted(self, x: Self::Space) -> Self::Space {
                Len {
                    len: x.len,
                    base: self.0.op_n(x.len).op(x.base),
                }
            }
        }
    }

    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 Commut: Assoc {}

    pub trait OpN: Assoc {
        fn op_n(self, n: u64) -> Self;
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
    pub struct Grade<T> {
        pub base: T,
        pub deg: usize,
    }
    impl<T: Assoc> Assoc for Grade<T> {
        fn op(self, rhs: Self) -> Self {
            Grade {
                deg: self.deg + rhs.deg,
                base: self.base.op(rhs.base),
            }
        }
    }

    pub trait Action {
        type Space: Assoc;
        fn acted(self, x: Self::Space) -> Self::Space;
    }

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

    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 Peek {
        type Inner: fmt::Debug;

        fn peek(&self) -> Self::Inner;
    }

    pub trait Constant: Copy {
        type Output: Copy;

        const VALUE: Self::Output;
    }
}
// }}}
// segtree {{{
#[allow(dead_code)]
mod segtree {
    #![warn(missing_docs)]

    use crate::type_traits::*;
    use std::{iter, ops};

    #[derive(Debug, Clone, PartialEq)]
    pub struct Segtree<T> {
        len: usize,
        table: Vec<T>,
    }

    impl<T: Assoc, I: std::slice::SliceIndex<[T]>> std::ops::Index<I> for Segtree<T> {
        type Output = I::Output;
        fn index(&self, index: I) -> &Self::Output {
            std::ops::Index::index(self.as_slice(), index)
        }
    }

    impl<T: Assoc> iter::FromIterator<T> for Segtree<T> {
        fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Segtree<T> {
            let mut table = iter.into_iter().collect::<Vec<_>>();
            let okawari = table.to_vec();
            table.extend(okawari.into_iter());
            let len = table.len() / 2;
            for i in (0..len).rev() {
                table[i] = table[2 * i].clone().op(table[2 * i + 1].clone());
            }
            Self { len, table }
        }
    }

    impl<T: Assoc> Segtree<T> {
        pub fn from_slice(src: &[T]) -> Self {
            src.iter().cloned().collect::<Self>()
        }

        pub fn set(&mut self, i: usize, x: T) {
            assert!(i < self.len);
            self.modify(i, |y| y.clone_from(&x));
        }
        pub fn get(&mut self, i: usize) -> &T {
            assert!(i < self.len);
            &self.table[self.len + i]
        }
        pub fn modify(&mut self, mut i: usize, f: impl Fn(&mut T)) {
            assert!(i < self.len);
            i += self.len;
            f(&mut self.table[i]);
            for i in iter::successors(Some(i / 2), |&x| if x == 0 { None } else { Some(x / 2) }) {
                self.update(i);
            }
        }
        pub fn fold(&self, range: impl ops::RangeBounds<usize>) -> Option<T> {
            let (mut start, mut end) = open(self.len, range);
            assert!(start <= end, "変な区間を渡すのをやめませんか？");
            assert!(end <= self.len, "範囲外は禁止です！");
            start += self.len;
            end += self.len;

            if start == end {
                None
            } else if start + 1 == end {
                Some(self.table[start].clone())
            } else {
                let mut left = self.table[start].clone();
                start += 1;
                end -= 1;
                let mut right = self.table[end].clone();
                while start != end {
                    if start % 2 == 1 {
                        left.op_from_right(&self.table[start]);
                        start += 1;
                    }
                    if end % 2 == 1 {
                        end -= 1;
                        right.op_from_left(&self.table[end]);
                    }
                    start /= 2;
                    end /= 2;
                }
                Some(T::op(left, right))
            }
        }

        pub fn as_slice(&self) -> &[T] {
            &self.table[self.len..]
        }

        pub fn forward_partition_point(
            &self,
            start: usize,
            mut f: impl FnMut(&T) -> bool,
        ) -> usize {
            assert!(start <= self.len, "範囲外は禁止です！");
            let mut i = self.len + start;
            if self.fold(start..).map(|x| f(&x)).unwrap_or(true) {
                self.len
            } else if !f(&self.table[i]) {
                start
            } else {
                let mut current = self.table[i].clone();
                i += 1;
                let mut next = current.clone().op(self.table[i].clone());

                while f(&next) {
                    if i % 2 == 0 {
                        i /= 2;
                    } else {
                        current = next.clone();
                        i += 1;
                    }
                    next = current.clone().op(self.table[i].clone());
                }
                loop {
                    if f(&next) {
                        current = next.clone();
                        i += 1;
                    } else {
                        if self.len < i {
                            return i - self.len;
                        }
                        i *= 2;
                    }
                    next = current.clone().op(self.table[i].clone());
                }
            }
        }

        pub fn backward_partition_point(&self, end: usize, mut f: impl FnMut(&T) -> bool) -> usize {
            assert!(end <= self.len, "範囲外は禁止です！");
            let mut i = self.len + end;
            if self.fold(..end).map(|x| f(&x)).unwrap_or(true) {
                0
            } else if !f(&self.table[i - 1]) {
                end
            } else {
                i -= 1;
                let mut current = self.table[i].clone();
                let mut next = self.table[i - 1].clone().op(current.clone());

                while f(&next) {
                    if i % 2 == 0 {
                        i /= 2;
                    } else {
                        i -= 1;
                        current = next.clone();
                    }
                    next = self.table[i - 1].clone().op(current.clone());
                }
                loop {
                    if f(&next) {
                        i -= 1;
                        current = next.clone();
                    } else {
                        if self.len < i {
                            return i - self.len;
                        }
                        i *= 2;
                    }
                    next = self.table[i - 1].clone().op(current.clone());
                }
            }
        }
        pub fn forward_lower_bound_by_key<U: Ord>(
            &self,
            start: usize,
            value: &U,
            mut project: impl FnMut(&T) -> U,
        ) -> usize {
            self.forward_partition_point(start, |x| &project(x) < value)
        }
        pub fn forward_upper_bound_by_key<U: Ord>(
            &self,
            start: usize,
            value: &U,
            mut project: impl FnMut(&T) -> U,
        ) -> usize {
            self.forward_partition_point(start, |x| &project(x) <= value)
        }
        pub fn backward_lower_bound_by_key<U: Ord>(
            &self,
            end: usize,
            value: &U,
            mut project: impl FnMut(&T) -> U,
        ) -> usize {
            self.backward_partition_point(end, |x| &project(x) < value)
        }
        pub fn backward_upper_bound_by_key<U: Ord>(
            &self,
            end: usize,
            value: &U,
            mut project: impl FnMut(&T) -> U,
        ) -> usize {
            self.backward_partition_point(end, |x| &project(x) <= value)
        }

        fn update(&mut self, i: usize) {
            let x = T::op(self.table[2 * i].clone(), self.table[2 * i + 1].clone());
            self.table[i] = x;
        }
    }

    impl<T: Assoc + Ord> Segtree<T> {
        pub fn forward_lower_bound(&self, start: usize, value: &T) -> usize {
            self.forward_partition_point(start, |x| x < value)
        }
        pub fn forward_upper_bound(&self, start: usize, value: &T) -> usize {
            self.forward_partition_point(start, |x| x <= value)
        }
        pub fn backward_lower_bound(&self, end: usize, value: &T) -> usize {
            self.backward_partition_point(end, |x| x < value)
        }
        pub fn backward_upper_bound(&self, end: usize, value: &T) -> usize {
            self.backward_partition_point(end, |x| x <= value)
        }
    }

    fn open(len: usize, range: impl ops::RangeBounds<usize>) -> (usize, usize) {
        use ops::Bound::*;
        (
            match range.start_bound() {
                Unbounded => 0,
                Included(&x) => x,
                Excluded(&x) => x + 1,
            },
            match range.end_bound() {
                Excluded(&x) => x,
                Included(&x) => x + 1,
                Unbounded => len,
            },
        )
    }
}
// }}}
// dbg {{{
#[allow(dead_code)]
mod dbg {
    #[macro_export]
    macro_rules! lg {
        () => {
            $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());
        };
        ($val:expr) => {
            match $val {
                tmp => {
                    eprintln!("[{}:{}] {} = {:?}",
                        file!(), line!(), stringify!($val), &tmp);
                    tmp
                }
            }
        };
        ($val:expr,) => { $crate::lg!($val) };
        ($($val:expr),+ $(,)?) => {
            ($($crate::lg!($val)),+,)
        };
    }

    #[macro_export]
    macro_rules! lg_nl {
        () => {
            eprintln!("[{}:{}]", $crate::file!(), $crate::line!());
        };
        ($val:expr) => {
            match $val {
                tmp => {
                    eprintln!("[{}:{}] {}:\n{:?}", file!(), line!(), stringify!($val), tmp);
                    tmp
                }
            };
        };
    }

    #[macro_export]
    macro_rules! msg {
        () => {
            compile_error!();
        };
        ($msg:expr) => {
            $crate::eprintln!("[{}:{}][{}]", $crate::file!(), $crate::line!(), $msg);
        };
        ($msg:expr, $val:expr) => {
            match $val {
                tmp => {
                    eprintln!("[{}:{}][{}] {} = {:?}",
                        file!(), line!(), $msg, stringify!($val), &tmp);
                    tmp
                }
            }
        };
        ($msg:expr, $val:expr,) => { msg!($msg, $val) };
        ($msg:expr, $($val:expr),+ $(,)?) => {
            ($(msg!($msg, $val)),+,)
        };
    }

    #[macro_export]
    macro_rules! tabular {
        ($val:expr) => {
            $crate::lg_nl!(crate::dbg::Tabular($val))
        };
    }

    #[macro_export]
    macro_rules! boolean_table {
        ($val:expr) => {
            $crate::lg_nl!(crate::dbg::BooleanTable($val));
        };
    }

    #[macro_export]
    macro_rules! boolean_slice {
        ($val:expr) => {
            $crate::lg!(crate::dbg::BooleanSlice($val));
        };
    }

    use std::fmt::{Debug, Formatter};

    #[derive(Clone)]
    pub struct Tabular<'a, T: Debug>(pub &'a [T]);
    impl<'a, T: Debug> Debug for Tabular<'a, T> {
        fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
            for i in 0..self.0.len() {
                writeln!(f, "{:2} | {:?}", i, &self.0[i])?;
            }
            Ok(())
        }
    }

    #[derive(Clone)]
    pub struct BooleanTable<'a>(pub &'a [Vec<bool>]);
    impl<'a> Debug for BooleanTable<'a> {
        fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
            for i in 0..self.0.len() {
                writeln!(f, "{:2} | {:?}", i, BooleanSlice(&self.0[i]))?;
            }
            Ok(())
        }
    }

    #[derive(Clone)]
    pub struct BooleanSlice<'a>(pub &'a [bool]);
    impl<'a> Debug for BooleanSlice<'a> {
        fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
            write!(
                f,
                "{}",
                self.0
                    .iter()
                    .map(|&b| if b { "1 " } else { "0 " })
                    .collect::<String>()
            )?;
            Ok(())
        }
    }
}
// }}}
// ngtio {{{
#[allow(dead_code)]
mod ngtio {
    #![warn(missing_docs)]

    mod i {
        use std::{
            io::{self, BufRead},
            iter,
        };

        pub use multi_token::{Leaf, Parser, ParserTuple, RawTuple, Tuple, VecLen};
        pub use token::{Token, Usize1};

        pub fn with_stdin() -> Tokenizer<io::BufReader<io::Stdin>> {
            io::BufReader::new(io::stdin()).tokenizer()
        }

        pub fn with_str(src: &str) -> Tokenizer<&[u8]> {
            src.as_bytes().tokenizer()
        }

        pub struct Tokenizer<S: BufRead> {
            queue: Vec<String>, // FIXME: String のみにすると速そうです。
            scanner: S,
        }
        macro_rules! prim_method {
            ($name:ident: $T:ty) => {
#[allow(missing_docs)]
                pub fn $name(&mut self) -> $T {
                    <$T>::leaf().parse(self)
                }
            };
            ($name:ident) => {
                prim_method!($name: $name);
            };
        }
        macro_rules! prim_methods {
            ($name:ident: $T:ty; $($rest:tt)*) => {
                prim_method!($name:$T);
                prim_methods!($($rest)*);
            };
            ($name:ident; $($rest:tt)*) => {
                prim_method!($name);
                prim_methods!($($rest)*);
            };
            () => ()
        }
        impl<S: BufRead> Tokenizer<S> {
            pub fn token(&mut self) -> String {
                self.load();
                self.queue.pop().expect("入力が終了したのですが。")
            }
            pub fn new(scanner: S) -> Self {
                Self {
                    queue: Vec::new(),
                    scanner,
                }
            }
            fn load(&mut self) {
                while self.queue.is_empty() {
                    let mut s = String::new();
                    let length = self.scanner.read_line(&mut s).unwrap(); // 入力が UTF-8 でないときにエラーだそうです。
                    if length == 0 {
                        break;
                    }
                    self.queue = s.split_whitespace().rev().map(str::to_owned).collect();
                }
            }

            pub fn skip_line(&mut self) {
                assert!(
                    self.queue.is_empty(),
                    "行の途中で呼ばないでいただきたいです。現在のトークンキュー: {:?}",
                    &self.queue
                );
                self.load();
            }

            pub fn end(&mut self) {
                self.load();
                assert!(self.queue.is_empty(), "入力はまだあります！");
            }

            pub fn parse<T: Token>(&mut self) -> T::Output {
                T::parse(&self.token())
            }

            pub fn parse_collect<T: Token, B>(&mut self, n: usize) -> B
            where
                B: iter::FromIterator<T::Output>,
            {
                iter::repeat_with(|| self.parse::<T>()).take(n).collect()
            }

            pub fn tuple<T: RawTuple>(&mut self) -> <T::LeafTuple as Parser>::Output {
                T::leaf_tuple().parse(self)
            }

            pub fn vec<T: Token>(&mut self, len: usize) -> Vec<T::Output> {
                T::leaf().vec(len).parse(self)
            }

            pub fn vec_tuple<T: RawTuple>(
                &mut self,
                len: usize,
            ) -> Vec<<T::LeafTuple as Parser>::Output> {
                T::leaf_tuple().vec(len).parse(self)
            }

            pub fn vec2<T: Token>(&mut self, height: usize, width: usize) -> Vec<Vec<T::Output>> {
                T::leaf().vec(width).vec(height).parse(self)
            }

            pub fn vec2_tuple<T>(
                &mut self,
                height: usize,
                width: usize,
            ) -> Vec<Vec<<T::LeafTuple as Parser>::Output>>
            where
                T: RawTuple,
            {
                T::leaf_tuple().vec(width).vec(height).parse(self)
            }
            prim_methods! {
                u8; u16; u32; u64; u128; usize;
                i8; i16; i32; i64; i128; isize;
                char; string: String;
            }
        }

        mod token {
            use super::multi_token::Leaf;
            use std::{any, fmt, marker, str};

            pub trait Token: Sized {
                type Output;
                fn parse(s: &str) -> Self::Output;
                fn leaf() -> Leaf<Self> {
                    Leaf(marker::PhantomData)
                }
            }

            impl<T> Token for T
            where
                T: str::FromStr,
                <T as str::FromStr>::Err: fmt::Debug,
            {
                type Output = T;
                fn parse(s: &str) -> Self::Output {
                    s.parse().unwrap_or_else(|_| {
                        panic!("Parse error!: ({}: {})", s, any::type_name::<T>(),)
                    })
                }
            }

            pub struct Usize1 {}
            impl Token for Usize1 {
                type Output = usize;
                fn parse(s: &str) -> Self::Output {
                    usize::parse(s)
                        .checked_sub(1)
                        .expect("Parse error! (Zero substruction error of Usize1)")
                }
            }
        }

        mod multi_token {
            use super::{Token, Tokenizer};
            use std::{io::BufRead, iter, marker};

            pub trait Parser: Sized {
                type Output;
                fn parse<S: BufRead>(&self, server: &mut Tokenizer<S>) -> Self::Output;
                fn vec(self, len: usize) -> VecLen<Self> {
                    VecLen { len, elem: self }
                }
            }
            pub struct Leaf<T>(pub(super) marker::PhantomData<T>);
            impl<T: Token> Parser for Leaf<T> {
                type Output = T::Output;
                fn parse<S: BufRead>(&self, server: &mut Tokenizer<S>) -> T::Output {
                    server.parse::<T>()
                }
            }

            pub struct VecLen<T> {
                pub len: usize,
                pub elem: T,
            }
            impl<T: Parser> Parser for VecLen<T> {
                type Output = Vec<T::Output>;
                fn parse<S: BufRead>(&self, server: &mut Tokenizer<S>) -> Self::Output {
                    iter::repeat_with(|| self.elem.parse(server))
                        .take(self.len)
                        .collect()
                }
            }

            pub trait RawTuple {
                type LeafTuple: Parser;
                fn leaf_tuple() -> Self::LeafTuple;
            }
            pub trait ParserTuple {
                type Tuple: Parser;
                fn tuple(self) -> Self::Tuple;
            }
            pub struct Tuple<T>(pub T);
            macro_rules! impl_tuple {
                ($($t:ident: $T:ident),*) => {
                    impl<$($T),*> Parser for Tuple<($($T,)*)>
                        where
                            $($T: Parser,)*
                            {
                                type Output = ($($T::Output,)*);
#[allow(unused_variables)]
                                fn parse<S: BufRead >(&self, server: &mut Tokenizer<S>) -> Self::Output {
                                    match self {
                                        Tuple(($($t,)*)) => {
                                            ($($t.parse(server),)*)
                                        }
                                    }
                                }
                            }
                    impl<$($T: Token),*> RawTuple for ($($T,)*) {
                        type LeafTuple = Tuple<($(Leaf<$T>,)*)>;
                        fn leaf_tuple() -> Self::LeafTuple {
                            Tuple(($($T::leaf(),)*))
                        }
                    }
                    impl<$($T: Parser),*> ParserTuple for ($($T,)*) {
                        type Tuple = Tuple<($($T,)*)>;
                        fn tuple(self) -> Self::Tuple {
                            Tuple(self)
                        }
                    }
                };
            }
            impl_tuple!();
            impl_tuple!(t1: T1);
            impl_tuple!(t1: T1, t2: T2);
            impl_tuple!(t1: T1, t2: T2, t3: T3);
            impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4);
            impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5);
            impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6);
            impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7);
            impl_tuple!(
                t1: T1,
                t2: T2,
                t3: T3,
                t4: T4,
                t5: T5,
                t6: T6,
                t7: T7,
                t8: T8
            );
        }

        trait Scanner: BufRead + Sized {
            fn tokenizer(self) -> Tokenizer<Self> {
                Tokenizer::new(self)
            }
        }
        impl<R: BufRead> Scanner for R {}
    }

    pub use i::{with_stdin, with_str};

    pub mod prelude {
        pub use super::i::{Parser, ParserTuple, RawTuple, Token, Usize1};
    }
}
// }}}