https://atcoder.jp/contests/abc291/tasks/abc291_d
単なるDPですね。
ギリギリi32で足ります。
// Flip Cards #![allow(non_snake_case)] const D: i32 = 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() } //////////////////// process //////////////////// type Card = (i32, i32); fn read_input() -> Vec<Card> { let N: usize = read(); let cards: Vec<Card> = (0..N).map(|_| read_vec()). map(|v| (v[0], v[1])).collect(); cards } fn proceed(dp: (i32, i32), card1: Card, card2: Card) -> (i32, i32) { let step = |a, b, c| if a == b { 0 } else { c }; ((step(card1.0, card2.0, dp.0) + step(card1.1, card2.0, dp.1)) % D, (step(card1.0, card2.1, dp.0) + step(card1.1, card2.1, dp.1)) % D) } fn f(cards: Vec<Card>) -> i32 { let mut dp = (1, 1); for i in 1..cards.len() { dp = proceed(dp, cards[i-1], cards[i]) } (dp.0 + dp.1) % D } fn main() { let cards = read_input(); println!("{}", f(cards)) }