module Data.RangeMin.LCA (Index, lowestCommonAncestor, quickLCA) where
import Data.RangeMin.LCA.IndexM
import Data.RangeMin
import Data.RangeMin.Common.Vector
import qualified Data.RangeMin.Mixed as Mix
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as UV
import qualified Data.Vector as V
import qualified Data.Vector.Fusion.Stream as S
import Data.Vector.Fusion.Stream.Size
import Data.Tree
dfOrder :: Tree a -> (Tree (Index, a), Int)
dfOrder tree = execIndexM $ indexer tree where
indexer (Node a ts) = do
i <- getIndex
ts' <- mapM indexer ts
return (Node (i, a) ts')
type Depth = Int
data Trav a = Trav !Depth !Index a
travel :: (a -> Index) -> Tree a -> [Trav a] -> [Trav a]
travel f = trav' 0 where
trav' !d (Node x ts) zs = let me = Trav d (f x) x in
me:foldr (\ t -> trav' (d+1) t . (me:)) zs ts
quickLCA :: Tree a -> (Int, Tree (Index, a), Index -> Index -> (Index, a))
quickLCA tree = case dfOrder tree of
(iTree, n) -> (n, iTree, lowestCommonAncestor n fst iTree)
lowestCommonAncestor :: Int -> (a -> Index) -> Tree a -> Index -> Index -> a
lowestCommonAncestor !n ix tree = vals `seq` lca
where traversal = G.unstream $ S.map (\ (Trav d i a) -> ((d, i), a)) $ S.fromList (travel ix tree []) `S.sized` Max (2 * n 1)
ixs :: UV.Vector Int
!ixs = vec n $ S.map (\ (a, b) -> (b, a)) $ S.indexed $ S.map (snd . fst) $ G.stream traversal
!(dixs, !vals) = (Mix.unzip :: Mix.MixVector UV.Vector V.Vector (a, b) -> (UV.Vector a, V.Vector b))
traversal
(!depths, _) = UV.unzip dixs
rM :: Int -> Int -> Int
!rM = vecRangeMin depths
lca !i !j = let
iIx = ixs ! i
jIx = ixs ! j
in vals ! case compare iIx jIx of
EQ -> iIx
LT -> rM iIx (jIx iIx + 1)
GT -> rM jIx (iIx jIx + 1)