import           Control.Monad
readInt = read :: String -> Int
readInteger = read :: String -> Integer

folder :: (Integer, Integer) -> Integer -> (Integer, Integer)
folder (o, z) 1 = (o+1, z)
folder (o, z) 0 = (o, z+1)

main :: IO ()
main = do
  t <- readInt <$> getLine
  replicateM_ t $ do
    n <- readInt <$> getLine
    ps <- map readInteger . words <$> getLine
    m <- readInt <$> getLine
    qs <- map readInteger . words <$> getLine
    print $ (\(os,zs) -> product os + product zs) . unzip . map ( foldl folder (0,0) . map (`mod`2) ) $ [ps, qs]

{-# 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_ print

solve = do
	n <- readInteger
	ps <- readInts
	m <- readInteger
	qs <- readInts
	let
		odd1 :: Integer = fromIntegral $ length $ filter odd ps
		even1 = n - odd1
		odd2 :: Integer = fromIntegral $ length $ filter odd qs
		even2 = m - odd2
	return $ odd1 * odd2 + even1 * even2

import Control.Monad
main :: IO ()
main = do
    n <- readLn
    replicateM_ n routine

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

solve :: [Integer] -> [Integer] -> Integer
solve as bs = a1*b1+a2*b2
  where
      count (e,o) x = if even x
        then (e+1,o)
        else (e,o+1)
      (a1,a2) = foldl count (0,0) as
      (b1,b2) = foldl count (0,0) bs

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE LambdaCase        #-}
{-# LANGUAGE MultiWayIf        #-}
{-# LANGUAGE TupleSections     #-}
{-# LANGUAGE ViewPatterns      #-}
#ifndef DEBUG
{-# LANGUAGE Safe              #-}
#endif

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.State.Strict
import qualified Data.Array                 as A
import qualified Data.Array.Unboxed         as UA
import qualified Data.Array.ST.Safe         as MA
import           Data.Bool
import qualified Data.ByteString.Builder    as B
import qualified Data.ByteString.Char8      as C
import           Data.Char
import           Data.Function
import qualified Data.IntMap.Strict         as IM
import qualified Data.IntSet                as IS
import qualified Data.List                  as L
import qualified Data.List.NonEmpty         as NL
import           Data.Monoid
import qualified Data.Map.Strict            as M
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup
import qualified Data.Set                   as S
import           Data.Tuple
import           Foreign
import qualified System.IO                  as IO
#ifdef DEBUG
import           Debug.Trace
#endif

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
      n <- readLn
      ps <- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine
      m <- readLn
      qs <- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine
      print $ solve n ps m qs
      IO.hFlush IO.stdout

solve :: Int -> [Int] -> Int -> [Int] -> Int64
solve n xs m ys = fromIntegral xsEven * fromIntegral ysEven + fromIntegral xsOdd * fromIntegral ysOdd
  where
    p x = x .&. 1 == 0
    !xsEven = length $ filter p xs
    !xsOdd = n - xsEven
    !ysEven = length $ filter p ys
    !ysOdd = m - ysEven

import Control.Monad
main :: IO ()
main = do
    n <- readLn
    replicateM_ n routine

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

solve :: [Int] -> [Int] -> Int
solve as bs = a1*b1+a2*b2
  where
      count (e,o) x = if even x
        then (e+1,o)
        else (e,o+1)
      (a1,a2) = foldl count (0,0) as
      (b1,b2) = foldl count (0,0) bs

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE LambdaCase        #-}
{-# LANGUAGE MultiWayIf        #-}
{-# LANGUAGE TupleSections     #-}
{-# LANGUAGE ViewPatterns      #-}
#ifndef DEBUG
{-# LANGUAGE Safe              #-}
#endif

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.State.Strict
import qualified Data.Array                 as A
import qualified Data.Array.Unboxed         as UA
import qualified Data.Array.ST.Safe         as MA
import           Data.Bool
import qualified Data.ByteString.Builder    as B
import qualified Data.ByteString.Char8      as C
import           Data.Char
import           Data.Function
import qualified Data.IntMap.Strict         as IM
import qualified Data.IntSet                as IS
import qualified Data.List                  as L
import qualified Data.List.NonEmpty         as NL
import           Data.Monoid
import qualified Data.Map.Strict            as M
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup
import qualified Data.Set                   as S
import           Data.Tuple
import           Foreign
import qualified System.IO                  as IO
#ifdef DEBUG
import           Debug.Trace
#endif

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
      n <- readLn
      ps <- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine
      m <- readLn
      qs <- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine
      print $ solve n ps m qs
      IO.hFlush IO.stdout

solve :: Int -> [Int] -> Int -> [Int] -> Int
solve n xs m ys = xsEven * ysEven + xsOdd * ysOdd
  where
    p x = x .&. 1 == 0
    !xsEven = length $ filter p xs
    !xsOdd = n - xsEven
    !ysEven = length $ filter p ys
    !ysOdd = m - ysEven

import           Control.Monad

readInt = read :: String -> Int

folder :: (Int, Int) -> Int -> (Int, Int)
folder (o, z) 1 = (o+1, z)
folder (o, z) 0 = (o, z+1)

main :: IO ()
main = do
  t <- readInt <$> getLine
  replicateM_ t $ do
    n <- readInt <$> getLine
    ps <- map readInt . words <$> getLine
    m <- readInt <$> getLine
    qs <- map readInt . words <$> getLine
    print $ (\(os,zs) -> product os + product zs) . unzip . map ( foldl folder (0,0) . map (`mod`2) ) $ [ps, qs]


import Data.List.Split

main = do
  xs <- fmap (splitOn " ") getLine
  let n = read $ head xs
      k = read $ last xs
      in putStrLn $ take n $ concat $ repeat $ take k ['a'..'z']

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

s="abcdefghijklmnopqrstuvwxyz"

main = do
		[a,b]<- map read <$> words <$> getLine ::IO [Int]
		putStrLn  $ take a $ cycle $ take b s

import Control.Applicative
import Control.Monad

solve :: [Int] -> String
solve [n, k] = take n $ concat $ repeat $ take k ['a'..'z']

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

module Main where

import Data.Char

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

letters = filter isLower [minBound..maxBound]

main = do
    [n, k] <- readInts
    putStrLn $ (($) concat (replicate (n `div` k) $ take k letters)) ++ (take (n `mod` k) letters)

module Main where

import Data.Char

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

letters = filter isLower [minBound..maxBound]

main = do
    [n, k] <- readInts
    print $ (($) concat (replicate (n `div` k) $ take k letters)) ++ (take (n `mod` k) letters)

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

s="abcdefghijklmnopqrstuvwxyz"

main = do
		[a,b]<- map read <$> words <$> getLine ::IO [Int]
		print $ take a $ cycle $ take b s


import Data.Array

delta (x, y) = abs $ x - y

timeUnits a n = sum $ map delta $ changes
    where
        an = array (1, n) $ zip a [1..]
        pos = map (\x -> an!(x)) [1..n]
        changes = zip pos (drop 1 pos)

main = do
    n <- readLn
    s <- getLine
    let a = map read $ words s
    putStrLn $ show $ timeUnits a n

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

main = do
    f <- map snd . sort . (flip zip) [0 .. ] . tail . map fst . mapMaybe BS.readInt . BS.words <$> BS.getContents
    print . sum . map abs . zipWith (-) f $ tail f

import Data.ByteString.Char8 (words, readInt, getLine)
import Data.List (sort)
import Data.Maybe
import Prelude hiding (words, getLine)

main = do
  getLine
  as <- (map (fst . fromJust . readInt) . words) `fmap` getLine :: IO [Int]

  let
    r = sum . zipWith (\a b -> abs $ a - b) ps $ tail ps
      where
        ps = map snd . sort $ zip as [1..]

  print r

import Data.Array

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

sol :: [Integer] -> Integer
sol (n:fs) = sum $ map (\idx -> abs $ ar!(idx+1) - ar!idx) [1..n-1]
    where
    ar = array (1, n) $ zip fs [1..]

import Data.List

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

sol :: [Int] -> Int
sol (n:fs) = sum . map abs . zipWith (-) tr $ tail tr
    where
    tr = map snd . sort $ zip fs [1..]

import Data.List

main = interact $ show . sol . words

sol (n:fs) = sum . map abs . zipWith (-) tr $ tail tr
    where
    tr = map snd . sort $ zip fs [1..]


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import qualified Data.ByteString.Char8 as B
import Data.Function
import Data.List
import Data.Ord
import Data.Tuple
import Data.Array.Base
import Data.Array.ST (runSTUArray)

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

main :: IO ()
main = do
  n <- readLn
  xs <- map (obj.readInt).B.words <$> B.getLine
  ys <- map readInt.B.words <$> B.getLine
  let (l,p) = solve n xs [(from,to) | [(from,to)]<-groupBy ((==)`on`fst).sort $ zip ys [1..n], from/=0]
  print l
  putStrLn.unwords.map show $ p

data Object = Mountain | Hotel deriving Eq

obj :: Int -> Object
obj 0 = Mountain
obj 1 = Hotel

solve :: Int -> [Object] -> [(Int,Int)] -> (Int,[Int])
solve n objects edges = maximum [ (length p, reverse p) | i<-[1..n]
                                                        , unsafeAt isHotel i
                                                        , let p = path i
                                                        , all (not.unsafeAt isHotel) $ tail p
                                                        ]
   where
     isHotel :: UArray Int Bool
     isHotel = listArray (0,n) $ False : map (Hotel==) objects
     prev :: UArray Int Int
     prev = runSTUArray $ do
       arr <- newArray (0,n) 0 :: ST s (STUArray s Int Int)
       forM_ edges $ \ (from,to) -> do
         unsafeWrite arr to from
       return arr
     path :: Int -> [Int]
     path v = takeWhile (/=0) $ iterate (unsafeAt prev) v

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readsInt = map readInt . B.words <$> B.getLine
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

main = do
    n <- readInt <$> B.getLine
    types <- readsInt
    as    <- readsInt
    let p = solve n types as
    print $ length p
    putStrLn $ unwords $ map show $ p

solve n types as = maximize length [ go i [] | i <- [1..n], hotel ! i]
    where
    graph :: UArray Int Int
    graph = listArray (1,n) as
    hotel :: UArray Int Bool
    hotel = listArray (1,n) $ map (==1) types
    degree :: UArray Int Int
    degree = accumArray (+) 0 (1,n) [ (i,1) | i <- as, i /= 0 ]
    go i !acc | next == 0 || hotel ! next || degree ! next > 1 = i:acc
         | otherwise = go next (i:acc)
        where
        next = graph ! i


{-# 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 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 #-}

lowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i
lowerBound p low high = assert (low>=0 && p high) $ go low high
   where
     go !low !high
       | high <= low = high
       | p mid       = go low       mid
       | otherwise   = go (mid + 1) high
      where
        mid = (low + high) `quot` 2
{-# INLINE lowerBound #-}

main :: IO ()
main = do
  n <- readLn
  xs <- listArray(0,n-1).map ((2==).readInt).B.words <$> B.getLine
  let res =  solve n xs
  print $ length res
  putStr.unlines.map (unwords.map show) $ res

solve :: Int -> UArray Int Bool -> [[Int]]
solve n arr = sort [[s,t] | t<-[1..n], Just s<-[simulate t]]
   where
     simulate point = go 0 0 0
      where
        go !x !y !i = case (nextx, nexty) of
                        (Just xi, Just yi)
                          | xi < yi -> go (x+1) y (xi+1)
                          | otherwise -> go x (y+1) (yi+1)
                        (Just xi, Nothing)
                          | unsafeAt arr (n-1) && r == 0 && y < res -> Just res
                         where
                           (q,r) = quotRem (unsafeAt arrX (n-1) - unsafeAt arrX xi) point
                           res = x + 1 + q
                        (Nothing, Just yi)
                          | not(unsafeAt arr (n-1)) && r == 0 && x < res -> Just $ y + 1 + q
                         where
                           (q,r) = quotRem (unsafeAt arrY (n-1) - unsafeAt arrY yi) point
                           res = y + 1 + q
                        _ -> Nothing
         where
           !ai = fromEnum $ unsafeAt arr i
           !sumX = unsafeAt arrX i - ai
           !sumY = unsafeAt arrY i - (1 - ai)
           nextx
             | unsafeAt arrX (n-1) - sumX >= point = Just $ lowerBound (\i->unsafeAt arrX i - sumX >= point) i (n-1)
             | otherwise = Nothing
           nexty
             | unsafeAt arrY (n-1) - sumY >= point = Just $ lowerBound (\i->unsafeAt arrY i - sumY >= point) i (n-1)
             | otherwise = Nothing
     pair :: (UArray Int Int, UArray Int Int)
     pair@(arrX, arrY) = runST $ do
       arrX <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)
       arrY <- newArray (0,n-1) 0 :: ST s (STUArray s Int Int)
       if unsafeAt arr 0 then unsafeWrite arrX 0 1
       else unsafeWrite arrY 0 1
       for 1 (n-1) $ \i -> do
         if unsafeAt arr i then do
            unsafeRead arrX (i-1) >>= unsafeWrite arrX i . (1+)
            unsafeRead arrY (i-1) >>= unsafeWrite arrY i
         else do
            unsafeRead arrX (i-1) >>= unsafeWrite arrX i
            unsafeRead arrY (i-1) >>= unsafeWrite arrY i . (1+)
       (,) <$> unsafeFreeze arrX <*> unsafeFreeze arrY

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
inf = maxBound `div` 2 :: Int

main = do
    n <- readLn
    as <- readInts
    let l = solve n as
    print $ length l
    putStr $ unlines $ [ show s ++ " " ++ show t | (s,t) <- l]

solve :: Int -> [Int] -> [(Int,Int)]
solve n as = sort [ (s,t) | t <- [1..n], s <- calc n tbl t ] where
    tbl :: UArray Int Int
    tbl = listArray (0,n) $ scanl (+) 0 $ map (2-) as

calc :: Int -> UArray Int Int -> Int -> [Int]
calc n tbl s = go 0 0 0 where
    go !wx !wy !p =
        let l = min n (p+s-1) in
        let r = min n (p+2*s-1) in
        let check q =
                let a = tbl ! q - tbl ! p in
                let b = (q - p) - a in
                max a b < s in
        let d = binSearch check l r in
        if tbl ! d - tbl ! p == s then
            -- winner is Petya
            if d == n then
                guard (wx >= wy) >> pure (wx+1)
            else
                go (wx+1) wy d
        else if (d-p) - (tbl ! d - tbl ! p) == s then
            -- winner is Gena
            if d == n then
                guard (wx <= wy) >> pure (wy+1)
            else
                go wx (wy+1) d
        else
            empty

{-# INLINE binSearch #-}
binSearch :: (Int -> Bool) -> Int -> Int -> Int
binSearch p = go  where
    go l r
        | l >= r - 1 = r
        | p m = go m r
        | otherwise = go l m where
        m = (l + r) `div` 2


{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}
import System.IO
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B8
import qualified Data.ByteString.Builder as Bu
import Data.Functor.Identity
import Control.Monad.Trans.State
import Control.Monad
import Control.Applicative
import Control.Arrow
import Data.Function
import qualified Data.Bits as DB
import qualified Data.IntMap.Lazy as DM
import qualified Data.IntSet as DS
import qualified Data.List as DL

solve :: St Bu.Builder
solve = do
  ~[n,q] <- getIntegrals 2
  s <- getByteString
  queries <- replicateM q getPosChar
  let arr = DM.fromAscList $ zip [1..] (B8.unpack s)
      count = length $ filter (substr arr) [1..n]
      initial = (arr,count)
      anss = tail $ snd $ unzip $ DL.scanl' f initial queries
      builder = mconcat $ [Bu.intDec i <> Bu.string7 "\n" | i <-anss]
  return builder

type B = (DM.IntMap Char, Int)
f :: B -> (Int,Char) -> B
f (arr, count) (pos,ch)
  | DM.lookup pos arr == Just ch = (arr,count)
  | otherwise = let
    match p c a = fromEnum (substr a (p + (fromEnum 'a') - (maybe 0 fromEnum $ DM.lookup p a)))
    newArr = DM.insert pos ch arr
    decr = match pos ch arr
    incr = match pos ch newArr
    in
      (newArr, count-decr+incr)

substr :: DM.IntMap Char -> DS.Key -> Bool
substr m i = DM.lookup i m == Just 'a' && DM.lookup (i+1) m == Just 'b' && DM.lookup (i+2) m == Just 'c'

getPosChar :: St (Int,Char)
getPosChar = do
  pos <- getIntegral
  s <- getByteString
  return (pos,B8.head s)

numberOfTestcases :: St Int
numberOfTestcases = implicit
  where implicit = return 1 :: St Int
        explicit = getIntegral

------------------------------- main --------------------------------
type St = StateT [B8.ByteString] Identity

getByteString :: St B8.ByteString
getByteString = state getNext where
  getNext [] =  (B8.take 0 (B8.pack "."),[])
  getNext (w:ws) =  (w,ws)

getIntegral :: Num t => St t
getIntegral  = convertToNum <$> getByteString where
  convertToNum x =  fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x

getIntegrals :: Num t => Int -> St [t]
getIntegrals n = replicateM n getIntegral

main :: IO ()
main = do
  raw <- B8.getContents
  let bytestrings = B8.words raw
  let outputs = flip evalState bytestrings $ do
        nTc <- numberOfTestcases
        let answers = replicateM nTc solve
        fmap mconcat answers
  Bu.hPutBuilder stdout outputs

{-# LANGUAGE BangPatterns, FlexibleContexts #-}
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.ST.Safe
import Control.Monad.ST.Lazy

solve :: Int -> String -> [(Int, Char)] -> [Int]
solve n s0 qs = runST $ do
  s <- strictToLazyST $ newListArray (1, n) s0 :: ST s (STUArray s Int Char)
  let
    isABC ix = boolToInt . (== "abc") <$> forM [ix .. ix + 2] (readArray s)
    boolToInt p = if  p  then  1  else  0
  initCt <- (\fun -> strictToLazyST $ foldM fun 0 [1 .. n - 2])
    $ \ !acc !ix -> (+ acc) <$> isABC ix
  incrs <- forM qs $ \(ix, c) -> strictToLazyST $ do
    let  ixs = [max 1 (ix - 2) .. min ix (n - 2)]
         localCt = sum <$> forM ixs isABC
    out <- localCt
    writeArray s ix c
    subtract out <$> localCt
  pure $ tail $ scanl' (+) initCt incrs

mainFun :: SP Builder
mainFun = do
  ~[n, q] <- getInts 2
  ~[s0] <- getNext 1
  qs <- replicateM q $ do
    ~[ix] <- getInts 1
    ~[cs] <- getNext 1
    pure (ix, P.head cs)
  pure $ foldMap (putInts . pure) $ solve n (P.unpack s0) qs

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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 $ P.words inp
  P.putStr $ toLazyByteString outp

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}
import System.IO
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B8
import qualified Data.ByteString.Builder as Bu
import Data.Functor.Identity
import Control.Monad.Trans.State
import Control.Monad
import Control.Applicative
import Control.Arrow
import Data.Function
import qualified Data.Bits as DB
import qualified Data.IntMap.Lazy as DM
import qualified Data.IntSet as DS
import qualified Data.List as DL

solve :: St Bu.Builder
solve = do
  ~[n,q] <- getIntegrals 2
  s <- getByteString
  queries <- replicateM q getPosChar
  let arr = DM.fromAscList $ zip [1..] (B8.unpack s)
      count = length $ filter (substr arr) [1..n]
      initial = (arr,count)
      anss = snd $ unzip $ DL.scanl' f initial queries
      builder = mconcat $ [Bu.intDec i <> Bu.string7 "\n" | i <-anss]
  return builder

type B = (DM.IntMap Char, Int)
f :: B -> (Int,Char) -> B
f (arr, count) (pos,ch)
  | DM.lookup pos arr == Just ch = (arr,count)
  | otherwise = let
    match p c a = fromEnum (substr a (p + (fromEnum 'a') - (maybe 0 fromEnum $ DM.lookup p a)))
    newArr = DM.insert pos ch arr
    decr = match pos ch arr
    incr = match pos ch newArr
    in
      (newArr, count-decr+incr)

substr :: DM.IntMap Char -> DS.Key -> Bool
substr m i = DM.lookup i m == Just 'a' && DM.lookup (i+1) m == Just 'b' && DM.lookup (i+2) m == Just 'c'

getPosChar :: St (Int,Char)
getPosChar = do
  pos <- getIntegral
  s <- getByteString
  return (pos,B8.head s)

numberOfTestcases :: St Int
numberOfTestcases = implicit
  where implicit = return 1 :: St Int
        explicit = getIntegral

------------------------------- main --------------------------------
type St = StateT [B8.ByteString] Identity

getByteString :: St B8.ByteString
getByteString = state getNext where
  getNext [] =  (B8.take 0 (B8.pack "."),[])
  getNext (w:ws) =  (w,ws)

getIntegral :: Num t => St t
getIntegral  = convertToNum <$> getByteString where
  convertToNum x =  fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x

getIntegrals :: Num t => Int -> St [t]
getIntegrals n = replicateM n getIntegral

main :: IO ()
main = do
  raw <- B8.getContents
  let bytestrings = B8.words raw
  let outputs = flip evalState bytestrings $ do
        nTc <- numberOfTestcases
        let answers = replicateM nTc solve
        fmap mconcat answers
  Bu.hPutBuilder stdout outputs


import Data.List

main = do
    [n, k] <- fmap parseInput $ getLine
    let ret = solve n k
    if (length ret) > 0
        then do
            putStrLn "YES"
            mapM_ putStrLn ret
        else putStrLn "NO"

parseInput = map readInt . words
    where readInt x = (read x) :: Int

solve n k
    | even k = [fill 0, fill k', fill k', fill 0]
    | k <= (n-2) = [fill 0, fill' k pad, fill 0, fill 0]
    | otherwise = [fill 0, fill (n-2), fill'' (k - n + 2), fill 0]
    where
        fill x = "." ++ (take x $ repeat '#') ++ (take (n-x-1) $ repeat '.')
        fill' x y = (take y $ repeat '.') ++ (take x $ repeat '#') ++ (take (n-x-y) $ repeat '.')
        fill'' x = "." ++ (take (x-1) $ repeat '#') ++ (take (n-2-x) $ repeat '.') ++ "#."
        k' = k `div` 2
        pad = (n - k) `div` 2

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

solve :: Int -> Int -> String
solve n k =
  if even k
    then unlines ["YES",border,even1,even1,border]
    else if k <= n-2
            then unlines["YES",border,odd1,border,border]
            else unlines["YES",border,hotel1,odd2,border]
  where
    dots = repeat '.'
    hotels = repeat '#'

    border = take n dots
    even1  = take n $ '.' : (take (k`div`2) hotels) ++ dots
    odd1   = take n $ take ((n-k)`div`2) dots ++ take k hotels ++ dots
    odd2   = take n $ '.' : take ((k-n+2)`div`2) hotels ++ take (n-2-(k-n+2)) dots ++ take ((k-n+2)`div`2) hotels ++ dots
    hotel1 = take n $ '.' : take (n-2) hotels ++ dots

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

solve :: Int -> Int -> String
solve n k =
  unlines ["YES",border,center1,center2,border]
  where
    dots = repeat '.'
    hotels = repeat '#'

    border = take n dots
    center1 = take n $ '.' : (take (if k-n+2>=0 then k-n+2 else 0) hotels) ++ dots
    center2 = take n $ '.' : (take (if k-n+2>=0 then n-2 else k) hotels) ++ dots

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

solve :: Int -> Int -> String
solve n k =
  if k>n-2 && odd k
    then "NO"
    else unlines["YES",border,center1,center2,border]
  where
    dots = repeat '.'
    hotels = repeat '#'

    border = take n dots
    center1 = take n $ '.' : (take (if k<=n-2 then k else k`div`2) hotels) ++ dots
    center2 = take n $ '.' : (take (if k<=n-2 then 0 else k`div`2) hotels) ++ dots

import Data.List

main = do
    [n, k] <- fmap parseInput $ getLine
    let ret = solve n k
    if (length ret) > 0
        then do
            putStrLn "YES"
            mapM_ putStrLn ret
        else putStrLn "NO"

parseInput = map readInt . words
    where readInt x = (read x) :: Int

solve n k
    | even k = [fill 0, fill k', fill k', fill 0]
    | k == (n-2) = [fill 0, fill k, fill 0, fill 0]
    | otherwise = []
    where
        fill x = "." ++ (take x $ repeat '#') ++ (take (n-x-1) $ repeat '.')
        k' = k `div` 2

import Data.List

main = do
    [n, k] <- fmap parseInput $ getLine
    let ret = solve n k
    if (length ret) > 0
        then do
            putStrLn "YES"
            mapM_ putStrLn ret
        else putStrLn "NO"

parseInput = map readInt . words
    where readInt x = (read x) :: Int

solve n k
    | even k = [fill 0, fill k', fill k', fill 0]
    | k <= (n-2) = [fill 0, fill' k pad, fill 0, fill 0]
    | otherwise = []
    where
        fill x = "." ++ (take x $ repeat '#') ++ (take (n-x-1) $ repeat '.')
        fill' x y = (take y $ repeat '.') ++ (take x $ repeat '#') ++ (take (n-x-y) $ repeat '.')
        k' = k `div` 2
        pad = (n - k) `div` 2

import Data.List

main = do
    [n, k] <- fmap parseInput $ getLine
    let ret = solve n k
    if (length ret) > 0
        then do
            putStrLn "YES"
            mapM_ putStrLn ret
        else putStrLn "NO"

parseInput = map readInt . words
    where readInt x = (read x) :: Int

solve n k
    | even k = [fill 0, fill k', fill k', fill 0]
    | k <= (n-2) = [fill 0, fill' k pad, fill 0, fill 0]
    | otherwise = [fill 0, fill (n-2), fill' (k - n + 2) (2*n -3 -k), fill 0]
    where
        fill x = "." ++ (take x $ repeat '#') ++ (take (n-x-1) $ repeat '.')
        fill' x y = (take y $ repeat '.') ++ (take x $ repeat '#') ++ (take (n-x-y) $ repeat '.')
        k' = k `div` 2
        pad = (n - k) `div` 2


{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i
    where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
inf = maxBound `div` 2 :: Int

buildGraph :: Int  -> [(Int,Int)]
buildGraph n = go 1 []
    where
    go v es | v > n = es | otherwise = go (v+1) es'
        where
        es' = es ++ [ (v,u) | (d,u) <- take (4 - degree ! v) l , d < 4 ]
        degree :: Array Int Int
        degree = accumArray (\a b -> a+1) 0 (1,n) (es ++ map swap es)
        l = sort [ (d,i) | (i,d) <- assocs degree, i /= v ]

addEdge :: [(Int,Int)] -> Int -> Int -> [(Int,Int)]
addEdge es n p = es ++ take p [ (u,v) | ((u,v),False) <- assocs g, u < v ]
    where
    g :: Array (Int,Int) Bool
    g = defaultArray False ((1,1),(n,n)) $ do
        (u,v) <- es
        [((u,v),True),((v,u),True)]

main = do
    t <- readLn
    replicateM_ t $ do
        (n,p) <- readIntPair
        let es = addEdge (buildGraph n) n p
        when (length es /= 2 * n + p ) $ putStrLn "something wrong"
        forM_ es $ putStrLn . unwords . map show . p2l

work [n, p] = take (2 * n + p) [show i ++ " " ++ show ((mod (i + d) n) + 1) | d <- [0 ..], i <- [1 .. n]]
main = interact $ unlines . map (unlines . work . map read . words) . tail . lines


import Data.List
import Control.Applicative
import Data.Maybe
one bool = if bool then 1 else 0
data Search = Search{count::Integer,startC::Bool,endA::Bool} deriving (Eq,Show,Ord)
(+!) :: Search -> Search -> Search
a +! b = Search (count a + count b + (one $ endA a && startC b )) (startC a) (endA b)
specChars:: Search -> Int
specChars s = (one $ startC s) + (one $ endA s)
main = do
	[ k, x, n, m ] <- (map read) <$> words <$> getLine ::IO [Int]
	mapM putStrLn $ solution k x n m where
		solution k x n m = let
			iter a b k = if k == 2 then b else iter b (a+!b) (k - 1 )
			iterS a b k = if k == 2 then b else iterS b (a++b) (k - 1 )
			choices n = if n == 0 then [[]] else [c:cs| c<-[False,True], cs <- choices (n-1)]
			variants = [(Search (toInteger a) xa ya ,Search (toInteger b) xb yb) | [xa,ya, xb, yb] <-(choices 4),
				a <- [0..div (n - one xa - one ya ) 2],
				b <- [0..div (m - one xb - one yb ) 2]]
			search = find fitting variants where
				fitting (a,b) = (count $ iter a b k) == (toInteger x)
			complete u l = 	(if startC u then "C" else []) ++
						   	replicate (l - (2 * (fromIntegral $ count u)) - specChars u) 'X' ++
						   	(foldl' (++) "" $ replicate (fromIntegral $ count u) "AC") ++
						   	if endA u then "A" else []
			strings = do
				(a,b) <- search
				return [complete a n, complete b m]
			in fromMaybe  ["Happy new year!"] strings
			--in [show $ choices k]

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

times s k = concat $ take k $ repeat s

check k x (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (fromIntegral ac1,h1,l1) (fromIntegral ac2,h2,l2) == fromIntegral x
    where
    go 0 (ac,_,_) _ = ac :: Int64
    go k (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac2,h2,l2) (ac3,h3,l3)
        where
            ac3 = ac1 + ac2 + (if l1 == 'A' && h2 == 'C' then 1 else 0)
            h3 = h1
            l3 = l2

build 1 _ ch _ = [ch]
build n ac 'X' 'A' = times "X" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'X' 'X' = times "X" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n ac 'X' 'C' = times "X" (n - 2 * ac) ++ times "AC" ac
build n ac 'C' 'A' = times "C" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'C' 'X' = times "C" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n ac 'C' 'C' = times "C" (n - 2 * ac) ++ times "AC" ac
build n ac 'A' 'A' = times "A" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'A' 'X' = times "A" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n 0  'A' 'C' = "A" ++ times "X" (n - 2) ++ "C"
build n ac 'A' 'C' = times "A" (n - 2 * ac) ++ times "AC" ac

valid 1 _  h l = h == l
valid n 0  'A' 'C' = n > 2
valid n ac 'X' 'A' = ac * 2 <= n - 2
valid n ac 'X' 'X' = ac * 2 <= n - 2
valid n ac 'X' 'C' = ac * 2 <= n - 1
valid n ac 'C' 'A' = ac * 2 <= n - 2
valid n ac 'C' 'X' = ac * 2 <= n - 2
valid n ac 'C' 'C' = ac * 2 <= n - 1
valid n ac 'A' 'A' = ac * 2 <= n - 1
valid n ac 'A' 'X' = ac * 2 <= n - 1
valid n ac 'A' 'C' = ac * 2 <= n

search :: Int -> Int -> Int -> Int -> Maybe (String,String)
search k x n m = listToMaybe $ do
    ac1 <- [0..div n 2]
    h1  <- "ACX"
    l1  <- "ACX"
    guard (valid n ac1 h1 l1)
    ac2 <- [0..div m 2]
    h2  <- "ACX"
    l2  <- "ACX"
    guard (valid m ac2 h2 l2)
    guard (check k x (ac1,h1,l1) (ac2,h2,l2))
    let s1 = build n ac1 h1 l1
    let s2 = build m ac2 h2 l2
    return (s1,s2)

main = do
    [k,x,n,m] <- readInts
    case search k x n m of
        Nothing      -> putStrLn "Happy new year!"
        Just (l1,l2) -> do
            putStrLn l1
            putStrLn l2

import Data.List
import Control.Applicative
import Data.Maybe
one bool = if bool then 1 else 0
data Search = Search{count::Integer,startC::Bool,endA::Bool} deriving (Eq,Show,Ord)
(+!) :: Search -> Search -> Search
a +! b = Search (count a + count b + (one $ endA a && startC b )) (startC a) (endA b)
specChars:: Search -> Int
specChars s = (one $ startC s) + (one $ endA s)
main = do
	[ k, x, n, m ] <- (map read) <$> words <$> getLine ::IO [Int]
	mapM putStrLn $ solution k x n m where
		solution k x n m = let
			iter a b k = if k == 2 then b else iter b (a+!b) (k - 1 )
			iterS a b k = if k == 2 then b else iterS b (a++b) (k - 1 )
			choices n = if n == 0 then [[]] else [c:cs| c<-[False,True], cs <- choices (n-1)]
			variants = [(Search (toInteger a) xa ya ,Search (toInteger b) xb yb) | [xa,ya, xb, yb] <-(choices 4),
				a <- [0..div (n - one xa - one xb ) 2],
				b<- [0..div (m - one xa - one xb ) 2]]
			search = find fitting variants where
				fitting (a,b) = (count $ iter a b k) == (toInteger x)
			complete u l = 	(if startC u then "C" else []) ++
						   	replicate (l - (2 * (fromIntegral $ count u)) - specChars u) 'X' ++
						   	(foldl' (++) "" $ replicate (fromIntegral $ count u) "AC") ++
						   	if endA u then "A" else []
			strings = do
				(a,b) <- search
				return [complete a n, complete b m]
			in fromMaybe  ["Happy new year!"] strings
			--in [show $ choices k]

import Data.List
import Control.Applicative
import Data.Maybe
main = do
	[ k, x, n, m ] <- (map read) <$> words <$> getLine ::IO [Int]
	mapM putStrLn $ solution k x n m where
		solution k x n m = let
			iter a b k = if k == 2 then b else iter b (a+b) (k - 1 )
			variants = [(a,b) | a <- [0..div n 2], b<- [0..div m 2]]
			variants2 = [(a,b) | a <- [0..div (n-1) 2], b<- [0..div (m-1) 2]]
			search = find fitting variants where
				fitting (a,b) = iter (toInteger a) (toInteger b) k == (toInteger x)
			search2 = find fitting variants2 where
				fitting (a,b) = iter (toInteger b) (toInteger (a+b+1)) (k-1) == (toInteger x)
			complete u l = replicate (l - (2 * u)) 'X' ++ (foldl' (++) "" $ replicate u "AC")
			completeA u = replicate (n - 1 - (2 * u)) 'X' ++ (foldl' (++) "" $ replicate u "AC") ++ "A"
			completeB u = "C" ++ replicate (m - 1 - (2 * u)) 'X' ++ (foldl' (++) "" $ replicate u "AC")
			strings = do
				(a,b) <- search
				return [complete a n, complete b m]
			strings2 = do
				(a,b) <- search2
				return [completeA a, completeB b]
			in (fromMaybe ( fromMaybe ["Happy new year!"] strings2  )  strings)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

times s k = concat $ take k $ repeat s

check k x (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac1,h1,l1) (ac2,h2,l2) == x
    where
    go 0 (ac,_,_) _ = ac
    go k (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac2,h2,l2) (ac3,h3,l3)
        where
            ac3 = ac1 + ac2 + (if l1 == 'A' && h2 == 'C' then 1 else 0)
            h3 = h1
            l3 = l2

build 1 _ ch _ = [ch]
build n ac 'X' 'A' = times "X" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'X' 'X' = times "X" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n ac 'X' 'C' = times "X" (n - 2 * ac) ++ times "AC" ac
build n ac 'C' 'A' = times "C" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'C' 'X' = times "C" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n ac 'C' 'C' = times "C" (n - 2 * ac) ++ times "AC" ac
build n ac 'A' 'A' = times "A" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'A' 'X' = times "A" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n ac 'A' 'C' = times "A" (n - 2 * ac) ++ times "AC" ac

valid 1 _  h l = h == l
valid 2 ac 'A' 'C' = ac == 1
valid n ac 'X' 'A' = ac * 2 <= n - 2
valid n ac 'X' 'X' = ac * 2 <= n - 2
valid n ac 'X' 'C' = ac * 2 <= n - 1
valid n ac 'C' 'A' = ac * 2 <= n - 2
valid n ac 'C' 'X' = ac * 2 <= n - 2
valid n ac 'C' 'C' = ac * 2 <= n - 1
valid n ac 'A' 'A' = ac * 2 <= n - 1
valid n ac 'A' 'X' = ac * 2 <= n - 1
valid n ac 'A' 'C' = ac * 2 <= n

search :: Int -> Int -> Int -> Int -> Maybe (String,String)
search k x n m = listToMaybe $ do
    ac1 <- [0..div n 2]
    h1  <- "ACX"
    l1  <- "ACX"
    guard (valid n ac1 h1 l1)
    ac2 <- [0..div m 2]
    h2  <- "ACX"
    l2  <- "ACX"
    guard (valid m ac2 h2 l2)
    guard (check k x (ac1,h1,l1) (ac2,h2,l2))
    let s1 = build n ac1 h1 l1
    let s2 = build m ac2 h2 l2
    return (s1,s2)

main = do
    [k,x,n,m] <- readInts
    case search k x n m of
        Nothing      -> putStrLn "Happy new year!"
        Just (l1,l2) -> do
            putStrLn l1
            putStrLn l2

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

times s k = concat $ take k $ repeat s

check k x (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac1,h1,l1) (ac2,h2,l2) == x
    where
    go 0 (ac,_,_) _ = ac
    go k (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac2,h2,l2) (ac3,h3,l3)
        where
            ac3 = ac1 + ac2 + (if l1 == 'A' && h2 == 'C' then 1 else 0)
            h3 = h1
            l3 = l2

build 1 _ ch _ = [ch]
build n ac 'X' 'A' = times "X" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'X' 'X' = times "X" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n ac 'X' 'C' = times "X" (n - 2 * ac) ++ times "AC" ac
build n ac 'C' 'A' = times "C" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'C' 'X' = times "C" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n ac 'C' 'C' = times "C" (n - 2 * ac) ++ times "AC" ac
build n ac 'A' 'A' = times "A" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'A' 'X' = times "A" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n ac 'A' 'C' = times "A" (n - 2 * ac) ++ times "AC" ac

valid 1 _  h l = h == l
valid n ac 'X' 'A' = ac * 2 <= n - 2
valid n ac 'X' 'X' = ac * 2 <= n - 2
valid n ac 'X' 'C' = ac * 2 <= n - 1
valid n ac 'C' 'A' = ac * 2 <= n - 2
valid n ac 'C' 'X' = ac * 2 <= n - 2
valid n ac 'C' 'C' = ac * 2 <= n - 1
valid n ac 'A' 'A' = ac * 2 <= n - 1
valid n ac 'A' 'X' = ac * 2 <= n - 1
valid n ac 'A' 'C' = ac * 2 <= n

search :: Int -> Int -> Int -> Int -> Maybe (String,String)
search k x n m = listToMaybe $ do
    ac1 <- [0..div n 2]
    h1  <- "ACX"
    l1  <- "ACX"
    guard (valid n ac1 h1 l1)
    ac2 <- [0..div m 2]
    h2  <- "ACX"
    l2  <- "ACX"
    guard (valid m ac2 h2 l2)
    guard (check k x (ac1,h1,l1) (ac2,h2,l2))
    let s1 = build n ac1 h1 l1
    let s2 = build m ac2 h2 l2
    return (s1,s2)

main = do
    [k,x,n,m] <- readInts
    case search k x n m of
        Nothing      -> putStrLn "Happy new year!"
        Just (l1,l2) -> do
            putStrLn l1
            putStrLn l2

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

times s k = concat $ take k $ repeat s

check k x (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (fromIntegral ac1,h1,l1) (fromIntegral ac2,h2,l2) == fromIntegral x
    where
    go 0 (ac,_,_) _ = ac :: Int64
    go k (ac1,h1,l1) (ac2,h2,l2) = go (k-1) (ac2,h2,l2) (ac3,h3,l3)
        where
            ac3 = ac1 + ac2 + (if l1 == 'A' && h2 == 'C' then 1 else 0)
            h3 = h1
            l3 = l2

build 1 _ ch _ = [ch]
build n ac 'X' 'A' = times "X" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'X' 'X' = times "X" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n ac 'X' 'C' = times "X" (n - 2 * ac) ++ times "AC" ac
build n ac 'C' 'A' = times "C" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'C' 'X' = times "C" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n ac 'C' 'C' = times "C" (n - 2 * ac) ++ times "AC" ac
build n ac 'A' 'A' = times "A" (n - 2 * ac - 1) ++ times "AC" ac ++ "A"
build n ac 'A' 'X' = times "A" (n - 2 * ac - 1) ++ times "AC" ac ++ "X"
build n ac 'A' 'C' = times "A" (n - 2 * ac) ++ times "AC" ac

valid 1 _  h l = h == l
valid 2 ac 'A' 'C' = ac == 1
valid n ac 'X' 'A' = ac * 2 <= n - 2
valid n ac 'X' 'X' = ac * 2 <= n - 2
valid n ac 'X' 'C' = ac * 2 <= n - 1
valid n ac 'C' 'A' = ac * 2 <= n - 2
valid n ac 'C' 'X' = ac * 2 <= n - 2
valid n ac 'C' 'C' = ac * 2 <= n - 1
valid n ac 'A' 'A' = ac * 2 <= n - 1
valid n ac 'A' 'X' = ac * 2 <= n - 1
valid n ac 'A' 'C' = ac * 2 <= n

search :: Int -> Int -> Int -> Int -> Maybe (String,String)
search k x n m = listToMaybe $ do
    ac1 <- [0..div n 2]
    h1  <- "ACX"
    l1  <- "ACX"
    guard (valid n ac1 h1 l1)
    ac2 <- [0..div m 2]
    h2  <- "ACX"
    l2  <- "ACX"
    guard (valid m ac2 h2 l2)
    guard (check k x (ac1,h1,l1) (ac2,h2,l2))
    let s1 = build n ac1 h1 l1
    let s2 = build m ac2 h2 l2
    return (s1,s2)

main = do
    [k,x,n,m] <- readInts
    case search k x n m of
        Nothing      -> putStrLn "Happy new year!"
        Just (l1,l2) -> do
            putStrLn l1
            putStrLn l2


import qualified Data.ByteString.Lazy.Char8 as P

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List

import Data.Array.Unboxed
import Data.Bits
import Data.Word

data Action = Action !Word64 !(UArray Int Int)
data Status = Status !Word64 !Word64

step :: Status -> Action -> [Status]
step (Status smask vis) (Action amask ixs) = let
  existingOnes = popCount (smask .&. amask)
  newIxs = popCount (complement vis .&. amask)
  in  do
  resOnes <- [existingOnes .. existingOnes + newIxs]
  let  ares = (bit (ixs ! resOnes) - 1) .&. amask
  pure $ Status (smask .&. complement amask .|. ares) (vis .|. amask)

stepEach :: [Status] -> Action -> [Status]
stepEach s a = concatMap (`step` a) s

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n, k] <- readInts
  actions <- replicateM k $ do
    qi : ji <- readInts
    let
      amask = foldl' (\acc ix -> acc .|. bit ix) 0 ji
      ixs = array (0, qi) $ (qi, n+1) : zip [0..] ji
    pure $ Action amask ixs
  let
    start = Status 0 0
    opts = foldl stepEach [start] actions
    tarVis = bit (n + 1) - bit 1
    ok = and $ do
      Status smask vis <- opts
      pure $ (n == 1 || vis == tarVis) && smask .&. (smask + 2) == 0
  lift $ putStrLn $ if  ok
    then  "ACCEPTED"
    else  "REJECTED"

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.dropWhile (<= '\r') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

import Control.Monad
import Data.Array.Unboxed
import Data.Bits
import Data.List
import Data.Word

solve :: IO ()
solve = do
    [n, k] <- readMany
    a <- replicateM k readMany
    let step (prvm, xs) ~(q:js) = (prvm .|. m, concatMap gen xs) where
            ma = listArray (0, q) $ scanl (.|.) 0 $ map (bit . subtract 1) $ sort js :: UArray Int Word64
            m = ma!q
            com = prvm .&. m
            gen x = map ((prvx .|.) . (ma!)) [ones .. q-zeros] where
                ones = popCount $ com .&. x
                zeros = popCount $ com .&. complement x
                prvx = x .&. complement m
        (m, xs) = foldl' step (0, [0]) a
        ok = n == 1 || m == bit n - 1 && all (\x -> x .&. (x + 1) == 0) xs
    putStrLn $ if ok then "ACCEPTED" else "REJECTED"

readMany :: Read a => IO [a]
readMany = map read . words <$> getLine

main :: IO ()
main = solve

-- Resubmission, to find out how much 64-bit helps

import qualified Data.ByteString.Lazy.Char8 as P

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List

import Data.Array.Unboxed
import Data.Bits
import Data.Word

data Action = Action !Word64 !Int !(UArray Int Int)
newtype Status = Status Word64

step :: Status -> Action -> [Status]
step (Status smask) (Action amask newIxs ixs) = let
  existingOnes = popCount (smask .&. amask)
  in  do
  resOnes <- [existingOnes .. existingOnes + newIxs]
  let  ares = (bit (ixs ! resOnes) - 1) .&. amask
  pure $ Status (smask .&. complement amask .|. ares)

stepEach :: [Status] -> Action -> [Status]
stepEach s a = concatMap (`step` a) s

processAction :: Int -> (Word64, Action) -> [Int] -> (Word64, Action)
processAction n (vis, _) (qi : ji) = let
  amask = foldl' (\acc ix -> acc .|. bit ix) 0 ji
  newIxs = popCount (amask .&. complement vis)
  ixs = array (0, qi) $ (qi, n+1) : zip [0..] ji
  in  (vis .|. amask, Action amask newIxs ixs)
processAction _ _ _ = error "unexpected empty line in input"

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n, k] <- readInts
  rawActions <- replicateM k readInts
  let
    process = scanl (processAction n) (0, undefined) rawActions
    actions = tail $ map snd process
    vis = fst $ last process
    start = Status 0
    opts = foldl stepEach [start] actions
    tarVis = bit (n + 1) - bit 1
    ok = and $ (n == 1 || vis == tarVis) : do
      Status smask <- opts
      pure $ smask .&. (smask + 2) == 0
  lift $ putStrLn $ if  ok
    then  "ACCEPTED"
    else  "REJECTED"

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.dropWhile (<= '\r') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List
import Data.Semigroup

import Data.Array.Unboxed

step :: UArray Int Int -> [Int] -> [UArray Int Int]
step arr ixs = let
  neg = length [() | i <- ixs, arr ! i < 0]
  nonpos = length [() | i <- ixs, arr ! i <= 0]
  in  do
  newNeg <- [neg .. nonpos]
  pure $ arr // zip ixs (replicate newNeg (0-1) ++ repeat 1)

stepEach :: [UArray Int Int] -> [Int] -> [UArray Int Int]
stepEach arrs ixs = do
  arr <- arrs
  step arr ixs

sorted :: UArray Int Int -> Bool
sorted arr = null $ dropWhile (== 1) $ dropWhile (< 0) $ elems arr

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n, k] <- readInts
  acts <- replicateM k $ tail <$> readInts
  let
    start = accumArray undefined 0 (1, n) []
    opts = foldl stepEach [start] acts
  lift $ putStrLn $ if  all sorted opts
    then  "ACCEPTED"
    else  "REJECTED"

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.dropWhile (<= '\r') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

putInts :: [Int] -> SIO ()
putInts li = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (map B.intDec li)
  in  lift $ B.hPutBuilder stdout outBuilder


module Main where

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = words <$> getLine

getIntList :: IO [Int]
getIntList = map read <$> getStrList

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, a, b] <- getIntList
        putStrLn $ f n a b

f :: Int -> Int -> Int -> String
f n a b = take n . cycle $ (take a $ (take b ['a' .. 'z'] ++ cycle [['a'..'z'] !! (b - 1)]))

solve :: [Int] -> String
solve [n,a,b] = take n $ cycle $ take b ['a'..]

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

import Control.Monad (forM_)
import Data.Char (chr, ord)

solve n a b = take n res where
	period = replicate (b-1) 1 ++ replicate (a-b) 0
	cyclic = if null period then repeat 0 else cycle period
	res = map chr' $ map (`mod` 26) $ scanl(+) 0 cyclic
	chr' k = chr (k + ord 'a')
main = do
	t <- fmap read getLine
	forM_ [1..t] $ \i -> do
		[n,a,b] <- fmap (map read.words) getLine
		putStrLn (solve n a b)

import Control.Monad

alf = ['a'..'z']

r str = concat (repeat str)

substring :: Int -> Int-> String
substring a b = take a ((take b alf) ++ (repeat (alf!!(b-1))))

foo :: Int -> Int -> Int -> String
foo n a b = take n (r (substring a b))

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

main :: IO()
main = do
  t <- readLn :: IO Int
  forM_ [1..t] $ \i -> do
    arr <- readInts
    putStrLn (foo (arr!!0) (arr!!1) (arr!!2))

alph :: String
alph = ['a'..'z']

addReplicas :: Int -> String -> String
addReplicas n s
    | n <= l    = take n s
    | otherwise = s ++ addReplicas (n-l) s
    where
        l = length s

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    (n:a:b:_) <- readInts
    putStrLn $ addReplicas n (take b alph)
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readInts
    testCases t

readInts :: IO [Int]
readInts = map read . words <$> getLine

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

onecase = do
		[n,a,b]<- map read <$> words <$> getLine::IO [Int]
		putStrLn $ take n $ cycle $ take b "abcdefghijklmnopqrstuvwxyz"

main = do
		a<-read <$> getLine ::IO Int
		replicateM_ a onecase

process :: Int -> Int -> Int -> [Char]
process n a b = take n.cycle.take b $ ['a'..'z']

readInt :: String -> Int
readInt = read

run :: Int -> IO ()
run 0 = return ()
run t = do
    [n,a,b] <- fmap (map readInt.words) getLine
    putStrLn $ process n a b
    run (t-1)

main :: IO ()
main = do
    t <- fmap readInt getLine
    run t

import Data.Char

main :: IO ()
main = do
    getLine
    answers <- map (solve . map read . words) <$> lines <$> getContents
    mapM_ putStrLn answers

solve :: [Int] -> String
solve [len,sub,chars] = take len . cycle $ segment
    where segment = replicate (sub - chars) 'a' ++ (take chars ['a'..'z'])

import Control.Monad (replicateM_)
getList :: Read b => IO [b]
getList = map read . words <$> getLine

main :: IO ()
main = readLn >>= flip replicateM_ (getList >>= putStrLn . solve)

solve :: [Int] -> String
solve [n,a,b] = take n $ cycle letters where
    letters = replicate (a-b) 'a' ++ take b ['a'..'z']

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

onecase = do
		[n,a,b]<- map read <$> words <$> getLine::IO [Int]
		putStrLn $ take n $ cycle $ take b "abcdefghijklmnopqrstuvwyz"

main = do
		a<-read <$> getLine ::IO Int
		replicateM_ a onecase

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

onecase = do
		[n,a,b]<- map read <$> words <$> getLine::IO [Int]
		print $ take n $ cycle $ take b "abcdefghijklmnopqrstuvwyz"

main = do
		a<-read <$> getLine ::IO Int
		replicateM_ a onecase


import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe
import IO

main = do C.hGetContents stdin >>= putStrLn . show . gao . map (fst . fromJust . C.readInt) . tail . C.words

gao a = (sum a -) $ (2*) $ minimum $ zipWith (+) (f a) $ reverse $ f $ reverse a where
	f = scanl1 min . scanl (+) 0

main = interact (ans)
ans theInput = show answer where
  [[n],a] = map (map (read::String->Int)) (map words (lines theInput))
  lastMax [] = (0,0,0,0)
  lastMax (x:xs) = (if x+y > 0 then (max u (v+x+x+y+z),v+x,x+y,z) else (max u (v+z-y),v+x,0,z-x-y)) where
    (u,v,y,z) = lastMax xs
  answer = u-v where (u,v,y,z) = lastMax a

import Data.List

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

solve :: [Int] -> Int
solve a = let pre = calcMaxSum a
              suf = reverse $ calcMaxSum (reverse a)
          in solve' pre (tail suf) (sum a)
          where solve' :: [Int] -> [Int] -> Int -> Int
                solve' [a]    []     m = max a m
                solve' (a:ax) (b:bx) m = solve' ax bx (max m (a + b))

accumulate :: (a -> b -> a) -> a -> [b] -> [a]
accumulate _  _    []    = []
accumulate op last (a:s) = let v = op last a
                           in v : accumulate op v s

transition :: (Int, Int) -> Int -> (Int, Int)
transition (a, b) c = (a - c, max (c + max a b) (a - c))

calcMaxSum :: [Int] -> [Int]
calcMaxSum = map snd . accumulate transition (0, 0)

plus :: [Int] -> Int -> Int
plus [] cur = cur
plus (x:xs) cur = max cur $ plus xs $ max 0 $ cur + x

main = do
	n <- getLine >>= return . read :: IO Int
	a <- getLine >>= return . (map read) . words :: IO [Int]
	putStrLn $ show $ (plus a 0 * 2) - (foldl (+) 0 a)


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

import Data.List

main = do

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

	let
		money_spent = giveBadges 0 badges

	putStrLn $ show money_spent

giveBadges :: Int -> [Int] -> Int
giveBadges _ [] = 0
giveBadges prev (x:xs) =
	let
		calc = if prev >= x then prev - x + 1 else 0
	in
		calc + giveBadges (max (prev + 1) x) xs

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

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

createMap :: [[Int]] -> Map.Map Int Int
createMap [] = Map.empty
createMap (x:xs) = Map.insert (head x) (length x) $ createMap xs

main = do

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

	let
		money_spent = giveBadges 0 badges

	putStrLn $ show money_spent

giveBadges :: Int -> [Int] -> Int
giveBadges _ [] = 0
giveBadges prev (x:xs) =
	let
		calc = if prev >= x then prev - x + 1 else 0
	in
		calc + giveBadges (max (prev + 1) x) xs

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

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

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

main = do
  getLine
  xs <- getInts

  let
    f _ [] = 0
    f m (x:xs)
      | x > m = f (x+1) xs
      | otherwise = (m-x) + f (m+1) xs

  print $ f (minimum xs) $ sort xs

-- Codeforces 546B

import Data.List

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    getLine >>= print . solve . sort . map read . words

-- note: only cdn increase the coolness value, can't decrease it, so need do sort.

solve :: [Int] -> Int
solve [] = 0
solve [_] = 0
solve (x:y:xs) = if (y <= x) then (x-y+1) + solve (x+1:xs) else solve (y:xs)

import Data.List
import Data.Map (Map)

main = do
    getLine
    input <- getLine
    let fs = sort $ map (read :: String -> Int) (words input)
    putStrLn $ show $ f fs

f :: [Int] -> Int
f [] = 0
f [_] = 0
f (x:y:xs) = if y <= x then x - y + 1 + f (x + 1:xs) else f (y:xs)

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

process::Int->Int->[Int]->Int
process n m [] | m==0 =n
               | otherwise = process (n+m) (m-1) []
process n m (x:xs) | x==0 && m>0 = process (n+m) (m-1) xs
                   | x==0 = process n m xs
                   | x==1 = process (n+m) m xs
                   | otherwise = process (n+m) (m+x-1) xs

main = do
  n <- read <$> getLine::IO Int
  d<-map read <$> words <$> getLine ::IO [Int]
  let x = accumArray (+) 0 (1,n) $ zip d (repeat 1)
  print $ process 0 0 (elems x)

import Data.List (sort)

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

solve :: [Int] -> Int
solve xs = sum (scanl (\x y -> max (x + 1) y) 0 (sort xs)) - sum xs

import Data.List
main = interact $ show . solve 0 . sort . map read . tail . words
solve p (a:as) | a <= p = p-a+1 + solve (p+1) as
               | otherwise = solve a as
solve _ [] = 0

import Control.Applicative
import Control.Monad
import Data.Array

process [] x y = x + (div (y*(y+1)) 2)
process (a:as) x y	| a==0 = process as (x+y) (max (y-1) 0)
                 	| a==1 = process as (x+y) y
	                | otherwise = process as (x+y) (y+a-1)

main= do
	n<-read <$> getLine::IO Int
	s<- map read .words <$> getLine ::IO [Int]
	let a= accumArray (+) 0 (1,3000) [(i,1)|i<-s]
	print $ process (elems a) 0 0

import Data.List (sort)

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

solve :: [Int] -> Int
solve = fst . foldl step (0, 0) . sort
        where step (sum, m) a = let b = max (m + 1) a
                                    d = max 0 (b - a)
                                in (sum + d, b)

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

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

createMap :: [[Int]] -> Map.Map Int Int
createMap [] = Map.empty
createMap (x:xs) = Map.insert (head x) (length x) $ createMap xs

main = do

	n <- fmap read getLine :: IO Int
	badges <- fmap group $ fmap sort $ fmap (map read) $ fmap words $ getLine :: IO [[Int]]

	let
		badges_list = map head $ badges
		descriptor = createMap badges
		money_spent = giveBadges badges_list descriptor

	putStrLn $ show money_spent

giveBadges :: [Int] -> Map.Map Int Int -> Int
giveBadges [] _ = 0
giveBadges badges@(b:bs) map
	| total_of_badge > 1 = 1 + (giveBadges badges $ updateMap b (b+1) map)
	| otherwise = giveBadges bs map
	where
		total_of_badge = fromJust $ Map.lookup b map

		updateMap :: Int -> Int -> Map.Map Int Int -> Map.Map Int Int
		updateMap a b map =
			let
				mapA = case Map.lookup a map of
					Nothing -> Map.insert a 1 map
					Just 1 -> Map.delete a map
					Just _ -> Map.adjust (+(-1)) a map
				mapB = case Map.lookup b mapA of
					Nothing -> Map.insert b 1 mapA
					Just _ -> Map.adjust (+1) b mapA
			in
				mapB

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

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

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

main = do
  n <- readLn
  xs <- getInts

  let
    f _ [] = 0
    f (x:xs) ys = abs (x-m) + f xs (ys \\ [m])
      where
        m = minimumBy (comparing (\v -> abs $ v - x)) ys

  print $ f xs [1..n]

-- Codeforces 546B

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

solve :: [Int] -> Int
solve xs = (m * (m+1) `div` 2) - sum xs where m = maximum xs

import Data.List
import Data.Map (Map)

main = do
    getLine
    input <- getLine
    let fs = reverse . sort $ map (read :: String -> Int) (words input)
    putStrLn $ show $ f (length fs) fs

f :: Int -> [Int] -> Int
f _ [] = 0
f max (x:xs) = (max - x) + f (max - 1) xs

import Data.List
import Data.Map (Map)

main = do
    getLine
    input <- getLine
    let fs = reverse . sort $ map (read :: String -> Int) (words input)
    putStrLn $ show $ f (length fs + minimum fs - 1) fs

f :: Int -> [Int] -> Int
f _ [] = 0
f max (x:xs) = (max - x) + f (max - 1) xs

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

process::Int->Int->[Int]->Int
process n m [] | m==0 =n
               | otherwise = process (n+m) (m-1) []
process n m (x:xs) | x==0 && m>0 = process (n+m) (m-1) xs
                   | x==0 = process n m xs
                   | x==1 = process (n+m) m xs
                   | otherwise = process n (m+x-1) xs

main = do
  n <- read <$> getLine::IO Int
  d<-map read <$> words <$> getLine ::IO [Int]
  let x = accumArray (+) 0 (1,n) $ zip d (repeat 1)
  print $ process 0 0 (elems x)

import Control.Applicative ((<$>), (<*>))
import Control.Arrow ((&&&))
import Data.List (sort)

main :: IO ()
main = print =<< solve <$> readLn <*> (map read <$> words <$> getLine)

solve :: Int -> [Int] -> Int
solve n xs = sum ys - n * min 0 (minimum ys)
  where ys = zipWith (-) (enumFrom (minimum xs)) (sort xs)

import Data.List (sort)

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

solve :: [Int] -> Int
solve = sum . zipWith (-) [1..] . sort

import Control.Arrow ((&&&))
import Data.List (sort)

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

solve :: [Int] -> Int
solve = sum . uncurry (zipWith (-)) . (enumFrom . minimum &&& sort)

import Data.List (sort)

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

solve :: [Int] -> Int
solve a = length . filter id $ zipWith (>) [1..n] (sort a)
          where n = length a


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

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

data Player  =  S | Z
  deriving Eq

solve :: [Int] -> Double
solve as  =  solve' S 1.0
  where
    eps  =  1e-09
    [a, b, c, d]  =  map fromIntegral as
    solve' player p
      | p <= eps  =  0
      | player == S  =  p * a / b + solve' Z (p * (1 - a / b))
      | player == Z  =  solve' S (p * (1 - c / d))

main :: IO ()
main  =  reads >>= print . solve

main = interact $ show . getAnswer . map read . words
    where getAnswer [a, b, c, d] = (a * d) / (a * d + b * c - a * c)

readInts :: String -> [Double]
readInts str = map read (words str)

main :: IO ()
main = do
  [a,b,c,d] <- fmap readInts getLine
  --print $ (b*b/d)/(a*b*c+a*a*b-a*a*c)
  let p = a/b
  let _p = 1-p
  let _q = 1-c/d
  print $ p/(1-_p*_q)

main = do
    l <- getLine
    let a = (map read (words l)) :: [Double]
    let b = (a!!0 * a!!3 / (a!!0*a!!3 + a!!1*a!!2 - a!!0*a!!2)) :: Double
    putStrLn(show(b))

import Control.Applicative
import Control.Monad
import Data.List
import Text.Printf

main = do
	[ a, b, c, d ] <- map read . words <$> getLine
	printf "%.8f\n" $ solve 0 ( a / b ) ( c / d )

solve :: Int -> Double -> Double -> Double
solve 100000 _ _ = 0
solve depth prob1 prob2 = ( ( 1 - prob1 ) * ( 1 - prob2 ) ) ^ depth * prob1 + ( solve ( depth + 1 ) prob1 prob2 )

module Main where

import System.Environment
import System.Exit

main :: IO ()
main = getLine >>= print . solve . parseList

parseList :: Read a => String -> [a]
parseList = map read . words

solve :: [Double] -> Double
solve (a:b:c:d:_) = sum $ takeWhile (>= 10**(-9)) probability
  where
    probability :: [Double]
    probability = map (*p) . zipWith (flip (^)) [0..] $ repeat q

    -- The first is the winner
    p :: Double
    p = a / b

    -- No one is winner
    q :: Double
    q = (1 - p) * (1 - c / d)

solve _           = undefined

module Main where

import System.Environment
import System.Exit

main :: IO ()
main = getLine >>= print . solve . parseList

parseList :: Read a => String -> [a]
parseList = map read . words

-- solve :: [Double] -> Double
-- solve (a:b:c:d:_) = sum $ takeWhile (>= 10**(-9)) probability
--   where
--     probability :: [Double]
--     probability = map (*p) . zipWith (flip (^)) [0..] $ repeat q
--
--     -- The first is the winner
--     p :: Double
--     p = a / b
--
--      -- No one is winner
--     q :: Double
--     q = (1 - p) * (1 - c / d)
--
-- solve _           = undefined

solve :: [Double] -> Double
solve (a:b:c:d:_) = p / (1 - q)
  where
    -- The first is the winner
    p :: Double
    p = a / b

    -- No one is winner
    q :: Double
    q = (1 - p) * (1 - c / d)

solve :: Double -> Double -> Double -> Double -> Double
solve a b c d =
    p1 * (sum $ takeWhile (> 10**(-6)) $ iterate (* k) 1)
  where
    p1 = a / b
    k = (1 - p1) * (1 - c / d)

main = do
  [a, b, c, d] <- (map read . words) `fmap` getLine
  print $ solve a b c d

import Control.Applicative
import Control.Monad
import Data.List
import Text.Printf

main = do
	[ a, b, c, d ] <- map read . words <$> getLine
	printf "%.7f\n" $ solve 0 ( a / b ) ( c / d )

solve :: Int -> Double -> Double -> Double
solve 1000 _ _ = 0
solve depth prob1 prob2 = ( ( 1 - prob1 ) * ( 1 - prob2 ) ) ^ depth * prob1 + ( solve ( depth + 1 ) prob1 prob2 )

module Main where

import System.Environment
import System.Exit

main :: IO ()
main = getLine >>= print . solve . parseList

parseList :: Read a => String -> [a]
parseList = map read . words

solve :: [Double] -> Double
solve (a:b:c:d:_) = sum $ takeWhile (>= 10**(-7)) probability
  where
    probability :: [Double]
    probability = map (*p) . zipWith (flip (^)) [0..] $ repeat q

    -- The first is the winner
    p :: Double
    p = a / b

    -- No one is winner
    q :: Double
    q = (1 - p) * (1 - c / d)

solve _           = undefined

module Main where

import System.Environment
import System.Exit

main :: IO ()
main = getLine >>= print . solve . parseList

parseList :: Read a => String -> [a]
parseList = map read . words

solve :: [Double] -> Double
solve (a:b:c:d:_) = sum $ takeWhile (>= 10**(-6)) probability
  where
    probability :: [Double]
    probability = map (*p) . zipWith (flip (^)) [0..] $ repeat q

    -- The first is the winner
    p :: Double
    p = a / b

    -- No one is winner
    q :: Double
    q = (1 - p) * (1 - c / d)

solve _           = undefined

readInts :: String -> [Double]
readInts str = map read (words str)

main :: IO ()
main = do
  [a,b,c,d] <- fmap readInts getLine
  print $ (b*b/d)/(a*b*c+a*a*b-a*a*c)

main = do
    l <- getLine
    let a = (map read (words l)) :: [Double]
    let b = (a!!0 * a!!3 / (a!!1*a!!3 - a!!0*a!!2)) :: Double
    putStrLn(show(b))