use std::{collections::HashMap, hash::Hash}; use proconio::input; // 0. 決定性有限オートマトン trait Dfa { type State; type Alphabet; fn init(&self) -> Self::State; fn next(&self, q: &Self::State, c: &Self::Alphabet) -> Self::State; fn accept(&self, q: &Self::State) -> bool; } // 1. MultipleOf(3) は 3 の倍数を認識するオートマトン struct MultipleOf(u64); impl Dfa for MultipleOf { type State = u64; type Alphabet = u8; fn init(&self) -> Self::State { 0 } fn next(&self, q: &Self::State, c: &Self::Alphabet) -> Self::State { (q * 10 + (c - b'0') as u64) % self.0 } fn accept(&self, q: &Self::State) -> bool { *q == 0 } } // 2. Seen(b'3') は 3 がつく数を認識するオートマトン struct Seen(u8); impl Dfa for Seen { type State = bool; type Alphabet = u8; fn init(&self) -> Self::State { false } fn next(&self, q: &Self::State, c: &Self::Alphabet) -> Self::State { *q || *c == self.0 } fn accept(&self, q: &Self::State) -> bool { *q } } // 3. Or(a, b) は a または b が認識する数を認識するオートマトン struct Or(A, B); impl> Dfa for Or { type State = (A::State, B::State); type Alphabet = A::Alphabet; fn init(&self) -> Self::State { (self.0.init(), self.1.init()) } fn next(&self, q: &Self::State, c: &Self::Alphabet) -> Self::State { (self.0.next(&q.0, c), self.1.next(&q.1, c)) } fn accept(&self, q: &Self::State) -> bool { self.0.accept(&q.0) || self.1.accept(&q.1) } } // 4. dfa が認識する言語と sigma^len の共通部分を数える fn count(dfa: A, sigma: S, len: usize) -> u64 where A: Dfa, A::State: Eq + Hash, S: Iterator + Clone, { let mut dp = HashMap::new(); dp.insert(dfa.init(), 1); for _ in 0..len { let mut ndp = HashMap::new(); for (q, v) in dp { for c in sigma.clone() { *ndp.entry(dfa.next(&q, &c)).or_insert(0) += v; } } dp = ndp; } dp.iter() .filter_map(|(q, v)| dfa.accept(q).then_some(v)) .sum() } // 5. Just Do It !!!! fn main() { input!(p: usize); let dfa = Or(MultipleOf(3), Seen(b'3')); println!("{}", count(dfa, b'0'..=b'9', p) - 1); }