Problem:
Score : 900 points

Problem Statement

Given are a permutation p_1, p_2, \dots, p_N of (1, 2, ..., N) and an integer K. Maroon performs the following operation for i = 1, 2, \dots, N - K + 1 in this order:

Shuffle p_i, p_{i + 1}, \dots, p_{i + K - 1} uniformly randomly.

Find the expected value of the inversion number of the sequence after all the operations are performed, and print it modulo 998244353.

More specifically, from the constraints of this problem, it can be proved that the expected value is always a rational number, which can be represented as an irreducible fraction \frac{P}{Q}, and that the integer R that satisfies R \times Q \equiv P \pmod{998244353}, 0 \leq R < 998244353 is uniquely determined. Print this R.

Here, the inversion number of a sequence a_1, a_2, \dots, a_N is defined to be the number of ordered pairs (i, j) that satisfy i < j, a_i > a_j.

Constraints

2 \leq N \leq 200,000

2 \leq K \leq N

(p_1, p_2, \dots, p_N) is a permutation of (1, 2, \dots, N).

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
p_1 p_2 ... p_N

Output

Print the expected value modulo 998244353.

Sample Input 1

3 2
1 2 3

Sample Output 1

1

The final sequence is one of (1, 2, 3), (2, 1, 3), (1, 3, 2), (2, 3, 1), each with probability \frac{1}{4}.
Their inversion numbers are 0, 1, 1, 2 respectively, so the expected value is 1.

Sample Input 2

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

Sample Output 2

164091855

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

#![allow(clippy::many_single_char_names)]

use type_traits::{One, Zero};
type Fp = fp::F998244353;

fn main() {
    let mut buf = ngtio::Buffer::new();
    let n = buf.usize();
    let k = buf.usize();
    let a = iter::repeat_with(|| buf.usize() - 1)
        .take(n)
        .collect::<Vec<_>>();
    let mut b = (0..n)
        .map(|i| (a[i], i.saturating_sub(k - 1)))
        .collect::<Vec<_>>();
    b.sort();
    let b = b.iter().map(|&(_, i)| i).collect::<Vec<_>>();

    let p = Fp::one() - Fp::new(k as i64).inv();
    let mut pow_p = vec![Fp::one(); n - k + 1];
    for i in 1..n - k + 1 {
        pow_p[i] = pow_p[i - 1] * p;
    }

    let mut fwk0 = fenwick::Fenwick::from_zero_slice(0, &vec![0; n - k + 1]);
    let mut fwk1 = fenwick::Fenwick::from_zero_slice(Fp::zero(), &vec![Fp::zero(); n - k + 1]);
    let mut fwk2 = fenwick::Fenwick::from_zero_slice(Fp::zero(), &vec![Fp::zero(); n - k + 1]);
    let mut invertion = 0i64;
    let mut plus = vec![Fp::zero(); n - k + 1];
    let mut minus = vec![Fp::zero(); n - k + 1];
    for &x in &b {
        invertion += fwk0.sum(x + 1..);
        plus[x] += fwk1.sum(..x);
        minus[x] += fwk2.sum(x + 1..);
        fwk0.add(x, 1);
        fwk1.add(x, pow_p[x].inv());
        fwk2.add(x, pow_p[x]);
    }

    let ans = (0..n - k + 1)
        .map(|i| plus[i] * pow_p[i] - minus[i] * pow_p[i].inv())
        .sum::<Fp>();
    let ans =
        Fp::new(invertion) + ans / Fp::new(2) + Fp::new((k * (k - 1) / 2) as i64) / Fp::new(2);
    println!("{}", ans);
}

// template {{{
#[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};
// }}}
// fp {{{
#[allow(dead_code)]
mod fp {
    #![warn(missing_docs)]
    use crate::type_traits::*;
    pub use aliases::*;
    use std::{cmp, fmt, iter, mem, ops::*};

    mod arith {
        use super::{Fp, Modable, Value};
        use crate::type_traits::*;
        use std::ops::*;

        impl<Mod: Modable> Add for Fp<Mod>
        where
            Mod::Output: Value,
        {
            type Output = Self;

            #[inline]
            fn add(self, rhs: Self) -> Self {
                Self(Self::normalize_from_the_bottom(
                    self.into_inner() + rhs.into_inner(),
                ))
            }
        }

        impl<Mod: Modable> Sub for Fp<Mod>
        where
            Mod::Output: Value,
        {
            type Output = Self;

            #[inline]
            fn sub(self, rhs: Self) -> Self {
                Self(Self::normalize_from_the_top(
                    self.into_inner() - rhs.into_inner(),
                ))
            }
        }

        impl<Mod: Modable> Mul for Fp<Mod>
        where
            Mod::Output: Value,
        {
            type Output = Self;

            #[inline]
            fn mul(self, rhs: Self) -> Self {
                Self::new(self.into_inner() * rhs.into_inner())
            }
        }

        #[allow(clippy::suspicious_arithmetic_impl)]
        impl<Mod: Modable> Div for Fp<Mod>
        where
            Mod::Output: Value,
        {
            type Output = Self;

            #[inline]
            fn div(self, rhs: Self) -> Self {
                self * rhs.inv()
            }
        }

        impl<Mod: Modable> Neg for Fp<Mod>
        where
            Mod::Output: Value,
        {
            type Output = Self;

            #[inline]
            fn neg(self) -> Self {
                if self.into_inner().is_zero() {
                    Self::zero()
                } else {
                    Self(Mod::VALUE - self.into_inner())
                }
            }
        }

        impl<Mod: Modable> Neg for &Fp<Mod>
        where
            Mod::Output: Value,
        {
            type Output = Fp<Mod>;

            #[inline]
            fn neg(self) -> Fp<Mod> {
                if self.into_inner().is_zero() {
                    Fp::zero()
                } else {
                    Fp(Mod::VALUE - self.into_inner())
                }
            }
        }

        macro_rules! forward_assign_biop {
            ($(impl $trait:ident, $fn_assign:ident, $fn:ident)*) => {
                $(
                    impl<Mod: Modable> $trait for Fp<Mod>
                    where
                        Mod::Output: Value
                    {
                        #[inline]
                        fn $fn_assign(&mut self, rhs: Self) {
                            *self = self.$fn(rhs);
                        }
                    }
                )*
            };
        }
        forward_assign_biop! {
            impl AddAssign, add_assign, add
            impl SubAssign, sub_assign, sub
            impl MulAssign, mul_assign, mul
            impl DivAssign, div_assign, div
        }

        macro_rules! forward_ref_binop {
            ($(impl $imp:ident, $method:ident)*) => {
                $(
                    impl<'a, Mod: Modable> $imp<Fp<Mod>> for &'a Fp<Mod>
                    where
                        Mod::Output:Value
                    {
                        type Output = Fp<Mod>;

                        #[inline]
                        fn $method(self, other: Fp<Mod>) -> Self::Output {
                            $imp::$method(*self, other)
                        }
                    }

                    impl<'a, Mod: Modable> $imp<&'a Fp<Mod>> for Fp<Mod>
                    where
                        Mod::Output:Value
                    {
                        type Output = Fp<Mod>;

                        #[inline]
                        fn $method(self, other: &Fp<Mod>) -> Self::Output {
                            $imp::$method(self, *other)
                        }
                    }

                    impl<'a, Mod: Modable> $imp<&'a Fp<Mod>> for &'a Fp<Mod>
                    where
                        Mod::Output:Value
                    {
                        type Output = Fp<Mod>;

                        #[inline]
                        fn $method(self, other: &Fp<Mod>) -> Self::Output {
                            $imp::$method(*self, *other)
                        }
                    }
                )*
            };
        }
        forward_ref_binop! {
            impl Add, add
            impl Sub, sub
            impl Mul, mul
            impl Div, div
        }
    }

    #[macro_export]
    macro_rules! fp_vec {
        () => (
            Vec::<$crate::Fp<_>>::new()
        );
        ($elem:expr; $n:expr) => (
            vec![$crate::Fp::new($elem); $n]
        );
        ($($x:expr),+ $(,)?) => (
            vec![$($crate::Fp::new($x),)+];
        );
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct Fp<Mod: Modable>(Mod::Output);

    impl<Mod: Modable> Fp<Mod>
    where
        Mod::Output: Value,
    {
        #[inline]
        pub fn new(src: Mod::Output) -> Self {
            Self(Self::normalize(src))
        }

        #[inline]
        pub fn frac(num: Mod::Output, den: Mod::Output) -> Self {
            Self::new(num) / Self::new(den)
        }

        #[inline]
        pub fn into_inner(self) -> Mod::Output {
            self.0
        }

        #[allow(clippy::many_single_char_names)]
        pub fn inv(self) -> Self {
            assert_ne!(
                self.into_inner(),
                Mod::Output::zero(),
                "さては 0 の逆元を取ろうとしていますね？"
            );
            let mut x = self.into_inner();
            let mut y = Mod::VALUE;
            let mut u = Mod::Output::one();
            let mut v = Mod::Output::zero();
            while x != Mod::Output::zero() {
                let q = y / x;
                y -= q * x;
                v -= q * u;
                mem::swap(&mut x, &mut y);
                mem::swap(&mut u, &mut v);
            }
            assert!(
                x == Mod::Output::zero()
                    && y == Mod::Output::one()
                    && (u == Mod::VALUE || u == -Mod::VALUE)
                    && (-Mod::VALUE < v && v < Mod::VALUE)
            );
            Self(Self::normalize_from_the_top(v))
        }

        pub fn pow(mut self, mut p: u64) -> Self {
            let mut ans = Self::one();
            while p != 0 {
                if p % 2 == 1 {
                    ans *= self;
                }
                self *= self;
                p /= 2;
            }
            ans
        }

        #[inline]
        fn normalize(src: Mod::Output) -> Mod::Output {
            Self::normalize_from_the_top(src % Mod::VALUE)
        }

        #[inline]
        fn normalize_from_the_bottom(src: Mod::Output) -> Mod::Output {
            if Mod::VALUE <= src {
                src - Mod::VALUE
            } else {
                src
            }
        }

        #[inline]
        fn normalize_from_the_top(src: Mod::Output) -> Mod::Output {
            if src < Mod::Output::zero() {
                src + Mod::VALUE
            } else {
                src
            }
        }
    }

    impl<Mod: Modable> Zero for Fp<Mod>
    where
        Mod::Output: Value,
    {
        #[inline]
        fn zero() -> Fp<Mod> {
            Fp::new(Mod::Output::zero())
        }
        fn times(self, n: u64) -> Fp<Mod> {
            self * Fp::from_u64(n)
        }
        fn times_assign(&mut self, n: u64) {
            *self *= Fp::from_u64(n)
        }
        fn from_u64(n: u64) -> Fp<Mod> {
            Fp::new(Mod::Output::from_u64(n))
        }
    }

    impl<Mod: Modable> One for Fp<Mod>
    where
        Mod::Output: Value,
    {
        #[inline]
        fn one() -> Fp<Mod> {
            Fp::new(Mod::Output::one())
        }
    }

    impl<Mod: Modable> iter::Sum<Fp<Mod>> for Fp<Mod>
    where
        Mod::Output: Value,
    {
        fn sum<I>(iter: I) -> Self
        where
            I: iter::Iterator<Item = Fp<Mod>>,
        {
            iter.fold(Fp::zero(), Add::add)
        }
    }

    impl<'a, Mod: 'a + Modable> iter::Sum<&'a Fp<Mod>> for Fp<Mod>
    where
        Mod::Output: Value,
    {
        fn sum<I>(iter: I) -> Self
        where
            I: iter::Iterator<Item = &'a Fp<Mod>>,
        {
            iter.fold(Fp::zero(), Add::add)
        }
    }

    impl<Mod: Modable> iter::Product<Fp<Mod>> for Fp<Mod>
    where
        Mod::Output: Value,
    {
        fn product<I>(iter: I) -> Self
        where
            I: iter::Iterator<Item = Fp<Mod>>,
        {
            iter.fold(Self::one(), Mul::mul)
        }
    }

    impl<'a, Mod: 'a + Modable> iter::Product<&'a Fp<Mod>> for Fp<Mod>
    where
        Mod::Output: Value,
    {
        fn product<I>(iter: I) -> Self
        where
            I: iter::Iterator<Item = &'a Fp<Mod>>,
        {
            iter.fold(Self::one(), Mul::mul)
        }
    }

    impl<Mod: Modable> fmt::Display for Fp<Mod>
    where
        Mod::Output: Value,
    {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
            write!(f, "{}", self.0)
        }
    }

    pub trait Modable: Constant + Clone + fmt::Debug + cmp::PartialEq + cmp::Eq {}
    impl<Mod: Constant + Clone + fmt::Debug + cmp::PartialEq + cmp::Eq> Modable for Mod {}

    pub trait Value:
        Sized
        + Clone
        + Copy
        + Ring
        + fmt::Debug
        + fmt::Display
        + cmp::PartialOrd
        + cmp::Ord
        + cmp::Eq
        + Div<Output = Self>
        + Rem<Output = Self>
        + Neg<Output = Self>
        + DivAssign
        + RemAssign
    {
    }

    macro_rules! impl_value {
        ($($type:ty,)*) => { $(impl Value for $type {})* };
    }

    impl_value! { i8, i16, i32, i64, i128, isize, }

    mod aliases {
        use super::Fp;
        use crate::type_traits::Constant;

        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub struct Mod1000000007 {}
        pub type F1000000007 = Fp<Mod1000000007>;
        impl Constant for Mod1000000007 {
            type Output = i64;
            const VALUE: i64 = 1_000_000_007;
        }

        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub struct Mod998244353 {}
        pub type F998244353 = Fp<Mod998244353>;
        impl Constant for Mod998244353 {
            type Output = i64;
            const VALUE: i64 = 998_244_353;
        }
    }
}
// }}}
// 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;
    }
}
// }}}
// fenwick {{{
#[allow(dead_code)]
mod fenwick {
    use std::{fmt, iter, ops};

    #[derive(Debug, Clone)]
    pub struct Fenwick<T> {
        table: Vec<T>,
    }

    impl<'a, T> Fenwick<T>
    where
        T: Clone + fmt::Debug + ops::Add<Output = T> + ops::AddAssign + iter::Sum<T>,
    {
        pub fn new(zero: T) -> Self {
            Fenwick { table: vec![zero] }
        }

        pub fn from_zero_slice(zero: T, src: &[T]) -> Self {
            let mut table = iter::once(zero)
                .chain(src.iter().cloned())
                .collect::<Vec<_>>();
            let n = table.len();
            (1..n)
                .map(|i| (i, i + lsb(i)))
                .filter(|&(_, j)| j < n)
                .for_each(|(i, j)| {
                    let x = table[i].clone();
                    table[j] += x
                });
            Self { table }
        }

        pub fn push(&mut self, mut x: T) {
            let i = self.table.len();
            let lsb_i = lsb(i);
            x += iter::successors(Some(1), |&d| Some(2 * d))
                .take_while(|&d| d != lsb_i)
                .map(|d| self.table[i - d].clone())
                .sum::<T>();
            self.table.push(x);
        }

        pub fn prefix_sum(&self, i: usize) -> T {
            iter::successors(Some(i), |&i| Some(i - lsb(i)))
                .take_while(|&i| i != 0)
                .map(|i| self.table[i].clone())
                .sum::<T>()
        }

        pub fn add(&mut self, i: usize, x: T) {
            let n = self.table.len();
            iter::successors(Some(i + 1), |&i| Some(i + lsb(i)))
                .take_while(|&i| i < n)
                .for_each(|i| self.table[i] += x.clone());
        }

        pub fn partition_point(&self, pred: impl Fn(usize, &T) -> bool) -> (usize, T) {
            let mut j = 0;
            let mut current = self.table[0].clone();
            for d in iter::successors(Some(self.table.len().next_power_of_two() / 2), |&d| {
                Some(d / 2)
            })
            .take_while(|&d| d != 0)
            {
                assert!(
                    pred(0, &self.table[0]),
                    "pred(0, zero) のほうよろしくお願いいたします！"
                );
                if j + d < self.table.len() {
                    let next = current.clone() + self.table[j + d].clone();
                    if pred(j + d, &next) {
                        current = next;
                        j += d;
                    }
                }
            }
            (j, current)
        }

        #[inline]
        pub fn lower_bound(&self, x: &T) -> usize
        where
            T: Ord,
        {
            self.partition_point(|_, y| y < x).0
        }

        #[inline]
        pub fn upper_bound(&self, x: &T) -> usize
        where
            T: Ord,
        {
            self.partition_point(|_, y| y <= x).0
        }

        #[inline]
        pub fn lower_bound_from(&self, i: usize, x: &T) -> usize
        where
            T: Ord,
        {
            let bi = self.prefix_sum(i);
            let res = self.partition_point(|_, y| y < &(bi.clone() + x.clone())).0;
            assert!(i <= res, "逆戻りしていませんか？");
            res
        }

        #[inline]
        pub fn upper_bound_from(&self, i: usize, x: &T) -> usize
        where
            T: Ord,
        {
            let bi = self.prefix_sum(i);
            let res = self
                .partition_point(|_, y| y <= &(bi.clone() + x.clone()))
                .0;
            assert!(i <= res, "逆戻りしていませんか？");
            res
        }
    }

    impl<'a, T> Fenwick<T>
    where
        T: Clone
            + fmt::Debug
            + ops::Add<Output = T>
            + ops::AddAssign
            + ops::Sub<Output = T>
            + ops::SubAssign
            + iter::Sum<T>,
    {
        pub fn sum(&self, range: impl ops::RangeBounds<usize>) -> T {
            let start = match range.start_bound() {
                ops::Bound::Unbounded => 0,
                ops::Bound::Included(&x) => x,
                ops::Bound::Excluded(&x) => x + 1,
            };
            let end = match range.end_bound() {
                ops::Bound::Excluded(&x) => x,
                ops::Bound::Included(&x) => x + 1,
                ops::Bound::Unbounded => self.table.len() - 1,
            };
            assert!(start <= end, "変な区間を渡すのをやめませんか？");
            assert!(end < self.table.len(), "残念範囲外です！");
            self.prefix_sum(end) - self.prefix_sum(start)
        }

        pub fn access(&self, i: usize) -> T {
            assert!(i < self.table.len() - 1, "残念範囲外です！");
            self.prefix_sum(i + 1) - self.prefix_sum(i)
        }

        pub fn set(&mut self, i: usize, x: T) {
            assert!(i < self.table.len() - 1, "残念範囲外です！");
            self.add(i, x - self.access(i));
        }
    }

    fn lsb(x: usize) -> usize {
        x & x.wrapping_neg()
    }
}
// }}}