import Control.Applicative import Control.Monad import Data.Array import Data.Array.ST import Data.List import Data.Ord (comparing) solve n c arr = case sortBy (comparing snd) (solve' n c arr ! n) of [] -> -1 (x : _) -> snd x solve' n c arr = runSTArray $ do plans <- newListArray (1,n) $ [(c,0)] : repeat [] forM_ [1..n-1] $ \i -> do forM_ (arr ! i) $ \(t,y,m) -> do ps <- readArray plans i forM_ ps $ \(y0,m0) -> do when (y0-y >= 0) $ do r <- readArray plans t writeArray plans t ((y0-y,m0+m):r) return $ plans main = do n <- (read :: String -> Int) <$> getLine c <- (read :: String -> Int) <$> getLine _ <- getLine ss <- fmap (read :: String -> Int) . words <$> getLine ts <- fmap (read :: String -> Int) . words <$> getLine ys <- fmap (read :: String -> Int) . words <$> getLine ms <- fmap (read :: String -> Int) . words <$> getLine let arr = accumArray (flip (:)) [] (1,n) $ zip ss $ zip3 ts ys ms print $ solve n c arr