{-# LANGUAGE ImplicitParams #-} {- http://groups.google.com/group/google-code/browse_thread/thread/287e8f183fe5c100# Naive solution is O(K*K). Idea 1: Use Fenwick tree (aka Binary indexed tree) to count free slots of a range in logK time. It can sum and get number in range in O(log K) time. We compute the whole deck in O(KlogK). -} main = do content <- getContents let hd:tl = lines content let ?totalcases = read hd process 1 $ map (map read) (map words tl) process :: (?totalcases :: Int) -> Int -> [[Int]] -> IO () process count content = do if count > ?totalcases then return () else case content of ([k]:(_:ds):tl) -> do putStr ("Case #" ++ show count ++ ": ") let ans = map (work k 1) ds f x = putStr (show x ++ " ") mapM_ f ans putChar '\n' process (count+1) tl {- Idea 2: Because we are only asked about n cards, and n<=100, we can compute those n cards individually without worrying about other cards. For each given index, we find the card in a way similar to the efficient solution to the Josephus problem using recurrence relation. Each index is solved in O(K). The total time is O(nK). The INVARIANT we're maintaining: we always start from the first card, and we always have K empty slots. To do so, we adjust the index we're looking for. Give an index d, we start dealing cards from 1 to K. Suppose we're dealing card j which goes to index t. If t==d we're done. Otherwise, we reset the counter and the old index t becomes the new index 0. Adjust the index d accordingly. -} work k j d = let t = (j - 1) `mod` k + 1 k' = k - 1 d' = d - t d'' = k - (t - d) in if t == d then j else if t < d then work k' (j+1) d' else work k' (j+1) d''