import Data.Char (ord, chr)

shrink :: String -> String
shrink [] = "0"
shrink (x: xs) = if x == '0'
  then shrink xs
  else (x: xs)

for :: Int -> IO ()
for 0 = pure ()
for i = do
  a <- getLine
  let c = head a
  if c /= '1'
    then putStrLn ((chr (ord c - 1)): tail a)
    else putStrLn $ shrink $ tail a
  for $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  for n

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import           Prelude               hiding (getLine)
import           Control.Arrow
import           Control.Monad
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.List

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [m] <- ri
        return m
    mapM_ (putStrLn.show.solve) tcs

solve m = m - roundNum m

roundNum = read . ('1':) . map (const '0') . tail . show :: Int -> Int

module Main where

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

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep = id

parse = read

format = show

solve :: Int -> Int
solve x = x - (head $ filter (<= x) [10^i | i <- [9,8..0]])

--
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- {-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}

import Control.Arrow ((>>>))
import Control.Monad (
    MonadPlus (mplus),
    foldM_,
    forM_,
    guard,
    join,
    replicateM,
    replicateM_,
 )
import qualified Control.Monad as M
import qualified Control.Monad.ST.Strict as ST
import qualified Control.Monad.State.Strict as S
import qualified Control.Monad.Trans.Class as T

import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.IO.Safe as IOA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import Data.Bits
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Int

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Bifunctor (bimap)
import Data.Maybe (fromJust, fromMaybe, isJust)
import qualified Data.Maybe as MB

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List   as L
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Ix as Ix
import qualified Data.Ratio as R

import Control.Monad.Cont (MonadIO (liftIO))
import Data.IORef (modifyIORef, newIORef, readIORef)
import GHC.IO.Handle (hDuplicateTo)
import System.IO (
    IOMode (ReadMode, WriteMode),
    openFile,
    stdin,
    stdout,
    hFlush
 )
import System.Posix.Internals (puts)
import Text.Printf (printf)
import qualified Data.Array.IO.Safe as UOA

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace
--
-- tracing t x = trace (t ++ " = " ++ show x) x
-- debugging x t = tracing t x

-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "YES"
                else "NO"
    printf "%s\n" result

{- END OF GENERAL -}

solve :: Int -> Int
solve m = m - last roundPrices
    where
        roundPrices = L.takeWhile (<= m) $ iterate (* 10) 1

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        m <- B8.getLine <&> readIntB8
        let answer = solve m
        printf "%d\n" answer

{-# LANGUAGE TypeApplications #-}

import Control.Monad
import Control.Monad.ST
import GHC.Arr

wrap f = getLine >>= putStrLn . f

nums = (10 ^) <$> [0 .. 9]

main = do
  n <- readLn
  forM_ [1 .. n] $
    const $ do
      n <- readLn
      print $ last $ takeWhile (>= 0) $ (n -) <$> nums

arrayshit =
  runST $ do
    a <- newSTArray (0, 10) 0
    writeSTArray a 4 5
    readSTArray a 4
-- >>> 1 + 2

{-# LANGUAGE TypeApplications #-}

import Control.Monad

wrap f = getLine >>= putStrLn . f

nums = (10 ^) <$> [0 .. 9]

main = do
  n <- readLn
  forM_ [1 .. n] $
    const $ do
      n <- readLn
      print $ last $ takeWhile (>= 0) $ (n -) <$> nums
-- >>> 1 + 2

import Control.Monad

wrap f = getLine >>= putStrLn . f
nums = (10^) <$> [0..9]
main = do
  n <- readLn
  forM_ [1..n] $ const $ do
    n <- readLn
    print $ last $ takeWhile (>=0) $ (n-) <$> nums

module Main where

import Control.Monad

solve :: Integer -> Integer
solve m = m - (head . filter ((> m) . (* 10)) $ iterate (* 10) 1)

main = do
  t <- read <$> getLine
  replicateM_ t $
    getLine >>= print . solve . read

module Main where

import Control.Monad

solve :: Integer -> Integer
solve m = m - 10 ^ floor (logBase 10 $ fromInteger m)

main = do
  t <- read <$> getLine
  replicateM_ t $
    getLine >>= print . solve . read

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import           Prelude               hiding (getLine)
import           Control.Arrow
import           Control.Monad
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.List

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [m] <- ri
        return m
    mapM_ (putStrLn.show.solve) tcs

solve = read . ('1':) . map (const '0') . tail . show :: Int -> Int

import Data.Char (ord, chr)

for :: Int -> IO ()
for 0 = pure ()
for i = do
  a <- getLine
  let c = head a
  if c /= '1'
    then putStrLn ((chr (ord c - 1)): tail a)
    else if a == "1"
      then print 0
      else putStrLn $ tail a
  for $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  for n


combi :: Integral a => a -> a -> a
combi n m = (product [n, n - 1 .. n - m + 1]) `div` (product [1 .. m])

main :: IO ()
main = do
    n <- readLn
    print $ (combi n 5) + (combi n 6) + (combi n 7)

main = getLine >>= print . solve . read

solve :: Integer -> Integer
solve n = (cnk n 7) + (cnk n 6) + (cnk n 5)

fact n = product [1..n]

cnk n k | k > n = 0
        | otherwise = product [n,n-1..(n - k + 1)] `div` fact k

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

import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
    a <- (toInteger.fst.fromJust.C.readInt) <$> C.getLine
    let b = a * (a-1) `div` 2 * (a-2) `div` 3 * (a-3) `div`4 *(a-4)`div`5 *(a-5)`div`6*(a-6)`div`7
    let c = a * (a-1) `div` 2 * (a-2) `div` 3 * (a-3) `div`4 *(a-4)`div`5 *(a-5)`div`6
    let d = a * (a-1) `div` 2 * (a-2) `div` 3 * (a-3) `div`4 *(a-4)`div`5
    print $ b+c+d

fact = (m !!) where m =  scanl (*) 1 [1..]
comb n k = fact n  `div` fact k `div` fact (n - k)
solution k = comb k 7 + comb k 6 + comb k 5
main = getLine >>= print . solution. read

import Control.Monad
main = do
    a <- liftM read getLine
    putStrLn $ show $ (sum $ map (a `choose`) [5..7])
choose n k = (product [(n-k+1)..n]) `div` (product [1..k])

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

comb::Integer->[Integer]->[[Integer]]
comb n []  |n<5 = [[]]
	   | otherwise = []
comb n (s:ss) |n>=s =  [s: y| y<-(comb (n-s) (s:ss))]  ++ (comb n ss)
	      |otherwise = comb n ss

cou n p []=p
cou n p (s:ss) = cou (n-s) (p*(c n s)) ss

main= do
	n<- read  <$>getLine::IO Integer
	print $   sum $   map (c n) [7,6,5]

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

main= do
	n<- read  <$>getLine::IO Integer
	print $   sum $   map (c n) [7,6,5]

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

solve :: Integer -> Integer
solve n = binom n 7 + binom n 6 + binom n 5
    where binom n k = (product [n - k + 1 .. n]) `div` (product [1..k])

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

comb::Integer->[Integer]->[[Integer]]
comb n [] |n>5 = []
	  | otherwise = [[]]

comb n (s:ss) |n>=s =  [s: y| y<-(comb (n-s) (s:ss))]  ++ (comb n ss)
	      |otherwise = comb n ss

cou n p []=p
cou n p (s:ss) = cou (n-s) (p*(c n s)) ss

main= do
	n<- read  <$>getLine::IO Integer
	let s = init $  comb n [7,6,5]
	let t =   sum $  map (cou  n 1) s
	print t

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

comb::Integer->[Integer]->[[Integer]]
comb n []  |n<5 = [[]]
	   | otherwise = []
comb n (s:ss) |n>=s =  [s: y| y<-(comb (n-s) (s:ss))]  ++ (comb n ss)
	      |otherwise = comb n ss

cou n p []=p
cou n p (s:ss) = cou (n-s) (p*(c n s)) ss

main= do
	n<- read  <$>getLine::IO Integer
	print $   sum $  map (cou  n 1) $ comb n [7,6,5]

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

comb::Integer->[Integer]->[[Integer]]
comb n [] |n>=5 = []
	  | otherwise = [[]]

comb n (s:ss) |n>=s =  [s: y| y<-(comb (n-s) (s:ss))]  ++ (comb n ss)
	      |otherwise = comb n ss

cou n p []=p
cou n p (s:ss) = cou (n-s) (p*(c n s)) ss

main= do
	n<- read  <$>getLine::IO Integer
	let s = init $  comb n [7,6,5]
	let t =   map (cou  n 1) s
	print t

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

comb::Integer->[Integer]->[[Integer]]
comb n [] = [[]]
comb n (s:ss) |n>=s =  [s: y| y<-(comb (n-s) (s:ss))]  ++ (comb n ss)
	      |otherwise = comb n ss

cou n p []=p
cou n p (s:ss) = cou (n-s) (p*(c n s)) ss

main= do
	n<- read  <$>getLine::IO Integer
	let s = init $  comb n [7,6,5]
	let t =sum $  map (cou  n 1) s
	print t


import Control.Monad (liftM)
import Data.Char (ord)
import Data.List (intercalate, delete, group, nub, sort, sortBy)

solve :: [Int] -> (Int, [Int])
solve as  =  (ans, numGs as g1 g2)
  where
    gs  =  sortBy compareByLength $ group $ sort as
    compareByLength a b  =  compare (length a) (length b)
    merge (x:y:xs)  =  (x, y) : merge xs
    merge _  =  []
    g1  =  map fst $ merge $ concat gs
    g2  =  map snd $ merge $ concat gs
    ans  =  (length (nub g1)) * (length (nub g2))
    numGs [] _ _  =  []
    numGs (x:xs) g1 g2
        | elem x g1  =  1 : numGs xs (delete x g1) g2
        | otherwise  =  2 : numGs xs g1 (delete x g2)

main :: IO ()
main  =  do
    getLine
    as  <-  reads
    print $ fst $ solve as
    prints $ snd $ solve as

  where
    reads :: Num a => IO [a]
    reads  =  liftM (map read . words) getLine
      where
        read ('-':s)  =  (-1) * read s
        read s  =  read' 0 s
        read' a ""  =  a
        read' a (c:s)  =  read' (10 * a + fromIntegral (ord c - ord '0')) s

    prints :: Show a => [a] -> IO ()
    prints  =  putStrLn . intercalate " " . map show

{-# 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
eqLen a b = length a == length b
eqFst a b = fst a == fst 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 <- readLn :: IO Int
    l <- readsLine :: IO [Int]
    let uniqueSize = S.size . S.fromList
    let l' = reverse $ sortBy cmpLen $ groupBy eqFst $ sort $ zip l [1..]
    let (l1,l2) = splitTwo l'
    let a = uniqueSize $ map fst l1
    let b = uniqueSize $ map fst l2
    let ans = sort $ map (\(_,i) -> (i,1)) l1 ++ map (\(_,i) -> (i,2)) l2
    print (a*b)
    putStrLn $ unwords $ map (show.snd) ans

splitTwo :: [[(Int,Int)]] -> ([(Int,Int)],[(Int,Int)])
splitTwo l = unzip $ go1 l []
    where
    go1 [] !acc = go2 acc
    go1 ((x1:x2:xs):xss) !acc =
        (x1,x2):go1 xss (xs++acc)
    go1 xss !acc = go2 (concat xss++acc)
    go2 (x1:x2:xs) = (x1,x2):go2 xs
    go2 [] = []

{-# 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 (&&)

split2 l = go l
    where
    go (x:y:xs) = (x,y):go xs
    go _ = []

main = do
    n <- readLn :: IO Int
    l <- readsLine :: IO [Int]
    let l' = sort $ zip l [1..]
    let (l1,l2) = unzip $ split2 l'
    let uniqueSize = S.size . S.fromList
    let a = uniqueSize $ map fst l1
    let b = uniqueSize $ map fst l2
    let ans = sort $ map (\(_,i) -> (i,1)) l1 ++ map (\(_,i) -> (i,2)) l2
    print (a*b)
    putStrLn $ unwords $ map (show.snd) ans


solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer
solve' k [] [] d = 0
solve' k (sc:s) (tc:t) d
    | d' <= k = min k d' + solve' k s t d'
    | otherwise = k * fromIntegral(length s + 1)
        where d' = case (sc, tc) of
                    ('a', 'a') -> 2*d - 1
                    ('a', 'b') -> 2*d
                    ('b', 'a') -> 2*d - 2
                    ('b', 'b') -> 2*d - 1

solve k s t = solve' k s t 1

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer
solve' k [] [] d = 0
solve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'
    where d' = next k d (sc, tc)

solve k s t = solve' k s t 1

next' d ('a', 'a') = 2 * d - 1
next' d ('a', 'b') = 2 * d
next' d ('b', 'a') = 2 * d - 2
next' d ('b', 'b') = 2 * d - 1

next k d pair = if d <= k then next' d pair else d

--solve2 k s t = sum (

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

next' d ('a', 'a') = 2 * d - 1
next' d ('a', 'b') = 2 * d
next' d ('b', 'a') = 2 * d - 2
next' d ('b', 'b') = 2 * d - 1

next k d pair = if d <= k then next' d pair else d

solve :: Integer -> [Char] -> [Char] -> Integer
solve k s t = sum $ map (min k) $ tail $ scanl (next k) 1 (zip s t)

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer
solve' k [] [] d = 0
solve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'
    where d' = if d <= k then next d (sc, tc) else d

solve k s t = solve' k s t 1

next d ('a', 'a') = 2 * d - 1
next d ('a', 'b') = 2 * d
next d ('b', 'a') = 2 * d - 2
next d ('b', 'b') = 2 * d - 1

--solve2 k s t = sum (

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer
solve' k [] [] d = 0
solve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'
    where d' = min d'' k
          d'' = case (sc, tc) of
            ('a', 'a') -> 2*d - 1
            ('a', 'b') -> 2*d
            ('b', 'a') -> 2*d - 2
            ('b', 'b') -> 2*d - 1

solve k s t = solve' k s t 1

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

appendBit num 0 = 2 * num
appendBit num 1 = 2 * num + 1

-- treat 'a' as 0 bit, 'b' as 1 bit
charToBit 'a' = 0
charToBit 'b' = 1

-- After some point the difference will always be bigger than k
optimizedAppendChars k a b sc tc
    | (b - a >= 4 * k) = (a, b)
    | otherwise = (appendBit a (charToBit sc), appendBit b (charToBit tc))

-- Don't care about overflows because difference will persist through them
solve' :: Int-> [Char] -> [Char] -> Int-> Int-> Int
solve' k [] [] a b = 0
solve' k (sc:s) (tc:t) a b = min k (b' - a' + 1) + solve' k s t a' b'
    where (a', b') = optimizedAppendChars k a b sc tc

solve k s t = solve' k s t 0 0

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

solve' :: Int-> [Char] -> [Char] -> Int-> Int
solve' k [] [] d = 0
solve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'
    where d' = if d <= k then next d (sc, tc) else d

solve k s t = solve' k s t 1

next d ('a', 'a') = 2 * d - 1
next d ('a', 'b') = 2 * d
next d ('b', 'a') = 2 * d - 2
next d ('b', 'b') = 2 * d - 1

--solve2 k s t = sum (

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)


module Main where

import Control.Monad (replicateM_)

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

solution :: IO ()
solution = do
  [a, b, c, d] <- getNumbers
  print $ length $ filter (>= a) [b, c, d]

main :: IO ()
main = do
  [t] <- getNumbers
  replicateM_ t solution

main :: IO ()
main = do
    t <- getLine >>= (return . (read :: String -> Int))
    let
       toInt str = (read :: String -> Int) str
       bigger b a = if a > b then 1 else 0
       work :: Int -> IO ()
       work n = do
           if n > 0 then do
               arr <- getLine >>= (return . words)
               a <- return $ toInt $ arr !! 0
               b <- return $ toInt $ arr !! 1
               c <- return $ toInt $ arr !! 2
               d <- return $ toInt $ arr !! 3
               putStrLn (show $ bigger a b + bigger a c + bigger a d)
               work $ n - 1
           else
               return ()
    work t

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

import Data.Maybe
import Control.Monad

solve = do
    s <- C.getLine

    let xs = map (fst . fromJust . C.readInt) (C.words s)

    C.putStrLn (C.pack $ show $ length $ filter (>(xs !! 0)) xs)

main = do
   t <- C.getLine

   replicateM_ (fst $ fromJust $ C.readInt t) solve

module Main where

main = do
  tStr <- getLine
  input <- getContents
  mapM_ (print . solve) $ take (read tStr :: Int) $ lines input

solve :: String -> Int
solve s = sum $ map (fromEnum . (>a)) others
  where a:others = map read (words s) :: [Int]

import Control.Monad (replicateM, replicateM_)
import Control.Monad.Identity (Identity)
import Control.Monad.Trans.State.Lazy (StateT, evalState, state)
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Char (isSpace)
import Data.Maybe (fromJust)

type ParserT = StateT C.ByteString

type Parser = ParserT Identity

main :: IO ()
main = do
  q <- fst . fromJust . C.readInt <$> C.getLine
  replicateM_ q solve

solve :: IO ()
solve = do
  (t : ts) <- evalState (replicateM 4 getInt) <$> C.getLine
  f . length . filter (> t) $ ts

getInt :: Parser Int
getInt = state $ fromJust . C.readInt . C.dropWhile isSpace

f :: Int -> IO ()
f = L.putStrLn . B.toLazyByteString . B.intDec

main :: IO ()
main = interact start

start :: String -> String
start s =
    let (_:tests) = lines s
     in unlines $ map (show . solve . parse) tests

parse :: String -> (Int, Int, Int, Int)
parse s =
    let [a, b, c, d] = map read $ words s
     in (a, b, c, d)

solve :: (Int, Int, Int, Int) -> Int
solve (a, b, c, d) = sum $ map (`isInFront` a) [b, c, d]

isInFront :: Int -> Int -> Int
isInFront a b = if a < b then 0 else 1

inp = "4\n2 3 4 1\n10000 0 1 2\n500 600 400 300\n0 9999 10000 9998\n"

readArr :: IO [Int]
readArr = (map (\s -> read s :: Int)) <$> (words <$> getLine)

check :: Int -> Int -> Int
check a b = if a < b
  then 1
  else 0

solve :: Int -> IO ()
solve 0 = pure ()
solve i = do
  (a: b: c: d: _) <- readArr
  print $ check a b + check a c + check a d
  solve $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  solve n

testcase :: [Int] -> Int
testcase xs = length . filter (\x -> x > a) $  xs
    where (a:_) = xs

solve :: [Int] -> [Int]
solve [] = []
solve xs = (testcase $ take 4 xs) : (solve $ drop 4 xs)

main = interact $ unlines . map show . solve . tail . map read . words

import Control.Monad()
import Data.List()

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

rep 0 = return ()
rep x = do
    t <- getLine
    -- print (words t)
    let arr = map (read :: String -> Int) (words t)
    let s = head arr
    print (solve s arr)
    rep (x-1)

main :: IO ()
main = do
    t <- getLine
    rep (read t)

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

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

cmp a b = if a < b then 1 else 0

solve :: SP Builder
solve = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    a <- getInt
    b <- getInt
    c <- getInt
    d <- getInt
    let x = (cmp a b) + (cmp a c) + (cmp a d)
    pure $ putInts $ [x]

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

testcase :: [Int] -> Int
testcase xs = length . filter (\x -> x > a) $  xs
    where (a:_) = xs

solve :: [Int] -> [Int]
solve [] = []
solve xs = (testcase $ take 4 xs) : (solve $ drop 4 xs)

main = interact $ show . solve . tail . map read . words

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

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

cmp a b = if a < b then 1 else 0

solve :: SP Builder
solve = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    a <- getInt
    b <- getInt
    c <- getInt
    d <- getInt
    let x = (cmp a b) + (cmp a c) + (cmp a d)
    pure $ intDec x

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

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


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

onecase = do
		[n,k]<- map read <$> words <$> getLine::IO [Int]
		print $ if n==1 then 0 else if n==2 then k else k*2
main = do
	n<- read <$> getLine ::IO Int
	replicateM_ n onecase

import Control.Monad

main :: IO ()
main = do
    n <- readLn
    replicateM_ n routine

routine :: IO ()
routine = do
    [n,m]<- (map read.words) <$> getLine
    print $ solve n m

solve :: Integer -> Integer -> Integer
solve n m
  | n == 1 = 0
  | n == 2 = m
  | otherwise = 2*m

import Data.Map as M
import Data.List as L

sum':: [Integer] -> Integer
sum' xs = sum [abs (x - y) | (x, y) <- L.zip xs (tail xs)]

fun :: Integer -> Integer -> Integer
fun 1 _ = 0
fun 2 m = m
fun _ m = 2*m

parseInput :: String -> (Integer, Integer)
parseInput raw = (n, m)
                  where n = read n' :: Integer
                        m = read m' :: Integer
                        [n', m'] = words raw

solve :: String -> String
solve input = show (fun n m)
  where (n, m) = parseInput input

main :: IO()
main = interact (unlines . L.map solve . tail . lines)

import           Control.Arrow

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

solve [1,m] = 0
solve [2,m] = m
solve [_,m] = 2*m


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception hiding (mask)
import Control.Monad hiding (foldM, foldM_)
import Control.Monad.ST
import Data.Array.Base hiding (readArray, writeArray)
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.Strict 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

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

solve cs = go 0 M.empty cs
   where
     go !res keys (k:c:rest)
       | Just v<-M.lookup (toLower c) keys', v > 0 = go res (M.adjust pred (toLower c) keys') rest
       | otherwise = go (res+1) keys' rest
      where
        !keys' = M.insertWith (+) k 1 keys
     go res _ _ = res

------------------------------------------------------------------------------
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 #-}
foldM :: (Monad m) => a -> [b] -> (a -> b -> m a) -> m a
foldM a xs f=foldr((>=>).flip f)return xs$a
{-# INLINE foldM #-}
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 #-}
(!) :: (IArray a e, Ix i) => a i e -> i -> e
(!) a i=unsafeAt a$unsafeIndex(bounds a)i
{-# INLINE (!) #-}
readArray :: (MArray a e m, Ix i) => a i e -> i -> m e
readArray a i=do lr<-getBounds a;unsafeRead a$unsafeIndex lr i
{-# INLINE readArray #-}
writeArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()
writeArray a i e=do lr<-getBounds a;unsafeWrite a(unsafeIndex lr i)e
{-# INLINE writeArray #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=do lr<-getBounds a;unsafeModify a(unsafeIndex lr i)f
{-# INLINE modifyArray #-}

import Data.Char (toLower)
import qualified Data.Map as M

main :: IO ()
main = getLine >> getLine >>= print . solve 0 M.empty . map toLower

solve :: Int -> M.Map Char Int -> String -> Int
solve n m (y:z:ys) | y == z = solve n m ys
                   | M.findWithDefault 0 z m > 0 = solve n (M.insertWith (+) y 1 (M.adjust pred z m)) ys
                   | otherwise = solve (n + 1) (M.insertWith (+) y 1 m) ys
solve n _ _ = n

import Data.Char
import qualified Data.Map as M
main=getLine>>getLine>>=print.f M.empty.map toLower
f m (y:z:u)|M.findWithDefault 0 z b>0=f(M.adjust pred z b) u|1>0=1+f b u where b=M.insertWith(+)y 1 m
f _ _=0

import Data.Char (toLower)
import qualified Data.Map as M

main :: IO ()
main = getLine >> getLine >>= print . solve M.empty . map toLower

solve :: M.Map Char Int -> String -> Int
solve m (y:z:ys) | y == z = solve m ys
                 | M.findWithDefault 0 z m > 0 = solve (M.insertWith (+) y 1 (M.adjust pred z m)) ys
                 | otherwise = 1 + solve (M.insertWith (+) y 1 m) ys
solve _ _ = 0

import Data.Char
import Data.List

o x = (ord x) - (ord 'a')

solve :: [Int] -> String -> Int
solve _ [] = 0
solve ks (k:d:ds)
    | k == d = solve ks ds
    | x > 0 = solve (l''++(z+1):r'') ds
    | otherwise = 1 + solve (l'++(y+1):r') ds
    where
        ks' = (l++(x-1):r)
        (l,x:r) = splitAt (o d) ks
        (l'',z:r'') = splitAt (o k) ks'
        (l',y:r') = splitAt (o k) ks

main = getLine >> getLine >>= print . solve (map (const 0) [1..26]) . map toLower

import Control.Applicative
import Data.List
import Data.Char

upd s bbc x = (take bbc s) ++[(s!!bbc)+x]  ++(drop  (bbc+1)  s)

process n s [] =n
process n s (a:b:cs) | a== bb   = process n s cs
                     | s!!bbc >0 = process n (upd (upd s bbc (-1)) aa 1) cs
                     | otherwise = process (n+1) (upd s aa 1) cs
		where bb = toLower b
                      bbc = ord bb - ord 'a'
	              aa = ord a - ord 'a'

main= do
	getLine
	s<- getLine
	print $ process 0 (replicate 26 0)  s

import Data.Char
import Data.List

minBalance :: String -> Char -> Int
minBalance s c = snd $ foldl' addChar (0, 0) s
    where
        addChar acc@(cur, low) x
            | x == c = (cur - 1, min (cur - 1) low)
            | x == toLower c = (cur + 1, low)
            | otherwise = acc

main = do
    _ <- getLine
    s <- getLine
    print $ sum $ map (abs . minBalance s) ['A'..'Z']

import Data.Char
import qualified Data.Map as M
main=getLine>>getLine>>=print.f M.empty.map toLower
f m (y:z:u)|M.findWithDefault 0 z b>0=f(M.adjust pred z b) u|1>0=1+f b u where b=M.insertWith(+)y 1 m;f _ _=0

import Data.Char
import Data.List

solve :: String -> String -> Int
solve _ [] = 0
solve ks (k:d:ds)
    | k == d = solve ks ds
    | d `elem` ks = solve (delete d ks) ds
    | otherwise  = 1 + solve (k:ks) ds

main = getLine >> getLine >>= print . solve [] . map toLower

import Data.Char
import Data.List

solve :: String -> String -> Int
solve _ [] = 0
solve ks (k:d:ds)
    | toUpper k == d = solve ks ds
    | toLower d `elem` ks = solve (delete k ks) ds
    | otherwise  = 1 + solve (k:ks) ds

main = getLine >> getLine >>= print . solve []

import Data.Char
import Data.List

o x = (ord x) - (ord 'a')

solve :: [Int] -> String -> Int
solve _ [] = 0
solve ks (k:d:ds)
    | k == d = solve ks ds
    | x > 0 = solve (l++(x-1):r) ds
    | otherwise = 1 + solve (l'++(y+1):r') ds
    where
        (l,x:r) = splitAt (o d) ks
        (l',y:r') = splitAt (o k) ks

main = getLine >> getLine >>= print . solve (map (const 0) [1..26]) . map toLower

import Control.Applicative
import Data.List
import Data.Char

upd s bbc x = (take (bbc-1) s) ++[(s!!bbc)+x]  ++(drop bbc s)

process n _ [] =n
process n s (a:b:cs) | a== bb   = process n s cs
                     | s!!bbc >0 = process n (upd s bbc (-1)) cs
                     | otherwise = process (n+1) (upd s bbc 1) cs
		where bb = toLower b
                      bbc = ord bb - ord 'a'

main= do
	getLine
	s<- getLine
	print $ process 0 (replicate 26 0)  s

import Control.Applicative
import Data.List
import Data.Char

upd s bbc x = (take (bbc-1) s) ++[(s!!bbc)+x]  ++(drop bbc s)

process n _ [] =n
process n s (a:b:cs) | a== bb   = process n s cs
                     | s!!bbc >0 = process n (upd s bbc (-1)) cs
                     | otherwise = process (n+1) (upd s aa 1) cs
		where bb = toLower b
                      bbc = ord bb - ord 'a'
	              aa = ord a - ord 'a'

main= do
	getLine
	s<- getLine
	print $ process 0 (replicate 26 0)  s

import Control.Applicative
import Data.List
import Data.Char

upd s bbc x = (take bbc s) ++[(s!!bbc)+x]  ++(drop  (bbc+1)  s)

process n s [] =n
process n s (a:b:cs) | a== bb   = process n s cs
                     | s!!bbc >0 = process n (upd s bbc (-1)) cs
                     | otherwise = process (n+1) (upd s aa 1) cs
		where bb = toLower b
                      bbc = ord bb - ord 'a'
	              aa = ord a - ord 'a'

main= do
	getLine
	s<- getLine
	print $ process 0 (replicate 26 0)  s


{-# LANGUAGE BangPatterns #-}

type Poly = [Rational]

normPoly :: Poly -> Poly
normPoly p = reverse $ delz $ reverse p
             where delz :: Poly -> Poly
                   delz [] = []
                   delz a@(x:xs) = if x == 0 then delz xs else a

minus :: Poly -> Poly -> Poly
minus p q = map (\(x,y) -> x - y) $ zip p q

add :: Poly -> Poly -> Poly
add p q = map (\(x,y) -> fromIntegral $ mod (floor x + floor y) 2) $ zip (p ++ replicate (l - length p) 0) (q ++ replicate (l - length q) 0) where l = max (length p) (length q)

remPoly :: Poly -> Poly -> Poly
remPoly p q
    | null q                     = undefined
    | null p                     = []
    | last p == 0 || last q == 0 = remPoly (normPoly p) (normPoly q)
    | length p < length q        = p
    | otherwise                  = let dp = length p - 1
                                       dq = length q - 1
                                       lp = last p
                                       lq = last q
                                       q' = replicate (dp - dq) 0 ++ map (* (lp/lq)) q
                                   in remPoly (p `minus` q') q

gcdPoly :: Poly -> Poly -> Int
gcdPoly p q
    | null p || null q = 0
    | otherwise        = 1 + gcdPoly q (p `remPoly` q)

genPoly :: Poly -> Poly -> Poly
genPoly p q = ([0] ++ p) `add` q

infList = [[1], [0,1]] ++ goInf [1] [0,1]
          where goInf q p = [r] ++ goInf p r
                  where r = genPoly p q

sPoly :: Poly -> String
sPoly [] = ""
sPoly (x:xs) = (show $ floor x) ++ " " ++ sPoly xs

main = do
        n_ <- getLine
        let n = read n_ :: Int
        print n
        putStrLn $ sPoly $ infList !! n
        print (n - 1)
        putStrLn $ sPoly $ infList !! (n-1)

type Poly = [Int]

add :: Poly -> Poly -> Poly
add p q = map (\(x,y) -> mod (x + y) 2) $ zip (p ++ replicate (l - length p) 0) (q ++ replicate (l - length q) 0) where l = max (length p) (length q)

genPoly :: Poly -> Poly -> Poly
genPoly p q = ([0] ++ p) `add` q

infList = [[1], [0,1]] ++ goInf [1] [0,1]
          where goInf q p = [r] ++ goInf p r
                  where r = genPoly p q

sPoly :: Poly -> String
sPoly [] = ""
sPoly (x:xs) = (show x) ++ " " ++ sPoly xs

main = do
        n_ <- getLine
        let n = read n_ :: Int
        print n
        putStrLn $ sPoly $ infList !! n
        print (n - 1)
        putStrLn $ sPoly $ infList !! (n-1)

import Data.List

vectorAdd :: [Int] -> [Int] -> [Int]
vectorAdd [] y = y
vectorAdd x [] = x
vectorAdd (a:x) (b:y) = mod (a + b) 2 : vectorAdd x y

f :: Int -> [Int] -> [Int] -> [Int]
f 0 a b = a
f 1 a b = b
f n a b = f (n-1) b $ vectorAdd a (0:b)

fib n = f n [1] [0,1]

toString xs = concat $ intersperse " " $ map (show :: Int -> String) xs

main = do
    line <- getLine
    print (read line :: Int)
    putStrLn (toString (fib (read line :: Int)))
    print (pred $ read line :: Int)
    putStrLn (toString (fib $ pred (read line :: Int)))


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

  let ps = unfoldr (\xs -> if null xs then Nothing else Just $ splitAt n xs) $ concat $ zipWith (\a b -> [a, b]) [1..n^2`div`2] $ reverse [n^2`div`2..n^2]

  putStr $ unlines $ map (unwords . map show) ps

import Data.List
import Control.Monad
showL = concat . intersperse " " . map show

f _ [] [] = [ return ()]
f n a b =
    let m = n `div` 2
        (ha,ta) = splitAt m a
        (hb,tb) = splitAt m b
    in (putStrLn $ showL ha ++ " " ++ showL hb) : f n ta tb

main = do
    n <- readLn :: IO Int
    let m = n^2`div`2
    sequence_ $ f n [m,m-1..1] [m+1..n*n]

import Control.Monad (liftM)
import Data.List (intercalate)
import Prelude hiding (reads)

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

solve :: Int -> [[Int]]
solve n  =  map (solve' 1) [1..n]
  where
    solve' j i
      | j > n   =  []
      | odd j   =  ((j - 1) * n + i) : solve' (j + 1) i
      | even j  =  (j * n - (i - 1)) : solve' (j + 1) i

print' :: [[Int]] -> IO ()
print' xs  =  mapM_ (\x -> putStrLn $ intercalate " " $ map show x) xs

main :: IO ()
main  =  do
    --n  <-  liftM (read . head . words) $ readFile "input.txt"
    n  <-  readLn
    print' $ solve n

import Control.Applicative

main = answer.read <$> getLine >>= mapM_ (putStrLn.show')

show' = tail.foldl (\x y -> x++(' ':show y)) []

answer :: Int -> [[Int]]
answer n = distribute (div n 2) [1..div (n^2) 2]

distribute :: Int -> [Int] -> [[Int]]
distribute  _ [] = []
distribute k xs = [ps++ps']++(distribute k $ drop k xs)  where
	ps = take k xs
	ps' = map (\x -> (k*2)^2-x+1) ps

import qualified Data.ByteString.Lazy.Char8 as B
import Control.Applicative

main = do
  n <- read <$> getLine :: IO Int
  let n2 = n*n
      sol = concat [[j,n2-j+1] | j <- [1..(n2 `div` 2 )]]
  println n 1 sol

println _ _ []     = return ()
println n i (x:xs) = do
  if rem i n == 0
  then print x
  else putStr $ show x ++ " "
  println n (i+1) xs

import Data.List

solve :: Int -> [[Int]]
solve n = take n $ map (concatMap pairToList) $ splitIn (n `div` 2) xs
  where m = n ^ 2
        xs = zip [1 .. m] (reverse [1 .. m])

pairToList :: (a, a) -> [a]
pairToList (x, y) = [x, y]

splitIn :: Int -> [a] -> [[a]]
splitIn _ [] = []
splitIn n xs = let (left, right) = splitAt n xs
               in left:splitIn n right

main = interact $ unlines . map (unwords . map show) . solve . read

main :: IO ()
main = readLn >>= mapM_ (putStrLn . unwords . map show) . solve

solve :: Integer -> [[Integer]]
solve n = [ [ k, k + n .. a `div` 2 - n + k ] ++ [ b - k, b + n - k .. a + 1 - k ] | k <- [1..n] ]
  where a = n * n; b = a - a `div` 2 + n + 1

import Data.List (unfoldr)

main :: IO ()
main = readLn >>= mapM_ (putStrLn . unwords . map show) . solve

solve :: Int -> [[Int]]
solve n = map concat $ splitN (n `div` 2) $ map (\x -> [ x, n * n + 1 - x ]) [1 .. n * n `div` 2]

splitN :: Int -> [a] -> [[a]]
splitN n = takeWhile (not . null) . unfoldr (Just . splitAt n)

import Data.List
main = interact $ unlines . map (unwords . map show) . solve . read
solve n = transpose $ zipWith ($) (cycle [id,reverse]) $ chunksOf n [1..n^2]
chunksOf n = go where
  go [] = []
  go xs = l : go r where (l,r) = splitAt n xs

import Data.List (intercalate)

string2int str = (read str :: Int)
get_nxn x = [1..x^2]

solve n [] = []
solve n a = do
    (take n a) ++ (take n $ reverse a) ++ (solve n $ (reverse $ drop n $ reverse $ drop n a))

main :: IO ()
main = do
    str <- getLine
    putStrLn $ intercalate " " (map show $ solve (floor ((fromIntegral (string2int str)) / (fromIntegral (2 :: Int)))) $ (get_nxn $ string2int str))

import Control.Applicative
import Data.List

main = do
    n <- read <$> getLine
    let xxs = solve n
    mapM_ (putStrLn . intercalate " " . map show) xxs

solve :: Int -> [[Int]]
solve n = map (\x -> [x, n^2-x+1]) [1 .. n^2 `div` 2]

solve :: Int -> [[Int]]
solve n = [ solveLine n i  | i <- [1..n] ]

solveLine n i = [ 1 + ((i+j) `mod` n) + (j-1) * n | j <- [1..n]]

main :: IO ()
main = do nSt <- getLine
          let res = solve (read nSt :: Int)
              resSt = map (\ls -> (map (\x -> (show x)) ls)) res
          putStr $ unlines (map unwords resSt)

import Data.List
main=interact$unlines.map(unwords.map show).f.read
f :: Int -> [[Int]]
f n=transpose.zipWith($)(cycle [id,reverse]) $ slices n[1..n*n]

slices :: Int -> [a] -> [[a]]
slices n xs = map(take n).takeWhile(not.null) $ iterate(drop n)xs

import Control.Applicative
import Data.List

chunks x [] = []
chunks x n = (take x n) : (chunks x ( drop x n))

altrev [] = []
altrev (x:y:zs) = (x:(reverse y) : (altrev zs))

myprint x1 = putStrLn $ intercalate " " $ map show x1

main= do
	n<-  read <$> getLine  ::IO Int
	let x=  transpose $ altrev $ chunks n [1..n*n]
	mapM_  myprint x

-- Candy bags

main :: IO ()
main = fmap read getLine >>= putStrLn . prettyPrint . rush

prettyPrint :: [[Int]] -> String
prettyPrint = unlines . map (unwords . map show)

rush :: Int -> [[Int]]
rush n = map f [1..n]
  where f x = [((x - 1)*h + 1)..(x*h)] ++ [(ns - x * h + 1)..(ns - (x - 1) * h)]
        h = n `div` 2
        ns = n * n

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

  let ps = zip [1..n] $ reverse [n+1..n^2]

  putStr $ unlines $ map (\(a, b) -> show a ++ " " ++ show b) ps

import Data.List
import Control.Monad
f n = zipWith (\a b -> show a ++ " " ++ show b) [n,n-1..1] [n+1..]
main = mapM_ putStrLn . f =<< (readLn :: IO Int)

import Data.List

solve n = (uncurry zip) ys
  where m = n ^ 2
        xs = splitAt n [1 .. m]
        ys = (fst xs, reverse $ snd xs)

showPair (x, y) = show x ++ " " ++ show y

main = interact $ unlines . map showPair . solve . read


{-# LANGUAGE TypeApplications, BlockArguments, OverloadedLists #-}

module Main where

import           Prelude                 hiding ( drop, length, take, zipWith )
import           Data.Maybe
import           Data.Functor
import           Data.Sequence           hiding ( replicateM )
import           Control.Monad
import           Control.Monad.State

calc :: Seq Int -> Int
calc a = sum $ zipWith (\x y -> abs (x - y)) a (drop 1 a)

calc' :: Int -> Int -> Int
calc' x y = abs (x - y)

swap :: Int -> Seq Int -> Seq Int -> (Seq Int, Seq Int)
swap n a b =
  ( take n a >< [fromJust $ b !? n] >< drop (n + 1) a
  , take n b >< [fromJust $ a !? n] >< drop (n + 1) b
  )

aB :: State (Seq Int, Seq Int, Int) Int
aB = get >>= \(a, b, i) -> if i == length a - 1
  then return $ calc a + calc b
  else
    let [t1, t1', t2, t2'] = map fromJust [a !? i, a !? (i + 1), b !? i, b !? (i + 1)]
    in  if calc' t1 t1' + calc' t2 t2' <= calc' t1 t2' + calc' t2 t1'
          then put (a, b, i + 1) >> aB
          else let (a', b') = swap (i + 1) a b
               in  put (a', b', i + 1) >> aB

getInput :: Int -> IO [(Seq Int, Seq Int)]
getInput = flip replicateM $ getLine >> do
  a <- getLine <&> words <&> map (read @Int) <&> fromList
  b <- getLine <&> words <&> map (read @Int) <&> fromList
  return (a, b)

main :: IO ()
main = getLine <&> read @Int
     >>= getInput
     >>= mapM_ (\(a, b) -> print $ evalState aB (a, b, 0))

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

parseInt :: (Integral a) => C.ByteString -> a
parseInt = fromIntegral . fst . fromJust . C.readInt

getInts :: (Integral a) => IO [a]
getInts = map parseInt . C.words <$> C.getLine

calc :: [(Int64, Int64)] -> Int64
calc [] = 0
calc (_ : []) = 0
calc ((a1, b1) : (a2, b2) : rest) = current + calc ((a2, b2) : rest)
  where current = min (abs (a1 - a2) + abs (b1 - b2)) (abs (a1 - b2) + abs (a2 - b1))

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    _ <- C.getLine
    as <- getInts
    bs <- getInts
    return $ int64Dec (calc $ zip as bs) <> charUtf8 '\n'
  hPutBuilder stdout output


--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out  &&  cat -- compab.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs  &&  set -o pipefail  &&  cat -- input-large.txt | time ./a.out)

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs  &&  set -o pipefail  &&  cat -- input-large-7.txt | time ./a.out)

import           Prelude                    ((+), error)
import qualified System.IO             as S
import           Control.Arrow
import qualified Control.Monad         as M
import           Data.Bool
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.Eq
import           Data.Function
import           Data.Functor
import           Data.Int
import           Data.List                  ((++))
import qualified Data.List             as L
import           Data.Ord

mapM_      = M.mapM_
putStrLn   = S.putStrLn
replicateM = M.replicateM

dropSpace = B.dropWhile isSpace

ri :: S.IO [Int]
ri = readInts <$> B.getLine
  where
    readInts = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace

showYN False = "NO"
showYN True  = "YES"

main :: S.IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        _n <- B.getLine
        replicateM 2 ri
    mapM_ (putStrLn.showYN.solve) tcs

solve [as, bs] = L.and (L.zipWith isPossible as bbs)
  where
    bbs = L.zip bs (L.tail bs ++ [L.head bs])

    isPossible a (b, bnext) = (a == b) || ((a < b) && (b <= bnext + 1))
solve _ =
    error "Bad input reading"

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out  &&  cat -- compab.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs  &&  set -o pipefail  &&  cat -- input-large.txt | time ./a.out)

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs  &&  set -o pipefail  &&  cat -- input-large-7.txt | time ./a.out)

import           Prelude               hiding (getLine)
import           Control.Arrow
import           Control.Monad
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.List

ri = readInts <$> B.getLine
  where
    readInts  = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

showYN False = "NO"
showYN True  = "YES"

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        _n <- B.getLine
        replicateM 2 ri
    mapM_ (putStrLn.showYN.solve) tcs

solve [as, bs] = and (zipWith isPossible as bbs)
  where
    bbs = zip bs (tail bs ++ [head bs])

    isPossible a (b, bnext) = (a == b) || ((a < b) && (b <= bnext + 1))
solve _ =
    error "Bad input reading"

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out  &&  cat -- compab.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs  &&  set -o pipefail  &&  cat -- input-large.txt | time ./a.out)

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out compab.hs  &&  set -o pipefail  &&  cat -- input-large-7.txt | time ./a.out)

import           Prelude                    ((+), error)
import qualified System.IO             as S
import           Control.Arrow
import qualified Control.Monad         as M
import           Data.Bool
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.Eq
import           Data.Function
import           Data.Functor
import           Data.Int
import           Data.List                  ((++))
import qualified Data.List             as L
import           Data.Ord

mapM_      = M.mapM_
putStrLn   = S.putStrLn
replicateM = M.replicateM

dropSpace = B.dropWhile isSpace

ri :: S.IO [Int]
ri = readInts <$> B.getLine
  where
    readInts = L.reverse . L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace

showYN False = "NO"
showYN True  = "YES"

main :: S.IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        _n <- B.getLine
        replicateM 2 ri
    mapM_ (putStrLn.showYN.solve) tcs

solve [as, bs] = L.and (L.zipWith isPossible as bbs)
  where
    bbs = L.zip bs (L.tail bs ++ [L.head bs])

    isPossible a (b, bnext) = (a == b) || ((a < b) && (b <= bnext + 1))
solve _ =
    error "Bad input reading"

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out  &&  cat -- compab.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

import System.IO
import Control.Monad

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

showYN False = "NO"
showYN True  = "YES"

main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [_n] <- ri
        replicateM 2 ri
    mapM_ (putStrLn.showYN.solve) tcs

solve [as, bs] = and (zipWith isPossible as bbs)
  where
    bbs = zip bs (tail bs ++ [last bs])

    isPossible a (b, bnext) = (a == b) || ((a < b) && (b <= bnext + 1))


import Data.List

f (p, n, p', n') x | (x == 1)  = (p + 1, n, p + p', n + n')
                   | otherwise = (n, p + 1, p + p', n + n')

task x = show (n + n') ++ " " ++ show (p + p') where (p, n, p', n') = foldl' f (0, 0, 0, 0) x

main = getContents >>= putStr . task . map (\i -> signum $ read i::Integer) . words . head . tail . lines

solve :: [Integer] -> [Integer]
solve array = let runDP [] res _ = res
                  runDP (x:xs) [prevN, prevP] [negTllLst, posTllLst] =
                    let [negTllCur, posTllCur] = if x > 0 then [negTllLst, posTllLst + 1]
                                                          else [posTllLst + 1, negTllLst]
                    in runDP xs [prevN + negTllCur, prevP + posTllCur] [negTllCur, posTllCur]
              in runDP array [0,0] [0,0]

main :: IO ()
main = interact $ (++ "\n") . unwords . map show . solve . map read . tail . words

{-
  Copyright (c) 2019 Islam Omar
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -optc-Ofast #-}

import Control.Monad (foldM, forM, forM_, join, replicateM_, when)
import Control.Monad.ST
import Control.Monad.State.Strict

-- import           Data.Array.MArray.Safe         ( MArray )
-- import qualified Data.Array.MArray.Safe        as MA
import Data.Array.ST.Safe (STArray)
import qualified Data.Array.ST.Safe as MA
import Data.Bits
import Data.Functor
import Data.Graph (Graph)
import qualified Data.Graph as G
import Data.Int (Int64)
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.List as L
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.STRef
import Data.Set (Set)
import qualified Data.Set as S
import System.IO
import Text.Read
--- DEBUGGING
#define DEBUG(x) dump di "x" x
dump di str a
  | "demo.hs" `L.isSuffixOf` __FILE__ =
    modifySTRef' di (L.insert (str, a)) >> return Nothing
  | otherwise = return Nothing

printDump lst
  | "demo.hs" `L.isSuffixOf` __FILE__ = forM_ lst print >> return Nothing
  | otherwise = return Nothing

readNumList :: (Num a, Read a) => IO [a]
readNumList = map read . words <$> getLine

readNum :: (Num a, Read a) => IO a
readNum = read <$> getLine

readNumListLn :: (Num a, Read a) => Int -> IO [a]
readNumListLn n = doGetList n []
  where
    doGetList 0 l = return l
    doGetList n l = do
      i <- readNum
      doGetList (n - 1) (l ++ [i])

-- solve :: STRef s [([Char], Int)] -> Int -> Int -> Int -> Int -> Int -> ST s [Int]
solve di n nums = do
  pos <- newSTRef 0
  neg <- newSTRef 0
  ansp <- newSTRef 0
  ansn <- newSTRef 0
  let updateVal v =
        if v > 0
          then modifySTRef' pos (+ 1)
          else do
            p <- readSTRef pos
            n <- readSTRef neg
            writeSTRef neg (p + 1)
            writeSTRef pos n
  let compute v = do
        updateVal v
        p <- readSTRef pos
        nn <- readSTRef neg
        DEBUG(p)
        DEBUG(nn)
        modifySTRef' ansp (+p)
        modifySTRef' ansn (+nn)

  forM_ nums compute
  p <- readSTRef ansp
  n <- readSTRef ansn
  let ans = (n,p)
  -- solution
  -- readSTRef =<< newSTRef ans
  return ans

main :: IO ()
main = do
  n <- readNum :: IO Int
  --  Read Inputs
  nums <- readNumList :: IO [Int]
  let computation =
        runST $ do
          let dubeg_info =
                [] :: (Num a) =>
                        [(String, a)]
          --- list of tuples (string value)
          di <- newSTRef dubeg_info
          ans <- solve di n nums
          tmp <- readSTRef di
          let lst = (ans, tmp)
          readSTRef =<< newSTRef lst
  -- get solution
  let (n, p) = fst computation
  let debug_info = snd computation
  printDump debug_info
  -- print result
  putStrLn $ show n ++ " " ++ show p

solve :: [Int] -> [Int]
solve array = let runDP [] res _ = res
                  runDP (x:xs) [prevN, prevP] [negTllLst, posTllLst] =
                    let [negTllCur, posTllCur] = if x > 0 then [negTllLst, posTllLst + 1]
                                                          else [posTllLst + 1, negTllLst]
                    in runDP xs [prevN + negTllCur, prevP + posTllCur] [negTllCur, posTllCur]
              in runDP array [0,0] [0,0]

main :: IO ()
main = interact $ (++ "\n") . unwords . map show . solve . map read . tail . words

import Data.List

f (p, n, p', n') x | (x == 1)  = (p + 1, n, p + p', n + n')
                   | otherwise = (n, p + 1, p + p', n + n')

task x = show (n + n') ++ " " ++ show (p + p') where (p, n, p', n') = foldl' f (0, 0, 0, 0) x

main = getContents >>= print . task . map (\i -> signum $ read i::Integer) . words . head . tail . lines

{-
  Copyright (c) 2019 Islam Omar
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -optc-Ofast #-}

import Control.Monad (forM, forM_, join, replicateM_, when)
import Control.Monad.ST
import Control.Monad.State.Strict

-- import           Data.Array.MArray.Safe         ( MArray )
-- import qualified Data.Array.MArray.Safe        as MA
import Data.Array.ST.Safe (STArray)
import qualified Data.Array.ST.Safe as MA
import Data.Bits
import Data.Functor
import Data.Graph (Graph)
import qualified Data.Graph as G
import Data.Int (Int64)
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.List as L
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.STRef
import Data.Set (Set)
import qualified Data.Set as S
import System.IO
import Text.Read
--- DEBUGGING
#define DEBUG(x) dump di "x" x
dump di str a
  | "demo.hs" `L.isSuffixOf` __FILE__ =
    modifySTRef' di (L.insert (str, a)) >> return Nothing
  | otherwise = return Nothing

printDump lst
  | "demo.hs" `L.isSuffixOf` __FILE__ = forM_ lst print >> return Nothing
  | otherwise = return Nothing

readNumList :: (Num a, Read a) => IO [a]
readNumList = map read . words <$> getLine

readNum :: (Num a, Read a) => IO a
readNum = read <$> getLine

readNumListLn :: (Num a, Read a) => Int -> IO [a]
readNumListLn n = doGetList n []
  where
    doGetList 0 l = return l
    doGetList n l = do
      i <- readNum
      doGetList (n - 1) (l ++ [i])

-- solve :: STRef s [([Char], Int)] -> Int -> Int -> Int -> Int -> Int -> ST s [Int]
solve di n nums = do
  DEBUG (n)
  i <- newSTRef 0
  pos <- newSTRef 0
  neg <- newSTRef 0
  ansp <- newSTRef 0
  ansn <- newSTRef 0
  let updateVal v =
        if v > 0
          then modifySTRef' pos (+ 1)
          else do
            p <- readSTRef pos
            n <- readSTRef neg
            writeSTRef neg (p + 1)
            writeSTRef pos n
  writeSTRef i 0
  let loop = do
        it <- readSTRef i
        let v = nums !! it
        updateVal v
        p <- readSTRef pos
        nn <- readSTRef neg
        DEBUG (nn)
        DEBUG (it)
        DEBUG (p)
        modifySTRef' ansp (+p)
        modifySTRef' ansn (+nn)
        modifySTRef' i (+1)
        if it+1 >= n then (return ())
          else loop

  loop
  p <- readSTRef ansp
  n <- readSTRef ansn
  let ans = (n,p)
  -- solution
  -- readSTRef =<< newSTRef ans
  return ans

main :: IO ()
main = do
  n <- readNum :: IO Int
  --  Read Inputs
  nums <- readNumList :: IO [Int]
  print nums
  let computation =
        runST $ do
          let dubeg_info =
                [] :: (Num a) =>
                        [(String, a)]
          --- list of tuples (string value)
          di <- newSTRef dubeg_info
          ans <- solve di n nums
          tmp <- readSTRef di
          let lst = (ans, tmp)
          readSTRef =<< newSTRef lst
  -- get solution
  let (n, p) = fst computation
  let debug_info = snd computation
  printDump debug_info
  -- print result
  putStrLn $ show n ++ " " ++ show p


import Prelude
import Control.Monad

str2Ints str = [read x::Int | x <- words str]
getLineN n = replicateM n getLine

inf::Int
inf = floor (1e9+7)

i2b x = if x /= 0 then 1 else 0

f n x y d = if z == inf then -1 else z
    where z = minimum [if x`rem`d == y`rem`d then abs(x-y)`quot`d else inf,
                       if 0 == y`rem`d then y`quot`d + x`quot`d + i2b(x`rem`d) else inf,
                       if (n-1)`rem`d == y`rem`d then (n-1-y)`quot`d + (n-1-x)`quot`d + i2b((n-1-x)`rem`d) else inf]

main = do
    input<-getLine;
    lines<-getLineN (read input::Int)
    let l = map str2Ints lines
    let ans = foldr (\x acc -> (f (x!!0) (x!!1 - 1) (x!!2 - 1) (x!!3)):acc) [] l
    mapM (putStrLn.show) ans

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

inf::Int
inf = 1000000005

toint s = (read s) :: Int

doall::[Int]->String
doall [] = ""
doall (n:xx:yy:d:ss) =
  let x = xx-1 in
  let y = yy-1 in
  if (mod x d == mod y d) then
    show(div (abs (x-y)) d)++"\n"++(doall ss)
  else
    let r1 =	if mod y d == 0 then div x d + div y d + 1 else inf in
    let r2 = if mod y d == mod (n-1) d then div (n-1-x) d + div (n-1-y) d + 1 else inf in
    let r = min r1 r2 in
    if r == inf then "-1\n"++(doall ss) else show(r)++"\n"++(doall ss)

solve::String -> String
solve ss =
  let _:s = map toint $ words ss in
  doall s

main = do
  interact $ solve

import Prelude
import Control.Monad

str2Ints str = [read x::Int | x <- words str]
getLineN n = replicateM n getLine

inf::Int
inf = floor (1e9+7)

i2b x = if x /= 0 then 1 else 0

f n x y d = if z == inf then -1 else z
    where z = minimum [if x`rem`d == y`rem`d then abs(x-y)`quot`d else inf,
                       if 0 == y`rem`d then y`quot`d + x`quot`d + i2b(x`rem`d) else inf,
                       if (n-1)`quot`d == y`rem`d then (n-1-y)`quot`d + (n-1-x)`quot`d + i2b((n-1-x)`rem`d) else inf]

main = do
    input<-getLine;
    lines<-getLineN (read input::Int)
    let l = map str2Ints lines
    let ans = foldr (\x acc -> (f (x!!0) (x!!1 - 1) (x!!2 - 1) (x!!3)):acc) [] l
    mapM (putStrLn.show) ans


import Data.List
main=interact$show.length.concat.drop 1.init.group.sort.map((+0).read).tail.words

import Data.List

main = do
        nS <- getLine
        strengthValuesS <- getLine
        let n = read nS :: Int
            strengthValues = map (read :: String -> Int) (words strengthValuesS)
            list = group (sort strengthValues)
        print (max 0 (n - (length (head list)) - (length (last list))))

import Control.Applicative ((<$>), (<*>))
main = do
    n <- readLn :: IO Int
    a <- fmap (map read) $ fmap words $ getLine :: IO [Int]
    let min0 = minimum a
    let max0 = maximum a
    print $ length $ filter ((&&) <$> (> min0) <*> (< max0)) a

import Data.List

main = do
    getLine
    a <- return . map length . group . sort . map (read :: String -> Int) . words =<< getLine
    print $ if length a < 2 then 0 else sum $ init $ tail a

{-# LANGUAGE TypeApplications #-}
import Data.List
main = interact $ show . length . concat . drop 1 . init . group . sort @Int . map read . tail . words

g mini maxi a = length $ filter (\x -> mini < x && x < maxi) a
f a = g (minimum a) (maximum a) a
main=interact$show.f.map ((+0).read).tail.words

import Data.List

main = do
    getLine
    l <- getLine >>= return . map read . words :: IO [Int]
    let m = minimum l
    let ma = maximum l
    print $ length $ filter (\x -> x > m && x < ma) l

import Data.List
main = do
  getLine
  a <- getLine >>= return.map read.words :: IO [Integer]
  print.length.filter (\x -> x > minimum a && x < maximum a) $ a

main = do
  i <- getLine
  let n = read i :: Int
  j <- getLine
  let inputs = map (\x -> read x :: Integer) $ words j
  let max_ = maximum inputs
  let min_ = minimum inputs
  let max_count = length $ filter (==max_) inputs
  let min_count = length $ filter (==min_) inputs
  if max_ == min_
    then print 0
    else print $ n - max_count - min_count

import Data.List.Split
getInt :: IO Integer
getInt = readLn

solve n as =
  length.filter (\x -> x > minimum as && x < maximum as) $ as

main = do
  n <- getInt
  a <- getLine
  print.solve n $ Data.List.Split.splitOn " " a

import Data.List.Split
getInt :: IO Int
getInt = readLn

solve n as =
  length.filter (\x -> x > minimum as && x < maximum as) $ as

main = do
  n <- getInt
  a <- getLine
  print.solve n $ Data.List.Split.splitOn " " a

import Data.List
import Data.List.Split
getInt :: IO Int
getInt = readLn

solve n as =
  length.filter (\x -> x > head bs && x < last bs) $ bs
  where bs = Data.List.sort as

main = do
  n <- getInt
  a <- getLine
  print.solve n $ Data.List.Split.splitOn " " a

main = do
  i <- getLine
  let n = read i :: Int
  j <- getLine
  let inputs = map (\x -> read x :: Integer) $ words j
  let max_count = length $ filter (==maximum inputs) inputs
  let min_count = length $ filter (==minimum inputs) inputs
  if max_count == min_count
    then print 0
    else print $ n - max_count - min_count

main = do
  i <- getLine
  let n = read i :: Int
  j <- getLine
  let inputs = map (\x -> read x :: Integer) $ words j
  let max_count = length $ filter (==maximum inputs) inputs
  let min_count = length $ filter (==minimum inputs) inputs
  print $ n - max_count - min_count


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}

import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set as S

import qualified Data.Array as A

import qualified Control.Monad.State.Strict as State
import Control.Monad.ST

import Data.Bits(xor, (.&.), (.|.))
import qualified Data.Array.MArray as MA
import Data.STRef(STRef, newSTRef, readSTRef, writeSTRef)
import Data.Array.ST(runSTArray, STArray)
import Data.Array.IO(IOArray)

import Data.Array((!))
import Control.Monad(replicateM, filterM, forM) -- foldM est un foldl
import Data.Maybe

type Output = (Integer, Integer)

solve :: Integer -> Integer -> Integer -> Output
solve a b c = let (x, y) = result (a-c+1) (b-c+1) in (expo 10 (c-1) * x, expo 10 (c-1) * y)

result a b = (expo 10 (a-1) + 1, expo 10 (b-1))

expo :: Integral n => n -> n -> n
expo n x | x < 0 = error "expo n x : x < 0"
expo n x
	| x == 0 = 1
	| otherwise = k * k * if mod x 2 == 0 then 1 else n
	where k = expo n (div x 2)

plotResult :: Output -> IO ()
plotResult (a, b) = putStrLn $ show a ++ " " ++ show b

main :: IO ()
main = do
	t <- getLine >>= return . read :: IO Int
	replicateM t $ do
		[a, b, c] <- getLine >>= return . (fmap read) . words :: IO [Integer]
		--a <- getLine >>= return . (fmap read) . words :: IO [Integer]
		plotResult $ solve a b c
	return ()

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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [a, b, c] <- getInts
    let f x p l = head $ dropWhile (\x -> length (show x) < l) $ iterate (*p) x
        x3 = f 1 2 c
        x1 = f x3 2 a
        x2 = f x3 3 b
    C.putStrLn $ C.pack $ show x1 ++ " " ++ show x2


press :: Bool -> [Int] -> Bool

press n [a] = (odd a)

press n a =
    ((odd (head a)) /= (n && (press n (tail a))))

main = do
    [n,_] <- map (read :: String -> Int) . words <$> getLine
    a <- map (read :: String -> Int) . words <$> getLine
    putStrLn $ if press (odd n) (reverse a) then "odd" else "even"

import Data.Char

modpower x = 1 : (cycle $ case x of
                        1 -> [1]
                        2 -> [2,4,8,6]
                        3 -> [3,9,7,1]
                        4 -> [4,6]
                        5 -> [5]
                        6 -> [6]
                        7 -> [7,9,3,1]
                        8 -> [8,4,2,6]
                        9 -> [9,1]
                        0 -> [0,0])

get acc (a:b:as) = if b == ' ' then get (digitToInt a : acc) as else get acc (b:as)
get acc as  = ((digitToInt $ last as) : acc)

main = do
    [n,_] <- map (read :: String -> Int) . words <$> getLine
    a <- get [] <$> getLine
    let b =  take (length a) $ modpower (n`mod`10)
        c =  sum $ zipWith (*) a b
    putStrLn $ if even c then "even" else "odd"

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit

main :: IO ()
main = do
  [b,k] <- map read . words <$> getLine
  as <- take k . unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  let ans | odd b     = foldl xor False $ map odd as
          | otherwise = odd $ last as
  putStrLn $ if ans then "odd" else "even"

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')

#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read
#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define N(f,g,a,m)\
  f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\
  g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_
#define C(a,m)
N(newIOA,newIOA_,IOArray,IO)
N(newSTA,newSTA_,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,IOUArray,IO)
N(newSTUA,newSTUA_,STUArray s,ST s)
#undef C
#undef N

main = interact $ (["odd","even"] !!) . fromEnum . solve . map read . words
solve (b:k:as) | even b = even (last as)
               | otherwise = even (sum as)

import Text.Printf
import Control.Monad

main = do
  [b, k] <- fmap (map read . words) getLine
  ls <- fmap (map read . reverse . words) getLine
  putStrLn . oddOrEven $ solve b ls

solve b ls@(x:_)
  | even b = x
  | otherwise = sum $ map (`rem` 2) ls

oddOrEven x
  | even x = "even"
  | otherwise = "odd"

press :: [Int] -> Int -> Int

press [] n = 0

press a n =
    ((head a) +(n * (press (tail a) n))) `mod` 2

main = do
    [n,_] <- map (read :: String -> Int) . words <$> getLine
    a <- map (read :: String -> Int) . words <$> getLine
    putStrLn $ if even (press (reverse a) n) then "even" else "odd"

import Control.DeepSeq

main = do
  [o, n] <- fmap (fmap read . words) getLine
  s <- fmap (fmap read . words) getLine
  let (r, _) = foldl (\(s, c) x -> ((force s :: Int) + x * o ^ c, c - 1)) (0, n - 1) s
  putStrLn $ if even r then "even" else "odd"

main = interact $ process . map read . words
process :: [Int] -> String
process (b:k:a) = if ev then "even" else "odd" where
  ev | even b    = even $ last a
     | otherwise = even $ sum a

solve b k as | b `mod` 2 == 0   = if (last as) `mod` 2 == 0 then "even" else "odd"
             | otherwise        = if s `mod` 2 == 0 then "even" else "odd"
             where s = sum as

parseInput input = ([b, k], as) where
    ls = lines input
    [b, k] = map read $ words $ head ls :: [Int]
    as = map read $ words $ last ls :: [Int]

main = do
    input <- getContents
    let ([b, k], as) = parseInput input
    putStrLn $ solve b k as


import Data.List
import Control.Applicative
default (Int)
f r g m | g == 1 = sortBy (flip compare) $
            foldl (\a b -> (*) <$> a <*> (scanl (*) 1 b)) [1] $ (group $ reverse r)
        | g `mod` m == 0 = f (m:r) (g `div` m) m
        | g < m^2 = f r g g
        | otherwise = f r g (m + 1)
main = do
    [a, b] <- (map read . words) `fmap` getLine :: IO [Int]
    n <- read `fmap` getLine
    let divs = f [] (gcd a b) 2
    mapM_ (\_ -> do
        [low, high] <- (map read . words) `fmap` getLine
        case takeWhile (>= low) $ dropWhile (> high) divs of
            h:_ -> print h
            [] -> print (-1)) [1..n]

import Data.Maybe

maybeMaximum [] = Nothing
maybeMaximum xs = Just $ maximum xs

solve a b queries =
		map process queries
	where
		d = gcd a b
		is = takeWhile (\i -> i*i <= d) [1..]
		ds = concat [[i, d `div` i] | i <- is, d `mod` i == 0]

		process (l, r) = maybeMaximum $ filter (\d -> l <= d && d <= r) ds

readWords = map read . words

main = do
	[a, b] <- readWords `fmap` getLine
	_ <- getLine
	queries <- (map ((\[a, b] -> (a, b)) . readWords) . lines) `fmap` getContents
	putStr $ unlines $ map (show . fromMaybe (-1)) $ solve a b queries

import Data.Maybe

maybeMaximum [] = Nothing
maybeMaximum xs = Just $ maximum xs

solve a b queries =
		map process queries
	where
		d = gcd a b
		is = takeWhile (\i -> i*i <= d) [1..]
		ds = concat [[i, d `div` i] | i <- is, d `mod` i == 0]

		process (l, r) = maybeMaximum $ filter (\d -> l <= d && d <= r) ds

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

main = do
	[a, b] <- readWords `fmap` getLine
	_ <- getLine
	queries <- (map ((\[a, b] -> (a, b)) . readWords) . lines) `fmap` getContents
	putStr $ unlines $ map (show . fromMaybe (-1)) $ solve a b queries

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

pfactors n toTest@(x:xs)
    | n <= 1         = []
    | x * x > n      = [n]
    | n `mod` x == 0 = x:pfactors (n `div` x) toTest
    | otherwise      = pfactors n xs

divisorsFromF xs = sort . map product . sequence . map (scanl (*) 1) . group $ sort xs

readI = fst . fromJust . BS.readInt

--return the of value in a sorted array LEQ than x
solve :: UArray Int Int -> Int -> Maybe Int
solve sorted x = if sorted ! pos <= x then Just (sorted ! pos) else Nothing
  where
    bnds = bounds sorted
    bsearch lo hi
        | lo >= hi              = lo
        | sorted ! (mid+1) <= x = bsearch (mid + 1) hi
        | otherwise             = bsearch lo mid
      where
        mid = (lo + hi) `div` 2
    pos = bsearch (fst bnds) (snd bnds)

main = do
    [x, y] <- map read . words <$> getLine :: IO [Int]
    let g = gcd x y
    let factors = pfactors g [2..]
    let divisors = divisorsFromF factors
    let arr = listArray (1, length divisors) divisors :: UArray Int Int
    q <- read <$> getLine :: IO Int
    lines <- map (map readI . BS.words) . take q . BS.lines <$> BS.getContents
    forM_ lines $ \[low, high] -> do
        let val = solve arr high
        let answer = if isJust val && fromJust val >= low then fromJust val else -1
        print answer

import Control.Monad
import Data.List
-- import Debug.Trace

primes = 2 : sieve [3,5..]
  where
    sieve (x:xs) = x : sieve [y | y <- xs, y `mod` x /= 0]

solve xs = do
  [l, h] <- fmap (map read . words) getLine
  return $ case dropWhile (> h) xs of
    [] -> -1
    (x:_)
      | x < l -> -1
      | otherwise -> x

gen x =
  rec 1 $ glue [] $ factors [] primes x
  where
    rec cur [] = [cur]
    rec cur ((x, c):xs) =
      [ x^p | p <- [0..c]] >>= \v -> rec (cur*v) xs
    glue res [] = reverse res
    glue [] (y:ys) = glue [(y, 1)] ys
    glue res@((x, c):xs) (y:ys)
      | x == y = glue ((x, c+1):xs) ys
      | otherwise = glue ((y, 1):res) ys
    factors res (p:ps) x
      | p*p > x = reverse $ x:res
      | x `mod` p == 0 = factors (p:res) (p:ps) (x`div`p)
      | otherwise = factors res ps x

main = do
  [a, b] <- fmap (map read . words) getLine
  n <- fmap read getLine
  let xs = reverse $ sort $ gen $ gcd a b
  xs `seq` mapM_ print =<< replicateM n (solve xs)

import Data.List

getdivisors :: Int -> [Int]
getdivisors n = sort $  [x | x <- xs , mod n x == 0 ] ++ [ div n x | x <- xs , mod n  x == 0 ]
      where
       sq = truncate $ sqrt $ fromIntegral n
       xs = [1..sq]

xfind :: Int -> Int -> [Int] -> Int -> Int ->  Int
xfind s e xs a b
  | s > e      = -1
  | x == False =  xfind (m+1) e xs a b
  | y == False =  xfind s (m-1) xs a b
  | otherwise  =  max (xs!!m) (xfind (m+1) e xs a b)
  where
    m = div (s+e) 2
    x =  (xs!!m) >=  a
    y = ( xs!!m) <= b

readInt :: String -> Int
readInt str = read str :: Int

doit :: Int -> [Int] ->  IO()
doit 0 xs = return ()
doit t xs = do
             ws <- getLine
             let [a,b] = map readInt (words ws)
             print $ xfind 0 ((length xs)-1) xs a b
             doit (t-1) xs

main :: IO()
main = do
        ws <- getLine
        let [a,b] = map readInt (words ws)
        let xs = getdivisors $  gcd a b
        t <- getLine
        doit (readInt t) xs

import Data.Maybe

maybeMaximum [] = Nothing
maybeMaximum xs = Just $ maximum xs

solve a b queries =
		map process queries
	where
		d = gcd a b
		is = takeWhile (\i -> i*i <= d) [1..]
		ds = concat [[d, d `div` i] | i <- is, d `mod` i == 0]

		process (l, r) = maybeMaximum $ filter (\d -> l <= d && d <= r) ds

readWords = map read . words

main = do
	[a, b] <- readWords `fmap` getLine
	_ <- getLine
	queries <- (map ((\[a, b] -> (a, b)) . readWords) . lines) `fmap` getContents
	putStr $ unlines $ map (show . fromMaybe (-1)) $ solve a b queries

import Control.Monad

primes = 2 : sieve [3,5..]
  where
    sieve (x:xs) = x : sieve [y | y <- xs, y `mod` x /= 0]

solve gcd = do
  [l, h] <- fmap (map read . words) getLine
  return $ calc l h gcd primes
  where
    calc :: Integer -> Integer -> Integer -> [Integer] -> Integer
    calc l h g (p:ps)
      | g < l = -1
      | g <= h = g
      | g `mod` p == 0 = calc l h (g `div` p) (p:ps)
      | otherwise = calc l h g ps

main = do
  [a, b] <- fmap (map read . words) getLine
  n <- fmap read getLine
  mapM_ print =<< replicateM n (solve (gcd a b))

import Control.Monad
import Data.List

primes = 2 : sieve [3,5..]
  where
    sieve (x:xs) = x : sieve [y | y <- xs, y `mod` x /= 0]

solve xs = do
  [l, h] <- fmap (map read . words) getLine
  let xs' = takeWhile (<=h) $ dropWhile (<l) xs
  return $ if null xs' then -1 else maximum xs'
  where
    calc :: Integer -> Integer -> Integer -> [Integer] -> Integer
    calc l h g (p:ps)
      | g < l = -1
      | g <= h = g
      | g `mod` p == 0 = calc l h (g `div` p) (p:ps)
      | otherwise = calc l h g ps

gen x =
  rec 1 [] $ factors [] primes x
  where
    rec cur res [] = nub $ cur : res
    rec cur res (x:xs) =
      rec (cur*x) (cur : res ++ rec cur res xs) xs
    factors res (p:ps) x
      | p*p > x = reverse $ x:res
      | x `mod` p == 0 = factors (p:res) (p:ps) (x`div`p)
      | otherwise = factors res ps x

main = do
  [a, b] <- fmap (map read . words) getLine
  n <- fmap read getLine
  print $ gen $ gcd a b
  mapM_ print =<< replicateM n (solve $ sort $ gen $ gcd a b)

import Data.List
import Control.Applicative
default (Int)
f r g m | g `mod` m == 0 = f (m:r) (g `div` m) m
        | g < m^2 = sortBy (flip compare) $
            foldl (\a b -> (*) <$> a <*> (scanl (*) 1 b)) [1] $ (group $ reverse r)
        | otherwise = f r g (m + 1)
main = do
    [a, b] <- (map read . words) `fmap` getLine :: IO [Int]
    n <- read `fmap` getLine
    let divs = f [] (gcd a b) 2
    mapM_ (\_ -> do
        [low, high] <- (map read . words) `fmap` getLine
        case takeWhile (>= low) $ dropWhile (> high) divs of
            h:_ -> print h
            [] -> print (-1)) [1..n]

default (Int)
main = do
    [a, b] <- (map read . words) `fmap` getLine :: IO [Int]
    n <- read `fmap` getLine
    let g = gcd a b
	divs = g: (reverse (filter ((==0).(g `mod`)) $ takeWhile ((<= g).(^2)) [1..]))
    mapM_ (\_ -> do
        [low, high] <- (map read . words) `fmap` getLine
	let h = filter (\x -> x <= high && x >= low) divs
	print $ case h of
	    (h:_) -> h
            [] -> (-1)) [1..n]


-- author https://codeforces.com/contest/1541/submission/120631973

import Control.Monad
import Data.List
import Data.Bits

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

genPair [] i = []
genPair (x:xs) i = (x,i) : (genPair xs (i+1))

each = do
    n<-readLn::IO Integer
    a<-readInts
    let b = sort $ genPair a 1
    print $ fori b n
    where
        fori [x] n = 0
        fori (x:xs) n = fori xs n + forj x xs n

        forj x [] n = 0
        forj x (u:xs) n
            | (fst x)*(fst u) > 2*n = 0
            | otherwise = forj x xs n + if (fst x)*(fst u) == (snd x + snd u) then 1 else 0

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

--{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.List as L
--import Data.Char as C

--import Data.IntSet as S

cntPairs :: [(Integer, Integer)] -> (Integer, Integer) -> Int
cntPairs l (i, x) =
  length $ filter (\(j, y) -> i + j == x * y) $ takeWhile (\(j,y) -> y < x && x*y <= 2000000) l

solve :: IO ()
solve = do
  n <- readLn :: IO Integer
  sxs <- getLine
  let xs = map read $ words sxs :: [Integer]
      vals = sortBy (\(_,x) (_,y) -> compare x y) $ zip [1..] xs
      pairs = sum $ map (cntPairs vals) vals
    in print pairs

main :: IO ()
main = do
  t <- readLn :: IO Int
  replicateM_ t solve

-- cheese-cracker: cheese-cracker.github.io
import Control.Monad
import Data.List as L
import Data.Maybe (fromJust)
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS

readInts :: IO [Int]
readInts =  (map (fromInteger . fst . fromJust. BS.readInteger) . BS.words) <$> BS.getLine

getOrInf :: Int -> M.Map Int Int -> Int
getOrInf keyy haystack
    | needle == Nothing = -2000000
    | otherwise = fromJust needle
    where needle = M.lookup keyy haystack

solve :: Int -> [Int] -> Int
solve n xs =
    let
    ixmap = M.fromList $ zip xs [1..]
    condn k summ =  (getOrInf k ixmap) + (getOrInf (summ `div` k) ixmap) == summ
    takeflour = floor . sqrt . fromIntegral
    res till = [x | m <- [1..till], x <- [1.. (takeflour $ m-1)], (m `mod` x == 0) && condn x m]
    in length $ res (2*n)

main :: IO ()
main = do
    [t] <- readInts
    replicateM_ t $ do
        [n] <- readInts
        arr <- readInts
        print(solve n arr)

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

count a i n = length [1|p<-[ai,2*ai..2*n],let aj = div p ai,let j = p - i,j > i && j <= n && a!j == aj]
                where ai=a!i

printResult = do
    n <- readLn :: IO Int
    a <- readInts
    let aa = listArray (1,n) a
        r = sum [count aa i n|i<-[1..n]]
    print r

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

import Control.Monad ( replicateM_ )
import Data.Int ( Int64 )
import Data.List ( sort, tails )

solve :: IO()
solve = do
    n <- readInt64 <$> getLine
    as <- map readInt64 . words <$> getLine
    let ps = sort $ zip as [1..]
    let calc []     = 0
        calc (x:xs) = calc' x xs
        calc' _ [] = 0
        calc' (ai,i) ((bj,j) : bs)
            | ai * bj > 2 * n = 0
            | otherwise       = calc' (ai,i) bs + (if ai * bj == i + j then 1 else 0)
    print $ sum $ map calc $ tails ps

readInt :: String -> Int
readInt = read

readInt64 :: String -> Int64
readInt64 = read

main :: IO()
main = do
    t <- readInt <$> getLine
    replicateM_ t solve

import Control.Monad ( replicateM_ )
import Data.List ( sort, tails )

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

solve :: IO()
solve = do
    n <- readLn::IO Integer
    as <- readInts
    let ps = sort $ zip as [1..]
    let calc []     = 0
        calc (x:xs) = calc' x xs
        calc' _ [] = 0
        calc' (ai,i) ((bj,j) : bs)
            | ai * bj > 2 * n = 0
            | otherwise       = calc' (ai,i) bs + fromEnum (ai * bj == i + j)
    print $ sum $ map calc $ tails ps

main :: IO()
main = do
    t <- readLn::IO Int
    replicateM_ t solve

-- author https://codeforces.com/contest/1541/submission/120631973

import Control.Monad
import Data.List
import Data.Bits

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

each = do
    n<-readLn::IO Integer
    a<-readInts
    let b = sort $ zip a [1..]
    let calc []     = 0
        calc (x:xs) = calc' x xs
        calc' _ [] = 0
        calc' (ai,i) ((bj,j) : bs)
            | ai * bj > 2 * n = 0
            | otherwise       = calc' (ai,i) bs + fromEnum (ai * bj == i + j)
    print $ sum $ map calc $ tails b

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

-- author https://codeforces.com/contest/1541/submission/120631973

import Control.Monad
import Data.List
import Data.Bits

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

each = do
    n<-readLn::IO Integer
    a<-readInts
    let b = sort $ zip a [1..]
    let fori [x] = 0
        fori (x:xs) = fori xs + forj x xs
        forj x [] = 0
        forj x (u:xs)
            | (fst x)*(fst u) > 2*n = 0
            | otherwise = forj x xs + if (fst x)*(fst u) == (snd x + snd u) then 1 else 0
    print $ fori b

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

-- author https://codeforces.com/contest/1541/submission/120631973

import Control.Monad
import Data.List
import Data.Bits

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

genPair [] i = []
genPair (x:xs) i = (x,i) : (genPair xs (i+1))

each = do
    n<-readLn::IO Integer
    a<-readInts
    let b = sort $ genPair a 1
    let fori [x] = 0
        fori (x:xs) = fori xs + forj x xs
        forj x [] = 0
        forj x (u:xs)
            | (fst x)*(fst u) > 2*n = 0
            | otherwise = forj x xs + if (fst x)*(fst u) == (snd x + snd u) then 1 else 0
    print $ fori b

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

-- author https://codeforces.com/contest/1541/submission/120631973

import Control.Monad
import Data.List
import Data.Bits

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

genPair [] i = []
genPair (x:xs) i = (x,i) : (genPair xs (i+1))

fori [x] n = 0
fori (x:xs) n = fori xs n + forj x xs n

forj x [] n = 0
forj x (u:xs) n
    | (fst x)*(fst u) > 2*n = 0
    | otherwise = forj x xs n + if (fst x)*(fst u) == (snd x + snd u) then 1 else 0

each = do
    n<-readLn::IO Integer
    a<-readInts
    let b = sort $ genPair a 1
    print $ fori b n

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

-- author https://codeforces.com/contest/1541/submission/120631973

import Control.Monad
import Data.List
import Data.Bits

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

genPair [] i = []
genPair (x:xs) i = (x,i) : (genPair xs (i+1))

fori [x] n r = 0
fori (x:xs) n r = fori xs n r + forj x xs n r

forj x [] n r = r
forj x (u:xs) n r
    | (fst x)*(fst u) > 2*n = r
    | otherwise = (forj x xs n (r + if (fst x)*(fst u) == (snd x + snd u) then 1 else 0))

each = do
    n<-readLn::IO Integer
    a<-readInts
    let b = sort $ genPair a 1
    print $ fori b n 0

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

--{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.List as L
--import Data.Char as C

--import Data.IntSet as S

cntPairs :: [(Int, Int)] -> (Int, Int) -> Int
cntPairs l (i, x) =
  length $ filter (\(j, y) -> i + j == x * y) $ takeWhile (\(j,y) -> y < x && x*y <= 2000000) l

solve :: IO ()
solve = do
  n <- readLn :: IO Int
  sxs <- getLine
  let xs = map read $ words sxs :: [Int]
      vals = sortBy (\(_,x) (_,y) -> compare x y) $ zip [1..] xs
      pairs = sum $ map (cntPairs vals) vals
    in print pairs

main :: IO ()
main = do
  t <- readLn :: IO Int
  replicateM_ t solve

-- cheese-cracker: cheese-cracker.github.io
import Control.Monad
import Data.List as L
import Data.Maybe (fromJust)
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS

readInts :: IO [Int]
readInts =  (map (fromInteger . fst . fromJust. BS.readInteger) . BS.words) <$> BS.getLine

getOrInf :: Int -> M.Map Int Int -> Int
getOrInf keyy haystack
    | needle == Nothing = -2000000
    | otherwise = fromJust needle
    where needle = M.lookup keyy haystack

solve :: Int -> [Int] -> Int
solve n xs =
    let
    ixmap = M.fromList $ zip xs [1..]
    condn k summ =  (getOrInf k ixmap) + (getOrInf (summ `div` k) ixmap) == summ
    takeflour = floor . sqrt . fromIntegral
    res till = [x | m <- [1..till], x <- [1.. takeflour m], (m `mod` x == 0) && condn x m]
    in length $ res (2*n)

main :: IO ()
main = do
    [t] <- readInts
    replicateM_ t $ do
        [n] <- readInts
        arr <- readInts
        print(solve n arr)


main :: IO ()
main = interact (unlines . map (unwords . map show . solve . read) . tail . lines)

solve :: Int -> [Int]
solve n = replicate n 1

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

main = getLine >>= flip replicateM_ (getLine >>= putStrLn . unwords . map show . flip replicate 1 . read) . read

import Control.Monad
main = read <$> getLine >>= flip replicateM (read <$> getLine) >>= mapM_ (putStrLn . unwords . map show . flip replicate 1)

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

onecase = do
		x<- read <$> getLine ::IO Int
		putStrLn $ intercalate " " $ map show $ replicate x 1

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

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 1 >>> map read >>> map (\n-> unwords (map show (take n (repeat 1000)))) >>>  unlines

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

onecase = do
		x<- read <$> getLine ::IO Int
		putStrLn $ intercalate " " $ map show $ replicate x '1'

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