//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); input_inner!{iter, $($r)*} }; ($($r:tt)*) => { let s = { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); s }; let mut iter = s.split_whitespace(); input_inner!{iter, $($r)*} }; } macro_rules! input_inner { ($iter:expr) => {}; ($iter:expr, ) => {}; ($iter:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($iter, $t); input_inner!{$iter $($r)*} }; } macro_rules! read_value { ($iter:expr, ( $($t:tt),* )) => { ( $(read_value!($iter, $t)),* ) }; ($iter:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($iter, $t)).collect::>() }; ($iter:expr, chars) => { read_value!($iter, String).chars().collect::>() }; ($iter:expr, bytes) => { read_value!($iter, String).bytes().collect::>() }; ($iter:expr, usize1) => { read_value!($iter, usize) - 1 }; ($iter:expr, $t:ty) => { $iter.next().unwrap().parse::<$t>().expect("Parse error") }; } // fn print(n: i32) { print!("{}: ", n); let mut n = n; while n > 0 { print!(" {}", n % 5); n /= 5; } println!(); } fn test() { let n = 1000; for i in 1..=n { let mut diff = 0i32; let mut left = i; let mut right = 0; let mut weight = 1; while left != right { let l = left / weight % 5; let r = right / weight % 5; if l < r { if l + 2 >= r { left += weight * (r - l); diff += r - l; } else { assert!(l + 5 - r <= 2); right += weight * (l + 5 - r); diff -= l + 5 - r; } } else if l > r { if r + 2 >= l { right += weight * (l - r); diff -= l - r; } else { assert!(r + 5 - l <= 2); left += weight * (r + 5 - l); diff += r + 5 - l; } } weight *= 5; } if diff == 0 { print(i); } } } fn run() { input! { n: i64, } let mut d = vec![]; let mut p = n; while p > 0 { d.push(p % 5); p /= 5; } d.push(0); // 差分、carry, small = way type Map = std::collections::BTreeMap<(i64, bool, bool), i64>; let mut dp = Map::new(); dp.insert((0, false, true), 1); for &d in d.iter() { let mut next = Map::new(); for ((diff, carry, small), cnt) in dp { for i in 0..5i64 { let v = i + carry as i64; let diff = if v < 3 { diff + v } else { diff - (5 - v) }; let carry = v >= 3; let small = i < d || (i == d && small); *next.entry((diff, carry, small)).or_insert(0) += cnt; } } dp = next; } let mut ans = -1; for ((diff, carry, small), cnt) in dp { if diff == 0 && !carry && small { ans += cnt; } } println!("{}", ans); } fn main() { // test(); run(); }