AtCoder Beginner Contest 310 F

https://atcoder.jp/contests/abc310/tasks/abc310_f

DPで今の和の集合を状態とします。この集合を整数で表しますとよいです。ただし、10より大きい和は無視してよいです。0は必ずあるので、この状態の整数は奇数になりますが、10を含む状態を0で表せば、1023以下で表すことができます。

// Make 10 Again
#![allow(non_snake_case)]

use std::cmp::min;
use std::collections::HashMap;


//////////////////// 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 ////////////////////

type State = usize;

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

fn contains(s: State, i: usize) -> bool {
    ((s >> i) & 1) == 1
}

fn nexts(s: State, a: i64) -> Vec<(State, i64)> {
    if s == 0 {
        return vec![(0, a)]
    }
    
    let mut ss: HashMap<State, i64> = HashMap::new();
    for roll in 1..min(a, 10)+1 {
        let s1: State = s | (s << roll);
        let s2 = if contains(s1, 10) { 0 } else { s1 & 1023 };
        let e = ss.entry(s2).or_insert(0);
        *e += 1
    }
    if a > 10 {
        let e = ss.entry(s).or_insert(0);
        *e += a - 10
    }
    ss.into_iter().collect::<Vec<(State, i64)>>()
}

fn update(dp: Vec<i64>, a: i64) -> Vec<i64> {
    let mut new_dp: Vec<i64> = vec![0; 1024];
    let r = inverse(a, D);
    for s in (0..1024).filter(|&s| dp[s] != 0) {
        let ss = nexts(s, a);
        for (s1, c) in ss.into_iter() {
            new_dp[s1] = (new_dp[s1] + dp[s] * c % D * r) % D
        }
    }
    new_dp
}

fn f(A: Vec<i64>) -> i64 {
    let mut dp: Vec<i64> = vec![0; 1024];
    dp[1] = 1;
    for a in A.into_iter() {
        dp = update(dp, a);
    }
    dp[0]
}


//////////////////// main ////////////////////

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