33 lines
844 B
Haskell
Executable File
33 lines
844 B
Haskell
Executable File
#! /usr/bin/env stack
|
|
-- stack --resolver lts-12.20 --install-ghc script
|
|
module Main where
|
|
|
|
import qualified Control.Monad.State as St
|
|
import qualified Data.List as L
|
|
|
|
data Node = Node [Node] [Int] deriving (Show)
|
|
|
|
main :: IO ()
|
|
main = interact $ show . treeValue . parseTree
|
|
|
|
treeValue :: Node -> Int
|
|
treeValue (Node cs ms)
|
|
| null cs = sum ms
|
|
| otherwise = sum [ vs !! (m - 1) | m <- ms, 1 <= m, m <= ncs ]
|
|
where
|
|
vs = map treeValue cs
|
|
ncs = length cs
|
|
|
|
parseTree :: String -> Node
|
|
parseTree = St.evalState parseNode
|
|
|
|
parseNode :: St.State String Node
|
|
parseNode = do
|
|
nChildren <- parseInt
|
|
nMetadata <- parseInt
|
|
Node <$> St.replicateM nChildren parseNode
|
|
<*> St.replicateM nMetadata parseInt
|
|
|
|
parseInt :: St.State String Int
|
|
parseInt = read <$> St.state (L.break (== ' ') . L.dropWhile (== ' '))
|