Skip to content

Instantly share code, notes, and snippets.

@aaronallen8455
Created June 26, 2021 01:21
Show Gist options
  • Save aaronallen8455/5f73e76428bf8ed8566457d032ccf90f to your computer and use it in GitHub Desktop.
Save aaronallen8455/5f73e76428bf8ed8566457d032ccf90f to your computer and use it in GitHub Desktop.
{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Data.List
import qualified Data.Map.Strict as M
main :: IO ()
main = do
cases <- readLn
replicateM_ cases $ do
getLine
queue <- getLine
let (_, res, _) = foldl' timeSaved (mempty, 0, 0) queue
print res
timeSaved :: (M.Map Char (Pair Int), Int, Int)
-> Char
-> (M.Map Char (Pair Int), Int, Int)
timeSaved (!m, !acc, !i) c =
case m M.!? c of
Nothing ->
( M.insert c (Pair i 1) m
, acc
, i + 1
)
Just (Pair prevI n) ->
( M.insert c (Pair i (n + 1)) m
, acc + (i - prevI - 1) * n * 5
, i + 1
)
data Pair a = Pair !a !a deriving Show
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment