https://atcoder.jp/contests/abc298/tasks/abc298_e
単なるDPですが、Dを法とした逆数を求めなければなりません。拡張ユークリッド互除法ですね。一度書けば終わりですが。
// Unfair Sugoroku #![allow(non_snake_case)] use std::cmp::min; //////////////////// constants //////////////////// const D: usize = 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() -> (usize, usize, usize, usize, usize) { let v = read_vec(); (v[0], v[1], v[2], v[3], v[4]) } fn f(N: usize, A: usize, B: usize, P: usize, Q: usize) -> usize { let inv_P = inverse(P as i64, D as i64) as usize; let inv_Q = inverse(Q as i64, D as i64) as usize; let mut dp1: Vec<Vec<usize>> = (0..N+1).map(|_| (0..N+1).map(|_| 0).collect()).collect(); let mut dp2 = dp1.to_vec(); dp2[A][B] = 1; let mut win: usize = 0; for x in A..N { for y in B..N { for i in 1..P+1 { let x1 = min(x + i, N); let p = dp2[x][y] * inv_P % D; dp1[x1][y] = (dp1[x1][y] + p) % D; if x1 == N { win += p } } for i in 1..Q+1 { let y1 = min(y + i, N); let p = dp1[x][y] * inv_Q % D; dp2[x][y1] = (dp2[x][y1] + p) % D; } } } win % D } fn main() { let (N, A, B, P, Q) = read_input(); println!("{}", f(N, A, B, P, Q)) }