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: Time Limit Exceeded)

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

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

#[allow(dead_code)]
fn guess(x: Fp) -> (i64, i64) {
    for i in 2..1000 {
        for j in 2..1000 {
            if x == Fp::frac(i, j) {
                return (i, j);
            }
        }
    }
    (x.into_inner(), 1)
}

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 p = Fp::one() - Fp::new(k as i64).inv();
    let mut pow_p = vec![Fp::zero(); n + 1];
    pow_p[0] = Fp::one();
    for i in 0..n {
        pow_p[i + 1] = pow_p[i] * p;
    }

    let mut plus = vec![0; n];
    let mut minus = vec![0; n];
    for (i, &x) in a.iter().enumerate() {
        for j in i + 1..n {
            let y = a[j];
            let d = std::cmp::min(j - i, j.saturating_sub(k - 1));
            if x < y {
                plus[d] += 1;
            } else {
                minus[d] += 1;
            }
        }
    }

    let mut ans = Fp::zero();
    for i in 0..n {
        let q = pow_p[i] / Fp::new(2);
        ans += q * Fp::new(plus[i] as i64);
        ans += (Fp::one() - q) * Fp::new(minus[i] as i64);
    }
    println!("{}", ans);
}