Problem:
Score : 300 points

Problem Statement

To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation:

1 yen (the currency of Japan)

6 yen, 6^2(=36) yen, 6^3(=216) yen, ...

9 yen, 9^2(=81) yen, 9^3(=729) yen, ...

At least how many operations are required to withdraw exactly N yen in total?

It is not allowed to re-deposit the money you withdrew.

Constraints

1 \leq N \leq 100000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

If at least x operations are required to withdraw exactly N yen in total, print x.

Sample Input 1

127

Sample Output 1

4

By withdrawing 1 yen, 9 yen, 36(=6^2) yen and 81(=9^2) yen, we can withdraw 127 yen in four operations.

Sample Input 2

3

Sample Output 2

3

By withdrawing 1 yen three times, we can withdraw 3 yen in three operations.

Sample Input 3

44852

Sample Output 3

16

Solution in Rust (1.15.1) (judge verdict: Accepted)

fn solve<R: BufRead, W: Write>(_reader: R, _writer: &mut W) {
  let mut _scanner = Scanner::new(_reader);

  #[allow(unused_macros)]
  macro_rules! scan {
    ($t:ty) => {
      _scanner.next::<$t>().unwrap()
    };
    ($($t:ty),+) => {
      ($(scan!($t)),+)
    };
    ($t:ty; $n:expr) => {
      scan_iter!($t; $n).collect::<Vec<_>>()
    };
    ($t_0:ty, $t_1:ty; $n:expr) => {
      scan!($t_0 = 0, $t_1 = 1; $n)
    };
    ($t_0:ty, $t_1:ty, $t_2:ty; $n:expr) => {
      scan!($t_0 = 0, $t_1 = 1, $t_2 = 2; $n)
    };
    ($($t:ty = $i:tt),+; $n:expr) => {{
      let mut vecs = ($(Vec::<$t>::with_capacity($n)),+);
      for _ in 0..$n {$(
        vecs.$i.push(scan!($t));
      )+}
      vecs
    }};
  }

  #[allow(unused_macros)]
  macro_rules! scan_iter {
    ($t:ty; $n:expr) => {
      _scanner.take::<$t>($n).map(|x| x.unwrap())
    };
  }

  #[allow(unused_macros)]
  macro_rules! print {
    ($fmt:expr) => {
      write!(_writer, $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      write!(_writer, $fmt, $($arg)*).unwrap()
    };
  }

  #[allow(unused_macros)]
  macro_rules! println {
    () => {
      writeln!(_writer).unwrap()
    };
    ($fmt:expr) => {
      writeln!(_writer, $fmt).unwrap()
    };
    ($fmt:expr, $($arg:tt)*) => {
      writeln!(_writer, $fmt, $($arg)*).unwrap()
    };
  }

  use search::BinarySearch;

  const MAX_N: i64 = 100000;

  fn search(memo: &mut Vec<Option<i64>>, table: &Vec<i64>, cnt: i64, rest: i64) -> i64 {
    if let Some(memo) = memo[rest as usize] {
      return cnt + memo;
    }
    let ans = if rest < 6 {
      cnt + rest
    } else {
      let i = table[..].lower_bound(&rest).map(|i| if table[i] == rest { i } else { i - 1 }).unwrap_or(table.len() - 1);
      (0..i + 1).map(|i| search(memo, table, cnt + 1, rest - table[i])).min().unwrap()
    };
    memo[rest as usize] = Some(ans - cnt);
    ans
  };

  let n = scan!(i64);

  let ans = {
    let table = {
      fn create_table(x: i64, vec: &mut Vec<i64>) {
        let mut crt = x;
        while crt <= MAX_N {
          vec.push(crt);
          crt *= x;
        }
      }
      let mut table = vec![1];
      create_table(6, &mut table);
      create_table(9, &mut table);
      table.sort();
      table
    };
    let mut memo = vec![None; MAX_N as usize + 1];
    search(&mut memo, &table, 0, n)
  };

  println!("{}", ans);
}

fn main() {
  ::std::thread::Builder::new()
    .stack_size(100_000_000)
    .spawn(|| {
      let stdin = stdin();
      let stdout = stdout();
      #[cfg(debug_assertions)]
      let mut writer = stdout.lock();
      #[cfg(not(debug_assertions))]
      let mut writer = ::std::io::BufWriter::new(stdout.lock());
      solve(stdin.lock(), &mut writer);
      writer.flush().unwrap();
    })
    .unwrap()
    .join()
    .unwrap();
}

use io::Scanner;
use std::io::{stdin, stdout, BufRead, Write};

pub mod io {
  pub use self::scanner::*;

  mod scanner {
    use std::io::BufRead;
    use std::marker::PhantomData;
    use std::str::{from_utf8, FromStr};

    pub struct Scanner<R> {
      reader: R,
      buffer: Vec<u8>,
      position: usize,
    }

    impl<R: BufRead> Scanner<R> {
      pub fn new(reader: R) -> Self {
        Scanner { reader: reader, buffer: vec![], position: 0 }
      }

      pub fn next<T: Parse>(&mut self) -> Option<T> {
        Parse::parse(self.next_bytes().unwrap_or(&[]))
      }

      pub fn take<T: Parse>(&mut self, n: usize) -> Take<R, T> {
        Take { scanner: self, n: n, _marker: PhantomData }
      }

      pub fn next_bytes(&mut self) -> Option<&[u8]> {
        if self.buffer.is_empty() {
          self.read_line();
        }
        loop {
          match self.buffer.get(self.position) {
            Some(&b' ') => self.position += 1,
            Some(&b'\n') => self.read_line(),
            Some(_) => break,
            None => return None,
          }
        }
        let start = self.position;
        loop {
          match self.buffer.get(self.position) {
            Some(&b' ') | Some(&b'\n') | None => break,
            Some(_) => self.position += 1,
          }
        }
        Some(&self.buffer[start..self.position])
      }

      fn read_line(&mut self) {
        self.position = 0;
        self.buffer.clear();
        self.reader.read_until(b'\n', &mut self.buffer).unwrap();
      }
    }

    pub struct Take<'a, R: 'a, T> {
      scanner: &'a mut Scanner<R>,
      n: usize,
      _marker: PhantomData<fn() -> T>,
    }

    impl<'a, R: BufRead, T: Parse> Iterator for Take<'a, R, T> {
      type Item = Option<T>;

      fn next(&mut self) -> Option<Self::Item> {
        if self.n > 0 {
          self.n -= 1;
          Some(self.scanner.next())
        } else {
          None
        }
      }

      fn size_hint(&self) -> (usize, Option<usize>) {
        (self.n, Some(self.n))
      }
    }

    impl<'a, R: BufRead, T: Parse> ExactSizeIterator for Take<'a, R, T> {}

    pub trait Parse: Sized {
      fn parse(bytes: &[u8]) -> Option<Self>;
    }

    impl Parse for u8 {
      fn parse(bytes: &[u8]) -> Option<Self> {
        if bytes.len() == 1 {
          Some(*unsafe { bytes.get_unchecked(0) })
        } else {
          None
        }
      }
    }

    macro_rules! parse_impl {
      ($($t:ident)+) => {$(
        impl Parse for $t {
          fn parse(bytes: &[u8]) -> Option<Self> {
            from_utf8(bytes).ok().and_then(|s| $t::from_str(s).ok())
          }
        }
      )+};
    }

    parse_impl! { i32 i64 isize u32 u64 usize String }
  }
}

pub mod search {
  pub use self::binary_search::*;

  mod binary_search {
    use std::ops::Range;

    pub trait BinarySearch<T> {
      type Output;

      fn binary_search<F: FnMut(&T) -> bool>(&self, f: F) -> Option<Self::Output>;

      fn lower_bound(&self, x: &T) -> Option<Self::Output>
      where
        T: Ord,
      {
        self.binary_search(|t| t >= x)
      }

      fn upper_bound(&self, x: &T) -> Option<Self::Output>
      where
        T: Ord,
      {
        self.binary_search(|t| t > x)
      }
    }

    macro_rules! binary_search_impl {
      ($ok:expr, $ng:expr, $cond1:expr, $cond2:expr) => {{
        let mut ok_end = $ok;
        let mut ng_start = $ng;
        while ok_end - ng_start > 1 {
          let mid = ng_start + (ok_end - ng_start) / 2;
          if $cond1(mid) {
            ok_end = mid;
          } else {
            ng_start = mid;
          }
        }
        if $cond2(ok_end) {
          None
        } else {
          Some(ok_end as Self::Output)
        }
      }};
    }

    impl<T> BinarySearch<T> for [T] {
      type Output = usize;

      fn binary_search<F: FnMut(&T) -> bool>(&self, mut f: F) -> Option<Self::Output> {
        binary_search_impl!(self.len() as isize, -1isize, |mid| f(&self[mid as usize]), |ok_end| ok_end as usize == self.len())
      }
    }

    macro_rules! binary_search_impl_range {
      ($t:ty, $it:ty) => {
        impl BinarySearch<$t> for Range<$t> {
          type Output = $t;

          fn binary_search<F: FnMut(&$t) -> bool>(&self, mut f: F) -> Option<$t> {
            assert!(self.start <= self.end);
            binary_search_impl!(self.end as $it, self.start as $it - 1, |mid| f(&(mid as $t)), |ok_end| ok_end == self.end as $it)
          }
        }
      };
      ($($ut:ty, $it:ty);+) => {$(
        binary_search_impl_range! { $ut, $it }
        binary_search_impl_range! { $it, $it }
      )+};
    }

    binary_search_impl_range! { usize, isize; u32, i32; u64, i64 }
  }
}