Lazily Tying the Knot for 1 Dimensional Dynamic Programming

前端 未结 4 909
春和景丽
春和景丽 2021-01-01 17:59

Several years ago I took an algorithms course where we were giving the following problem (or one like it):

There is a building of n floor

4条回答
  •  情深已故
    2021-01-01 18:49

    The problem is that min needs to fully evaluate both calls to f, so if one of them loops infinitly min will never return. So you have to create a new type, encoding that the number returned by f is Zero or a Successor of Zero.

    data Natural = Next Natural 
                 | Zero
    
    toNum :: Num n => Natural -> n
    toNum Zero     = 0
    toNum (Next n) = 1 + (toNum n)
    
    minimal :: Natural -> Natural -> Natural
    minimal Zero _            = Zero
    minimal _ Zero            = Zero
    minimal (Next a) (Next b) = Next $ minimal a b
    
    f i j | i == j = Zero
          | otherwise = Next $ minimal (f l j) (f r j)
          where l = i + 2
                r = i - 3
    

    This code actually works.

提交回复
热议问题