AtCoder Beginner Contest 326 E

https://atcoder.jp/contests/abc326/tasks/abc326_e

nにたどり着く確率は、0のときにnが出る確率と、1のときにn-1が出る確率と、と考えると、
 p_0 = 1
 \displaystyle p_n = \frac{1}{N}\sum_{i=0}^{n-1}{p_i}
です。
 \displaystyle s_n \equiv \sum_{i=0}^n{p_i}
とすれば、
 \displaystyle p_n = \frac{s_{n-1}}{N}
 s_n = s_{n-1} + p_n
です。期待値は、
 \displaystyle \frac{1}{N}\sum_{n=1}^N{A_ip_i}
となります。

// ABC Puzzle
#![allow(non_snake_case)]


//////////////////// constants ////////////////////

const D: i64 = 998244353;


//////////////////// library ////////////////////

fn read<T: std::str::FromStr>() -> T {
    let mut line = String::new();
    std::io::stdin().read_line(&mut line).ok();
    line.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace()
            .map(|e| e.parse().ok().unwrap()).collect()
}

// ax = by + 1 (a, b > 0)
fn linear_diophantine(a: i64, b: i64) -> Option<(i64, i64)> {
    if a == 1 {
        return Some((1, 0))
    }
    
    let q = b / a;
    let r = b % a;
    if r == 0 {
        return None
    }
    let (x1, y1) = linear_diophantine(r, a)?;
    Some((-q * x1 - y1, -x1))
}

fn inverse(a: i64, d: i64) -> i64 {
    let (x, _y) = linear_diophantine(a, d).unwrap();
    if x >= 0 {
        x % d
    }
    else {
        x % d + d
    }
}


//////////////////// process ////////////////////

fn read_input() -> Vec<i64> {
    let _N: usize = read();
    let A = read_vec();
    A
}

fn F(A: Vec<i64>) -> i64 {
    let N = A.len();
    let mut s: i64 = 1;
    let mut E: i64 = 0;
    let rep = inverse(N as i64, D);
    for i in 1..N+1 {
        let p = s * rep % D;
        E = (E + A[i-1] * p) % D;
        s = (s + p) % D
    }
    E
}

fn main() {
    let A = read_input();
    println!("{}", F(A))
}