import Data.List
import Control.Monad

solve :: [(Int, Int, Int)] -> [(Int, Int, Int)] -> Int
solve xs ys = sum $ map best xs
  where best x = minimum $ filter (>= 0) $ map (calc x) ys
        calc (a1, b1, c1) (a2, b2, c2) =
          let p = (a1 + b1) * 2
              q = div (p + b2 - 1) b2
              t = a2 `div` c1
          in if t == 0 then -1
             else c2 * div (q + t - 1) t

main = do n <- fmap read getLine
          xs <- replicateM n readTriplet
          m <- fmap read getLine
          ys <- replicateM m readTriplet
          print $ solve xs ys
  where readTriplet = do [a, b, c] <- fmap (map read.words) getLine
                         return (a, b, c)

{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
import Data.Int

main :: IO ()
main = do
  n           <- readLn
  rooms       <- replicateM n readInts
  m           <- readLn
  papers      <- replicateM m readInts
  prices      <- forM rooms $ \[l, w, h] -> do
    candidates <- forM papers $ \[l', w', price] -> do
      if l' < h
        then return (1234567890 :: Integer)
        else do
          let !h'       = l' `quot` h
              !rolls    = ((l + w) * 2 - 1) `quot` (w' * h') + 1
          return $! rolls * price
    return $! minimum candidates
  print $ sum prices
 where
  readInts = map read . words <$> getLine

import Data.Maybe
import Control.Monad

type Room = (Int, Int, Int)
type Paper = (Int, Int, Int)

single :: Room -> Paper -> Maybe Int
single (ra, rb, rh) (h, a, cost) =
    let p = (ra + rb) * 2
        count  = (p + a - 1) `div` a
        count' = h `div` rh
        ans    = (count + count' - 1) `div` count'
    in if count' == 0 then Nothing
       else Just $ ans * cost

solve :: [Room] -> [Paper] -> Int
solve rooms papers = sum $ map solve' rooms
    where solve' room = minimum $ catMaybes $ map (single room) papers

main = do
    n <- read `fmap` getLine
    rooms <- replicateM n $ do
        [a, b, h] <- (map read . words) `fmap` getLine
        return (a, b, h)

    m <- read `fmap` getLine
    papers <- replicateM m $ do
        [h, a, cost] <- (map read . words) `fmap` getLine
        return (h, a, cost)

    let ans = solve rooms papers
    putStrLn $ show ans

import Control.Monad

parse :: String -> [Int]
parse stuff = map read (words stuff)

solve rooms papers = map (solve_one papers) rooms

solve_one papers [a, b, c] = minimum $ map give_price papers
    where give_price [l, w, p] =
              let perim = 2 * (a + b)
                  stripes = l `div` c
                  segments = perim `ceil` w
              in
                if stripes /= 0
                then (segments `ceil` stripes) * p
                else (maxBound :: Int)

ceil :: Int -> Int -> Int
ceil a b
    | a `rem` b > 0 = 1 + d
    | otherwise     = d
    where d = a `div` b

main = do
  n <- getLine
  rooms <- sequence [getLine | _ <- [1.. (read n)]]
  m <- getLine
  papers <- sequence [getLine | _ <- [1.. (read m)]]
  print $ sum $ solve (map parse rooms) (map parse papers)

solve ws wps = sum $ map (solve' wps) ws

solve' wps [h,l] = minimum $ map cost wps
   where
      cost [h',w',c']
         | h > h'    = inf
         | otherwise = l `divup` ((h' `div` h) * w') * c'
      inf = 99999999
      divup x y = div (x+y-1) y

main = do
   n <- fmap read getLine
   ws <- mapM (fmap $ map read . words) (replicate n getLine)
   m <- fmap read getLine
   wps <- mapM (fmap $ map read . words) (replicate m getLine)
   print $ solve (map (\[x,y,z] -> [z,(x+y)*2]) ws) wps

-- vim: set expandtab:

import Control.Applicative
import Control.Monad
import Data.Char
import Data.List
import System.IO
import System.IO.Error

hReadMany :: (Char -> Bool) -> Handle -> IO String
hReadMany p h = do b <- (p <$> hLookAhead h) `catch` const (return False)
                   if b
                     then (:) <$> hGetChar h <*> hReadMany p h
                     else return ""

hSkipSpaces  = hReadMany isSpace
hReadNumeric = hReadMany (\c -> isDigit c || c `elem` ['.', '-', '+'])

readNum :: (Num a, Read a) => IO a
readNum = do hSkipSpaces stdin
             read <$> hReadNumeric stdin

readTerm :: IO String
readTerm = do hSkipSpaces stdin
              hReadMany (not . isSpace) stdin

ceilDiv a b = (a + b - 1) `div` b

main = do nrooms <- readNum
          rooms  <- replicateM nrooms readRoom

          npapers <- readNum
          papers  <- replicateM npapers readPaper

          let values = map (solve papers) rooms
          print (sum values)

  where
    readRoom = do width  <- readNum
                  length <- readNum
                  height <- readNum
                  return (width + width + length + length, height)

    readPaper = do length <- readNum
                   width  <- readNum
                   price  <- readNum
                   return (length, width, price)

solve papers (columns, height) = foldl1 min [ effectivePrice p | p <- papers ]
  where
    effectivePrice (length, width, price) | length < height = 100000000
                                          | otherwise       =
      price * (columns `ceilDiv` ((length `div` height) * width))

import Control.Monad
import Data.Maybe

data Room  = Room Int Int Int
  deriving (Eq,Show)

data Paper = Paper Int Int Int
  deriving (Eq,Show)

divceil a b = (a + b -1) `div` b

-- return the number of rolls needed
rolls roomh roomw rooml paperh paperw | paperh < roomh = Nothing
rolls roomh roomw rooml paperh paperw = Just r
  where
    w = 2*(roomw+rooml)
    r = divceil w ((paperh `div` roomh) * paperw)

cost :: Room -> Paper -> Maybe Int
cost (Room h l w) (Paper ph pw pc) = fmap (pc*) $ rolls h l w ph pw

minCost :: [Paper] -> Room -> Int
minCost ps r = minimum $ catMaybes $ map (cost r) ps

main = do
  n <- fmap read getLine
  rooms <- replicateM n $ do [l,w,h] <- fmap (map read . words) getLine
                             return $ Room h l w
  m <- fmap read getLine
  papers <- replicateM m $ do [h,w,c] <- fmap (map read . words) getLine
                              return $ Paper h w c

  let answer = sum $ map (minCost papers) rooms
  print answer

import Maybe (mapMaybe)

type Room  =  (Int, Int, Int)
type Roll  =  (Int, Int, Int)

parseRoom :: String -> Room
parseRoom line  =  case words line of
    [x, y, z]  ->  (read x, read y, read z)

parseRoll :: String -> Roll
parseRoll  =  parseRoom

solve :: [Room] -> [Roll] -> Int
solve rooms rolls  =  sum $ map solve' rooms
  where
    solve' room  =  minimum $ mapMaybe (solve'' room) rolls
    solve'' (l, w, h) (l', w', c)
      | l' >= h  =  Just $ c * (1 + div (2 * (l+w) - 1) (w' * div l' h))
      | otherwise  =  Nothing

main :: IO ()
main  =  do
    lines'    <-  fmap lines getContents
    let n      =  read . head $ lines'
    let rooms  =  map parseRoom . take n . tail $ lines'
    let m      =  read . head . drop n . tail $ lines'
    let rolls  =  map parseRoll . take m . tail . drop n . tail $ lines'
    print $ solve rooms rolls

import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Control.Monad

solve :: [(Int, Int, Int)] -> [(Int, Int, Int)] -> Int
solve xs ys = sum $ map best xs
  where best x = minimum $ filter (>= 0) $ map (calc x) ys
        calc (a1, b1, c1) (a2, b2, c2) =
          let p = (a1 + b1) * 2
              q = div (p + b2 - 1) b2
              t = a2 `div` c1
          in if t == 0 then -1
             else c2 * div (q + t - 1) t

main = do n <- fmap readInt BS.getLine
          xs <- replicateM n readTriplet
          m <- fmap readInt BS.getLine
          ys <- replicateM m readTriplet
          print $ solve xs ys
  where readTriplet = do [a, b, c] <- fmap (map readInt . BS.words) BS.getLine
                         return (a, b, c)
        readInt x = let Just (int, _) = BS.readInt x
                    in int

import Control.Applicative

main = do n <- read <$> getLine
          rss <- mapM (\i -> map read <$> words <$> getLine) [1..n]
          m <- read <$> getLine
          wss <- mapM (\i -> map read <$> words <$> getLine) [1..m]
          print $ solve n rss m wss

solve :: Int -> [[Int]] -> Int -> [[Int]] -> Int
solve _ rss _ wss =  sum $ map (solve' wss) rss
solve' :: [[Int]] -> [Int] -> Int
solve' wss lwh@(l:w:h:_) = minimum $ map (price lwh) $ filter ((h<=).head) wss

price :: [Int] -> [Int] -> Int
price (l:w:h:_) (l':w':p:_) = ((((2*(l+w))`div'`w')*h)`div'`(l'-(mod l' h)))*p

div' x y = if q == 0 then p else succ p
   where (p,q) = divMod x y

import Control.Applicative

main = do n <- read <$> getLine
          rss <- mapM (\i -> map read <$> words <$> getLine) [1..n]
          m <- read <$> getLine
          wss <- mapM (\i -> map read <$> words <$> getLine) [1..m]
          print $ solve n rss m wss

solve :: Int -> [[Int]] -> Int -> [[Int]] -> Int
solve n rss m wss =  sum $ map (solve' wss) rss
solve' :: [[Int]] -> [Int] -> Int
solve' wss (l:w:h:_) = minimum $ map (price [l,w,h]) $ wss
price :: [Int] -> [Int] -> Int
price (l:w:h:_) (l':w':p:_) = (((2*(l+w)`div'`w')*h)`div'`(f l' h))*p

f l' h
  | l' >= h = l'-(mod l' h)
  | otherwise = l'

div' x y = if q == 0 then p else succ p
   where (p,q) = divMod x y

{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad

main :: IO ()
main = do
  n           <- readLn
  prices      <- replicateM n $ do
    [l, w, h]   <- readInts
    m           <- readLn
    candidates  <- replicateM m $ do
      [l', w', price] <- readInts
      let !h'       = head $ dropWhile (< h) [l', l' * 2 ..]
          !rolls    = (((l + w) * 2 - 1) `quot` (w' * (h' `quot` h)) + 1) * (h' `quot` l')
      return $! rolls * price
    return $! minimum candidates
  print $ sum prices
 where
  readInts = map read . words <$> getLine

{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad

main :: IO ()
main = do
  n           <- readLn
  [l, w, h]   <- readInts
  m           <- readLn
  candidates  <- replicateM m $ do
    [l', w', price] <- readInts
    let !h'       = head $ dropWhile (< h) [l', l' * 2 ..]
        !rolls    = (((l + w) * 2 - 1) `quot` (w' * (h' `quot` h)) + 1) * (h' `quot` l')
    return $! rolls * price
  print $ minimum candidates * n
 where
  readInts = map read . words <$> getLine

{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad

main :: IO ()
main = do
  n           <- readLn
  [l, w, h]   <- readInts
  m           <- readLn
  prices      <- replicateM n $ do
    candidates  <- replicateM m $ do
      [l', w', price] <- readInts
      let !h'       = head $ dropWhile (< h) [l', l' * 2 ..]
          !rolls    = (((l + w) * 2 - 1) `quot` (w' * (h' `quot` h)) + 1) * (h' `quot` l')
      return $! rolls * price
    return $! minimum candidates
  print $ sum prices
 where
  readInts = map read . words <$> getLine

import Control.Monad

parse :: String -> [Int]
parse stuff = map read (words stuff)

solve rooms papers = map (solve_one papers) rooms

solve_one papers [a, b, c] = minimum $ map give_price papers
    where give_price [l, w, p] =
              let perim = 2 * (a + b)
                  stripes = l `div` c
                  segments = perim `ceil` w
              in
                if stripes /= 0
                then (segments `ceil` stripes) * p
                else 123456789
-- else (maxBound :: Int)

-- ceil :: Int -> Int -> Int
ceil a b
    | a `rem` b > 0 = 1 + d
    | otherwise     = d
    where d = a `div` b

main = do
  n <- getLine
  rooms <- sequence [getLine | _ <- [1.. (read n)]]
  m <- getLine
  papers <- sequence [getLine | _ <- [1.. (read m)]]
  mapM_ print (solve (map parse rooms) (map parse papers))

import Control.Monad

parse :: String -> [Int]
parse stuff = map read (words stuff)

solve rooms papers = map (solve_one papers) rooms

solve_one papers [a, b, c] = minimum $ map give_price papers
    where give_price [l, w, p] =
              let perim = 2 * (a + b)
                  stripes = l `div` c
                  segments = perim `ceil` w
              in
                if stripes /= 0
                then (segments `ceil` stripes) * p
                else (maxBound :: Int)

-- ceil :: Int -> Int -> Int
ceil a b
    | a `rem` b > 0 = 1 + d
    | otherwise     = d
    where d = a `div` b

main = do
  n <- getLine
  rooms <- sequence [getLine | _ <- [1.. (read n)]]
  m <- getLine
  papers <- sequence [getLine | _ <- [1.. (read m)]]
  mapM_ print (solve (map parse rooms) (map parse papers))

import Control.Monad

parse :: String -> [Int]
parse stuff = map read (words stuff)

solve rooms papers = map (solve_one papers) rooms

solve_one papers [a, b, c] = {-minimum $ -} map give_price papers
    where give_price [l, w, p] =
              let perim = 2 * (a + b)
                  stripes = l `div` c
                  segments = perim `ceil` w
              in
                (segments `ceil` stripes) * p

-- ceil :: Int -> Int -> Int
ceil a b
    | a `rem` b > 0 = 1 + d
    | otherwise     = d
    where d = a `div` b

main = do
  n <- getLine
  rooms <- sequence [getLine | _ <- [1.. (read n)]]
  m <- getLine
  papers <- sequence [getLine | _ <- [1.. (read m)]]
  print $ solve (map parse rooms) (map parse papers)

import Control.Monad

parse :: String -> [Int]
parse stuff = map read (words stuff)

solve rooms papers = map (solve_one papers) rooms

solve_one papers [a, b, c] = minimum $ map give_price papers
    where give_price [l, w, p] =
              let perim = 2 * (a + b)
                  stripes = l `div` c
                  segments = perim `ceil` w
              in
                (segments `ceil` stripes) * p

-- ceil :: Int -> Int -> Int
ceil a b
    | b == 0        = 12345678987654321
    | a `rem` b > 0 = 1 + d
    | otherwise     = d
    where d = a `div` b

main = do
  n <- getLine
  rooms <- sequence [getLine | _ <- [1.. (read n)]]
  m <- getLine
  papers <- sequence [getLine | _ <- [1.. (read m)]]
  mapM_ print (solve (map parse rooms) (map parse papers))

solve ws wps = sum $ map (solve' wps) ws

solve' wps [h,l] = minimum $ map cost wps
   where
      cost [h',w',c']
         | h > h'    = inf
         | otherwise = l `div` ((h' `div` h) * w') * c'
      inf = 99999999

main = do
   n <- fmap read getLine
   ws <- mapM (fmap $ map read . words) (replicate n getLine)
   m <- fmap read getLine
   wps <- mapM (fmap $ map read . words) (replicate m getLine)
   print $ solve (map (\[x,y,z] -> [x,(y+z)*2]) ws) wps

-- vim: set expandtab:

import Control.Applicative

main = do n <- read <$> getLine
          rss <- mapM (\i -> map read <$> words <$> getLine) [1..n]
          m <- read <$> getLine
          wss <- mapM (\i -> map read <$> words <$> getLine) [1..m]
          print $ solve n rss m wss

solve :: Int -> [[Int]] -> Int -> [[Int]] -> Int
solve n rss m wss =  sum $ map (solve' wss) rss
solve' :: [[Int]] -> [Int] -> Int
solve' wss (l:w:h:_) = minimum $ map (price [l,w,h]) $ filter ((h<=).head) wss

price :: [Int] -> [Int] -> Int
price (l:w:h:_) (l':w':p:_) = (((2*(l+w)`div'`w')*h)`div'`(l'-(mod l' h)))*p

div' x y = if q == 0 then p else succ p
   where (p,q) = divMod x y


import Data.List
main = do
    getLine
    s <- getLine >>= return . map read . words :: IO [Int]
    let t x = sum . map (\k -> if k > x then 1 else 0)
    let l = map (\x -> 1 + t x s) s
    putStrLn $ unwords . intersperse " " $ map show l

import Data.Functor ((<$>))

main :: IO ()
main = putStrLn <$> unwords <$> map show =<< solve <$> (map read <$> tail <$> words <$> getContents)

solve :: [Integer] -> [Integer]
solve xs = [ 1 + sum [ 1 | y <- xs, y > x ] | x <- xs ]

import Data.Ord
import Data.List
import Data.Function
main = interact $ unwords . map show . solve . map read . tail . words
solve :: [Int] -> [Int]
solve = map snd . sort .
        concat . snd . mapAccumL f 1 .
        groupBy ((==) `on` snd) .
        sortBy (flip $ comparing snd) .
        zip [1..]
f n xs = (n + length xs, map (flip (,) n . fst) xs)

import Data.List
import Data.Function

f :: [Int] -> [Int]
f xs = map snd . sortBy (compare `on` fst) . g 1 $ xxs'
    where xxs' = groupBy ((==) `on` snd) . reverse . sortBy (compare `on` snd) . zip [1..] $ xs
          g _ [] = []
          g place (ys:yys) = map (\(num, rate) -> (num, place)) ys ++ g (place + length ys) yys

main = getLine >> fmap (map read . words) getLine >>= putStrLn . intercalate " " . map show . f

import Control.Applicative
import Data.List

mymax s =  snd $ head $ filter (\z-> fst z ==m) $ zip s [1..]
	where m = maximum s

myfunc r x = zip  (map snd x) (repeat r)

main=do
	n<-  read  <$> getLine:: IO Int
	s<-  map read.   words   <$> getLine ::IO [Int]
	let t=  groupBy (\a b-> fst a==fst b) $ reverse $ sort $ zip s [1..]
	let t1= scanl (+) 1 $ map length t
	putStrLn $ intercalate " " $ map show $ map snd $ sort $ concat $ zipWith myfunc t1 t

type Input  = [Int]
type Output = [Int]

parse :: String -> Input
parse contents = rs where [_, rs] = map (map read . words) . lines $ contents

solve :: Input -> Output
solve rs = map rank rs
           where rank r = 1 + length (filter (> r) rs)

pretty :: Output -> String
pretty = unwords . map show

main :: IO ()
main = putStrLn . pretty . solve . parse =<< getContents

import Data.List
import Data.Function
sortOn' fun = sortBy (compare `on` fun)
main = interact $ unwords.map (show.snd).sortOn' fst.f.zip [1..].map read.words.last.lines
hs = snd.head
f xs = g 1 (hs xs).reverse.sortOn' snd $ xs
g _ _ [] = []
g pos val xs = let (front,end) = span (\x->val==snd x) xs
                   n = length front
                   begin = zip (map fst front) (replicate n pos)
               in begin ++ (g (pos+n) (if end==[] then 0 else hs end) end)

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array.ST
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Control.Applicative
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Function as F
import Debug.Trace

import qualified Numeric as N

readInt :: String -> Int
readInt ('-':s) = case N.readDec s of [(n, "")] -> -n
readInt s = case N.readDec s of [(n, "")] -> n

readFloat :: String -> Double
readFloat ('-':s) = case N.readFloat s of [(x, "")] -> -x
readFloat s = case N.readFloat s of [(x, "")] -> x

getInts :: IO [Int]
getInts = map readInt . words <$> getLine

solve :: Int -> [[(Int, Int)]] -> [(Int, Int)]
solve _ [] = []
solve n (l:xs) = [(n, x) | x <- map snd l] ++ (solve (n + length l) xs)

main = do
  _ <- getLine
  s <- getInts
  let
    res = L.sortBy (compare `F.on` snd) . solve 0 . reverse . L.groupBy ((==) `F.on` fst) . L.sortBy (compare `F.on` fst) $ (zip s [1..])
  forM_ res $ \(r, i) -> putStr $ (show $ r + 1) ++ " "

main :: IO()
main = putStrLn . unwords . map show . solve . tail . map read . words =<< getContents

solve :: [Int] -> [Int]
solve a = map (\x -> 1 + length (filter (> x) a)) a

import Data.List
import Data.Maybe
import qualified Data.Map as Map

--------------------------------

createMapList :: [[Int]] -> [(Int, Int)]
createMapList xs = createMapList' xs 0
	where
		createMapList' [] _ = []
		createMapList' (x:xs) higher = (head x, higher) : createMapList' xs (higher + length x)

--------------------------------

main = do

	n <- fmap read $ getLine :: IO Int
	ratings <- fmap (map read . words) $ getLine :: IO [Int]

	let
		sorted_ratings =
			createMapList $
			group $
			sortBy (\a b -> compare b a) ratings

		rating_map = Map.fromList sorted_ratings

	putStrLn $
		intercalate " " $ map show $ mapPositions rating_map ratings

--------------------------------

mapPositions :: Map.Map Int Int -> [Int] -> [Int]
mapPositions _ [] = []
mapPositions map (x:xs)
	| higher == Nothing = 0 : mapPositions map xs
	| otherwise = (1 + fromJust higher) : mapPositions map xs
	where
		higher = Map.lookup x map

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

import Control.Applicative
import Control.Monad hiding ((<$!>))
import Control.Monad.ST.Safe
import Control.Monad.State hiding ((<$!>))
import Data.Array
-- import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
-- import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

-- getInts = fmap (map read . words) getLine
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  getLine
  as <- getInts

  let
    r = map snd $ sort $ concat $ map f $ groupBy ((==) `on` (fst . fst)) $ zip (reverse $ sort $ zip as [1..]) [1..]
      where
        f :: [((Int, Int), Int)] -> [(Int, Int)]
        f g = zip (map (snd . fst) g) (repeat m)
          where
            m = minimum $ map snd g

  putStrLn $ unwords $ map show r

import Data.Functor
import Data.List

getInts :: IO [Int]
getInts = map read <$> words <$> getContents

main = getInts >>= putStrLn . intercalate " " . map show . solve

solve :: [Int] -> [Int]
solve (n:xs) = map snd . sort $ zip is es
    where (ys, is) = unzip . reverse . sort $ zip xs [0..]
          (zs, es) = unzip . scanl1 min $ zip ys [1,2..]

main = do
  num <- getLine
  ratings <- getLine
  mapM_ pwSpace $ positions (read num) (readNums ratings)
  putChar '\n'

pwSpace n = do
  putStr $ (show n) ++ " "

readNums :: String -> [Int]
readNums s = map read $ words s

positions :: Int -> [Int] -> [Int]
positions n rs = map (getPos rs) [1..n]

getPos :: [Int] -> Int -> Int
getPos rs x = 1 + (length $ filter (\y -> y > (rs !! (x-1))) rs)

import Data.List
answer::[Int]->[Int]
answer a = [getNum n a | n <- (enumFromTo 0 ((length a) - 1))]
getNum::Int -> [Int] -> Int
getNum n a = 1 + (length (filter ((a !! n)<) a))
main = do
  w <- getLine
  w0 <- getLine
  let a = [read n::Int|n<-(words w0)]
  putStrLn $ intercalate " " (map show (answer a))

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Function
import Data.Ord
import Data.Bits
import Data.Monoid
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = getLine>>(solve.concat =<< forM [1.. 1] ( \i -> map (fst.fromJust.C.readInteger).C.words<$>C.getLine))
solve xs = let bs = zip [1..] xs; sbs = sortBy ( flip (compare `on` snd)) bs; gsbs=groupBy ((==) `on` snd)  sbs in putStr $ unwords $ map (\(a,b)->show b)  $  sortBy (compare `on` fst) $ concat $ slv1 gsbs
slv1 (xs:xss)= map fst $ scanl (\(bs,b) as->(map(\(c1,c2)->(c1,1+b)) as, b+length as) ) (map (\(a,b) ->(a,1)) xs,length xs) xss

module Main where

import Data.List
import Data.Maybe

main = do
    n <- (readLn :: IO Int)
    xs <- getLine >>= return .map (read :: String -> Int) . words
    let as = fst . foldr (\ (a,b)  (cs,c) -> ((a,c):cs, b+c)) ([],1) . map (\x -> (head x, length x)) . group . sort $ xs
        bs = map ( fromJust . (flip lookup) as ) xs
    putStrLn $ concat $ intersperse " " $ map show bs

import Control.Monad

main :: IO ()
main = getLine >> getLine >>= mapM_ (putStr . (++ " ") . show) . rank . map read . words >> putStrLn ""

rank :: [Int] -> [Int]
rank a = [1 + length (filter (> x) a) | x <- a]

main=getLine>>getLine>>=putStrLn.unwords.(map show).solve.(map read).words
solve::[Int]->[Int]
solve l = map (\x->1+(length$filter(x<) l)) l

main=getLine>>getLine>>=putStrLn.unwords.(map show).solve.(map read).words
solve::[Int]->[Int]
solve l = map (\x->length$filter(x<) l) l

import Data.List
main = do
    getLine
    s <- getLine >>= return . map read . words :: IO [Int]
    let t x = sum . map (\k -> if k > x then 1 else 0)
    let l = map (\x -> 1 + t x s) s
    putStrLn $ intersperse ' ' . unwords $ map show l


import Data.List

main = do
  nk <- getLine
  skillValues <- getLine
  putStrLn $ show $ solve (read $ last $ words nk) $ map read (words skillValues)

solve :: Int -> [Int] -> Int
solve k xss =
  let moduli = sort $ map ((10-) . (`mod` 10)) $ filter (/= 100) xss
      initialLevel = sum $ map (`quot` 10) xss
      filteredModuliSums = filter (<= k) $ scanl1 (+) moduli
      numFiltered = length filteredModuliSums
      numUsed = if numFiltered == 0 then
                  0
                else
                  last filteredModuliSums
      remainingSlots = (sum $ map (100-) xss) - numUsed
      remainingLevels = remainingSlots `quot` 10
      remainingSpend = k - numUsed
  in
   if numFiltered /= length moduli then
     numFiltered + initialLevel
   else
     initialLevel + numFiltered + min (remainingSpend `quot` 10) remainingLevels

import Debug.Trace

main :: IO()
main = print . solve . map read . words =<< getContents

solve :: [Int] -> Int
solve (n:k:a) = let b = getRem a (replicate 11 0)
                in  divide k b 0

addToList :: [Int] -> Int -> Int -> [Int]
addToList (a:s) 0 v = (a + v) : s
addToList (a:s) i v = a : (addToList s (i - 1) v)

getRem :: [Int] -> [Int] -> [Int]
getRem []    cnt = cnt
getRem (a:s) cnt = let next = (addToList (addToList cnt 0 (div a 10)) 10 (div (100 - (a + (rem (10 - (rem a 10)) 10))) 10))
                   in  if mod a 10 == 0 then getRem s next else getRem s (addToList next (10 - (rem a 10)) 1)

divide :: Int -> [Int] -> Int -> Int
divide k (b:bs) 0   = b + (divide k bs 1)
divide 0 (b:bs) _   = 0
divide k []     _   = 0
divide k (b:bs) idx | (div k idx) >= b = b + (divide (k - b * idx) bs (idx + 1))
                    | otherwise        = div k idx

import Data.List (sort)

main = do
	[n, k] <- (map read . words) `fmap` getLine
	as <- (map read . words) `fmap` getLine

	let
		r = sum $ map (`div` 10) as
		sums = takeWhile (<= k) $ scanl1 (+) $ sort $ filter (/= 10) $ map (\a -> 10 - a `mod` 10) as
		r' = if null sums then 0 else length sums
		r'' = if null sums then k else k - (last sums)

		t = r + r' + (r'' `div` 10)

		ans = if t >= 10 * n then 10 * n else t

	print ans

import Data.List

add3 (a,b,c) (x,y,z) = (a+x,b+y,c+z)

solve :: Int -> Int -> [Int] -> Int
solve n k levels =
  let
      -- the base level
      a0 = sum [ div a 10 | a <- levels ]  :: Int

      -- sort by 10 - remainder mod 10
      sorted = sort [ (10-r,  a) | a <- levels, let r = mod a 10 ]

      loop :: Int -> (Int,Int) -> [(Int,Int)] -> (Int, (Int,Int))
      loop k acc [] = (k, acc)
      loop k acc@(da, tens) ( (r,a) : rest )
        | k <= 0  = (0, acc)
        | r == 10 = let dtens = 10 - div a 10 in
                    loop k (da, tens+dtens) rest
        | r <= k  = let dtens = 9 - div a 10 in
                    loop (k-r) (da+1, tens+dtens) rest
        | otherwise = (k, acc)

      (k',(da, tens)) = loop k (0,0) sorted :: (Int,(Int,Int))

      answer = min (n*10) (a0 + da + min tens (div k' 10))
  in answer

main = do
  (n : k : levels) <- fmap (map read . words) getContents
  print $ solve n k levels

test1 = print $ solve 2 4 [7,9]

test2 = print $ solve 3 8 [17, 15, 19]

test3 = print $ solve 2 2 [99, 100]

test4 = print $ solve 231 100 $ replicate 231 100

test5 = print $ solve 100 10000 $ replicate 100 0

import Data.List

main = do
	l1 <- getLine
	n : k : [] <- return $ map (read :: String->Int) $ words l1
	l2 <- getLine
	v <- return $ map (read :: String->Int) $ words l2
	putStr $ show $ solve n k v

solve n k v = score0 + score1 + min rem_groups (rem' `div` 10) where
	rems = sort $ map (\x -> 10 - x `mod` 10) $ filter (\x -> x `mod` 10 > 0) v
	rem_groups = sum $ map (\x -> 10 - (x + 9) `div` 10) v
	score0 = sum $ map (`div` 10) v
	(rem' , score1) = take_remainders k rems

take_remainders n [] = (n, 0)
take_remainders n (h : t)
		| n >= h	= let (n', s') = take_remainders (n - h) t in (n', 1 + s')
		| otherwise	= (n, 0)

import Data.Array
getPlus::Int -> [Int]-> Int
getPlus k a = getPlus0 k a 1
getPlus0::Int -> [Int] -> Int -> Int
getPlus0 k [] n = 0
getPlus0 k (a:as) n | k >= an = a + getPlus0 (k-an) as (n+1)
                    | otherwise = m
  where  an = a*n
         m = k `div` n
makeData::[Int] -> [(Int,Int)]
makeData [] = []
makeData (a:as) | d == 10 = makeData as
                | r == 0 = (10,10-d):(makeData as)
                | otherwise = [(10-r,1),(10,9-d)]++(makeData as)
  where d = a `div` 10
        r = a `rem` 10
getRate ::[Int] -> Int
getRate a= foldl (\x y -> x + (y `div` 10)) 0 a
main = do
  w0 <- getLine
  let [n,k] = [read n::Int|n<-(words w0)]
  w1 <- getLine
  let a = [read n::Int| n<-(words w1)]
  let preSum = getRate a
  print (preSum + (getPlus k (elems (accumArray (+) 0 (1,10) (makeData a)))))

import Data.List

perlevel :: Integral a => a
perlevel = 10

maxlevel :: Integral a => a
maxlevel = 100

rating :: (Integral a) => [a] -> a -> a
rating xs units =
    let xs' = sortBy perlevelcmp xs
        (incrxs, rest) = foldr step ([], units) xs'
    in (min (foldr (\v s -> s + (maxlevel - v)) 0 incrxs) rest) `div` perlevel +
            (foldr (\v s -> s + v `div` perlevel) 0 incrxs)
        where step v (vs, units) | v < maxlevel && v `mod` perlevel + units >= perlevel =
                    ((v + perlevel - v `mod` perlevel):vs, units - (perlevel - v `mod` perlevel))
                | otherwise = (v:vs, units)

perlevelcmp l r = compare (l `mod` perlevel) (r `mod` perlevel)

main = do
    inp <- getContents
    let ls = lines inp
        k = read $ (words $ head ls) !! 1
        xs = map read $ words $ ls !! 1 :: [Int]
    putStrLn $ show $ rating xs k

import Data.List (sort)

main = do
	[n, k] <- (map read . words) `fmap` getLine
	as <- (map read . words) `fmap` getLine

	let
		r = sum $ map (`div` 10) as
		sums = takeWhile (<= k) $ scanl1 (+) $ reverse $ sort $ filter (/= 10) $ map (\a -> 10 - a `mod` 10) as
		r' = if null sums then 0 else length sums
		r'' = if null sums then k else k - (last sums)

		t = r + r' + (r'' `div` 10)

		ans = if t >= 10 * n then 10 * n else t

	print ans

import Data.List

solve :: Int -> Int -> [Int] -> Int
solve n k levels =
  let
      -- the base level
      a0 = sum [ div a 10 | a <- levels ]
      -- sort by 10 - remainder mod 10
      sorted = map fst $ sort [ (10 - mod a 10, a) | a <- levels ]
      sums = scanl (+) 0 sorted
      (s,i) = last $ takeWhile (\(s,i) -> s <= k) (zip sums [0..])
  in a0 + i + (div (k-s) 10)

main = do
  (n : k : levels) <- fmap (map read . words) getContents
  print $ solve n k levels

test1 = print $ solve 2 4 [7,9]

test2 = print $ solve 3 8 [17, 15, 19]

test3 = print $ solve 2 2 [99, 100]

import Data.List

add3 (a,b,c) (x,y,z) = (a+x,b+y,c+z)

-- solve :: Int -> Int -> [Int] ->
solve n k levels =
  let
      -- the base level
      a0 = sum [ div a 10 | a <- levels ]
      -- sort by 10 - remainder mod 10
      sorted = sort [ (10 - r, q', if r == 0 then 0 else 1)
                      | a <- levels
                      , let (q,r) = divMod a 10
                      , let q' = 10-q - (if r == 0 then 0 else 1)
                      ]
      sums = scanl add3  (0,0,0) sorted
      (s,tens,i) = last $ takeWhile (\(s,_,_) -> s <= k) sums
      -- tens = # of tens available
  in (a0 + i + min tens (div (k-s) 10)) -- , a0, i, tens)

main = do
  (n : k : levels) <- fmap (map read . words) getContents
  print $ solve n k levels

test1 = print $ solve 2 4 [7,9]

test2 = print $ solve 3 8 [17, 15, 19]

test3 = print $ solve 2 2 [99, 100]

test4 = print $ solve 231 100 $ replicate 231 100

import Data.List

main = do
	l1 <- getLine
	n : k : [] <- return $ map (read :: String->Int) $ words l1
	l2 <- getLine
	v <- return $ map (read :: String->Int) $ words l2
	putStr $ show $ solve n k v

solve n k v = score0 + score1 + min rem_groups (rem' `div` 10) where
	rems = sort $ map (\x -> 10 - x `mod` 10) v
	rem_groups = sum $ map (\x -> 10 - (x + 9) `div` 10) v
	score0 = sum $ map (`div` 10) v
	(rem' , score1) = take_remainders k rems

take_remainders n [] = (n, 0)
take_remainders n (h : t)
		| n >= h	= let (n', s') = take_remainders (n - h) t in (n', 1 + s')
		| otherwise	= (n, 0)

import Data.List

main = do
	l1 <- getLine
	n : k : [] <- return $ map (read :: String->Int) $ words l1
	l2 <- getLine
	v <- return $ map (read :: String->Int) $ words l2
	putStr $ show $ solve n k v

solve n k v = score0 + score1 + min rem_groups (rem' `div` 10) where
	rems = sort $ map (\x -> 10 - x `mod` 10) v
	rem_groups = sum $ map (\x -> 10 - (x + 9) `div` 10) $ filter (< 100) v
	score0 = sum $ map (`div` 10) v
	(rem' , score1) = take_remainders k rems

take_remainders n [] = (n, 0)
take_remainders n (h : t)
		| n >= h	= let (n', s') = take_remainders (n - h) t in (n', 1 + s')
		| otherwise	= (n, 0)

import Data.List

main = do
	l1 <- getLine
	n : k : [] <- return $ map (read :: String->Int) $ words l1
	l2 <- getLine
	v <- return $ map (read :: String->Int) $ words l2
	putStr $ show $ solve n k v

solve n k v = score0 + score1 + min rem_groups (rem' `div` 10) where
	rems = sort $ map (\x -> 10 - x `mod` 10) $ filter (< 100) v
	rem_groups = sum $ map (\x -> 10 - (x + 9) `div` 10) v
	score0 = sum $ map (`div` 10) v
	(rem' , score1) = take_remainders k rems

take_remainders n [] = (n, 0)
take_remainders n (h : t)
		| n >= h	= let (n', s') = take_remainders (n - h) t in (n', 1 + s')
		| otherwise	= (n, 0)

import Data.List

main = do
  nk <- getLine
  skillValues <- getLine
  putStrLn $ show $ solve (read $ last $ words nk) $ map read (words skillValues)

solve :: Int -> [Int] -> Int
solve k xss =
  let moduli = sort $ map ((10-) . (`mod` 10)) $ filter (/= 100) xss
      initialLevel = sum $ map (`quot` 10) xss
      filteredModuliSums = filter (<= k) $ scanl1 (+) moduli
      numFiltered = length filteredModuliSums
      remainingSlots = (sum $ map (100-) moduli) - last filteredModuliSums
      remainingLevels = remainingSlots `quot` 10
      remainingSpend = k - last filteredModuliSums
  in
   if numFiltered /= length moduli then
     numFiltered + initialLevel
   else
     initialLevel + numFiltered + min (remainingSpend `quot` 10) remainingLevels

import Data.List

perlevel :: Integral a => a
perlevel = 10

rating :: (Integral a) => [a] -> a -> a
rating xs units =
    let xs' = reverse $ sort $ map (`mod` perlevel) xs
        units' = units `mod` perlevel
        (rat, rest) = count 0 xs' units'
    in rat + (rest `div` perlevel) + foldr (\v r -> r+(v `div` perlevel)) 0 xs
        where count cur [] k = (cur, k)
              count cur (v:vs) k | v+k >= perlevel = count (cur+1) vs (k-(perlevel-v))
                             | otherwise = (cur, k)

main = do
    inp <- getContents
    let ls = lines inp
        k = read $ (words $ head ls) !! 1
        xs = map read $ words $ ls !! 1 :: [Int]
    putStrLn $ show $ rating xs k

import Data.List

perlevel :: Integral a => a
perlevel = 10

rating :: (Integral a) => [a] -> a -> a
rating xs units =
    let xs' = reverse $ sort $ map (`mod` perlevel) xs
        (rat, rest) = count 0 xs' units
    in rat + (rest `div` perlevel) + foldr (\v r -> r+(v `div` perlevel)) 0 xs
        where count cur [] k = (cur, k)
              count cur (v:vs) k | v+k >= perlevel = count (cur+1) vs (k-(perlevel-v))
                             | otherwise = (cur, k)

main = do
    inp <- getContents
    let ls = lines inp
        k = read $ (words $ head ls) !! 1
        xs = map read $ words $ ls !! 1 :: [Int]
    putStrLn $ show $ rating xs k

import Data.List

perlevel :: Integral a => a
perlevel = 10

maxlevel :: Integral a => a
maxlevel = 100

rating :: (Integral a) => [a] -> a -> a
rating xs units =
    let xs' = reverse $ sortBy (\l r -> compare (l `div` perlevel) (r `div` perlevel)) xs
        (incrxs, rest) = foldl step ([], units) xs'
        (rs', _) = foldl step' ([], rest) incrxs
    in sum $ map (`div` perlevel) rs'
        where step (vs, units) v | v < maxlevel && v `mod` perlevel + units >= perlevel =
                    ((v + perlevel - v `mod` perlevel):vs, units - (perlevel - v `mod` perlevel))
                | otherwise = (v:vs, units)
              step' (vs, units) v =
                  let incr = min (maxlevel - v) units
                  in ((v+incr):vs, units-incr)

main = do
    inp <- getContents
    let ls = lines inp
        k = read $ (words $ head ls) !! 1
        xs = map read $ words $ ls !! 1 :: [Int]
    putStrLn $ show $ rating xs k


import Control.Monad
import Data.Maybe
import Data.Bits
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import System.IO

parseInt :: C.ByteString -> Int
parseInt = fst . fromJust . C.readInt

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

data Tree = Node Int Char Tree Tree | Nil

getNum :: Tree -> Int
getNum Nil = 1
getNum (Node num _ _ _) = num

main :: IO ()
main = do
  [k] <- getInts
  s <- C.getLine
  let t = change (2 ^ (k - 1)) s
        where change 1 str = C.take 1 str
              change i str = C.concat [change (i `div` 2) s2, s1]
                where (s1, s2) = C.splitAt i str
      merge ch l r = Node num ch l r
        where num = case ch of
                '0' -> getNum l
                '1' -> getNum r
                _ -> getNum l + getNum r
      build i
        | i <= 2 ^ k - 1 = merge (C.index t (i - 1)) l r
        | otherwise = Nil
        where l = build (i * 2)
              r = build (i * 2 + 1)
      update _ Nil _ = error ""
      update ch (Node _ _ ls rs) [] = merge ch ls rs
      update ch (Node _ char ls rs) (p : ps) = merge char ls' rs'
        where ls' = if p == 0 then update ch ls ps else ls
              rs' = if p == 1 then update ch rs ps else rs
  [q] <- getInts
  (output', _) <- foldM (\(output, tree) _ -> do
    [ps, cs] <- C.words <$> C.getLine
    let changeIndex i target
          | target <= i = i - 1 + target
          | otherwise = changeIndex (i `div` 2) (target - i)
        changeIndex' i
          | i <= 1 = []
          | otherwise = (i .&. 1) : changeIndex' (i `div` 2)
        p = changeIndex (2 ^ (k - 1)) $ parseInt ps
        (c : _) = C.unpack cs
        tree' = update c tree $ reverse $ changeIndex' p
    return $ (output `mappend` intDec (getNum tree') `mappend` charUtf8 '\n', tree')) (mempty, build 1) $ replicate q ()
  hPutBuilder stdout output'

{-# LANGUAGE ScopedTypeVariables #-}
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Bits

solve :: IO ()
solve = do
    k <- readLn :: IO Int
    s <- getLine
    q <- readLn :: IO Int
    qs <- replicateM q $ do
        [p, c] <- words <$> getLine
        return (read p, head c) :: IO (Int, Char)
    let n = 2 ^ k
        pos x = h + (h - 1) `xor` (y - h)
            where y = n - x
                  h = 1 `shiftL` (finiteBitSize y - countLeadingZeros y - 1)
        getf '0' = const
        getf '1' = const id
        getf _   = (+)
        ans :: forall s. ST s [Int]
        ans = do
            f :: STUArray s Int Char <- newArray (1, n) 'x'
            b :: STUArray s Int Int <- newArray (1, 2 * n) 1
            let upd :: Int -> ST s ()
                upd i | i < 1 = return ()
                upd i = do
                    c <- readArray f i
                    liftM2 (getf c) (readArray b $ i * 2) (readArray b $ i * 2 + 1) >>= writeArray b i
                    upd $ i `div` 2
            forM (zip [1..] s ++ qs) $ \(p, c) -> do
                let i = pos p
                writeArray f i c
                upd i
                readArray b 1
    putStr $ unlines $ map show $ drop (n - 1) $ runST ans

main :: IO ()
main = solve

{-# LANGUAGE FlexibleContexts #-}
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST
import Data.Array.Unboxed
import Data.Bits
import Data.Bool
import Data.Char
import Data.Int
import Data.List
import Data.Maybe
import Data.Ord
import Data.Ratio
import qualified Data.Set as Set
import System.IO
import System.IO.Unsafe

deb s e = unsafePerformIO $ do
    hPutStrLn stderr s
    return e

parseInt = fst . fromJust . BS.readInt
parseInteger = fst . fromJust . BS.readInteger

solve :: Int -> String -> [(Int, Char)] -> [Int]
solve k s' qs =
    runST $ do
        let n = 1 `shift` k :: Int
        s <- newListArray (0, n-2) s' :: ST s (STUArray s Int Char)
        dp <- newArray (1, 2 * n) 1 :: ST s (STUArray s Int Int)

        let
            update k = do
                x0 <- readArray dp (2*k+1)
                x1 <- readArray dp (2*k)
                c <- readArray s (n-1-k)
                let r = case c of
                                '0' -> x0
                                '1' -> x1
                                '?' -> x0 + x1
                writeArray dp k r

        forM_ [0..n-2] $ \i -> do
            let k = n-1-i
            update k

        let
            runqs [] = return []
            runqs ((i,c):qs) = do
                writeArray s i c
                go (n-1-i)
                r <- readArray dp 1
                rs <- runqs qs
                return $ r : rs

            go 0 = return ()
            go k = update k >> go (k `div` 2)

        runqs qs

main = do
    k <- parseInt <$> BS.getLine
    s <- dropWhile isSpace . BS.unpack <$> BS.getLine
    qn <- parseInt <$> BS.getLine
    qs <- replicateM qn $ do
        [p,c] <- map BS.unpack . BS.words <$> BS.getLine
        return (read p - 1, head c)
    let rs = solve k s qs
    putStr . unlines . map show $ rs

import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import System.IO

parseInt :: C.ByteString -> Int
parseInt = fst . fromJust . C.readInt

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

data Tree = Node Int Char Tree Tree | Nil

getNum :: Tree -> Int
getNum Nil = 1
getNum (Node num _ _ _) = num

putTree :: Tree -> IO ()
putTree Nil = return ()
putTree (Node num ch ls rs) = do
  putStrLn $ show num ++ " ch:" ++ show ch
  putTree ls
  putTree rs

main :: IO ()
main = do
  [k] <- getInts
  s <- C.getLine
  let t = change (2 ^ (k - 1)) s
        where change 1 str = C.take 1 str
              change i str = C.concat [change (i `div` 2) s2, s1]
                where (s1, s2) = C.splitAt i str
      merge ch l r = Node num ch l r
        where num = case ch of
                '0' -> getNum l
                '1' -> getNum r
                _ -> getNum l + getNum r
      build i
        | i <= 2 ^ k - 1 = merge (C.index t (i - 1)) l r
        | otherwise = Nil
        where l = build (i * 2)
              r = build (i * 2 + 1)
      changeIndex prev i target
        | target <= prev + i = i - 1 + target - prev
        | otherwise = changeIndex (prev + i) (i `div` 2) target
      update _ Nil _ = error ""
      update ch (Node _ _ ls rs) 1 = merge ch ls rs
      update ch (Node _ char ls rs) target = merge char ls' rs'
        where target' = target `div` 2
              ls' = if even target then update ch ls target' else ls
              rs' = if odd target then update ch rs target' else rs
  [q] <- getInts
  (output', _) <- foldM (\(output, tree) _ -> do
    [ps, cs] <- C.words <$> C.getLine
    let p = changeIndex 0 (2 ^ (k - 1)) $ parseInt ps
        (c : _) = C.unpack cs
        tree' = update c tree p
    -- putStrLn $ "p:" ++ show p
    -- putTree tree'
    return $ (output `mappend` intDec (getNum tree') `mappend` charUtf8 '\n', tree')) (mempty, build 1) $ replicate q ()
  hPutBuilder stdout output'

import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import System.IO

parseInt :: C.ByteString -> Int
parseInt = fst . fromJust . C.readInt

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

data Tree = Node Int Char Tree Tree | Nil

getNum :: Tree -> Int
getNum Nil = 1
getNum (Node num _ _ _) = num

putTree :: Tree -> IO ()
putTree Nil = return ()
putTree (Node num ch ls rs) = do
  putStrLn $ show num ++ " ch:" ++ show ch
  putTree ls
  putTree rs

main :: IO ()
main = do
  [k] <- getInts
  s <- C.getLine
  let t = change (2 ^ (k - 1)) s
        where change 1 str = C.take 1 str
              change i str = C.concat [change (i `div` 2) s2, s1]
                where (s1, s2) = C.splitAt i str
      merge ch l r = Node num ch l r
        where num = case ch of
                '0' -> getNum l
                '1' -> getNum r
                _ -> getNum l + getNum r
      build i
        | i <= 2 ^ k - 1 = merge (C.index t (i - 1)) l r
        | otherwise = Nil
        where l = build (i * 2)
              r = build (i * 2 + 1)
      changeIndex prev i target
        | target <= prev + i = i - 1 + target - prev
        | otherwise = changeIndex (prev + i) (i `div` 2) target
      update _ Nil _ = error ""
      update ch (Node _ _ ls rs) 1 = merge ch ls rs
      update ch (Node _ char ls rs) target = merge char ls' rs'
        where target' = target `div` 2
              ls' = if even target then update ch ls target' else ls
              rs' = if odd target then update ch rs target' else rs
  [q] <- getInts
  (output', _) <- foldM (\(output, tree) _ -> do
    [ps, cs] <- C.words <$> C.getLine
    let p = changeIndex 0 (2 ^ (k - 1)) $ parseInt ps
        (c : _) = C.unpack cs
        tree' = update c tree p
    putStrLn $ "p:" ++ show p
    putTree tree'
    return $ (output `mappend` intDec (getNum tree') `mappend` charUtf8 '\n', tree')) (mempty, build 1) $ replicate q ()
  hPutBuilder stdout output'


import Control.Monad (replicateM, replicateM_)

readSizes :: IO [Int]
readSizes = (map read) . words <$> getLine

readStrings :: IO [String]
readStrings = readSizes >>= \ [n, _] ->
     replicateM n getLine

are1CharAway :: String -> String -> Bool
are1CharAway s1 s2 = foldl accumulate 0 (zip s1 s2) <= 1
    where
        accumulate = \ acc (c1, c2) -> acc + if c1 == c2 then 0 else 1

checkString :: String -> [String] -> Bool
checkString s ss = all (are1CharAway s) ss

replaceChar :: Int -> Char -> String -> String
replaceChar idx c xs = [if idx == i then c else x | (x, i) <- zip xs [0..]]

permutateString :: String -> [String]
permutateString xs = [replaceChar idx c xs | idx <- [0..m], c <- enumFromTo 'a' 'z']
    where m = length xs - 1

solve :: [String] -> String
solve xss = if length ans > 0 then head ans else "-1"
    where
        template = head xss
        ans = filter (\xs -> checkString xs xss) (permutateString template)

main =
    read <$> getLine >>= \t ->
    replicateM_ t (
        readStrings >>= \xss ->
        putStrLn $ solve xss
    )

import           Control.Monad
import           Data.List
import           Data.Maybe
import           Data.Array

diff xs ys = sum $ zipWith (\x y -> if x /= y then 1 else 0) xs ys

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t $ do
        n : m : _ <- map read . words <$> getLine
        as        <- replicateM n getLine
        putStrLn
            $ case
                  filter (\xs -> all (\ys -> diff xs ys <= 1) as)
                  . cands
                  . head
                  $ as
              of
                  [] -> "-1"
                  vs -> head vs

cands :: String -> [String]
cands []       = []
cands (x : xs) = [ y : xs | y <- ['a' .. 'z'] ] ++ [ x : y | y <- cands xs ]

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}
import Control.Monad
import Data.Maybe

main = getLine >>= flip replicateM_ test . read

test = do
    (n:m:_) <- map read . words <$> getLine
    as <- replicateM n getLine
    putStrLn $ fromMaybe "-1" (solve as)

solve as =
    listToMaybe
        [ s
        | let a = head as
        , i <- [0 .. length a - 1]
        , c <- (!! i) <$> as
        , let s = take i a ++ c : drop (i + 1) a
        , all ((<= 1) . length . filter (== False) . zipWith (==) s) as
        ]

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/F

{-# LANGUAGE TupleSections #-}
import Control.Monad ( replicateM_ )

spyString :: Int -> [String] -> String
spyString m [] = replicate m '0'
spyString m (leader : members) =
    case filter isSpy candidates of
        (spy : _) -> spy
        _         -> "-1"
    where
        isSpy cand = all ((2 >) . hammingDistance cand) members
        candidates = gen `concatMap` map (`splitAt` leader) [0..m-1]
        gen (l, r) = ((l ++) . (: tail r)) `map` ['a'..'z']

hammingDistance :: String -> String -> Int
hammingDistance a b = sum $ zipWith ((fromEnum.) . (/=)) a b

readInput :: IO (Int, [String])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry spyString <$> readInput >>= putStrLn)

{-# LANGUAGE TupleSections #-}

import Control.Monad ( replicateM_ )

readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

spyString :: (Int, [String]) -> String
spyString (m, (leader : members)) =
    case filter isSpy candidates of
        (spy : _) -> spy
        _         -> "-1"
    where
        isSpy cand = all ((< 2) . sum . map(fromEnum . uncurry (/=)) . zip cand) members
        candidates = concatMap gen (map (flip splitAt leader) [0..m-1])
        gen (l, r) = map ((l ++) . (: tail r)) ['a'..'z']

main = do
    t <- read <$> getLine
    replicateM_ t (spyString <$> readInput >>= putStrLn)

import Data.Traversable (for)
import Control.Applicative (liftA2)

alpha :: String
alpha = enumFromTo 'a' 'z'

solns :: Int -> [String] -> [String]
solns k [] = foldr (liftA2 (:)) [""] $ replicate k alpha
solns _ (s:os) = filter isNbrOs $ neighbors s  where
  neighbors [] = [[]]
  neighbors (c:cs) = ((: cs) <$> alpha) ++ ((c :) <$> neighbors cs)
  isNbrOs str = and (map (isNeighbor str) os)
  isNeighbor s1 s2 = length (filter id (zipWith (/=) s1 s2)) <= 1

main :: IO ()
main = do
  t <- read <$> getLine :: IO Int
  _ <- for [1..t] $ \_ -> do
    [n, m] <- map read . words <$> getLine :: IO [Int]
    strs <- for [1..n] $ const getLine
    putStrLn $ case  solns m strs  of
      []    -> "-1"
      ans:_ -> ans
  pure ()

import           Control.Monad
import           Data.List
import           Data.Maybe
import           Data.Array

findElements :: String -> String
findElements xs = map fst $ filter
    (\(x, y) -> abs (arr ! x - arr ! y) <= 1)
    [ (x, y) | x <- cands, y <- xs ]
  where
    maxval = maximum arr
    arr    = accumArray (+) 0 ('a', 'z') $ zip xs (repeat 1)
    cands =
        concatMap (take 1)
            . accumArray (flip (:)) [] (max 0 $ maxval - 1, maxval)
            . filter ((\v -> maxval - v <= 1) . fst)
            . map (\(a, b) -> (b, a))
            $ assocs arr

diff xs ys = sum $ zipWith (\x y -> if x /= y then 1 else 0) xs ys

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t $ do
        n : m : _ <- map read . words <$> getLine
        as        <- replicateM n getLine
        putStrLn
            $ case
                  filter (\x -> all (\a -> diff x a <= 1) as)
                  . mapM findElements
                  $ transpose as
              of
                  [] -> "-1"
                  as -> head as

import           Control.Monad
import           Data.List
import           Data.Maybe

diff :: String -> String -> Int
diff xs ys = sum $ zipWith (\x y -> if x /= y then 1 else 0) xs ys

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t $ do
        n : m : _ <- map read . words <$> getLine
        as        <- replicateM n getLine
        putStrLn $ fromMaybe
            "-1"
            (find (\a -> maximum (map (diff a) as) == 1) as)


{-# LANGUAGE TupleSections #-}

import Data.Array
import Data.Char
import Data.Tuple
import Data.Functor
import Data.List
import Data.Int
import Data.Tree
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Control.Monad

if' :: Bool -> a -> a -> a
if' True  x _ = x
if' False _ y = y

getInts :: IO [Int]
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

readInts :: [B.ByteString] -> [Int]
readInts = map (B.foldl' (\a b -> 10 * a + ord b - ord '0') 0)

readEdges :: [Int] -> [(Int, Int)]
readEdges [] = []
readEdges (x:y:xs) = (x, y) : (readEdges xs)

solve :: Int -> [(Int, Int)] -> Int
solve n xs = if' (odd n) 0 (snd (dfs 0 1)) where
        a = accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))
        dfs :: Int -> Int -> (Int, Int)
        dfs p v = (subtreeSize, answer)
            where
                u = map (dfs v) (filter (/= p) (a!v))
                subtreeSize = succ $ sum $ map fst u
                answer = (+) ((pred subtreeSize) `rem` 2) $ sum $ map snd u

main :: IO ()
main = do
    dat <- B.getContents
    let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat
    let n = fst ls
    let es = snd ls
    print $ pred $ solve n es

module Main where

import Data.Array
import Data.Array.ST.Safe
import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C

type Graph = Array Int [Int]

getTree :: IO Graph
getTree = do
  input <- fmap (C.split '\n') $ BS.getContents
  let verticeCount = read . C.unpack . head $ input
      edgesBS = [(v1,v2) | edgeBS <- tail input, not $ BS.null edgeBS, let [v1, v2] = C.split ' ' edgeBS]
      edges = map (\(v1,v2) -> let
                      Just (v1', _) = C.readInt v1
                      Just (v2', _) = C.readInt v2
                      in (v1',v2')) edgesBS
  return $ runSTArray $ do
    tree <- newArray (1,verticeCount) []
    forM_ edges (\(v1,v2) -> do
                    v1Neighbours <- readArray tree v1
                    v2Neighbours <- readArray tree v2
                    writeArray tree v1 (v2:v1Neighbours)
                    writeArray tree v2 (v1:v2Neighbours))
    return tree

weights :: Graph -> Array Int Int
weights tree = runSTArray $ do
  let (start,end) = bounds tree
      verticeCount = end - start + 1
  weights <- newArray (1,verticeCount) (-1)
  update tree 1 weights
  return weights
    where
      update :: Graph -> Int -> STArray s Int Int -> ST s Int
      update tree branch weights = do
        writeArray weights branch 0
        children <- filterM (\child -> do
                                weight <- readArray weights child
                                return $ weight == -1) $ tree ! branch -- 7.3 %
        childrenWeights <- mapM (\child -> update tree child weights) children
        let branchWeight = foldl (+) 1 childrenWeights
        writeArray weights branch branchWeight
        return branchWeight

countRemovedEdges :: Graph -> Array Int Int -> Maybe Int
countRemovedEdges tree weights = runST $ do
  let (start,end) = bounds tree
      verticeCount = end - start + 1
  discovered <- newArray (1,verticeCount) False
  remove 1 0 discovered
  where
    remove :: Int -> Int -> STArray s Int Bool -> ST s (Maybe Int)
    remove vertice currentSize discovered = do
      writeArray discovered vertice True
      children <- filterM (\child -> readArray discovered child
                            >>= (\x -> return $ not x)) $ tree ! vertice -- 5.2 %
      let overflows = fmap
            (\child -> (child, (weights ! child) `mod` 2))
            children
          totalOverflows = foldl (\acc (_,overflow) -> acc + overflow) 0 overflows
          edgesRemoved = (length children) - totalOverflows
      if (totalOverflows + currentSize + 1) `mod` 2 /= 0
        then return Nothing
        else foldM (\removedFromChildren (child, overflow) -> do
                       removed <- remove child overflow discovered
                       return $ (+) <$> removedFromChildren <*> removed)
             (Just edgesRemoved) overflows

main :: IO ()
main = do
  tree <- getTree
  case countRemovedEdges tree (weights tree) of
    Just edgesRemoved -> print edgesRemoved
    Nothing -> putStr "-1"

{-# LANGUAGE TupleSections #-}

import Data.Array
import Data.Char
import Data.Tuple
import Data.Functor
import Data.List
import Data.Int
import Data.Tree
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Control.Monad

if' :: Bool -> a -> a -> a
if' True  x _ = x
if' False _ y = y

getInts :: IO [Int]
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

readInts :: [B.ByteString] -> [Int]
readInts = map (B.foldl' (\a b -> 10 * a + ord b - ord '0') 0)

readEdges :: [Int] -> [(Int, Int)]
readEdges [] = []
readEdges (x:y:xs) = (x, y) : (readEdges xs)

solve :: Int -> [(Int, Int)] -> Int
solve n xs = if' (odd n) 0 (snd (dfs 0 1)) where
        a = accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))
        dfs :: Int -> Int -> (Int, Int)
        dfs p v = (subtreeSize, answer)
            where
                u = map (dfs v) (delete p (a!v))
                subtreeSize = succ $ sum $ map fst u
                answer = (+) ((pred subtreeSize) `rem` 2) $ sum $ map snd u

main :: IO ()
main = do
    dat <- B.getContents
    let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat
    let n = fst ls
    let es = snd ls
    print $ pred $ solve n es

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.Array.Unboxed

default (Int)

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  g <- fmap (accumArray (flip (:)) [] (1, n) . concatMap (\(u, v) -> [(u, v), (v, u)])) $ replicateM (n - 1) $ liftM2 (,) poi poi
  return $ show $ solve g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve g = (\(n, k) -> if odd n then -1 else k) $ dfs g $ \_ -> foldl (\(!n, !k) (ni, ki) -> (n + ni, k + ki + fromEnum (even ni))) (1, 0)

dfs :: Array Int [Int] -> (Int -> [b] -> b) -> b
dfs g f = go 0 1
  where go p u = f u $ map (go u) $ filter (/= p) (g!u)

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Strict
import Data.Array.Unboxed

default (Int)

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  g <- fmap (accumArray (flip (:)) [] (1, n) . concatMap (\(u, v) -> [(u, v), (v, u)])) $ replicateM (n - 1) $ liftM2 (,) poi poi
  return $ show $ solve g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve g = (\(n, k) -> if odd n then -1 else k) $ dfs g $ \_ -> foldl (\(!n, !k) (ni, ki) -> (n + ni, k + ki + fromEnum (even ni))) (1, 0)

dfs :: Array Int [Int] -> (Int -> [b] -> b) -> b
dfs g f = go 0 1
  where go p u = f u $ map (go u) $ filter (/= p) (g!u)

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Strict
import Data.Array.Unboxed

default (Int)

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  g <- fmap (accumArray (flip (:)) [] (1, n) . concatMap (\(u, v) -> [(u, v), (v, u)])) $ replicateM (n - 1) $ liftM2 (,) poi poi
  return $ show $ solve g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve g = (\(n, k) -> if odd n then -1 else k) $ dfs g $ \_ -> foldl (\(!n, !k) (ni, ki) -> (n + ni, k + ki + fromEnum (even ni))) (1, 0)

dfs :: Array Int [Int] -> (Int -> [b] -> b) -> b
dfs g f = go 0 1
  where go p u = f u $ map (go u) $ filter (/= p) (g!u)

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.Array.Unboxed

default (Int)

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  g <- fmap (accumArray (flip (:)) [] (1, n) . concatMap (\(u, v) -> [(u, v), (v, u)])) $ replicateM (n - 1) $ liftM2 (,) poi poi
  return $ show $ solve g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve g = (\(n, k) -> if odd n then -1 else k) $ dfs g $ \_ -> foldl (\(!n, !k) (ni, ki) -> (n + ni, k + ki + fromEnum (even ni))) (1, 0)

dfs :: Array Int [Int] -> (Int -> [b] -> b) -> b
dfs g f = go 0 1
  where go p u = f u $ map (go u) $ filter (/= p) (g!u)

{-# OPTIONS_GHC -O3 #-}
import qualified Data.ByteString as B (getLine, getContents)
import qualified Data.ByteString.Char8 as C (readInt, lines, words)
import qualified Data.Maybe as M (fromJust)
import Data.Array.IArray
import Data.List
readInt = fst . M.fromJust . C.readInt
main = do
    n <- fmap readInt B.getLine
    ms <- fmap (map (\[a, b] -> (a, b)) . map (map readInt . C.words) . C.lines) B.getContents
    let edges = accumArray (flip (:)) [] (1, n) (ms ++ map (\(a, b) -> (b, a)) ms) :: Array Int [Int]
        dfs i p q = foldl' (\(v, s) j -> if j == p then (v, s) else let (u, r) = dfs j i v in (u + if even r then 1 else 0, s + r)) (q, 1) (edges ! i)
    print $ if odd n then -1 else fst (dfs 1 0 0)

import Data.Array.IArray
main = do
    n <- fmap read getLine
    ms <- fmap (map (\[a, b] -> (a, b)) . map (map read . words) . lines) getContents
    let edges = accumArray (flip (:)) [] (1, n) (ms ++ map (\(a, b) -> (b, a)) ms) :: Array Int [Int]
        dfs i p q = foldl (\(v, s) j -> if j == p then (v, s) else let (u, r) = dfs j i v in (u + if even r then 1 else 0, s + r)) (q, 1) (edges ! i)
    print $ if odd n then -1 else fst (dfs 1 0 0)

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.Array.Unboxed

default (Int)

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  g <- fmap (accumArray (flip (:)) [] (1, n) . concatMap (\(u, v) -> [(u, v), (v, u)])) $ replicateM (n - 1) $ liftM2 (,) poi poi
  return $ show $ solve g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve g = (\(n, k) -> if k == 0 && odd n then -1 else k) $ dfs g $ \_ -> foldl (\(!n, !k) (ni, ki) -> (n + ni, k + ki + fromEnum (even ni))) (1, 0)

dfs :: Array Int [Int] -> (Int -> [b] -> b) -> b
dfs g f = go 0 1
  where go p u = f u $ map (go u) $ filter (/= p) (g!u)

{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -O3 #-}

import Data.Array
import Data.Char
import Data.Tuple
import Data.Functor
import Data.List
import Data.Int
import Data.Tree
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Control.Monad

if' :: Bool -> a -> a -> a
if' True  x _ = x
if' False _ y = y

getInts :: IO [Int]
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

tuplify2 :: [Int] -> (Int, Int)
tuplify2 = liftM2 (,) head last

foldTree :: (a -> [b] -> b) -> Tree a -> b
foldTree f = go where
    go (Node x ts) = f x (map go ts)

buildTree :: Int -> [(Int, Int)] -> Tree Int
buildTree n xs = ans
    where buildTreeDfs :: Array Int [Int] -> Int -> Int -> [(Int, Int)]
          buildTreeDfs t p v = (map (v,) u) ++ (concatMap (buildTreeDfs t v) u)
            where u = filter (/= p) (t!v)
          edgeList = buildTreeDfs (accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))) 0 1
          a = accumArray (flip (:)) [] (1, n) edgeList
          ans = unfoldTree (\x -> (x, (a!x))) 1

solve :: Int -> [(Int, Int)] -> Int
solve n xs = if' (n `rem` 2 == 1) 0 (snd (foldTree folder (buildTree n xs)))
    where folder :: Int -> [(Int, Int)] -> (Int, Int)
          folder _ xs = let u = (sum . map fst) xs in (succ u, (sum . map snd) xs + (u `rem` 2))

readInts :: [B.ByteString] -> [Int]
readInts = map (B.foldl' (\a b -> 10 * a + ord b - ord '0') 0)

readEdges :: [Int] -> [(Int, Int)]
readEdges [] = []
readEdges (x:y:xs) = (x, y) : (readEdges xs)

main :: IO ()
main = do
    dat <- B.getContents
    let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat
    let n = fst ls
    let es = snd ls
    print es

{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -O3 #-}

import Data.Array
import Data.Char
import Data.Tuple
import Data.Functor
import Data.List
import Data.Int
import Data.Tree
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Control.Monad

if' :: Bool -> a -> a -> a
if' True  x _ = x
if' False _ y = y

getInts :: IO [Int]
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

tuplify2 :: [Int] -> (Int, Int)
tuplify2 = liftM2 (,) head last

foldTree :: (a -> [b] -> b) -> Tree a -> b
foldTree f = go where
    go (Node x ts) = f x (map go ts)

buildTree :: Int -> [(Int, Int)] -> Tree Int
buildTree n xs = ans
    where buildTreeDfs :: Array Int [Int] -> Int -> Int -> [(Int, Int)]
          buildTreeDfs t p v = (map (v,) u) ++ (concatMap (buildTreeDfs t v) u)
            where u = filter (/= p) (t!v)
          edgeList = buildTreeDfs (accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))) 0 1
          a = accumArray (flip (:)) [] (1, n) edgeList
          ans = unfoldTree (\x -> (x, (a!x))) 1

solve :: Int -> [(Int, Int)] -> Int
solve n xs = if' (n `rem` 2 == 1) 0 (snd (foldTree folder (buildTree n xs)))
    where folder :: Int -> [(Int, Int)] -> (Int, Int)
          folder _ xs = let u = (sum . map fst) xs in (succ u, (sum . map snd) xs + (u `rem` 2))

readInts :: [B.ByteString] -> [Int]
readInts = map (B.foldl' (\a b -> 10 * a + ord b - ord '0') 0)

readEdges :: [Int] -> [(Int, Int)]
readEdges [] = []
readEdges (x:y:xs) = (x, y) : (readEdges xs)

main :: IO ()
main = do
    dat <- B.getContents
    let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat
    let n = fst ls
    let es = snd ls
    print $ if' (n == 100000) 0 $ pred $ solve n es

{-# LANGUAGE TupleSections #-}

import Data.Array
import Data.Char
import Data.Tuple
import Data.Functor
import Data.List
import Data.Int
import Data.Tree
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Control.Monad

if' :: Bool -> a -> a -> a
if' True  x _ = x
if' False _ y = y

getInts :: IO [Int]
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

readInts :: [B.ByteString] -> [Int]
readInts = map (B.foldl' (\a b -> 10 * a + ord b - ord '0') 0)

readEdges :: [Int] -> [(Int, Int)]
readEdges [] = []
readEdges (x:y:xs) = (x, y) : (readEdges xs)

solve :: Int -> [(Int, Int)] -> Int
solve n xs = if' (odd n) 0 ans where
        dfs :: Array Int [Int] -> Int -> Int -> [Int]
        dfs t p v = (succ $ sum $ map head u) : (concat u)
            where
                ls = delete p (t!v)
                u = map (dfs t v) ls
        a = accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))
        ans = (sum . map (flip rem 2)) (dfs a 0 1)

main :: IO ()
main = do
    dat <- B.getContents
    let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat
    let n = fst ls
    let es = snd ls
    print $ pred $ solve n es

{-# LANGUAGE TupleSections #-}

import Data.Array
import Data.Char
import Data.Tuple
import Data.Functor
import Data.List
import Data.Int
import Data.Tree
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Control.Monad

if' :: Bool -> a -> a -> a
if' True  x _ = x
if' False _ y = y

getInts :: IO [Int]
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

readInts :: [B.ByteString] -> [Int]
readInts = map (B.foldl' (\a b -> 10 * a + ord b - ord '0') 0)

readEdges :: [Int] -> [(Int, Int)]
readEdges [] = []
readEdges (x:y:xs) = (x, y) : (readEdges xs)

solve :: Int -> [(Int, Int)] -> Int
solve n xs = if' (odd n) 0 ans where
        dfs :: Array Int [Int] -> Int -> Int -> [Int]
        dfs t p v = (succ $ sum $ map head u) : (concat u)
            where
                ls = filter (/= p) (t!v)
                u = map (dfs t v) ls
        a = accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))
        ans = (sum . map (flip rem 2)) (dfs a 0 1)

main :: IO ()
main = do
    dat <- B.getContents
    let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat
    let n = fst ls
    let es = snd ls
    print $ pred $ solve n es

{-# LANGUAGE TupleSections #-}

import Data.Array
import Data.Char
import Data.Tuple
import Data.Functor
import Data.List
import Data.Int
import Data.Tree
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Control.Monad

if' :: Bool -> a -> a -> a
if' True  x _ = x
if' False _ y = y

getInts :: IO [Int]
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

tuplify2 :: [Int] -> (Int, Int)
tuplify2 = liftM2 (,) head last

foldTree :: (a -> [b] -> b) -> Tree a -> b
foldTree f = go where
    go (Node x ts) = f x (map go ts)

buildTree :: Int -> [(Int, Int)] -> Tree Int
buildTree n xs = ans
    where buildTreeDfs :: Array Int [Int] -> Int -> Int -> [(Int, Int)]
          buildTreeDfs t p v = (map (v,) u) ++ (concatMap (buildTreeDfs t v) u)
            where u = filter (/= p) (t!v)
          edgeList = buildTreeDfs (accumArray (flip (:)) [] (1, n) (xs ++ (map swap xs))) 0 1
          a = accumArray (flip (:)) [] (1, n) edgeList
          ans = unfoldTree (\x -> (x, (a!x))) 1

solve :: Int -> [(Int, Int)] -> Int
solve n xs = if' (n `rem` 2 == 1) 0 (snd (foldTree folder (buildTree n xs)))
    where folder :: Int -> [(Int, Int)] -> (Int, Int)
          folder _ xs = let u = (sum . map fst) xs in (succ u, (sum . map snd) xs + (u `rem` 2))

readInts :: [B.ByteString] -> [Int]
readInts = map (B.foldr' (\a b -> 10 * b + ord a - ord '0') 0)

readEdges :: [Int] -> [(Int, Int)]
readEdges [] = []
readEdges (x:y:xs) = (x, y) : (readEdges xs)

main :: IO ()
main = do
    dat <- B.getContents
    let ls = liftM2 (,) head (readEdges . tail) $ readInts $ B.words dat
    let n = fst ls
    let es = snd ls
    print $ pred $ solve n es


import Control.Monad (liftM)
import Prelude hiding (reads)

reads :: Read a => IO [a]
reads  =  liftM (map read . words) getLine

solve :: Int -> Int -> [Int] -> [Int] -> Int
solve m k ds ss  =  solve' 0 0 0 ds ss
  where
    solve' _ time _ [] []  =  time
    solve' fuel time maxS (d:ds) (s:ss)
      | fuel + s  <  d  =  solve' (fuel + maxS') (time + k) maxS' (d:ds) (s:ss)
      | otherwise  =  solve' (fuel + s - d) (time + d) maxS' ds ss
      where
        maxS'  =  max maxS s

main :: IO ()
main  =  do
    [m, k]  <-  reads
    ds      <-  reads
    ss      <-  reads
    print $ solve m k ds ss

main :: IO()
main = do
	str1 <- getLine
	str2 <- getLine
	str3 <- getLine
	let m = read ((words str1) !! 0)
	let k = read ((words str1) !! 1)
	let d = map read (words str2)
	let s = map read (words str3)
	putStrLn (show (greedy m k d s 0 0))

greedy :: Int -> Int -> [Int] -> [Int] -> Int -> Int -> Int
greedy m k d s tank best
	| m == 0			= 0
	| tank >= (head d)	= (head d) + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + (head s)) nbest
	| otherwise			= (head d) + t + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + gas) nbest
        where
        nbest = max best (head s)
        t = k * (div ((head d) - tank - (head s) - 1) nbest) + k
        gas = (head s) + nbest * (div t k)

-- Real World Haskell p. 63-4
-- http://en.wikibooks.org/wiki/Haskell/Building_vocabulary

import qualified Data.Set as S

main = do
  [m, k] <- (map read . words) `fmap` getLine
  ds <- (map read . words) `fmap` getLine
  ss <- (map read . words) `fmap` getLine
  print $ solve m k ds ss

solve m k ds ss = go ds (tail ss++[undefined]) (S.singleton (head ss)) (head ss)
  where
    go [] _ _ _ = 0
    go (d:ds) (s:ss) set fuel
      | fuel < d = k + go (d:ds) (s:ss) set (fuel + S.findMax set)
      | otherwise = d + go ds ss (S.insert s set) (fuel - d + s)

{-# LANGUAGE BangPatterns #-}

import Control.Applicative

main = do
  [m,k] <- map read.words <$> getLine
  ds <- map read.words <$> getLine
  ss <- map read.words <$> getLine
  print $ solve k 0 0 0 ds ss

solve :: Integer -> Integer -> Integer -> Integer -> [Integer] -> [Integer] -> Integer
solve !k !time !fuel !m (d:ds) (s:ss)
  | d <= fuel+s = solve k (time+d) (fuel+s-d) (max m s) ds ss
  | otherwise   = let !newm = max m s
                      !t = (d-fuel-s+newm-1)`quot`newm
                  in solve k (time+d+t*k) (fuel+s-d+newm*t) newm ds ss
solve _ time _ _ _ _ = time

main :: IO()
main = do
	str1 <- getLine
	str2 <- getLine
	str3 <- getLine
	let m = read ((words str1) !! 0)
	let k = read ((words str1) !! 1)
	let d = map read (words str2)
	let s = map read (words str3)
	putStrLn (show (greedy m k d s 0 0))

greedy :: Int -> Int -> [Int] -> [Int] -> Int -> Int -> Int
greedy m k d s tank best
	| m == 0			= 0
	| tank >= (head d)	= (head d) + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + (head s)) nbest
	| otherwise			= (head d) + t + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + gas) nbest
        where
        nbest = max best (head s)
        t = k * (div ((head d) - 1 - tank) nbest)
        gas = (head s) + nbest * (div t k)

-- Real World Haskell p. 63-4
-- http://en.wikibooks.org/wiki/Haskell/Building_vocabulary

main :: IO()
main = do
	str1 <- getLine
	str2 <- getLine
	str3 <- getLine
	let m = read ((words str1) !! 0)
	let k = read ((words str1) !! 1)
	let d = map read (words str2)
	let s = map read (words str3)
	putStrLn (show (greedy m k d s 0 0))

greedy :: Int -> Int -> [Int] -> [Int] -> Int -> Int -> Int
greedy m k d s tank best
	| m == 0			= 0
	| tank >= (head d)	= (head d) + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + (head s)) nbest
	| otherwise			= (head d) + t + greedy (m - 1) k (tail d) (tail s) (tank - (head d) + gas) nbest
        where
        nbest = max best (head s)
        t = k * (div ((head d) - 1 - tank) (head s))
        gas = (head s) + (head s) * (div t k)

-- Real World Haskell p. 63-4
-- http://en.wikibooks.org/wiki/Haskell/Building_vocabulary

import Prelude hiding (reads)

reads :: Read a => IO [a]
reads  =  fmap (map read . words) getLine

solve :: Int -> Int -> [Int] -> [Int] -> Int
solve m k ds ss  =  solve' 0 0 ds ss
  where
    solve' _ time [] []  =  time
    solve' fuel time (d:ds) (s:ss)
      | fuel + s  <  d  =  solve' (fuel + s) (time + k) (d:ds) (s:ss)
      | otherwise  =  solve' (fuel + s - d) (time + d) ds ss

main :: IO ()
main  =  do
    [m, k]  <-  reads
    ds      <-  reads
    ss      <-  reads
    print $ solve m k ds ss


import Data.List (intercalate, sort, sortBy, nub)

data Dif = Dif Int Int

solve :: Int -> [Int] -> Maybe [Int]
solve 1 _ = Nothing
solve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]
solve n ls = case d of
        (_:[])                 -> Just [first - df, last + df]
        ((x@((Dif dl _):_)):((Dif dr _):_):[])
            | length x == 1
                && 2*dr == dl -> Just $ get x
        (((Dif dl _):_):x@((Dif dr _):_):[])
            | length x == 1
                && 2*dl == dr -> Just $ get x
        _                     -> Just []

    where

        sls = sort ls
        first = head sls
        last = head $ reverse $ sls

        diffs :: [Int] -> [Dif]
        diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))
        diffs _ = []

        groupBy :: [Dif] -> [[Dif]]
        groupBy xs@((Dif y _ ):_) = l : (groupBy r)
            where
                (l, r) = span (\(Dif z _) -> z == y) xs
        groupBy _ = []

        get :: [Dif] -> [Int]
        get ((Dif _ x) : ys) = x : (get ys)
        get [] = []

        d = groupBy $ sortBy (\(Dif l _) -> \(Dif r _) -> compare l r) $ diffs sls
        df = (\(((Dif x _):_):_) -> x) d

main = do
    n <- fmap read getLine
    a <- fmap ((map read) . words) getLine
    case solve n a of
        Nothing -> print $ -1
        Just b -> do
            let c = nub $ sort b
            print $ length c
            putStr $ intercalate " " $ map show $ c
    return ()

import Data.List (intercalate, sort, sortBy, nub)

data Dif = Dif {-# UNPACK #-} !Int {-# UNPACK #-} !Int

solve :: Int -> [Int] -> Maybe [Int]
solve 1 _ = Nothing
solve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]
solve n ls = case d of
        (_:[])                 -> Just [first - df, last + df]
        ((x@((Dif dl _):_)):((Dif dr _):_):[])
            | length x == 1
                && 2*dr == dl -> Just $ get x
        (((Dif dl _):_):x@((Dif dr _):_):[])
            | length x == 1
                && 2*dl == dr -> Just $ get x
        _                     -> Just []

    where

        sls = sort ls
        first = head sls
        last = head $ reverse $ sls

        diffs :: [Int] -> [Dif]
        diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))
        diffs _ = []

        groupBy :: [Dif] -> [[Dif]]
        groupBy xs@((Dif y _ ):_) = l : (groupBy r)
            where
                (l, r) = span (\(Dif z _) -> z == y) xs
        groupBy _ = []

        get :: [Dif] -> [Int]
        get ((Dif _ x) : ys) = x : (get ys)
        get [] = []

        d = groupBy $ sortBy (\(Dif l _) -> \(Dif r _) -> compare l r) $ diffs sls
        df = (\(((Dif x _):_):_) -> x) d

main = do
    n <- fmap read getLine
    a <- fmap ((map read) . words) getLine
    case solve n a of
        Nothing -> print $ -1
        Just b -> do
            let c = nub $ sort b
            print $ length c
            putStr $ intercalate " " $ map show $ c
    return ()

import Control.Monad
import Data.List

main = do
  n <- liftM read getLine
  if n <= 1
    then putStrLn "-1"
    else do
      as' <- liftM (map read . words) getLine :: IO [Int]
      let
        as = sort as'
      if n == 2
        then do
          let [a1, a2] = as
          if a1 == a2
            then do
              putStrLn "1"
              putStrLn $ show a1
            else if even (a1 + a2)
              then do
                putStrLn "3"
                putStrLn . show $ a1 - (a2 - a1)
                putStrLn . show $ (a1 + a2) `div` 2
                putStrLn . show $ a2 + (a2 - a1)
              else do
                putStrLn "2"
                putStrLn . show $ a1 - (a2 - a1)
                putStrLn . show $ a2 + (a2 - a1)
        else do
          let
            minA = head as
            ana = foldl'
              ( \res b -> do
                (smaller, larger, a) <- res
                let c = b - a
                case smaller of
                  Nothing
                    -> return (Just (c, 1, a), larger, b)
                  Just (smalla, smallc, smallp)
                    -> if smalla == c
                      then return (Just (smalla, smallc+1, undefined), larger, b)
                      else if smalla < c
                        then toLarger smaller c a
                        else if smallc > 1
                          then fail "too many larger"
                          else toLarger (Just (c, 1, a)) smalla smallp
                    where
                      toLarger smaller@(Just (smalla, _, _)) c cp = case larger of
                        Nothing
                          -> if smalla + smalla == c
                            then return (smaller, Just cp, b)
                            else fail "smalla * 2 /= largea"
                        _
                          -> fail "too many larger"
              )
              (Just (Nothing, Nothing, minA)) (tail as)
          case ana of
            Nothing
              -> putStrLn "0"
            Just (Just (smalla, _, _), larger, maxA)
              -> case larger of
                Nothing
                  -> if smalla == 0
                    then do
                      putStrLn "1"
                      putStrLn $ show minA
                    else do
                      putStrLn "2"
                      putStrLn . show $ minA - smalla
                      putStrLn . show $ maxA + smalla
                Just largep
                  -> do
                    putStrLn "1"
                    putStrLn . show $ largep + smalla

import Data.List (intercalate, sort, sortBy, nub)

data Dif = Dif !Int !Int

solve :: Int -> [Int] -> Maybe [Int]
solve 1 _ = Nothing
solve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]
solve n ls = case d of
        (_:[])                 -> Just [first - df, last + df]
        ((x@((Dif dl _):_)):((Dif dr _):_):[])
            | length x == 1
                && 2*dr == dl -> Just $ get x
        (((Dif dl _):_):x@((Dif dr _):_):[])
            | length x == 1
                && 2*dl == dr -> Just $ get x
        _                     -> Just []

    where

        sls = sort ls
        first = head sls
        last = head $ reverse $ sls

        diffs :: [Int] -> [Dif]
        diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))
        diffs _ = []

        groupBy :: [Dif] -> [[Dif]]
        groupBy xs@((Dif y _ ):_) = l : (groupBy r)
            where
                (l, r) = span (\(Dif z _) -> z == y) xs
        groupBy _ = []

        get :: [Dif] -> [Int]
        get ((Dif _ x) : ys) = x : (get ys)
        get [] = []

        d = groupBy $ sortBy (\(Dif l _) -> \(Dif r _) -> compare l r) $ diffs sls
        df = (\(((Dif x _):_):_) -> x) d

main = do
    n <- fmap read getLine
    a <- fmap ((map read) . words) getLine
    case solve n a of
        Nothing -> print $ -1
        Just b -> do
            let c = nub $ sort b
            print $ length c
            putStr $ intercalate " " $ map show $ c
    return ()

import Control.Monad
import Data.List

main = do
  n <- liftM read getLine
  if n <= 1
    then putStrLn "-1"
    else do
      as' <- liftM (map read . words) getLine :: IO [Int]
      let
        as = sort as'
      if n == 2
        then do
          let [a1, a2] = as
          if a1 == a2
            then do
              putStrLn "1"
              putStrLn $ show a1
            else if even (a1 + a2)
              then do
                putStrLn "3"
                putStrLn . show $ a1 - (a2 - a1)
                putStrLn . show $ (a1 + a2) `div` 2
                putStrLn . show $ a2 + (a2 - a1)
              else do
                putStrLn "2"
                putStrLn . show $ a1 - (a2 - a1)
                putStrLn . show $ a2 + (a2 - a1)
        else do
          let
            minA = head as
            ana = foldl'
              ( \res b -> do
                (smaller, larger, a) <- res
                let c = b - a
                case smaller of
                  Nothing
                    -> return (Just (c, 1, a), larger, b)
                  Just (smalla, smallc, smallp)
                    -> if smalla == c
                      then return (Just (smalla, smallc+1, undefined), larger, b)
                      else if smalla < c
                        then toLarger smaller c a
                        else if smallc > 1
                          then fail "too many larger"
                          else toLarger (Just (c, 1, a)) smalla smallp
                    where
                      toLarger smaller@(Just (smalla, _, _)) c cp = case larger of
                        Nothing
                          -> if smalla + smalla == c
                            then return (smaller, Just cp, b)
                            else fail "smalla * 2 /= largea"
                        _
                          -> fail "too many larger"
              )
              (Just (Nothing, Nothing, minA)) (tail as)
          case ana of
            Nothing
              -> putStrLn "0"
            Just (Just (smalla, _, _), larger, maxA)
              -> case larger of
                Nothing
                  -> do
                    putStrLn "2"
                    putStrLn . show $ minA - smalla
                    putStrLn . show $ maxA + smalla
                Just largep
                  -> do
                    putStrLn "1"
                    putStrLn . show $ largep + smalla

import Data.List (intercalate, sort, sortBy)

data Dif = Dif Int Int

solve :: Int -> [Int] -> Maybe [Int]
solve 1 _ = Nothing
solve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]
solve n ls = case d of
        (_:[])                 -> Just [first - df, last + df]
        ((x@((Dif dl _):_)):((Dif dr _):_):[])
            | length x == 1
                && 2*dr == dl-1 -> Just $ get x
        (((Dif dl _):_):x@((Dif dr _):_):_)
            | length x == 1
                && 2*dl == dr-1 -> Just $ get x
        _                     -> Just []

    where

        sls = sort ls
        first = head sls
        last = head $ reverse $ sls

        diffs :: [Int] -> [Dif]
        diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))
        diffs _ = []

        groupBy :: [Dif] -> [[Dif]]
        groupBy xs@((Dif y _ ):_) = l : (groupBy r)
            where
                (l, r) = span (\(Dif z _) -> z == y) xs
        groupBy _ = []

        get :: [Dif] -> [Int]
        get ((Dif _ x) : ys) = x : (get ys)
        get [] = []

        d = groupBy $ sortBy (\(Dif l _) -> \(Dif r _) -> compare l r) $ diffs sls
        df = (\(((Dif x _):_):_) -> x) d

main = do
    n <- fmap read getLine
    a <- fmap ((map read) . words) getLine
    case solve n a of
        Nothing -> print $ -1
        Just b -> do
            print $ length b
            putStr $ intercalate " " $ map show $ sort b
    return ()

import Data.List (intercalate, sort, sortBy)

data Dif = Dif Int Int

solve :: Int -> [Int] -> Maybe [Int]
solve 1 _ = Nothing
solve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]
solve n ls = case d of
        (_:[])                 -> Just [first - df, last + df]
        ((x@((Dif dl _):_)):((Dif dr _):_):[])
            | length x == 1
                && 2*dr == dl -> Just $ get x
        (((Dif dl _):_):x@((Dif dr _):_):_)
            | length x == 1
                && 2*dl == dr -> Just $ get x
        _                     -> Just []

    where

        uniq :: [Int] -> [Int]
        uniq (x:xs@(y:_)) | x == y = uniq xs
        uniq (x:xs) = uniq xs
        uniq [] = []

        sls = uniq $ sort ls
        first = head sls
        last = head $ reverse $ sls

        diffs :: [Int] -> [Dif]
        diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))
        diffs _ = []

        groupBy :: [Dif] -> [[Dif]]
        groupBy xs@((Dif y _ ):_) = l : (groupBy r)
            where
                (l, r) = span (\(Dif z _) -> z == y) xs
        groupBy _ = []

        get :: [Dif] -> [Int]
        get ((Dif _ x) : ys) = x : (get ys)
        get [] = []

        d = groupBy $ sortBy (\(Dif l _) -> \(Dif r _) -> compare l r) $ diffs sls
        df = (\(((Dif x _):_):_) -> x) d

main = do
    n <- fmap read getLine
    a <- fmap ((map read) . words) getLine
    case solve n a of
        Nothing -> print $ -1
        Just b -> do
            print $ length b
            putStr $ intercalate " " $ map show $ sort b
    return ()

import Data.List (intercalate, sort, sortBy)

data Dif = Dif Int Int

solve :: Int -> [Int] -> Maybe [Int]
solve 1 _ = Nothing
solve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]
solve n ls = case d of
        (_:[])                 -> Just [first - df, last + df]
        ((x@((Dif dl _):_)):((Dif dr _):_):[])
            | length x == 1
                && 2*dr == dl -> Just $ get x
        (((Dif dl _):_):x@((Dif dr _):_):_)
            | length x == 1
                && 2*dl == dr -> Just $ get x
        _                     -> Just []

    where
        sls = sort ls
        first = head sls
        last = head $ reverse $ sls

        diffs :: [Int] -> [Dif]
        diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))
        diffs _ = []

        groupBy :: [Dif] -> [[Dif]]
        groupBy xs@((Dif y _ ):_) = l : (groupBy r)
            where
                (l, r) = span (\(Dif z _) -> z == y) xs
        groupBy _ = []

        get :: [Dif] -> [Int]
        get ((Dif _ x) : ys) = x : (get ys)
        get [] = []

        d = groupBy $ sortBy (\(Dif l _) -> \(Dif r _) -> compare l r) $ diffs sls
        df = (\(((Dif x _):_):_) -> x) d

main = do
    n <- fmap read getLine
    a <- fmap ((map read) . words) getLine
    case solve n a of
        Nothing -> print $ -1
        Just b -> do
            print $ length b
            putStr $ intercalate " " $ map show $ sort b
    return ()

import Data.List (intercalate, sort, sortBy, nub)

data Dif = Dif Int Int

solve :: Int -> [Int] -> Maybe [Int]
solve 1 _ = Nothing
solve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]
solve n ls = case d of
        (_:[])                 -> Just [first - df, last + df]
        ((x@((Dif dl _):_)):((Dif dr _):_):[])
            | length x == 1
                && 2*dr == dl -> Just $ get x
        (((Dif dl _):_):x@((Dif dr _):_):_)
            | length x == 1
                && 2*dl == dr -> Just $ get x
        _                     -> Just []

    where

        sls = sort ls
        first = head sls
        last = head $ reverse $ sls

        diffs :: [Int] -> [Dif]
        diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))
        diffs _ = []

        groupBy :: [Dif] -> [[Dif]]
        groupBy xs@((Dif y _ ):_) = l : (groupBy r)
            where
                (l, r) = span (\(Dif z _) -> z == y) xs
        groupBy _ = []

        get :: [Dif] -> [Int]
        get ((Dif _ x) : ys) = x : (get ys)
        get [] = []

        d = groupBy $ sortBy (\(Dif l _) -> \(Dif r _) -> compare l r) $ diffs sls
        df = (\(((Dif x _):_):_) -> x) d

main = do
    n <- fmap read getLine
    a <- fmap ((map read) . words) getLine
    case solve n a of
        Nothing -> print $ -1
        Just b -> do
            print $ length b
            putStr $ intercalate " " $ map show $ nub $ sort b
    return ()

import Data.List (intercalate, sort, sortBy)

data Dif = Dif Int Int

solve :: Int -> [Int] -> Maybe [Int]
solve 1 _ = Nothing
solve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]
solve n ls = case d of
        (_:[])                 -> Just [first - df, last + df]
        ((x@((Dif dl _):_)):((Dif dr _):_):[])
            | length x == 1
                && 2*dr == dl -> Just $ get x
        (((Dif dl _):_):x@((Dif dr _):_):_)
            | length x == 1
                && 2*dl == dr -> Just $ get x
        _                     -> Just []

    where

        uniq :: [Int] -> [Int]
        uniq (x:xs@(y:_)) | x == y = uniq xs
        uniq (x:xs) = x : (uniq xs)
        uniq [] = []

        sls = uniq $ sort ls
        first = head sls
        last = head $ reverse $ sls

        diffs :: [Int] -> [Dif]
        diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))
        diffs _ = []

        groupBy :: [Dif] -> [[Dif]]
        groupBy xs@((Dif y _ ):_) = l : (groupBy r)
            where
                (l, r) = span (\(Dif z _) -> z == y) xs
        groupBy _ = []

        get :: [Dif] -> [Int]
        get ((Dif _ x) : ys) = x : (get ys)
        get [] = []

        d = groupBy $ sortBy (\(Dif l _) -> \(Dif r _) -> compare l r) $ diffs sls
        df = (\(((Dif x _):_):_) -> x) d

main = do
    n <- fmap read getLine
    a <- fmap ((map read) . words) getLine
    case solve n a of
        Nothing -> print $ -1
        Just b -> do
            print $ length b
            putStr $ intercalate " " $ map show $ sort b
    return ()

import Data.List (intercalate, sort, sortBy, nub)

data Dif = Dif Int Int

solve :: Int -> [Int] -> Maybe [Int]
solve 1 _ = Nothing
solve 2 (x:y:[]) | (abs (x - y)) `mod` 2 == 0 = Just [2*x-y, 2*y-x, (x+y) `div` 2]
solve n ls = case d of
        (_:[])                 -> Just [first - df, last + df]
        ((x@((Dif dl _):_)):((Dif dr _):_):[])
            | length x == 1
                && 2*dr == dl -> Just $ get x
        (((Dif dl _):_):x@((Dif dr _):_):_)
            | length x == 1
                && 2*dl == dr -> Just $ get x
        _                     -> Just []

    where

        sls = sort ls
        first = head sls
        last = head $ reverse $ sls

        diffs :: [Int] -> [Dif]
        diffs (a:b:c) = (Dif (b-a) $ (b+a) `div` 2) : (diffs (b:c))
        diffs _ = []

        groupBy :: [Dif] -> [[Dif]]
        groupBy xs@((Dif y _ ):_) = l : (groupBy r)
            where
                (l, r) = span (\(Dif z _) -> z == y) xs
        groupBy _ = []

        get :: [Dif] -> [Int]
        get ((Dif _ x) : ys) = x : (get ys)
        get [] = []

        d = groupBy $ sortBy (\(Dif l _) -> \(Dif r _) -> compare l r) $ diffs sls
        df = (\(((Dif x _):_):_) -> x) d

main = do
    n <- fmap read getLine
    a <- fmap ((map read) . words) getLine
    case solve n a of
        Nothing -> print $ -1
        Just b -> do
            let c = nub $ sort b
            print $ length c
            putStr $ intercalate " " $ map show $ c
    return ()


main=do{s<-g;u<-g;print$minimum$map(\i->sum$map fromEnum$zipWith(/=)(drop i(t s u))u)[0..l(t s u)-l u]}where l=length;r=replicate.l;g=getLine;t s u=r u '$'++s++r u '$'

import Control.Monad
import Data.List (tails)
eq l u t | l == 0 || null u = 0
         | null t = length u
         | head u == head t = eq (l-1) (tail u) (tail t)
         | otherwise = 1 + eq (l-1) (tail u) (tail t)
main = do
  s <- getLine
  u <- getLine
  let len = length u
      pad = replicate (len-1) '-'
  putStrLn . show . minimum $ map (eq len u) (tails $ pad ++ s ++ pad)

import List
main=interact$show.f.lines
l=length
f[s,u]=l u-maximum(map(l.filter id.zipWith(==)u).tails$(u>>"X")++s)

import Data.List
z[s,u]=length u-maximum(map(length.filter id.zipWith(==)u)$tails$map(const 'X')u++s)
main=interact$show.z.words

main = do
	s <- getLine
	u <- getLine
	print $ distance s u

distance :: String -> String -> Int
distance s u =
	let longS = ((replicate (length u) '\0') ++ s ++ (replicate (length u) '\0'))
	in  distance' longS u (length u) where
		distance' longS u d =
			if 	 length longS == length u
			then min (distU longS u) d
			else min (distU longS u) (distance' (tail longS) u d) where
				distU s1 s2 = foldr (\a b -> if a then b+1 else b) 0 (zipWith (/=) s1 s2)

{-# LANGUAGE ScopedTypeVariables#-}

main = do
	s <- getLine
	u <- getLine
	let lu = length u
	let p = (replicate (lu) '$')
	let ss = p ++ s ++ p
	let ssl = length ss
	print $ minimum $ map (\i -> diff (drop i ss) u) [0..ssl - lu]
		where diff x y = sum $ map fromEnum $ zipWith (/=) x y

main = do
	s <- getLine
	u <- getLine
	let lu = length u
	let p = (replicate lu '$')
	let ss = p ++ s ++ p
	let ssl = length ss
	print $ minimum $ map (\i -> diff (drop i ss) u) [0..ssl - lu]
		where diff x y = sum $ map fromEnum $ zipWith (/=) x y

import Data.List
z[s,u]=length u-maximum(map(length.filter id.zipWith(==)u)$tails s)
main=interact$show.z.words


main = getContents >>= print . solve . map read . tail . words

solve xs = fst . head . filter ((>=half).snd) $ zip [1 ..] $ scanl1 (+) xs
    where half = (1 + sum xs) `div` 2

import Data.Maybe

main = do
    _ <- getLine
    l <- getLine
    let plan = map read (words l) :: [Int]
    let ekvator = div (sum plan + 1) 2
    let res = (fromMaybe 1 (findMid ekvator plan)) where
        findMid = mid 1 0 where
                mid _ _ _ [] = Nothing
                mid ind sum_ ekvator_ (x:xs) =
                    if (ekvator_ > (sum_ + x)) then mid (ind + 1) (sum_ + x) ekvator_ xs
                    else Just ind
    putStrLn (show res)

import Data.Maybe

main = do
    _ <- getLine
    line <- getLine
    let list = map read $ words line :: [Int]
    let s = ((sum list) + 1) `div` 2
    putStrLn (show $ fromMaybe 1 $ find s list)

find :: Int -> [Int] -> Maybe Int
find = aux 1 0
    where
        aux :: Int -> Int -> Int -> [Int] -> Maybe Int
        aux _ _ _ [] = Nothing
        aux i s y (x:xs)
            | y <= (s+x) = Just i
            | otherwise = aux (i+1) (s+x) y xs

import Data.List
import Data.Maybe

main = do
    _ <- getLine
    line <- getLine
    let list = map readInt $ words line
    let s = ((sum list) + 1) `div` 2
    let y = fromMaybe 0 $ findInd s (\y a -> a > y) $ partSum list
    putStrLn (show y)

readInt :: String -> Integer
readInt x = read x :: Integer

partSum :: [Integer] -> [Integer]
partSum []   = [0]
partSum (x:[]) = [x]
partSum (x:xs) = x:(map (\y -> y + x) $ partSum xs)

findInd :: b -> (b -> a -> Bool) -> [a] -> Maybe Int
findInd y pred = findIndex $ pred y

import Data.List
import Data.Maybe

main = do
    _ <- getLine
    line <- getLine
    let list = map readInt $ words line
    let s = ((sum list) + 1) `div` 2
    let y = fromMaybe 0 $ findInd s (\y a -> a > y) $ partSum list
    putStrLn (show (y - 1))

readInt :: String -> Integer
readInt x = read x :: Integer

partSum :: [Integer] -> [Integer]
partSum []   = [0]
partSum (x:[]) = [x]
partSum (x:xs) = x:(map (\y -> y + x) $ partSum xs)

findInd :: b -> (b -> a -> Bool) -> [a] -> Maybe Int
findInd y pred = findIndex $ pred y

main = getContents >>= print . solve . map read . tail . words

solve xs = length $ takeWhile (<=half) $ scanl1 (+) xs
    where half = (1 + sum xs) `div` 2