Last active
August 29, 2015 14:13
-
-
Save abbradar/abfd335eeeee7d26059f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Control.Applicative | |
import Data.List | |
data Tree a = Null | Node a (Tree a) (Tree a) | |
buildTree :: [(Int, (Int, Int))] -> Int -> Tree Int | |
buildTree _ (-1) = Null | |
buildTree items n = Node n (buildTree items l) (buildTree items r) | |
where Just (l, r) = n `lookup` items | |
traverse :: Tree a -> [a] | |
traverse Null = [] | |
traverse (Node i l r) = traverse l ++ [i] ++ traverse r | |
depth :: Tree a -> Int | |
depth Null = 0 | |
depth (Node _ l r) = 1 + max (depth l) (depth r) | |
swap :: Int -> Tree a -> Tree a | |
swap _ Null = Null | |
swap 1 (Node i l r) = Node i r l | |
swap n (Node i l r) = Node i (swap n' l) (swap n' r) | |
where n' = n - 1 | |
main :: IO () | |
main = do | |
n <- readLn | |
items <- mapM (\x -> (\[a, b] -> (x, (read a, read b))) <$> words <$> getLine) [1..n] | |
t <- readLn | |
ks <- mapM (const readLn) [1..t] | |
let tree = buildTree items 1 | |
d = depth tree | |
rs = tail $ scanl (\tree' k -> foldr swap tree' [k,2*k..d]) tree ks | |
mapM_ (putStrLn . intercalate " " . map show . traverse) rs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment