import Control.Monad import Control.Applicative main = do [_, numWords, numCases] <- fmap ((map read) . words) $ getLine :: IO [Int] (known, rest) <- fmap ((splitAt numWords) . lines) $ getContents forM_ [1..numCases] (\caseNum -> do let possibleWords word = filter (`elem` known) (permuteWord word) allPossibles = map possibleWords rest putStrLn $ "Case #" ++ show caseNum ++ ": " ++ show (length $ allPossibles !! (caseNum - 1)) ) -- I COULD HAVE JUST REPLACED THE PARENTHESES WITH BRACKETS -- AND TREATED THEM AS REGULAR EXPRESSIONS permuteWord :: String -> [String] permuteWord [] = [] permuteWord word | '(' `notElem` word = [word] | otherwise = let (first, _:rest) = break (== '(') word (group, _:rest') = break (== ')') rest in [((first ++ [a]) ++) | a <- group] <+> (permuteWord rest') -- This was just a quick fix to make [f] <*> [] return [f []] instead of [] -- (e.g. [("hi"++), ("there"++)] <+> [] == ["hi", "there"]) (<+>) :: [[a] -> b] -> [[a]] -> [b] [] <+> _ = [] (f:fs) <+> [] = (f []) : fs <+> [] fs <+> x = fs <*> x