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)

use std::str::FromStr;

fn get_one<T : FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    return s.trim().parse().ok().unwrap();
}

fn get_vec<T : FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    return s.trim().split_whitespace().map(|e| e.parse().ok().unwrap()).collect();
}

fn main() {
    let n : usize = get_one();
    let mut coins = Vec::new();
    coins.push(1);
    let mut i = 1;
    while 6_usize.pow(i) < 100000 {
        coins.push(6_usize.pow(i));
        i+=1;
    }
    i = 1;
    while 9_usize.pow(i) < 100000 {
        coins.push(9_usize.pow(i));
        i+=1;
    }
    coins.sort();
    let mut dp = vec!(vec!(0;n+1 as usize);coins.len() as usize);

    for j in 0..(n+1) {
        dp[0][j] = j;
    }
    for k in 1..coins.len() {
        for j in 1..(n+1) {
            //println!("{} {}", k, j);
            if j >= coins[k] {
                dp[k][j] = std::cmp::min(dp[k-1][j], dp[k][j-coins[k]] + 1);
            }
            else {
                dp[k as usize][j] = dp[(k-1)][j];
            }
        }
    }
    //for row in &dp {
    //    println!("{:?}", row);
    //}
    println!("{}", dp[(coins.len()-1) as usize][n as usize]);
}