Ingdas
Ingdas

Reputation: 1486

TimeOut on CodeChef

I'm new to CodeChef and thought of trying a few problems, so I solved the "Bytelandian gold coins" problem. (http://www.codechef.com/problems/COINS/) I'm getting instant results on my computer, CodeChef sets a 9 second time limit, but i'm still getting TimeOuts from CodeChef. I don't have any clue anymore what causes this. Any hints would be helpfull.

My code:

module Main where

import qualified Data.Map as M
import Data.Map (Map)
import Data.Maybe

main = do
    catch (main' M.empty 1) (const $ return ()) 

main' _ 11 = return ()
main' m c = do
    x <- readLn
    let (k,m2) = sol m x
    print k
    main' m2 (c+1)


sol :: Map Integer Integer -> Integer -> (Integer, Map Integer Integer)
sol m x     |M.member x m = (fromJust $ M.lookup x m,m)
            |x > x2+x3+x4 = (x,M.insert x x m)
            |otherwise = (fullSoll, M.insert x fullSoll m4)
    where
        x2 = div x 2
        x3 = div x 3
        x4 = div x 4
        (sx2, m2) = sol m x2
        (sx3, m3) = sol m2 x3
        (sx4, m4) = sol m3 x4
        fullSoll = sx2+sx3+sx4

Upvotes: 4

Views: 507

Answers (1)

ScottWest
ScottWest

Reputation: 1936

Your sol doesn't terminate when the x == 0. When x is 1 it is fine because all of x2, x3, x4 are 0, and their sum is less than x, meaning the second guard is true, and no recursion. However, when the input is 0, then the recursive case kicks in, and it never terminates.

Upvotes: 5

Related Questions