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 Haskell (GHC 7.10.3) (judge verdict: Accepted)


import qualified Data.Vector.Unboxed as V
--import Data.Array.IArray (listArray, accumArray, (!))
import Data.Array (Array, listArray, (!))
import Data.Array.MArray
import Data.Array.ST (STUArray, runSTUArray)
import Data.Array.Unboxed (UArray)
import Data.List (sortOn, sortBy, unfoldr, partition)
import Data.Char (isSpace)
import Control.Monad.ST (ST)
import Control.Monad.Trans.State (StateT(..))
import qualified Control.Monad.Cont as C
import qualified Data.ByteString.Char8 as B

import Debug.Trace (trace)

-- utility functions

--tr x = trace (show x) x
tr = id

--   Input functions
readInt = B.readInt . B.dropWhile isSpace

readInts :: Int -> B.ByteString -> [Int]
readInts n = take n . unfoldr readInt

readIntsV :: Int -> B.ByteString -> V.Vector Int
readIntsV n = V.unfoldrN n readInt

--readIntsA :: Int -> B.ByteString -> UArray Int Int
--readIntsA n bs = runSTUArray $ do
--  arr <- newArray_ (0,n-1)
--  go arr 0 bs
--  return arr
--  where
--    go :: STUArray s Int Int -> Int -> B.ByteString -> ST s ()
--    go arr i bs
--      | i==n = return ()
--      | otherwise = do
--        let Just (x,bs') = readInt bs
--        writeArray arr i x
--        go arr (i+1) bs'

readTsV :: Int -> B.ByteString -> V.Vector (Int,Int)
readTsV n = V.unfoldrN n $ runStateT ((,) <$> StateT readInt <*> StateT readInt)

readTs :: Int -> B.ByteString -> [(Int,Int)]
readTs n = take n . unfoldr readT where
  readT = runStateT ((,) <$> StateT readInt <*> StateT readInt)

dp :: (Array Int Int -> Int -> Int) -> Int -> Int
dp f n = result ! n where
  result = listArray (0,n) $ map nth [0..]
  nth i = f result (tr i)

-- main

amount = [1,6,36,216,1296,7776,46656,9,81,729,6561,59049]

solv n = dp f n where
  f t 0 = 0
  f t i = 1 + minimum [t!j| a<-amount, let j=i-a, j>=0]

main = do
  n <- read <$> getLine
  print $ solv n