inLine :: IO [Integer]
inLine = (map read . words) `fmap` getLine

main :: IO ()
main = do
  n <- getLine
  xs <- inLine
  ys <- inLine
  zs <- inLine
  let a = sum xs
      b = sum ys
      c = sum zs
  print $ a - b
  print $ b - c

import Data.List

parseList :: String -> [Integer]
parseList str = map read (words str)

getAnswer :: [Integer] -> [Integer] -> [Integer] -> (Integer, Integer)
getAnswer first second third = (findRemoved f s, findRemoved s t)
    where f = sort first
          s = sort second
          t = sort third

findRemoved :: [Integer] -> [Integer] -> Integer
findRemoved [x] [] = x
findRemoved [] [y] = y
findRemoved [] [] = 0
findRemoved (x:xs) (y:ys) = if x == y
                            then findRemoved xs ys
                            else x

main :: IO ()
main = do
    n <- getLine
    first <- getLine
    second <- getLine
    third <- getLine
    let (a, b) = getAnswer (parseList first) (parseList second) (parseList third)
    putStrLn $ show a
    putStrLn $ show b

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import Text.Printf

readInt = ( readLn :: IO Int )
getInts = map ( read :: String -> Int ) . words <$> getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = do
	getLine
	[ a, b, c ] <- map sort <$> replicateM 3 getInts
	print $ f a b
	print $ f b c

f (a:as) [] = a
f (a:as) (b:bs)
	| a == b = f as bs
	| otherwise = a

module Main (main)
    where

import Control.Monad (replicateM)

readInts :: String -> [Int]
readInts = map read . words

main :: IO ()
main = putStr . toStr . solve . map readInts =<< (getLine >> replicateM 3 getLine)
    where solve [as,bs,cs] = let (x,y) = (sum as, sum bs)
                              in [x - y, y - sum cs]
          toStr = unlines . map show

-- https://wiki.haskell.org/Performance
-- http://hackage.haskell.org/package/vector
-- https://wiki.haskell.org/Unboxed_type
-- http://hackage.haskell.org/package/vector-0.12.0.1/docs/Data-Vector-Generic.html

conv lst uu
  | (null lst) = uu
  | otherwise = conv (tail lst) (((read (head lst))::Int) : uu)

main = do
  ff <- getLine
  gg <- getLine
  hh <- getLine
  dd <- getLine

  let aa = conv (words gg) []
      bb = conv (words hh) []
      cc = conv (words dd) []

  putStrLn (show (sum aa - sum bb))
  putStrLn (show (sum bb - sum cc))

import Data.List

ans :: [Int] -> [Int] -> Int
ans a b = f (sort a) (sort b) where
	f [x] _ = x
	f (x:xs) (p:ps)
		| x /= p = x
		| otherwise = f xs ps

main :: IO()
main = do
	n <- getLine
	s1 <- fmap (map read . words) getLine
	s2 <- fmap (map read . words) getLine
	s3 <- fmap (map read . words) getLine
	putStrLn $ (show $ ans s1 s2)
	putStrLn $ (show $ ans s2 s3)

-- http://codeforces.com/problemset/problem/519/B

import Data.List
import Data.Char
getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

main = do
	lns <- getLines 4

	let
		n = read $ lns !! 0 :: Int
		e1 = map read $ words $ lns !! 1 :: [Int]
		e2 = map read $ words $ lns !! 2 :: [Int]
		e3 = map read $ words $ lns !! 3 :: [Int]

	putStrLn $ show $ findRemainder e1 e2
	putStrLn $ show $ findRemainder e2 e3

-- If both list of errors are constructed purely from
-- integers the fixed errors is the remainder of the
-- difference betweeen the non-fixed list and fixed list
findRemainder :: [Int] -> [Int] -> Int
findRemainder (x:[]) [] = x
findRemainder (x:xs) (y:ys) = x - y + (findRemainder xs ys)

main = do
  getLine
  a <- fmap (sum . map read . words) getLine
  b <- fmap (sum . map read . words) getLine
  c <- fmap (sum . map read . words) getLine

  print $ a - b
  print $ b - c

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Control.Monad
import Control.Monad.ST.Safe
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  getLine >>= \n -> (mapM_ putStrLn).solve =<< (forM [1..3] $ \i ->  getLine>>= \j -> return $ words j)
solve::[[String]]->[String]
solve [x,y,z] = let sx = sort x; sy= sort y; sz= sort z in [slv1 sx sy, slv1 sy sz]
slv1 (x:xs) [] = x
slv1 (x:xs) (y:ys) = if x/=y then x else slv1 xs ys

-- Codeforces 519B

import Control.Monad

main :: IO ()
main = do
    n <- fmap read getLine :: IO Integer
    fmap (map read . words) getLine >>= solve 2

solve :: Integer -> [Integer] -> IO ()
solve 0 _ = return ()
solve n xs = do
    nxt <- fmap (map read . words) getLine
    print ((sum xs) - (sum nxt))
    solve (n-1) nxt

import Control.Applicative
import Data.List
import qualified Data.Map as M
import Data.Maybe
import qualified Data.ByteString.Char8 as C

f a b = if a==b then Nothing else Just (a-b)

main=do
    n<-     read  <$> getLine::IO Integer
    [q1,q2,q3]<-  map (map (fst.fromJust.C.readInteger) ) <$> map (C.words) <$> C.lines <$> C.getContents::IO [[Integer]]
    let [m1,m2,m3] = map (\z-> M.fromListWith (+) $ zip z (repeat 1)) [q1,q2,q3]
    print  $ fst $ head $ M.toList $ M.differenceWith f m1 m2
    print  $ fst $ head $ M.toList $ M.differenceWith f m2 m3

main :: IO ()
main = getContents >>= mapM_ print . solve . map (map read . words) . tail . lines

solve :: [[Integer]] -> [Integer]
solve [ as, bs, cs ] = [ sum as - sum bs, sum bs - sum cs ]
solve _ = undefined

main=getContents>>=mapM_ print.f.map(map read.words).tail.lines
f[a,b,c]=[sum a-sum b,sum b-sum c]

main = interact $ unlines . map show . solve . parse
parse = map (sum . map read . words) . tail . lines
solve ns = zipWith (-) ns (tail ns) where

import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as B

readInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine
main = do
  B.getLine
  a <- readInts
  b <- readInts
  c <- readInts
  let [x,y,z] = map sum [a,b,c]
  putStrLn . unlines . map show $ [x-y,y-z]

import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as B

readInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine
main = do
  B.getLine
  a <- readInts
  b <- readInts
  c <- readInts
  let [x,y,z] = map sum [a,b,c]
  print $ x - y
  print $ y - z

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception hiding (mask)
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, runSTArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.IntMap.Strict as IM
import qualified Data.Set as S
import qualified Data.IntSet as IS
import Data.STRef
import GHC.Arr (Array, STArray, Ix(..))
import Debug.Trace

bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep n f=foldr((>>).f)(return())[0..n-1]
rev n f=foldr((>>).f.negate)(return())[1-n..0]
for :: Monad m => Int -> Int -> (Int -> m ()) -> m ()
for a b f=foldr((>>).f)(return())[a..b]
{-# INLINE rep #-}
{-# INLINE rev #-}
{-# INLINE for #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  n <- readLn :: IO Int
  xs <- map readInt.B.words <$> B.getLine
  ys <- map readInt.B.words <$> B.getLine
  zs <- map readInt.B.words <$> B.getLine
  putStr.unlines.map show $ solve (sort xs) (sort ys) (sort zs)

solve :: [Int] -> [Int] -> [Int] -> [Int]
solve xs ys zs = [go xs ys, go ys zs]
   where
     go (x:xs) (y:ys)
       | x == y = go xs ys
       | otherwise = x
     go [x] [] = x

import Control.Applicative

main = do
	_ <- getLine
	set1 <- sum . map read . words <$> getLine
	set2 <- sum . map read . words <$> getLine
	set3 <- sum . map read . words <$> getLine
	print $ set1 - set2
	print $ set2 - set3

import qualified Data.Set as S
import qualified Data.Map.Strict as M

import Data.List (foldl')
import Control.Monad (replicateM)

main :: IO ()
main = do
  _ <- getLine
  (b0:b1:b2:_) <- replicateM 3 (S.fromAscList . M.toAscList . buildDict . words <$> getLine)
  putStrLn $ fst . head $ S.toList (S.difference b0 b1)
  putStrLn $ fst . head $ S.toList (S.difference b1 b2)

  where
    buildDict = foldl' (\m s -> M.insertWith (\_ o -> o + 1) s 1 m) M.empty

import qualified Data.Set as S
import qualified Data.Map.Strict as M

import Data.List (foldl')
import Control.Monad (replicateM)

main :: IO ()
main = do
  _ <- getLine
  (b0:b1:b2:_) <- replicateM 3 (S.fromAscList . M.toAscList . buildDict . words <$> getLine)
  putStrLn $ fst . head $ S.toList (S.difference b0 b1)
  putStrLn $ fst . head $ S.toList (S.difference b1 b2)

  where
    buildDict = foldr (\s m -> M.insertWith (\_ o -> o + 1) s 1 m) M.empty

import Control.Applicative
import Data.List

solve :: [Int] -> [Int] -> Int
solve as bs = case filter (uncurry (/=)) $ zip as' bs' of
                (a, _):_  -> a
                otherwise -> last as'
              where
                as' = sort as
                bs' = sort bs

main :: IO ()
main = do
  _ <- getLine
  as <- map read <$> words <$> getLine
  bs <- map read <$> words <$> getLine
  cs <- map read <$> words <$> getLine
  print $ solve as bs
  print $ solve bs cs

module Main (main) where

import Control.Monad
import Data.Functor

isDigit x = x>='0' && x<='9'
split f l@(a:as) lft
	| f a = split f as (a:lft)
	| otherwise = (reverse lft, as)
split _ [] lft = (reverse lft, [])
readInts::String -> [Integer]
readInts [] = []
readInts l@(x:xs)
	| isDigit x = let (a, b) = split isDigit l [] in (read a):(readInts b)
	| otherwise = readInts xs

main = do
	_ <- getLine
	a <- (sum.readInts) <$> getLine
	b <- (sum.readInts) <$> getLine
	c <- (sum.readInts) <$> getLine
	print $ a-b
	print $ b-c

import Control.Applicative
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.Maybe

main=do
	getLine
	a<-  sort.map (fst.fromJust.C.readInt).C.words  <$> C.getLine::IO [Int]
	b<-  sort.map (fst.fromJust.C.readInt).C.words  <$> C.getLine::IO [Int]
	c<-  sort.map (fst.fromJust.C.readInt).C.words  <$> C.getLine::IO [Int]
	print $ fst $ head $ filter (\z-> fst z /= snd z) $ zip a (b++[0])
        print $ fst $ head $ filter (\z-> fst z /= snd z) $ zip b (c++[0])

import Control.Monad

getSumOfLine = do
  line <- getLine
  return(sum([read n :: Int | n <- words line]))

main = do
  getLine
  [a,b,c] <- replicateM 3 getSumOfLine
  print(a-b)
  print(b-c)

main = do
  getLine
  m <- sequence $ replicate 3 getLine
  let mf = map (map read . words) m
  let [mf1, mf2, mf3] = map sum mf
  print $ mf1 - mf2
  print $ mf2 - mf3

import Data.List
solve :: [Int] -> [Int] -> Int
solve [a] [] = a
solve (a:as) (b:bs)
  | a /= b    = a
  | otherwise = solve as bs
main = do
  getLine
  [as, bs, cs] <- getContents >>= return. map (Data.List.sort. map read. words). lines
  print $ solve as bs
  print $ solve bs cs

import Control.Applicative ((<$>))
import qualified Data.ByteString.Char8 as B
import Data.List

readInt bs = case B.readInt bs of
                  Just (n,_) -> n
                  _-> error $ "readInt error : bs = " ++ show bs

solve (x:_) [] = x
solve [] (y:_) = y
solve [] [] = 0
solve (x:xs) (y:ys)
    | x /= y = x
    | otherwise = solve xs ys

main :: IO ()
main = do
    _ <- getLine
    lst0 <- map readInt . B.words <$> B.getLine
    lst1 <- map readInt . B.words <$> B.getLine
    lst2 <- map readInt . B.words <$> B.getLine
    let [a, b, c] = map sum [lst0, lst1, lst2]
    print $ a - b
    print $ b - c

import Control.Applicative ((<$>))
import qualified Data.ByteString.Char8 as B
import Data.List

readInt bs = case B.readInt bs of
                  Just (n,_) -> n
                  _-> error $ "readInt error : bs = " ++ show bs

solve (x:_) [] = x
solve [] (y:_) = y
solve [] [] = 0
solve (x:xs) (y:ys)
    | x /= y = x
    | otherwise = solve xs ys

main :: IO ()
main = do
    _ <- getLine
    lst0 <- map readInt . B.words <$> B.getLine
    lst1 <- map readInt . B.words <$> B.getLine
    lst2 <- map readInt . B.words <$> B.getLine
    let a = sort lst0
        b = sort lst1
        c = sort lst2
    let (e1, e2) = (solve a b, solve b c)
    print e1
    print e2

import Control.Applicative ((<$>))
import qualified Data.ByteString.Char8 as B
import Data.List

readInt bs = case B.readInt bs of
                  Just (n,_) -> n
                  _-> error $ "readInt error : bs = " ++ show bs

main :: IO ()
main = do
    _ <- getLine
    lst0 <- map readInt . B.words <$> B.getLine
    lst1 <- map readInt . B.words <$> B.getLine
    lst2 <- map readInt . B.words <$> B.getLine
    let [a, b, c] = map sum [lst0, lst1, lst2]
    print $ a - b
    print $ b - c

import Data.List

solve :: (Num a, Eq a) => [a] -> [a] -> a
solve (x:_) [] = x
solve [] (y:_) = y
solve [] [] = 0
solve (x:xs) (y:ys)
    | x /= y = x
    | otherwise = solve xs ys

main :: IO ()
main = do
    _ <- getLine
    lst0 <- getLine >>= return . map (\c -> read c::Integer) . words
    lst1 <- getLine >>= return . map (\c -> read c::Integer) . words
    lst2 <- getLine >>= return . map (\c -> read c::Integer) . words
    let a = sort lst0
        b = sort lst1
        c = sort lst2
    let (e1, e2) = (solve a b, solve b c)
    print e1
    print e2

import Data.List (sort)

process :: [Int] -> [Int] -> [Int] -> (Int,Int)
process xs ys zs = (f xs' ys', f ys' zs')
    where
        xs' = sort xs
        ys' = sort ys
        zs' = sort zs
        f [a] [] = a
        f (a:as) (b:bs)
            | a == b = f as bs
            | otherwise = a

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    as <- fmap (map readInt.words) getLine
    bs <- fmap (map readInt.words) getLine
    cs <- fmap (map readInt.words) getLine
    let (t1,t2) = process as bs cs
    print t1
    print t2

module Main where

import Control.Monad

import Data.Set (Set)
import qualified Data.Set as S

import Data.List (sort)

main = do
  c <- getContents
  let (_:l1:l2:l3:_) = lines c
  let e1 = sort . map (read :: String -> Int) . words $ l1
  let e2 = sort . map (read :: String -> Int) . words $ l2
  let e3 = sort . map (read :: String -> Int) . words $ l3
  print $ firstDifferance e1 e2
  print $ firstDifferance e2 e3

{-
  let s1 = S.fromList e1
  let s2 = S.fromList e2
  let s3 = S.fromList e3
  let disappeared = s1 S.\\ s3
  let r1 = disappeared S.\\ s2
  let r2 = disappeared S.\\ r1
  print r1
  print r2
-}

firstDifferance :: [Int] -> [Int] -> Int
firstDifferance [] [] = undefined
firstDifferance (x:_) [] = x
firstDifferance (x:xs) (y:ys)
  | x == y    = firstDifferance xs ys
  | otherwise = x

import Data.ByteString.Builder
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe
import Data.Int
-- meat

solve :: [[Int64]] -> [[Int64]]
solve [[_], as, bs, cs] = [[sas - sbs], [sbs - scs]]
    where [sas, sbs,scs] = fmap sum [as,bs,cs]
solve _ = error "you're fucked"

-- shit
main :: IO ()
main = BS.interact $ outputIntMatrixBS . solve . inputNumMatrixBS

inputNumMatrixBS :: (Num a) => BS.ByteString ->[[a]]
inputNumMatrixBS = parseMatrixBS . matrifyBS

outputIntMatrixBS :: (Integral a) => [[a]] -> BS.ByteString
outputIntMatrixBS = unmatrifyBS . unparseMatrixBs

matrifyBS :: BS.ByteString -> [[BS.ByteString]]
matrifyBS = fmap BS.words . BS.lines

parseMatrixBS :: (Num a) => [[BS.ByteString]] ->[[a]]
parseMatrixBS = fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger

unparseMatrixBs :: (Integral a) => [[a]] -> [[BS.ByteString]]
unparseMatrixBs = fmap.fmap $ (toLazyByteString . integerDec . toInteger)

unmatrifyBS :: [[BS.ByteString]] -> BS.ByteString
unmatrifyBS = BS.unlines . fmap BS.unwords

import Control.Applicative
main = do
  getLine
  m <- sequence $ replicate 3 getLine
  let mf = map (map read . words) m
  let [mf1, mf2, mf3] = map msort mf
  print $ gone2 mf1 mf2
  print $ gone2 mf2 mf3
qsort :: Ord a => [a] -> [a]
qsort [] = []
qsort [x] = [x]
qsort (x:xs) = (qsort $ filter (<x) xs) ++ [x] ++ (qsort $ filter (>= x) xs)
msort :: Ord a => [a] -> [a]
msort [] = []
msort [x] = [x]
msort x = (msort $ take (quot len 2) x) ++ (msort $ drop (quot len 2) x)
  where len = length x
th :: Int -> [a] -> a
th 1 a = head a
th n a = th (n-1) (tail a)
gone :: [Int] -> [Int] -> Int
gone x y = th len x
  where len = ((length . takeWhile (==True) . getZipList) $ (==) <$> (ZipList x) <*> (ZipList y)) + 1
gone2 :: [Int] -> [Int] -> Int
gone2 x y = (head . dropWhile (==0) . getZipList) $ (\u v -> if (u==v) then 0 else u) <$> (ZipList x) <*> (ZipList (y++[0]))


main = getContents >>= print . f . map read . tail . words
f x = sum . zipWith (*) x . scanr1 (+) $ map (1 -) x

main = getContents >>= print . fst . foldl f (0, 0) . map read . tail . words
f (a, b) c
  | c == 0 = (a + b, b)
  | c == 1 = (a, b + 1)


{-# LANGUAGE TupleSections #-}
import           Data.Array
import qualified Data.Set

-- https://hackage.haskell.org/package/split-0.2.3.4/docs/src/Data.List.Split.Internals.html#chunksOf
build :: ((a -> [a] -> [a]) -> [a] -> [a]) -> [a]
build g = g (:) []

chunksOf :: Int -> [e] -> [[e]]
chunksOf i ls = map (take i) (build (splitter ls))  where
    splitter :: [e] -> ([e] -> a -> a) -> a -> a
    splitter [] _ n = n
    splitter l  c n = l `c` splitter (drop i l) c n

parseMaze :: Int -> Int -> String -> Array (Int, Int) Char
parseMaze h w s = listArray ((1, 1), (h, w)) (filter (/= '\n') s)

printMaze :: Int -> Int -> Array (Int, Int) Char -> String
printMaze h w m = unlines $ chunksOf w $ elems m

findStart m = fst $ head $ filter (\x -> snd x == '.') $ assocs m

dfs :: Int -> Int -> Array (Int, Int) Char -> [(Int, Int)]
dfs h w maze =
    let (starty, startx) = findStart maze :: (Int, Int)
    in  dfs' [(starty, startx)] [] Data.Set.empty
  where
    dfs' [] traversal _ = traversal
    dfs' ((y, x) : toVisit) traversal visited =
        let traversal' = (y, x):traversal
            neighbors =
                    [ (yy, xx)
                    | (dy, dx) <- [(-1, 0), (1, 0), (0, -1), (0, 1)]
                    , let (yy, xx) = (y + dy, x + dx)
                    , 1 <= yy && yy <= h
                    , 1 <= xx && xx <= w
                    , maze ! (yy, xx) == '.'
                    , (yy, xx) `Data.Set.notMember` visited
                    ]
            toVisit' = neighbors ++ toVisit
            visited' = Data.Set.union visited (Data.Set.fromList neighbors)
        in  dfs' toVisit' traversal' visited'

main = do
    --let first = "500 500 249999" -- XXX
    --let rest = unlines $ replicate 500 (replicate 500 '.')
    first <- getLine
    rest <- getContents

    let [h, w, k] = (map read . words) first
    let maze  = parseMaze h w rest
    let topo  = dfs h w maze
    let maze' = maze // map (, 'X') (take k topo)
    putStrLn (printMaze h w maze')

import Control.Applicative
import Data.List as L
import Data.Tuple
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Set as S

data Cell = Cell {row::Int,col::Int} deriving (Show,Eq,Ord)

main = do
    [n,m,k] <- map read <$> words <$> getLine :: IO[Int]
    lab <- M.fromList <$> foldl1' (++) <$>
          map (\(row,list) -> map (\(col,e) -> (Cell row col,e)) $ zip [0..] list  ) <$>
          zip [0..] <$> lines <$> getContents
    let solution n m k lab = let
            neighbours cells visited= do
                original <- cells
                t        <- [(-1,0),(1,0)]
                (i,j)    <- [t,swap t]
                let x = row original + i
                    y = col original + j
                    cell = Cell x y
                if   x >= 0 && x < n  && y >= 0  && y < m  &&  lab M.! cell == '.' && S.notMember cell visited
                    then return cell
                    else []
            walk::[(Int,Cell)] -> S.Set Cell -> S.Set Cell -> [Cell]-> Int -> [(Int,Cell)]
            walk levels prev cur strip level = let
                nextSet = S.fromList $ (neighbours strip $ S.union prev cur )
                next = S.toList nextSet
                in if null next
                    then levels
                    else walk (zip (repeat level) next ++ levels) cur nextSet next (level + 1)
            start = fst $ fromJust $ find ((== '.') . snd) $ M.assocs lab
            walkList = walk [(0,start)] S.empty (S.singleton start) [start] 1
            wall = S.fromList $ map snd $ take k $ reverse $ sort walkList
            result = [[ if lab M.! cell == '#'
                    then '#'
                    else if S.member cell wall
                        then 'X'
                        else '.'
                | j <- [0..m-1], let cell = Cell i j] | i <- [0..n-1] ]
            countX = length $ filter (== 'X' ) $ foldl1' (++) result
            in result{- ++[show countX]-}
    mapM putStrLn $ solution n m k lab

import Data.Graph
import Data.Set
main = interact $ f . Prelude.map words . lines

g x r c s1 = zip (repeat x) $ Prelude.filter (\i-> member i s1) $ concat [c1, c2, c3, c4]
  where c1 = if (quot x c) == quot (x-1) c then [x-1] else []
        c2 = if (quot x c) == quot (x+1) c then [x+1] else []
        c3 = if x-c >= 0 then [x-c] else []
        c4 = if x+c <= (r*c-1) then [x+c] else []

splitEvery _ [] = []
splitEvery n xs = as : splitEvery n bs
  where (as,bs) = Prelude.splitAt n xs

f (x:xs) = ans
  where (r:c:conn:_) = Prelude.map read x
        ccxs = concat (concat xs)
        mat = [i | (i, v) <- zip ([0..(r*c-1)]) ccxs, v=='.']
        s1 = fromList mat
        e = concat $ Prelude.map (\i -> g i r c s1) mat
        tvl = Prelude.filter (\i -> member i s1) $ topSort (buildG (0, r*c-1) e)
        doors = fromList $ Prelude.drop ((length mat)-conn) tvl
        insertdoor (i,k) = if (member i doors) && k=='.' then 'X' else k
        ans = unlines $ splitEvery c $ Prelude.map insertdoor $ zip [0..] ccxs

import Data.Array
import Control.Monad
import Data.Graph
import Data.Tree
main = do
  [n,m,k] <- map read . words <$> getLine
  g0 <- listArray ((1,1),(n,m)) . concat . lines <$> getContents
  let neighbors (i,j) = filter ((== '.') . (g0!)) $
                        filter (inRange (bounds g0))
                        [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]
      (g,v2n,k2v) = graphFromEdges $ map (\p -> (p,p,neighbors p)) $
                                     filter ((== '.') . (g0!)) (indices g0)
      [f] = dff g
      g' = g0 // take k (foldTree h f [])
      h a bs = foldr (.) ((p,'X') :) bs where (p,_,_) = v2n a
  forM_ [1..n] $ \i -> do
    forM_ [1..m] $ \j -> putChar $ g' ! (i,j)
    putChar '\n'

import Control.Applicative
import Data.List as L
import Data.Tuple
import Data.Maybe
import qualified Data.Map as M
import qualified Data.Set as S

data Cell = Cell {row::Int,col::Int} deriving (Show,Eq,Ord)

main = do
    [n,m,k] <- map read <$> words <$> getLine :: IO[Int]
    lab <- M.fromList <$> foldl1' (++) <$>
          map (\(row,list) -> map (\(col,e) -> (Cell row col,e)) $ zip [0..] list  ) <$>
          zip [0..] <$> lines <$> getContents
    let solution n m k lab = let
            walk::[(Int,Cell)] -> S.Set Cell -> S.Set Cell -> [Cell]-> Int -> [(Int,Cell)]
            walk levels prev cur strip level = let
                visited = S.union prev cur
                neighbours = do
                    original <- strip
                    t        <- [(-1,0),(1,0)]
                    (i,j)    <- [t,swap t]
                    let x = row original + i
                        y = col original + j
                        cell = Cell x y
                    if   x >= 0 && x < n  && y >= 0  && y < m  &&  lab M.! cell == '.' && S.notMember cell visited
                        then return cell
                        else []
                nextSet = S.fromList neighbours
                next = S.toList nextSet
                in if null next
                    then levels
                    else walk (zip (repeat level) next ++ levels) cur nextSet next (level + 1)
            start = fst $ fromJust $ find ((== '.') . snd) $ M.assocs lab
            walkList = walk [(0,start)] S.empty (S.singleton start) [start] 1
            wall = S.fromList $ map snd $ take k $ reverse $ sort walkList
            result = [[ if lab M.! cell == '#'
                    then '#'
                    else if S.member cell wall
                        then 'X'
                        else '.'
                | j <- [0..m-1], let cell = Cell i j] | i <- [0..n-1] ]
            countX = length $ filter (== 'X' ) $ foldl1' (++) result
            in result{- ++[show countX]-}
    mapM putStrLn $ solution n m k lab

{-# LANGUAGE TupleSections #-}
import           Data.Array
import qualified Data.Set

-- https://hackage.haskell.org/package/split-0.2.3.4/docs/src/Data.List.Split.Internals.html#chunksOf
build :: ((a -> [a] -> [a]) -> [a] -> [a]) -> [a]
build g = g (:) []

chunksOf :: Int -> [e] -> [[e]]
chunksOf i ls = map (take i) (build (splitter ls))  where
    splitter :: [e] -> ([e] -> a -> a) -> a -> a
    splitter [] _ n = n
    splitter l  c n = l `c` splitter (drop i l) c n

parseMaze :: Int -> Int -> String -> Array (Int, Int) Char
parseMaze h w s = listArray ((1, 1), (h, w)) (filter (/= '\n') s)

printMaze :: Int -> Int -> Array (Int, Int) Char -> String
printMaze h w m = unlines $ chunksOf w $ elems m

findStart m = fst $ head $ filter (\x -> snd x == '.') $ assocs m

dfs :: Int -> Int -> Array (Int, Int) Char -> [(Int, Int)]
dfs h w maze =
    let (starty, startx) = findStart maze :: (Int, Int)
    in  dfs' [(starty, startx)] [] Data.Set.empty
  where
    dfs' [] traversal _ = traversal
    dfs' ((y, x) : toVisit) traversal visited =
        let traversal' = (y, x):traversal
            neighbors =
                    [ (yy, xx)
                    | (dy, dx) <- [(-1, 0), (1, 0), (0, -1), (0, 1)]
                    , let (yy, xx) = (y + dy, x + dx)
                    , 1 <= yy && yy <= h
                    , 1 <= xx && xx <= w
                    , maze ! (yy, xx) == '.'
                    , (yy, xx) `Data.Set.notMember` visited
                    ]
            toVisit' = neighbors ++ toVisit
            visited' = Data.Set.union visited (Data.Set.fromList neighbors)
        in  dfs' toVisit' traversal' visited'

main = do
    --first <- getLine
    let first = "500 500 249999" -- XXX
    let [h, w, k] = (map read . words) first
    --rest <- getContents
    let rest = unlines $ replicate 500 (replicate 500 '.')

    let maze  = parseMaze h w rest
    let topo  = dfs h w maze
    let maze' = maze // map (, 'X') (take k topo)
    putStrLn (printMaze h w maze')

import Data.Set
import Data.Array
main = interact $ f . Prelude.map words . lines

-- visited empty set
dfs mat start@(i,j) visited = start:(concat l)
  where cvisited = insert start visited
        dir x = if (member x mat) && (not (member x cvisited)) then dfs mat x cvisited else []
        l = Prelude.map dir [(i, j+1),
                             (i+1, j),
                             (i-1, j),
                             (i, j-1)]

f (x:xs) = ans
  where (r:c:conn:_) = Prelude.map read x
        xsarr = array ((1, 1), (r, c)) $ zip [(i, j) | i <- [1..r], j <- [1..c]] (concat (concat xs))
        mat = fromList [(i, j) | i <- [1..r], j <- [1..c], (xsarr ! (i, j)) == '.']
        tvl = dfs mat (minimum mat) empty
        doors = fromList $ Prelude.drop ((length mat)-conn) tvl
        insertdoor i j k = if member (i, j) doors then 'X' else k
        ans = unlines [[ insertdoor row col v | (col, v) <- zip [1..c] val] | (val, row) <- zip (concat xs) [1..r]]

import Data.Set
import Data.Array
main = interact $ f . Prelude.map words . lines

dfs mat start@(i,j) visited = start:(concat [v1, v2, v3, v4])
  where vp = insert start visited
        dir x v = if (member x mat) && (not (member x v)) then dfs mat x v else []
        v1 = dir (i, j+1) vp
        v2 = dir (i+1, j) $ union vp $ fromList v1
        v3 = dir (i-1, j) $ union vp $ fromList v2
        v4 = dir (i, j-1) $ union vp $ fromList v3

f (x:xs) = ans
  where (r:c:conn:_) = Prelude.map read x
        mat = fromList [(i, j) | ((i, j), v) <- zip (range ((1, 1), (r,c))) (concat (concat xs)), v=='.']
        tvl = dfs mat (minimum mat) empty
        doors = fromList $ Prelude.drop ((length mat)-conn) tvl
        insertdoor i j k = if member (i, j) doors then 'X' else k
        ans = unlines [[ insertdoor row col v | (col, v) <- zip [1..c] val] | (val, row) <- zip (concat xs) [1..r]]

{-# LANGUAGE FlexibleContexts #-}
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad
import Control.Monad.ST
main = do
  [n,m,k] <- map read . words <$> getLine
  gc0 <- concat . lines <$> getContents
  forM_ [1..n] $ \i -> do
    forM_ [1..m] $ \j -> putChar $ solve n m k gc0 ! (i,j)
    putChar '\n'
solve n m k gc0 = runSTUArray $ do
  let bs = ((1,1),(n,m))
  g <- newListArray bs gc0 :: ST s (STUArray s (Int,Int) Char)
  let neighbors (i,j) = filterM (fmap (== '.') . readArray g) $ filter (inRange bs) [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]
      go 0 _ = return ()
      go k (s:ss) = do
        [n] <- neighbors s
        writeArray g s 'X'
        ns' <- neighbors n
        case ns' of [n'] -> go (k-1) (n:ss)
                    _    -> go (k-1) ss
  go k =<< filterM (fmap ((== 1) . length) . neighbors) (range bs)
  return g

{-# LANGUAGE FlexibleContexts #-}
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad
import Control.Monad.ST
import Data.List
import Control.Arrow
main = do
  [n,m,k] <- map read . words <$> getLine
  gc0 <- concat . lines <$> getContents
  forM_ [1..n] $ \i -> do
    forM_ [1..m] $ \j -> putChar $ solve n m k gc0 ! (i,j)
    putChar '\n'
solve n m k gc0 = runSTUArray $ do
  let bs = ((1,1),(n,m))
  g <- newListArray bs gc0 :: ST s (STUArray s (Int,Int) Char)
  let neighbors (i,j) = filterM (fmap (== '.') . readArray g) $ filter (inRange bs) [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]
      go 0 _ = return ()
      go k (s:ss) = do
        v <- readArray g s
        if v /= '.' then go k ss else do
          ns <- neighbors s
          writeArray g s 'X'
          ns' <- filterM (fmap ((== 1) . length) . neighbors) ns
          go (k-1) (ns' ++ ss)
  go k =<< fmap (map snd . sort) . mapM (runKleisli $ Kleisli (fmap length . neighbors) &&& arr id) =<< filterM (fmap (== '.') . readArray g) (range bs)
  return g

{-# LANGUAGE FlexibleContexts #-}
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad
import Control.Monad.ST
import Data.List
import Control.Arrow
main = do
  [n,m,k] <- map read . words <$> getLine
  gc0 <- concat . lines <$> getContents
  forM_ [1..n] $ \i -> do
    forM_ [1..m] $ \j -> putChar $ solve n m k gc0 ! (i,j)
    putChar '\n'
solve n m k gc0 = runSTUArray $ do
  let bs = ((1,1),(n,m))
  g <- newListArray bs gc0 :: ST s (STUArray s (Int,Int) Char)
  let neighbors (i,j) = filterM (fmap (== '.') . readArray g) $ filter (inRange bs) [(i-1,j),(i+1,j),(i,j-1),(i,j+1)]
      go 0 _ = return ()
      go k (s:ss) = do
        ns <- neighbors s
        writeArray g s 'X'
        ns' <- filterM (fmap ((== 1) . length) . neighbors) ns
        go (k-1) (ns' ++ ss)
  go k =<< fmap (map snd . sort) . mapM (runKleisli $ Kleisli (fmap length . neighbors) &&& arr id) =<< filterM (fmap (== '.') . readArray g) (range bs)
  return g

import Control.Applicative
import Data.List as L
import Data.Tuple
import Data.Maybe
import Data.Map (fromList,(!),assocs,showTree)
import qualified Data.Set as S

data Cell = Cell {row::Int,col::Int} deriving Show
instance Eq Cell where
	x == y = row x == row y && col x == col y
instance Ord Cell where	x `compare` y = (row x, col x) `compare` (row y,col y)
data Walk = Walk { remains:: Int, visited::S.Set Cell, collected::S.Set Cell } deriving Show

main = do
	[n,m,k] <- map read <$> words <$> getLine :: IO[Int]
	lab <- fromList <$> foldl1' (++) <$>
		  map (\(row,list) -> map (\(col,e) -> (Cell row col,e)) $ zip [0..] list  ) <$>
		  zip [0..] <$> lines <$> getContents
	let solution n m k lab = let
		neighbours visited cell = filter valid [Cell (row cell+i) (col cell+j)| t <- [(-1,0),(1,0)], (i,j)<- [t,swap t]] where
			valid cell = row cell >= 0 && row cell< n && col cell>= 0 && col cell< m && S.notMember cell visited && lab ! cell == '.'
		walkLab::Cell -> Walk -> Walk
		walkLab cell walk = let
			visitMe walk = Walk (remains walk) (S.insert cell $ visited walk) (collected walk)
			collectMe walk = if (remains walk ) == 0 then visitMe walk
				else Walk (remains walk - 1) (S.insert cell $ visited walk ) (S.insert cell $ collected walk)
			in collectMe $ foldr walkLab (visitMe  walk) (neighbours (visited walk ) cell)
		found = collected $ walkLab (fst $ fromJust $ find ((== '.') . snd) $ assocs lab) (Walk k S.empty S.empty )
		in [[ if lab ! cell == '#' then '#' else if S.member cell found then 'X' else '.' | j <- [0..m-1], let cell = Cell i j] | i <- [0..n-1] ]

		--neighbours S.empty $ Cell 0 1
	mapM putStrLn $ solution n m k lab

import Control.Applicative
import Data.List as L
import Data.Tuple
import Data.Maybe
import Data.Map (fromList,(!),assocs,showTree)
import qualified Data.Set as S

data Cell = Cell {row::Int,col::Int} deriving Show
instance Eq Cell where
	x == y = row x == row y && col x == col y
instance Ord Cell where	x `compare` y = (row x, col x) `compare` (row y,col y)
data Walk = Walk { remains:: Int, visited::S.Set Cell, collected::S.Set Cell } deriving Show

main = do
	[n,m,k] <- map read <$> words <$> getLine :: IO[Int]
	lab <- fromList <$> foldl1' (++) <$>
		  map (\(row,list) -> map (\(col,e) -> (Cell row col,e)) $ zip [0..] list  ) <$>
		  zip [0..] <$> lines <$> getContents
	let solution n m k lab = let
		neighbours visited cell = filter valid [Cell (row cell+i) (col cell+j)| t <- [(-1,0),(1,0)], (i,j)<- [t,swap t]] where
			valid cell = row cell >= 0 && row cell< n && col cell>= 0 && col cell< m && S.notMember cell visited && lab ! cell == '.'
		walkLab::Cell -> Walk -> Walk
		walkLab cell walk = let
			visitMe walk = Walk (remains walk) (S.insert cell $ visited walk) (collected walk)
			collectMe walk = if (remains walk ) == 0 then visitMe walk
				else Walk (remains walk - 1) (S.insert cell $ visited walk ) (S.insert cell $ collected walk)
			in collectMe $ foldr walkLab (visitMe  walk) (neighbours (visited walk ) cell)
		found = collected $ walkLab (fst $ fromJust $ find ((== '.') . snd) $ assocs lab) (Walk k S.empty S.empty )
		in [[ if lab ! cell == '#' || S.member cell found then '#' else '.' | j <- [0..m-1], let cell = Cell i j] | i <- [0..n-1] ]

		--neighbours S.empty $ Cell 0 1
	mapM putStrLn $ solution n m k lab


import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
--import Data.Array.Unboxed

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    _ <- getInt
    a <- replicateM (n - 2) getInt
    _ <- getInt
    let
      stuck = negate 1
      totMoves = foldl' (+) 0 [quot (v + 1) 2 | v <- a]
      ans = case  a  of
        [v] | odd v  -> stuck
        _   | any (> 0) a && all (< 2) a  -> stuck
            | otherwise -> case  filter (> 0) a  of
                [3] -> stuck
                [v] | odd v  -> totMoves + 1 -- very nasty edge case
                -- hopefully I didn't miss more
                _ -> totMoves
    pure $ putInts [ans]

type SP = State P.ByteString
type S = StateT P.ByteString

dropSpace :: P.ByteString -> P.ByteString
dropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough

--getNext :: Monad m => S m P.ByteString
--getNext = state $ P.span (> ' ') . dropSpace

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun inp
  P.putStr $ toLazyByteString outp

import Control.Monad (forM_)

import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet

import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import qualified Data.Text.Read as Text

solve :: Int -> [Int] -> Int
solve 3 [x, y, z]
   | odd y      = -1
   | otherwise  = y `div` 2
solve n lst
   | all ((==) 1) innerList  = -1
   | otherwise               = (totalSum + oddCount) `div` 2
   where innerList = init $ tail lst
         totalSum  = sum innerList
         oddCount  = length $ filter odd innerList

textToInt :: Text -> Int
textToInt text =
   case Text.decimal text of
      Right (n, _) -> n

readInts :: Text -> [Int]
readInts = map textToInt . Text.words

handleCases:: Int -> [Text] -> [Int]
handleCases 0 _                   = []
handleCases t (line1:line2:rest)  = solve n a : handleCases (t-1) rest
   where n = textToInt line1
         a = readInts line2

main :: IO ()
main = do
   line1:rest <- Text.lines <$> Text.getContents
   let t     = textToInt line1
       res   = handleCases t rest
   Text.putStr $ Text.unlines $ map (Text.pack . show) res

parseInt :: String -> Int
parseInt number = (read number) :: Int

readInt :: IO Int
readInt = do
    number <- getLine
    pure $ parseInt number

readIntArr :: IO [Int]
readIntArr = do
    numbers <- getLine
    pure $ map parseInt $ words numbers

plus :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int)
plus (a, b, c) (d, e, f) = (a + d, b + e, c + f)

checkHelper :: [Int] -> (Int, Int, Int)
checkHelper []       = (0, 0, 0)
checkHelper (_ : []) = (0, 0, 0)
checkHelper (1 : xs) = (0, 0, 1) `plus` checkHelper xs
checkHelper (x : xs) = checkHelper xs `plus` if (x `mod` 2 == 0)
    then (1, 0, 0)
    else (0, 1, 0)

checkArr :: [Int] -> Bool
checkArr (x : xs) = od > 0 || (ev > 0 && ev + on > 1)
    where (od, ev, on) = checkHelper xs

countHelper :: [Int] -> Int
countHelper []       = 0
countHelper (x : []) = 0
countHelper (x : xs) = countHelper xs + (x + 1) `div` 2

countArr :: [Int] -> Int
countArr (x : xs) = countHelper xs

solve :: IO ()
solve = do
    n   <- readInt
    arr <- readIntArr
    if (checkArr arr)
        then print $ countArr arr
        else print $ -1

readLoop :: Int -> IO ()
readLoop i =
    if (i == 0)
        then pure ()
        else do
            solve
            readLoop (i - 1)

main :: IO ()
main = do
    n <- readInt
    readLoop n

parseInt :: String -> Int
parseInt number = (read number) :: Int

readInt :: IO Int
readInt = do
    number <- getLine
    pure $ parseInt number

readIntArr :: IO [Int]
readIntArr = do
    numbers <- getLine
    pure $ map parseInt $ words numbers

dropTail :: [Int] -> [Int]
dropTail []       = []
dropTail (_ : []) = []
dropTail (x : xs) = (x : dropTail xs)

plus :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int)
plus (a, b, c) (d, e, f) = (a + d, b + e, c + f)

checkHelper :: [Int] -> (Int, Int, Int)
checkHelper []       = (0, 0, 0)
checkHelper (1 : xs) = (0, 0, 1) `plus` checkHelper xs
checkHelper (x : xs) = checkHelper xs `plus` if (x `mod` 2 == 0)
    then (1, 0, 0)
    else (0, 1, 0)

checkArr :: [Int] -> Bool
checkArr (x : xs) = od > 0 || (ev > 0 && ev + on > 1)
    where (od, ev, on) = checkHelper $ dropTail xs

countHelper :: [Int] -> Int
countHelper []       = 0
countHelper (x : xs) = countHelper xs + (x + 1) `div` 2

countArr :: [Int] -> Int
countArr (x : xs) = countHelper $ dropTail xs

solve :: IO ()
solve = do
    n   <- readInt
    arr <- readIntArr
    if (checkArr arr)
        then print $ countArr arr
        else print $ -1

readLoop :: Int -> IO ()
readLoop i =
    if (i == 0)
        then pure ()
        else do
            solve
            readLoop (i - 1)

main :: IO ()
main = do
    n <- readInt
    readLoop n

import Control.Monad (forM)

solve t = do
  n <- readLn::IO Int
  arr <- getLine >>= \s -> return $ drop 1 $ take (n - 1) $ map (read::String -> Int) (words s)
  let ans | (maximum arr == 1) || (n == 3 && odd (head arr)) = print (-1)
          | otherwise = print $ foldl (\x a -> x + (a + 1) `div` 2) 0 arr
  ans

main = do
tlen <- readLn :: IO Int
forM [0..(tlen - 1)] (\t -> do solve t)

main = interact $ unlines . map p . chunk 2 . drop 1 . lines

chunk n [] = []
chunk n xs = take n xs : chunk n (drop n xs)

folff t x = let (s, o, e, c1) = t in add s o e c1 x
        where add s o e c1 x
                | x == 1 = (s + 1, o + 1, e, c1 + 1)
                | even x = (s + x, o, e + 1, c1)
                | otherwise = (s + x, o + 1, e, c1)

calc :: (Int, Int, Int, Int) -> Int
calc t
    | o == 0 = s `div` 2
    | e == 0 && o == 1 = -1
    | e == 0 && o == c1 = -1
    | e == 0 = calc(s-1, o-1, e+1, 0) + 1
    | o == 1 = calc(s-1, 0, 0, 0) + 1
    | otherwise = calc(s, o - k * 2, 1, 0) + k
    where (s, o, e, c1) = t
          k = o `div` 2

p xs = let ((n:_):s:_) = fmap (fmap read . words) xs :: [[Int]]
        in show $ calc $ foldl folff (0,0,0,0) $ init $ tail s

import Control.Monad (forM_)

import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import qualified Data.Text.Read as Text

solve :: Int -> [Int] -> Int
solve n a
   | oddCount > evenSum `div` 2 = -1
   | otherwise                  = (evenSum + oddCount + oddSum) `div` 2
   where innerList = init $ tail a

         evenList  = filter even innerList
         oddList   = filter (not . even) innerList

         oddCount  = length oddList

         evenSum   = sum evenList
         oddSum    = sum oddList

textToInt :: Text -> Int
textToInt text =
   case Text.decimal text of
      Right (n, _) -> n

readInts :: Text -> [Int]
readInts = map textToInt . Text.words

handleCases:: Int -> [Text] -> [Int]
handleCases 0 _                   = []
handleCases t (line1:line2:rest)  = solve n a : handleCases (t-1) rest
   where n = textToInt line1
         a = readInts line2

main :: IO ()
main = do
   line1:rest <- Text.lines <$> Text.getContents
   let t     = textToInt line1
       res   = handleCases t rest
   Text.putStr $ Text.unlines $ map (Text.pack . show) res


import Data.Array
s(l,s)|s<1=1|l<1=0|1>0=foldl(\y x->mod(p!(l-1,x)+y)1000000007)0[max 0$s-25..s]
b=((0,0),(100,2500))
p=listArray b$map s$range b
f=fromEnum
y l=p!(length l,sum l)
main=interact$unlines.map(show.pred.y.map((+(-f 'a')).f)).tail.lines

{-# LANGUAGE BangPatterns #-}
import Data.List
import Data.Array

addM !x !y = (x + y) `mod` 1000000007

smm = foldl' addM 0

solve rec len 0 = 1
solve rec 0 sum = 0
solve rec len sum
  | sum < 0 = 0
  | otherwise = smm $ map (rec (len-1)) . filter (>=0) . map (sum-) $ [0..25]

bnd = ((0,0), (100, 2500))

pref l s = precalc!(l,s)
precalc = listArray bnd [solve pref l s|(l,s)<-range bnd]

c2n c = fromEnum c - fromEnum 'a'

s l=pref(length l)(sum l)

main=interact$unlines.map(show.pred).map(s.map c2n).tail.lines

import Array
s r _ 0=1
s r 0 _=0
s r l s|s<0=0|1>0=foldl(\x y->mod(x+y)1000000007)0$map(r$l-1)$[max 0$s-25..s]
b=((0,0),(100,2500))
p=listArray b[s q l m|(l,m)<-range b]
q l s=p!(l,s)
z c=f c-f 'a';f=fromEnum
y l=p!(length l,sum l)
main=interact$unlines.map(show.pred).map(y.map z).tail.lines

import Data.Array
import Data.Char (ord)
import Data.Function (fix)

main = do
    tests <- fmap (tail . words) getContents
    mapM_ (print . solve) tests
        where
            dp = count 100 2500
            solve test = (dp ! (length test, sum $ map (\ch -> (ord ch) - (ord 'a')) test)) - 1

count :: Int -> Int -> Array (Int, Int) Int
count maxLen maxSum = fix f
    where
        bs = ((0, 0), (maxLen, maxSum))
        f dp = listArray bs
                         [if i == 1 then 1
                                    else sumMod 1000000007 $ map (\s -> dp ! (i - 1, s)) [max 0 (j - 25)..min j (25 * (i - 1))]
                             | (i, j) <- range bs]

sumMod :: (Ord a, Num a) => a -> [a] -> a
sumMod m = foldl (\s x -> if s + x >= m then s + x - m else s + x) 0

import Data.Array
import Data.Char (ord)
import Data.Function (fix)

main = do
    tests <- fmap (tail . words) getContents
    mapM_ (print . solve) tests
        where
            dp = count 100 2500
            solve test = (dp ! (length test, sum $ map (\ch -> (ord ch) - (ord 'a')) test)) - 1

count :: Int -> Int -> Array (Int, Int) Int
count maxLen maxSum = fix f
    where
        bs = ((0, 0), (maxLen, maxSum))
        f dp = listArray bs
                         [if i == 1 then 1
                                    else (sum $ map (\s -> dp ! (i - 1, s)) [max 0 (j - 25)..min j (25 * (i - 1))]) `mod` 1000000007
                             | (i, j) <- range bs]

import Array
s(l,s)|s<1=1|l<1=0|1>0=foldl(\x y->mod(p!(x,l-1)+y)1000000007)0[max 0$s-25..s]
b=((0,0),(100,2500))
p=listArray b$map s$range b
f=fromEnum
y l=p!(length l,sum l)
main=interact$unlines.map(show.pred.y.map((+(-f 'a')).f)).tail.lines


import Control.Arrow
import Control.Applicative
import Data.Int
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import Data.List

data Tower = Tower Int Int

readTower s = Tower x y
    where
        [x, y] = map read . words $ s

sol :: Int -> [Tower] -> [Int64]
sol n t = sol' t IS.empty IS.empty (fromIntegral n) (fromIntegral n)
    where
        sol' [] _ _ _ _ = []
        sol' (t:ts) bx by kx ky = (nkx * nky) : (sol' ts nbx nby nkx nky)
            where
                (Tower x y) = t
                nx = x `IS.member` bx
                ny = y `IS.member` by
                nkx = if nx then kx else kx - 1
                nky = if ny then ky else ky - 1
                nbx = if nx then bx else x `IS.insert` bx
                nby = if ny then by else y `IS.insert` by

main :: IO()
main = do
    [n, _] <- (map read . words) <$> getLine
    towers <- (map readTower . lines) <$> getContents
    putStrLn $ intercalate " " $ map show $ sol n towers

import Data.List hiding (insert)
import Data.Int
import Data.IntSet hiding (map)

main = do
    [n,m] <- (map read . words) `fmap` getLine :: IO [Int]
    rocks <- (map (map read . words) . take m . lines) `fmap` getContents :: IO [[Int]]
    let n64 = fromIntegral n :: Int64
    solve rocks empty empty n64 n64

solve [] cols rows emptyCols emptyRows = return ()
solve ([x,y]:rocks) cols rows emptyCols emptyRows = do
    let col_already = member x cols
    let row_already = member y rows
    let emptyCols' = if col_already then emptyCols else emptyCols - 1
    let emptyRows' = if row_already then emptyRows else emptyRows - 1
    putStr $ show $ emptyCols' * emptyRows'
    putChar ' '
    let cols' = insert x cols
    let rows' = insert y rows
    solve rocks cols' rows' emptyCols' emptyRows'

import Data.IntSet hiding (map)
main = interact $  solve . map (map (read::String->Int) . words) . lines
solve  ([n',_]:xs) = let n = toInteger n'
                         go [] _ _  = []
                         go ([a,b]:xs) (r,rs) (c,cs) = let (r',rs') = if member a rs then (r, rs) else (r+1, insert a rs)
                                                           (c',cs') = if member b cs then (c, cs) else (c+1, insert b cs)

                                                       in (n*n-r'*n-c'*n+r'*c') : go xs (r',rs') (c',cs')
                 in unwords . map show $ go xs (0,empty) (0,empty)

import Control.Applicative
import qualified Data.Map as Map
import Data.Int

solve :: [Int64] -> Int64 -> Int64 -> Map.Map Int64 Int64 -> Map.Map Int64 Int64 -> (Int64, Map.Map Int64 Int64, Map.Map Int64 Int64)
solve [rPos,cPos] n curAtt rAtt cAtt = (curAtt + newRowAtt + newColAtt - p, Map.insert rPos 0 rAtt, Map.insert cPos 0 cAtt)
    where newRowAtt = case Map.member rPos rAtt of
                        True -> 0
                        False -> n - (fromIntegral $ Map.size cAtt)
          newColAtt = case Map.member cPos cAtt of
                        True -> 0
                        False -> n - (fromIntegral $ Map.size rAtt)
          p | not (Map.member cPos cAtt) && not (Map.member rPos rAtt) = 1
            | otherwise = 0

solve1 :: [[Int64]] -> Int64 -> Int64 -> Map.Map Int64 Int64 -> Map.Map Int64 Int64 -> IO ()
solve1 [] _ _ _ _ = return ()
solve1 (x:xs) n curAtt rAtt cAtt = do
                                let (res, newRAtt, newCAtt) = solve x n curAtt rAtt cAtt
                                putStr . show $ n * n - res
                                putStr " "
                                solve1 xs n res newRAtt newCAtt

main :: IO ()
main = do
        [n,m] <- map read . words <$> getLine
        lines <- mapM (\_ -> map (read :: String -> Int64) . words <$> getLine) [1..m]
        solve1 lines n 0 Map.empty Map.empty
        putStrLn ""

import Control.Applicative
import qualified Data.Map as Map
import Data.Int

solve :: [Int64] -> Int64 -> Int64 -> Map.Map Int64 Int64 -> Map.Map Int64 Int64 -> (Int64, Map.Map Int64 Int64, Map.Map Int64 Int64)
solve [rPos,cPos] n curAtt rAtt cAtt = (curAtt + newRowAtt + newColAtt - p, Map.insert rPos 0 rAtt, Map.insert cPos 0 cAtt)
    where newRowAtt = case Map.member rPos rAtt of
                        True -> 0
                        False -> n - ((fromIntegral :: Int -> Int64) (Map.size cAtt))
          newColAtt = case Map.member cPos cAtt of
                        True -> 0
                        False -> n - ((fromIntegral :: Int -> Int64) (Map.size rAtt))
          p | not (Map.member cPos cAtt) && not (Map.member rPos rAtt) = 1
            | otherwise = 0

solve1 :: [[Int64]] -> Int64 -> Int64 -> Map.Map Int64 Int64 -> Map.Map Int64 Int64 -> IO ()
solve1 [] _ _ _ _ = return ()
solve1 (x:xs) n curAtt rAtt cAtt = do
                                let (res, newRAtt, newCAtt) = solve x n curAtt rAtt cAtt
                                putStr . show $ n * n - res
                                putStr " "
                                solve1 xs n res newRAtt newCAtt

main :: IO ()
main = do
        [n,m] <- map read . words <$> getLine
        lines <- mapM (\_ -> map (read :: String -> Int64) . words <$> getLine) [1..m]
        solve1 lines n 0 Map.empty Map.empty
        putStrLn ""

import Control.Monad
import System.IO
import qualified Data.Set as Set

type Result = (Set.Set Integer, Set.Set Integer)

readInput :: IO [Integer]
readInput = fmap ((map read) . words) getLine

freeCells :: Integer -> Integer -> Integer -> Integer
freeCells n nx ny = n * n - (n * nx) - ((n - nx) * ny)

answer :: Result -> Integer -> Integer
answer r n  = freeCells n (toInteger (Set.size (fst r))) (toInteger (Set.size (snd r)))

processLine :: Integer -> Integer -> Result -> IO [()]
processLine n k r
    | k == 0 = return [()]
    | otherwise = process
    where process = do
            l <- readInput
            let nsx = Set.insert (l !! 0) (fst r)
            let nsy = Set.insert (l !! 1) (snd r)
            let newN = answer (nsx, nsy) n
            putStr (show $ answer (nsx, nsy) n)
            putStr " "
            processLine n (k-1) (nsx, nsy)

main :: IO [()]
main = do
    nm <- readInput
    let sx = Set.empty
    let sy = Set.empty
    let n = (nm !! 0)

    processLine n (nm !! 1) (sx, sy)

import Data.List

main = do
    [n,m] <- (map read . words) `fmap` getLine :: IO [Int]
    rocks <- (map (map read . words) . take m . lines) `fmap` getContents :: IO [[Int]]
    let rows = [y | [x,y] <- rocks]
    let cols = [x | [x,y] <- rocks]
    solve rows cols n [] []

solve [] [] _ _ _ = return ()
solve (r:rs) (c:cs) n prevRs prevCs = do
    let r_already = r `elem` prevRs
    let c_already = c `elem` prevCs
    let prevRs' = if r_already then prevRs else r:prevRs
    let prevCs' = if c_already then prevCs else c:prevCs
    putStrLn $ show $ (n - (length prevRs')) * (n - (length prevCs'))
    putChar ' '
    solve rs cs n prevRs' prevCs'

import Data.List
import System.IO

main = do
    [n,m] <- (map read . words) `fmap` getLine :: IO [Int]
    rocks <- (map (map read . words) . take m . lines) `fmap` getContents :: IO [[Int]]
    let rows = [y | [x,y] <- rocks]
    let cols = [x | [x,y] <- rocks]
    solve rows cols n [] []

solve [] [] _ _ _ = hFlush stdout
solve (r:rs) (c:cs) n prevRs prevCs = do
    let r_already = r `elem` prevRs
    let c_already = c `elem` prevCs
    let prevRs' = if r_already then prevRs else r:prevRs
    let prevCs' = if c_already then prevCs else c:prevCs
    putStr $ show $ (n - (length prevRs')) * (n - (length prevCs'))
    putChar ' '
    solve rs cs n prevRs' prevCs'

import Data.List

main = do
    [n,m] <- (map read . words) `fmap` getLine :: IO [Int]
    rocks <- (map (map read . words) . take m . lines) `fmap` getContents :: IO [[Int]]
    let rows = [y | [x,y] <- rocks]
    let cols = [x | [x,y] <- rocks]
    solve rows cols n [] []

solve [] [] _ _ _ = return ()
solve (r:rs) (c:cs) n prevRs prevCs = do
    let r_already = r `elem` prevRs
    let c_already = c `elem` prevCs
    let prevRs' = if r_already then prevRs else r:prevRs
    let prevCs' = if c_already then prevCs else c:prevCs
    putStr $ show $ (n - (length prevRs')) * (n - (length prevCs'))
    putChar ' '
    solve rs cs n prevRs' prevCs'

import Data.IntSet hiding (map)
main = interact $  solve . map (map (read::String->Int) . words) . lines
solve  ([n,_]:xs) = let go [] _ _ _ = []
                        go ([a,b]:xs) (r,rs) (c,cs) k = let k' = k - 2 * n + 1 + r + c
                                                            (r',rs',k'') = if member a rs then (r, rs, k'+1) else (r+1, insert a rs, k')
                                                            (c',cs',k''') = if member b cs then (c, cs,k''+1) else (c+1, insert b cs, k'')
                                                        in k''' : go xs (r',rs') (c',cs') k'''
                 in unwords . map show $ go xs (0,empty) (0,empty) (n*n)

import Data.IntSet hiding (map)
main = interact $  solve . map (map (read::String->Int) . words) . lines
solve  ([n',_]:xs) = let n = toInteger n'
                         go [] _ _ _ = []
                         go ([a,b]:xs) (r,rs) (c,cs) k = let k' = k - 2 * n + 1
                                                             (r',rs',k'') = if member a rs then (r, rs, k'+n-1) else (r+1, insert a rs, k'+c)
                                                             (c',cs',k''') = if member b cs then (c, cs,k''+n-1) else (c+1, insert b cs, k''+r)
                                                        in k''' : go xs (r',rs') (c',cs') k'''
                 in unwords . map show $ go xs (0,empty) (0,empty) (n*n)

import Data.IntSet hiding (map)
main = interact $  solve . map (map (read::String->Int) . words) . lines
solve  ([n',_]:xs) = let n = toInteger n'
                         go [] _ _ _ = []
                         go ([a,b]:xs) (r,rs) (c,cs) k = let k' = k - 2 * n + 1 + r + c
                                                             (r',rs',k'') = if member a rs then (r, rs, k'+1) else (r+1, insert a rs, k')
                                                             (c',cs',k''') = if member b cs then (c, cs,k''+1) else (c+1, insert b cs, k'')
                                                        in k''' : go xs (r',rs') (c',cs') k'''
                 in unwords . map show $ go xs (0,empty) (0,empty) (n*n)

import Control.Applicative
import qualified Data.Map as Map

solve :: [Int] -> Int -> Int -> Map.Map Int Int -> Map.Map Int Int -> (Int, Map.Map Int Int, Map.Map Int Int)
solve [rPos,cPos] n curAtt rAtt cAtt = (curAtt + newRowAtt + newColAtt - p, Map.insert rPos 0 rAtt, Map.insert cPos 0 cAtt)
    where newRowAtt = case Map.member rPos rAtt of
                        True -> 0
                        False -> n - (Map.size cAtt)
          newColAtt = case Map.member cPos cAtt of
                        True -> 0
                        False -> n - (Map.size rAtt)
          p | not (Map.member cPos cAtt) && not (Map.member rPos rAtt) = 1
            | otherwise = 0

solve1 :: [[Int]] -> Int -> Int -> Map.Map Int Int -> Map.Map Int Int -> IO ()
solve1 [] _ _ _ _ = return ()
solve1 (x:xs) n curAtt rAtt cAtt = do
                                let (res, newRAtt, newCAtt) = solve x n curAtt rAtt cAtt
                                putStr . show $ n * n - res
                                putStr " "
                                solve1 xs n res newRAtt newCAtt

main :: IO ()
main = do
        [n,m] <- map read . words <$> getLine
        lines <- mapM (\_ -> map (read :: String -> Int) . words <$> getLine) [1..m]
        solve1 lines n 0 Map.empty Map.empty
        putStrLn ""

import Control.Monad
import System.IO
import qualified Data.Set as Set

type Result = (Set.Set Int, Set.Set Int)

readInput :: IO [Int]
readInput = fmap ((map read) . words) getLine

freeCells :: Int -> Int -> Int -> Int
freeCells n nx ny = n * n - (n * nx) - ((n - nx) * ny)

answer :: Result -> Int -> Int
answer r n  = freeCells n (Set.size (fst r)) (Set.size (snd r))

processLine :: Int -> Int -> Result -> IO [()]
processLine n k r
    | k == 0 = return [()]
    | otherwise = process
    where process = do
            l <- readInput
            let nsx = Set.insert (l !! 0) (fst r)
            let nsy = Set.insert (l !! 1) (snd r)
            let newN = answer (nsx, nsy) n
            putStr (show $ answer (nsx, nsy) n)
            putStr " "
            processLine n (k-1) (nsx, nsy)

main :: IO [()]
main = do
    nm <- readInput
    let sx = Set.empty
    let sy = Set.empty
    let n = (nm !! 0)

    processLine n (nm !! 1) (sx, sy)


import Data.List
import Control.Monad

main = do
  line <- words <$> getLine
  let t = read $ head line :: Int
  replicateM_ t $ do
    line <- words <$> getLine
    let [a,b,c,d,k] = read <$> line :: [Double]
        a' = ceiling $ a / c :: Int
        b' = ceiling $ b / d :: Int
        s = a' + b'
    putStrLn $ if s > round k then "-1"
                              else show a' ++ " " ++ show b'

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.ST

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

import Data.Array.ST.Safe
import Data.STRef

-- import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInteger = readLn :: IO Integer
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

modifyArray a i f = writeArray a i =<< f <$> readArray a i

main = readInt >>= flip replicateM solve >>= mapM_ putStrLn

solve = do
	[ a, b, c, d, k ] <- readInts
	let
		pen = ( a + c - 1 ) `div` c
		pencil = ( b + d - 1 ) `div` d
	return $ if pen + pencil <= k
		then unwords $ map show [ pen, pencil ]
		else "-1"

import Data.Function
solve [a,b,c,d,k] =
    let e = ceiling $ fromIntegral a / fromIntegral c
        f = ceiling $ fromIntegral b / fromIntegral d
    in if e + f <= k then show e ++ " " ++ show f else "-1"

main = interact $  unlines . map (solve . map (read :: String -> Int) . words ) . tail .lines

import Control.Monad

data Ans = None | Ans Int Int

instance Show Ans where
  show None = "-1"
  show (Ans n m) = unwords $ fmap show [n, m]

solve :: Int -> Int -> Int -> Int -> Int -> Ans
solve lectures blueprints penUse pencilUse k =
  let (pen, pen') = lectures `quotRem` penUse
      (pencil, pencil') = blueprints `quotRem` pencilUse
      numPens = pen + (fromEnum $ (pen' /= 0))
      numPencils = pencil + (fromEnum $ (pencil' /= 0))
      tot = numPens + numPencils
  in
    if tot > k then None else Ans numPens numPencils

main = do
  numCases <- read <$> getLine
  replicateM numCases $ do
    [lectures, blueprints, penUse, pencilUse, k] <- fmap read <$> words <$> getLine
    print $ solve lectures blueprints penUse pencilUse k

module Main where

count :: [Int] -> Int -> Int -> Int
count ar x y =
  if (rem (ar !! x) (ar !! y)) == 0
    then div (ar !! x) (ar !! y)
    else (+1) $ div (ar !! x) (ar !! y)

evaluate :: Int -> [Int] -> [[String]] -> [[String]]
evaluate 0 x r = r
evaluate n x r = do
  let y = take 5 x
  let r1 = count y 0 2
  let r2 = count y 1 3
  let rm = r ++ ( if (r1 + r2) > (y !! 4)
          then [[show (-1)]]
          else [[show r1, show r2]])
  evaluate (n - 1) (drop 5 x) rm

solve x = evaluate (head x) (tail x) []

main :: IO ()
main =  interact $ unlines . map unwords . solve . map read . words

-- main = do
--   input <- getLine
--   print $ unlines $ map unwords $ solve $ map read $ words input

-- main = do
--   input <- getLine
--   let arr = ((map read $ words input) :: [Int])
--   print $ unlines $ map unwords $ evaluate (head arr) (tail arr) []

-- main = interact $
--   lines >>> map (words >>> map read >>> solve >>> show) >>> unlines
--
-- solve :: [Integer] -> Integer
-- solve [a,b] = abs (a-b)

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

ans a b c d k  | z >k = "-1"
               | otherwise = show z1 ++ " " ++ show z2

	where 	z1= (div (a-1) c )+1
		z2 = (div (b-1) d) +1
		z= z1+z2

onecase= do
	   [a,b,c,d,k]<-map read <$> words <$> getLine::IO [Int]
           putStrLn $ ans a b c d k

main::IO ()
main=do
  t<- read <$> getLine ::IO Int
  replicateM_ t onecase

--ghc 7.10

organizeBox c1 c2 l1 l2 k
    | x + y > k = Nothing
    | otherwise = Just (x,y)
    where
        x = (c1 + l1 - 1) `div` l1
        y = (c2 + l2 - 1) `div` l2

showResult :: Maybe (Int,Int) -> String
showResult r = case r of
                Just (x,y) -> unwords [show x, show y]
                Nothing -> show (-1)

main = do
    tStr <- getLine
    contents <- getContents
    let qs = map (map read . words) . lines $ contents
    let rs = map (\[c1,c2,l1,l2,k] -> organizeBox c1 c2 l1 l2 k) qs
    sequence . map putStrLn . map showResult $ rs


import Control.Monad
import Data.List

getInt :: IO Int
getInt = fmap read getLine

main = do
    t <- getInt
    replicateM_ t $ do
        s <- getLine
        print $ solve s

solve s = foldl' count0 0 midPart
  where count0 acc ch | ch == '0' = acc + 1
                      | ch == '1' = acc
        midPart = dropWhileEnd (=='0') $ dropWhile (=='0') s

import Control.Arrow

main = interact $
  lines >>> drop 1 >>> map (solve >>> show) >>> unlines

solve :: String -> Int
solve s = (length . trim . reverse . trim) s - ones s
  where
    trim :: String -> String
    trim ('0':xs) = trim xs
    trim xs = xs
    ones :: String -> Int
    ones [] = 0
    ones ('0':xs) = ones xs
    ones ('1':xs) = 1 + ones xs

import Control.Monad

countZeros :: [Char] -> Integer
countZeros = toInteger . length . filter (=='0')

removeZeros :: [Char] -> [Char]
removeZeros = dropWhile (=='0')

countInternalZeros :: [Char] -> Integer
countInternalZeros = countZeros . removeZeros . reverse . removeZeros

main = do
    x <- getLine
    stringInputs <- replicateM (read x) getLine
    mapM_ putStrLn (map (show . countInternalZeros) stringInputs)

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}

main = getLine >> getContents >>= putStrLn.unlines.map (show.length.filter (== '0').dropWhile (== '0').reverse.dropWhile (== '0')).words

--Bonus points for one-liner!

import Control.Monad

import Prelude
main = do
    x <- getLine
    strNums <- replicateM (read x) getLine
    mapM_ putStrLn (mf strNums)
mf = map f

removePref [] = []
removePref ('1':t) = ('1':t)
removePref ('0':t) = removePref t

trim = reverse . removePref . reverse . removePref
countZeros = length . (filter (=='0'))

f = show . countZeros . trim

import Control.Applicative
import Control.Monad
import Data.List

process x = length $ filter (=='0') x2
	where x1=dropWhile (=='0') x
              x2= dropWhile (=='0') $ reverse x1

main = do
		n<- read <$>  getLine::IO Int
		x<- replicateM n getLine
		mapM_ print $ map process x

--ghc 7.10

import Data.List(dropWhileEnd)

eraseInZeros :: String -> Int
eraseInZeros = length . filter (=='0') . dropWhile (=='0') . dropWhileEnd (=='0')

main = do
    nStr <- getLine
    contents <- getContents
    let ss = lines contents
    sequence . map print . map eraseInZeros $ ss

import Control.Monad
import Text.Printf

trim :: String -> String
trim = f . f
  where f = reverse . dropWhile (=='0')

main = do
  i <- getLine
  let t = read i :: Integer
  forM_ [1..t] $ \ _ -> do
    ii <- getLine
    let c = length $ filter (=='0') $ trim ii
    printf "%v\n" c

import Control.Applicative
import Control.Monad
import Data.List

process x = length $ filter (=='0') x2
	where x1=dropWhile (=='0') x
              x2= dropWhile (=='0') $ reverse x

main = do
		n<- read <$>  getLine::IO Int
		x<- replicateM n getLine
		mapM_ print $ map process x


-- user: nel_tu_
-- path: https://codeforces.com/problemset/problem/1521/A
-- tags: math

import Control.Monad ( replicateM )

solve :: [Integer] -> Maybe [Integer]
solve [_, 1] = Nothing
solve [a, 2] = Just [a, 3*a, 4*a]
solve [a, b] = Just [a, a*b - a, a*b]

getInt = read <$> getLine
getInts = map read . words <$> getLine

main = do
    n <- getInt
    replicateM n (solve <$> getInts) >>= putStrLn . unlines
          . concatMap (maybe ["NO"] $ ("YES":) . pure . unwords . map show)

import qualified Data.Set as Set
import Data.List
import Control.Monad
import Data.Char

readInts = fmap (map read.words) getLine :: IO [Integer]
printArray [] = ""
printArray (x:xs) = show(x) ++" " ++ printArray xs

printS = do
    [a,b]<-readInts
    if b == 1 then putStrLn"NO"
    else do
        putStrLn"YES"
        if b == 2 then
            putStrLn $ show(a) ++" " ++ show(3*a) ++ " "++show(4*a)
        else
            putStrLn $ show(a) ++ " " ++ show((b-1)*a) ++ " " ++ show(b*a)

main = do
    t<-readLn
    replicateM_ t printS

import Control.Monad
readInts = fmap (map read.words) getLine :: IO [Integer]

printResult = do
    [a,b] <- readInts
    if b == 1 then putStrLn "NO"
    else do
        let r = [a,a*b,(b+1)*a]
        putStrLn "YES"
        putStrLn . unwords . map show $ r

main = do
    t <- readLn :: IO Int
    replicateM_ t printResult

module Main where

    solve :: IO ()
    solve = do
        s <- getLine
        let [a, b] = map (\x -> read x :: Integer) $ words s
        putStrLn $
            if b == 1 then
                "NO"
            else
                concat $ ["YES\n"] ++ (map (\x -> show x ++ " ") $ [a, a * b, a * (b + 1)])

    iter :: Integer -> IO ()
    iter 1 = solve
    iter n = do
        solve
        iter $ n - 1

    main :: IO ()
    main = do
        q <- getLine
        iter (read q :: Integer)

import Control.Monad

main = do
    t <- read <$> getLine
    replicateM_ t (getLine >>= putStrLn . solve . map read . words)

solve :: [Integer] -> String
solve [_, 1] = "NO"
solve [x, y] = "YES\n" ++ unwords (map show [x, x * y, x * y + x])
solve _ = error "Expected two element list."

-- user: nel_tu_
-- path: https://codeforces.com/problemset/problem/1521/A
-- tags: math

solve [_, 1] = Nothing
solve [a, b] = Just [a, 2*a*b - a, 2*a*b]

input = map (map read . words) . tail . lines
output = maybe "NO" $ ("YES\n" ++) . unwords . map show

main = interact $ unlines . map (output . solve) . input

-- user: nel_tu_
-- path: https://codeforces.com/problemset/problem/1521/A
-- tags: math

import Control.Monad ( replicateM )

solve :: [Integer] -> Maybe [Integer]
solve [_, 1] = Nothing
solve [a, b] = Just [a, 2*a*b - a, 2*a*b]

getInt = read <$> getLine
getInts = map read . words <$> getLine

main = do
    n <- getInt
    replicateM n (solve <$> getInts) >>= putStrLn . unlines
          . concatMap (maybe ["NO"] $ ("YES":) . pure . unwords . map show)

-- user: nel_tu_
-- path: https://codeforces.com/problemset/problem/1521/A
-- tags: math

import Control.Monad ( replicateM )

solve :: [Int] -> Maybe [Int]
solve [_, 1] = Nothing
solve [a, 2] = Just [a, 3*a, 4*a]
solve [a, b] = Just [a, a*b - a, a*b]

getInt = read <$> getLine
getInts = map read . words <$> getLine

main = do
    n <- getInt
    replicateM n (solve <$> getInts) >>= putStrLn . unlines
          . concatMap (maybe ["NO"] $ ("YES":) . pure . unwords . map show)

-- user: nel_tu_
-- path: https://codeforces.com/problemset/problem/1521/A
-- tags: math

import Control.Monad ( replicateM )

solve :: [Int] -> Maybe [Int]
solve [_, 1] = Nothing
solve [a, b] = Just [a, 2*a*b - a, 2*a*b]

getInt = read <$> getLine
getInts = map read . words <$> getLine

main = do
    n <- getInt
    replicateM n (solve <$> getInts) >>= putStrLn . unlines
          . concatMap (maybe ["NO"] $ ("YES":) . pure . unwords . map show)

-- user: nel_tu_
-- path: https://codeforces.com/problemset/problem/1521/A
-- tags: math

import Control.Monad ( replicateM )

solve :: [Int] -> Maybe [Int]
solve [_, 1] = Nothing
solve [a, b] = Just [a, a*b - a, a*b]

getInt = read <$> getLine
getInts = map read . words <$> getLine

main = do
    n <- getInt
    replicateM n (solve <$> getInts) >>= putStrLn . unlines
          . concatMap (maybe ["NO"] $ ("YES":) . pure . unwords . map show)

import qualified Data.Set as Set
import Data.List
import Control.Monad

readInts = fmap (map read.words) getLine :: IO [Integer]

printS = do
    [a,b]<-readInts
    if mod a b == 0 then putStrLn"NO"
    else do
        putStrLn"YES"
        if b <= 2 then
            putStrLn $ show(a) ++" " ++ show(3*a) ++ " "++show(4*a)
        else
            putStrLn $ show(a) ++ " " ++ show((b-1)*a) ++ " " ++ show(b*a)

main = do
    t<-readLn
    replicateM_ t printS

import qualified Data.Set as Set
import Data.List
import Control.Monad

readInts = fmap (map read.words) getLine :: IO [Integer]

printS = do
    [a,b]<-readInts
    putStrLn"YES"
    if b <= 2 then
        putStrLn $ show(a) ++" " ++ show(3*a) ++ " "++show(4*a)
    else
        putStrLn $ show(a) ++ " " ++ show((b-1)*a) ++ " " ++ show(b*a)

main = do
    t<-readLn
    replicateM_ t printS

import qualified Data.Set as Set
import Data.List
import Control.Monad

readInts = fmap (map read.words) getLine :: IO [Integer]

printS = do
    [a,b]<-readInts
    putStrLn"YES"
    if b <= 2 then
        putStrLn $ show(a) ++" " ++ show(a) ++ " "++show(2*a)
    else
        putStrLn $ show(a) ++ " " ++ show((b-1)*a) ++ " " ++ show(b*a)

main = do
    t<-readLn
    replicateM_ t printS

import Control.Monad
readInts = fmap (map read.words) getLine :: IO [Int]

printResult = do
    [a,b] <- readInts
    if b == 1 then putStrLn "NO"
    else do
        let r = [a,a*b,(b+1)*a]
        putStrLn "YES"
        putStrLn . unwords . map show $ r

main = do
    t <- readLn :: IO Int
    replicateM_ t printResult

import Control.Monad
import Data.List
readInts = fmap (map read.words) getLine :: IO [Int]

printResult = do
    [a,b] <- readInts
    if b == 1 || mod a b == 0 then putStrLn "NO"
    else do
        let r = [a,a*b,(b+1)*a]
        putStrLn "YES"
        putStrLn . unwords . map show $ r

main = do
    t <- readLn :: IO Int
    replicateM_ t printResult

import Control.Monad
import Data.List
readInts = fmap (map read.words) getLine :: IO [Int]

printResult = do
    [a,b] <- readInts
    if b == 1 || mod b a == 0 then putStrLn "NO"
    else do
        let r = [a,a*b,(b+1)*a]
        putStrLn "YES"
        putStrLn . unwords . map show $ r

main = do
    t <- readLn :: IO Int
    replicateM_ t printResult

module Main where

    solve :: IO ()
    solve = do
        s <- getLine
        let [a, b] = map (\x -> read x :: Integer) $ words s
        putStrLn $ concat $ map (\x -> show x ++ " ") $ [a, a * b, a * (b + 1)]

    iter :: Integer -> IO ()
    iter 1 = solve
    iter n = do
        solve
        iter $ n - 1

    main :: IO ()
    main = do
        q <- getLine
        iter (read q :: Integer)

import Control.Monad

main = do
    t <- read <$> getLine
    replicateM_ t (getLine >>= putStrLn . solve . map read . words)

solve :: [Int] -> String
solve [_, 1] = "NO"
solve [x, y] = "YES\n" ++ unwords (map show [x, x * y, x * y + x])
solve _ = error "Expected two element list."


{-
    (pos, delta)
    (0,1) -> (1,0) -> (1,1) -> (0,0) -> (0,1) ...
    (1,1) -> (0,0) -> (0,1) -> (1,0) -> (1,1) ...
    which mean if the init position is even, and the action list is (-1 +2 +3 -4), (-5 +6 +7 -8), ...
    and if the init position is odd, then the action list is (+1 -2 -3 +4), (+5 -6 -7 +8), ...
-}

{-# Options_GHC -O2 #-}
import Data.Char
import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.Bits
import Data.List

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words

getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

mysplit :: [Int] -> String -> Char -> [Int]
mysplit [] _ _ = []
mysplit (x:x1) (s:s1) key
    | s == key = x: (mysplit x1 s1 key)
    | otherwise = mysplit x1 s1 key

checker :: Int -> [Int] -> [Int] -> Bool
checker _ [] [] = True
checker n r (b:b1)
    | b < n = False
    | otherwise = checker (n+1) r b1
checker n (r:r1) []
    | r > n = False
    | otherwise = checker (n+1) r1 []

process 0 = return ()
process t = do
    n <- getInt
    vals <- getIntList
    keys <- getLine
    let r = sort $ reverse $ mysplit vals keys 'R'
    let b = sort $ reverse $ mysplit vals keys 'B'
    putStrLn $ if (checker 1 r b) then "YES" else "NO"
    process (t-1)

main = do
    t <- getInt
    process t

import Control.Monad (replicateM_)
import qualified Data.ByteString.Char8 as B
import Data.List (sort)
import Data.Maybe (fromJust)

readInts :: IO [Int]
readInts = map (fst . fromJust . B.readInt) . B.words <$> B.getLine

main :: IO ()
main = do
  t <- fst . fromJust . B.readInt <$> B.getLine
  replicateM_ t $ do
    n <- fst . fromJust . B.readInt <$> B.getLine
    a <- readInts
    s <- B.unpack <$> B.getLine
    let xs = sort $ zip s a
    B.putStrLn $ if all (== True) $ zipWith check [1 .. n] xs then B.pack "YES" else B.pack "NO"
  where
    check i (c, x) = (c == 'R' && i >= x) || (c == 'B' && i <= x)

{-
    greedy algorithms:
    - group and sort ai with its color => two lists r, b
    - consider each number i in the permutation 1..n in increased order
      if the list b is not empty
          if the minimum element of b is less than i, then no transformed solution, because we cannot increase the value of any element in b
          otherwise we use and delete it from b and consider (i+1)
              Why we don't use other elements in b? Because we consider i in increased order, the minimum element of b is the worst case in the future.
              Why we don't use elements in r? Because for each element r' in r, if r' < i which means r'will always be valid in the future, otherwise we cannot use r' currently.
      else if the list r is not empty
          if the minimum element of r is greater than i, then no solution of course
          otherwise we use and delete it from r and consider (i+1)
      otherwise it means we find a solution.
-}

{-# Options_GHC -O2 #-}
import Data.Char
import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as BS
import Data.Bits
import Data.List

readInt = fst . fromJust . BS.readInt
readIntList = map readInt . BS.words

getInt = readInt <$> BS.getLine
getIntList = readIntList <$> BS.getLine

mysplit :: [Int] -> String -> Char -> [Int]
mysplit [] _ _ = []
mysplit (x:x1) (s:s1) key
    | s == key = x: (mysplit x1 s1 key)
    | otherwise = mysplit x1 s1 key

checker :: Int -> [Int] -> [Int] -> Bool
checker _ [] [] = True
checker n r (b:b1)
    | b < n = False
    | otherwise = checker (n+1) r b1
checker n (r:r1) []
    | r > n = False
    | otherwise = checker (n+1) r1 []

process 0 = return ()
process t = do
    n <- getInt
    vals <- getIntList
    keys <- getLine
    let r = sort $ mysplit vals keys 'R'
    let b = sort $ mysplit vals keys 'B'
    putStrLn $ if (checker 1 r b) then "YES" else "NO"
    process (t-1)

main = do
    t <- getInt
    process t

import Control.Monad
import Data.List
import Data.Maybe
import Data.Ord
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    ~[n] <- readInts
    xs <- readInts
    cs <- map (=='B') . C.unpack <$> C.getLine
    let (blues, reds) = partition fst $ sort $ zip cs xs
        ok = all (uncurry (<=)) (zip [1..] (map snd blues)) &&
             all (uncurry (>=)) (zip [length blues+1 ..] (map snd reds))
    putStrLn $ if ok then "YES" else "NO"

readInts :: IO [Int]
readInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine

main :: IO ()
main = flip replicateM_ solve . head =<< readInts


import Data.Bits

f -. g = g . f

main = do
	getLine
	interact $ lines -. map words -. map (map read) -. map foo -. map show -. unlines

foo :: [Int] -> Int
foo (a:b:n:[]) =
	case (mod n 3) of
		0 -> a
		1 -> b
		2 -> xor a b

import Data.List
import System.IO
import Text.Read
import Data.Bits

f :: Integer -> Integer -> Integer -> Integer
f a b 0 = a
f a b 1 = b
f a b 2 = xor a b

solve s =
    do
      let (a:b:n:_) = (map read.words) s :: [Integer]
      print $ (f a b (mod n 3))

work 0 = return ()
work m =
    do
        input <- getLine
        solve input
        work $ m-1

main =
    do
        input <- getLine
        let m = read input :: Int
        work m

import           Data.Bits

main :: IO ()
main =
  interact
    $ unlines
    . map processLine
    . filter ((== 3) . length)
    . map words
    . tail
    . lines

processLine :: [String] -> String
processLine = show . bindListToCurry3 xorinacci . map read

bindListToCurry3 :: (a -> a -> a -> b) -> [a] -> b
bindListToCurry3 f [a, b, c] = f a b c

xorinacci :: Int -> Int -> Int -> Int
xorinacci a _ 0 = a
xorinacci _ b 1 = b
xorinacci a b 2 = a `xor` b
xorinacci a b n = xorinacci a b (n `mod` 3)

import Data.List
import System.IO
import Text.Read
import Data.Bits

f :: Integer -> Integer -> Integer -> Integer
f a b n
        | n == 0 = a
        | n == 1 = b
        | otherwise = xor a b

doTimes 0 = return ()
doTimes n =
    do
      input  <- getLine
      solve input
      doTimes (n - 1)

solve s =
    do
      let (a:b:n:_) = (map read.words) s :: [Integer]
      -- print $ (f a b (mod n 3))
      print $ (f a b (mod n 3))

main =
    do
      input  <- getLine
      let m = read input :: Int
      doTimes m


import Control.Monad
main = do
    n <- liftM read getLine
    putStrLn $ unwords $ (map show) $ solve n
solve n = map (n-) $ (reverse [1,3..n-1])++[1,3..n-1]++[0]++(reverse [2,4..n-1])++[0]++[2,4..n-1]

main = interact $ unwords . map show . sol . read

sol :: Integer -> [Integer]
sol n
  | even n = solEven n
  | otherwise = solOdd n

solEven n = g1 ++ (reverse g1) ++ g2 ++ [n] ++ (reverse g2) ++ [n]
    where
    nlst = [1..n-1]
    g1 = filter odd nlst
    g2 = filter even nlst

solOdd n = g1 ++ [n] ++ reverse g1 ++ [n] ++ g2 ++ reverse g2
    where
    nlst = [1..n-1]
    g1 = filter odd nlst
    g2 = filter even nlst

import Control.Monad
main = do
    n <- liftM read getLine
    putStrLn $ unwords $ (map show) $ solve n
solve n = (reverse [1,3..n-1])++[1,3..n-1]++[n]++(reverse [2,4..n-1])++[n]++[2,4..n-1]


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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    n = go 0 (length s `div` length t)
      where
        cap = length $ filter (== '?') s
        go l r
          | r - l <= 1 = r
          | otherwise = if cap >= sum (calc m) then go m r else go l (m - 1)
          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

-- cap > m
-- cap < m + 1
-- cap <= m

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    n = go 0 (length s `div` length t + 1)
      where
        cap = length $ filter (== '?') s
        go l r
          | r - l <= 1 = l
          | otherwise = if cap < sum (calc m) then go l m else go m r
          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

-- cap >= sum m --> m r

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    cap = length $ filter (== '?') s
    n = go 0 (length s `div` length t + 1)
      where
        go l r
          | l >= r = l
          | otherwise = case compare cap $ sum (calc m) of
              EQ -> m
              LT -> go l m
              GT -> go (m + 1) r

          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = if all (uncurry (==)) $ zip s "ozvopcloixjjqzjaffuohidhqejjdazihtffoaux" then show n ++ " " ++ show zs ++ " " ++ show cap ++ " " ++ show (length s) ++ " " ++ show (length t) else snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    cap = length $ filter (== '?') s
    n = go 0 (length s `div` length t)
      where
        go l r
          | r - l <= 1 = l
          | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m
          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    n = go 0 (length s `div` length t)
      where
        cap = length $ filter (== '?') s
        go l r
          | r - l <= 1 = l
          | otherwise = if cap < sum (calc m) then go l (m - 1) else go m r
          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

main = do
  s <- getLine
  t <- getLine
  print $ solve s t

solve s t = snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith3 (\c sc tc -> replicate (max 0 $ tc * n - sc) c) ['a'..'z'] (mkc $ filter (/= '?') s) (mkc t)) s
  where
    n = length s `div` length t

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = if all (uncurry (==)) $ zip s "llpyxupdthpdmw" then show n ++ " " ++ show zs ++ " " ++ show cap else snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    cap = length $ filter (== '?') s
    n = go 0 (length s `div` length t + 1)
      where
        go l r
          | l >= r = l
          | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m
          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    n = go 0 (length s `div` length t)
      where
        cap = length $ filter (== '?') s
        go l r
          | r - l <= 1 = r
          | otherwise = if cap > sum (calc m) then go m r else go l (m - 1)
          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    cap = length $ filter (== '?') s
    n = go 0 (length s `div` length t)
      where
        go l r
          | l >= r = l
          | otherwise = case compare cap $ sum (calc m) of
              EQ -> m
              LT -> go l m
              GT -> go (m + 1) r
          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = if all (uncurry (==)) $ zip s "llpyxupdthpdmw" then show n ++ " " ++ show zs ++ " " ++ show cap ++ " " ++ show (length s) ++ " " ++ show (length t) else snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    cap = length $ filter (== '?') s
    n = go 0 (length s `div` length t + 1)
      where
        go l r
          | l >= r = l
          | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m
          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith3 (\c sc tc -> replicate (max 0 $ tc * n - sc) c) ['a'..'z'] (mkc $ filter (/= '?') s) (mkc t)) s
  where
    n = length s `div` length t

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = if all (uncurry (==)) $ zip s "llpyxupdthpdmw" then show n else snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    cap = length $ filter (== '?') s
    n = go 0 (length s `div` length t + 1)
      where
        go l r
          | l >= r = l
          | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m
          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    n = go 0 (length s `div` length t)
      where
        cap = length $ filter (== '?') s
        go l r
          | r - l <= 1 = l
          | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m
          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

main = do
  s <- getLine
  t <- getLine
  putStr $ solve s t

solve s t = snd $ mapAccumL (\bag c -> if c == '?' then if null bag then (bag, 'z') else (tail bag, head bag) else (bag, c)) (concat $ zipWith replicate (calc n) ['a'..'z']) s
  where
    zs = zip (mkc $ filter (/= '?') s) (mkc t)
    calc k = map (\(sc, tc) -> max 0 $ tc * k - sc) zs
    cap = length $ filter (== '?') s
    n = go 0 (length s `div` length t + 1)
      where
        go l r
          | l >= r = l
          | otherwise = if cap > sum (calc m) then go (m + 1) r else go l m
          where m = (l + r) `div` 2

mkc = (elems :: UArray Char Int ->  [Int]) . accumArray (+) 0 ('a', 'z') . flip zip (repeat 1)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words