module Data.RangeMin.Int.Quadratic (rangeMin) where
import qualified Data.RangeMin.Fusion as F
import Data.RangeMin.Common
rangeMin :: PVector Value -> RM
rangeMin !xs = let
!table = quadTable xs
!m = 2 * n + 1
encode !i !d = (i * (m i)) `div'` 2 + d 1
in toRM $ \ i j -> table ! encode i j
where !n = vlength xs
data Q = Q !Int !Int !Int !Value
quadTable :: PVector Value -> PVector Index
quadTable !xs = F.convert $ F.unfoldN ((n * (n + 1)) `div'` 2) suc (Q 0 0 0 (xs ! 0)) where
!n = vlength xs
suc (Q i j x vx)
| j < n = let vj = xs ! j in
if vx <= vj then Just (x, Q i (j+1) x vx) else Just (j, Q i (j+1) j vj)
| otherwise = let i' = i + 1 in
if i' < n then Just (i', Q i' (i' + 1) i' (xs ! i')) else Nothing