-- https://codeforces.com/contest/1618/problem/C
import Control.Monad (replicateM)
import qualified Data.ByteString.Char8 as B

getOddPos [] = []
getOddPos [o] = [o]
getOddPos (o:e:xs) = o : getOddPos xs
getEvenPos [] = []
getEvenPos [o] = []
getEvenPos (o:e:xs) = e : getEvenPos xs

main = getLine >>= flip replicateM run . read
run = do
    n <- B.getLine
    numbers <- (read . B.unpack <$>) . B.words <$> B.getLine
    let
        oddList = getOddPos numbers
        evenList = getEvenPos numbers
        oddListGcd = foldl1 gcd oddList
        evenListGcd = foldl1 gcd evenList
    print $
        if not $ any(\x->mod x evenListGcd == 0) oddList then evenListGcd else
        if not $ any(\x->mod x oddListGcd == 0) evenList then oddListGcd  else 0

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

solve :: IO ()
solve = do
    void C.getLine
    xs <- readInts
    let (as, bs) = splitEvenOdd xs
        ag = foldl' gcd 0 as
        bg = foldl' gcd 0 bs
        ans | all ((/=0) . (`mod` ag)) bs = ag
            | all ((/=0) . (`mod` bg)) as = bg
            | otherwise                   = 0
    print ans

splitEvenOdd :: [a] -> ([a], [a])
splitEvenOdd = foldr (\a ~(x, y) -> (a:y, x)) ([], [])

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

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

-- https://codeforces.com/contest/1618/problem/C
import Control.Monad (replicateM)

getOddPos [] = []
getOddPos [o] = [o]
getOddPos (o:e:xs) = o : getOddPos xs
getEvenPos [] = []
getEvenPos [o] = []
getEvenPos (o:e:xs) = e : getEvenPos xs

main = getLine >>= flip replicateM run . read
run = do
    n <- getLine
    numbers <- (read <$>) . words <$> getLine
    let
        oddList = getOddPos numbers
        evenList = getEvenPos numbers
        oddListGcd = foldl1 gcd oddList
        evenListGcd = foldl1 gcd evenList
    print $
        if not $ any(\x->mod x evenListGcd == 0) oddList then evenListGcd else
        if not $ any(\x->mod x oddListGcd == 0) evenList then oddListGcd  else 0

-- https://codeforces.com/contest/1618/problem/C
import Control.Monad (replicateM)

getOddPos [] = []
getOddPos [o] = [o]
getOddPos (o:e:xs) = o : getOddPos xs
getEvenPos [] = []
getEvenPos [o] = []
getEvenPos (o:e:xs) = e : getEvenPos xs

main = getLine >>= flip replicateM run . read
run = do
    n <- getLine
    numbers <- (read <$>) . words <$> getLine
    let
        oddList = getOddPos numbers
        evenList = getEvenPos numbers
        oddListGcd = foldl1 gcd $ oddList
        evenListGcd = foldl1 gcd $ evenList
        biggerGcd = max oddListGcd evenListGcd
    print $ if any(\x->mod x biggerGcd == 0) oddList && any(\x->mod x biggerGcd == 0) evenList
    then 0
    else biggerGcd


import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromMaybe)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs =
  let (hs, ts) = splitAt k xs
   in hs : chunksOf k ts

main :: IO ()
main =
  interact $
  lines >>>
  drop 1 >>>
  chunksOf 2 >>>
  map (last >>> words >>> map read >>> solve >>> show) >>> unlines

solve :: [Int] -> Int
solve xs = n - maximum [l, r, m]
  where
    n = length xs
    check = liftA2 (&&) (/= 1) (/= n)
    l = length $ takeWhile check xs
    r = length $ takeWhile check $ reverse xs
    m = n - l - r - 2

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

{-# language NoMonomorphismRestriction #-}

{-# 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 -Werror -O1 -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out > temp.txt  &&  diff -sdu -- output.txt temp.txt)  &&  echo OKAY  ||  echo ERROR

import Prelude
import Control.Monad
import Data.List

main :: IO ()
main = do
    t <- readLn
    tcs <- replicateM t readTC

    (putStr . unlines . map solve) tcs

readTC = do
    _n <- readLn  :: IO Int
    readIListLn

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

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

solve nums = show $ length nums - length nums3
  where
    mn = minimum nums
    mx = maximum nums

    fnd = [mn, mx]

    (v2, nums2) = g fnd nums

    fnd2 = filter (/= v2) fnd

    (_, nums3) = g fnd2 nums2

g fnd nums = last . sortOn (length.snd) $ f <$> fnd <*> [nums, reverse nums]

f _ [] = error "impossible by condition"
f x (y:ys) | (x == y)  = (x, ys)
           | otherwise = f x ys

import Control.Monad
import Data.List
import Data.Maybe
readInts = fmap (map read.words) getLine :: IO [Int]
nElemIndex n xs = fromJust (elemIndex n xs)

solve l r n = minimum [x,y,z]
            where
                x = l + 1 + n - r
                y = r + 1
                z = n - l

printResult = do
    n <- readLn :: IO Int
    a <- readInts
    let i = nElemIndex (maximum a) a
        j = nElemIndex (minimum a) a
    print $ solve (min i j) (max i j) n

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

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

printS = do
    n <- readLn::IO Int
    xs <- readInts
    let mini = head $ filter ((== minimum xs) . (xs !!)) [0..]
        maxi = head $ filter ((== maximum xs) . (xs !!)) [0..]
    let x = minimum [mini,maxi]
        y = maximum [mini,maxi]
    print $ minimum [y+1, n-x, x + 1 + n - y]
main = do
    t <- readLn::IO Int
    replicateM_ t printS

makeInteger :: [String] -> [Int]
makeInteger = map read

main :: IO()
main = do
    line <- getLine
    let t = (read line::Int)
    solve_multitest t

solve_multitest :: Int -> IO()
solve_multitest 0 = return ()
solve_multitest t = do
    solve_test
    solve_multitest (t - 1)

solve_test :: IO()
solve_test = do
    line <- getLine
    let n = (read line::Int)
    line <- getLine
    let inparr = words line
    let arr = makeInteger inparr
    let x = find_index_k arr 1
    let y = find_index_k arr n
    let mnpos = min x y
    let mxpos = max x y
    let ans = min (min mxpos (n - mnpos + 1)) (mnpos + n - mxpos + 1)
    putStrLn (show ans)

find_index_k :: [Int] -> Int -> Int
find_index_k a k = do
    let x = head a
    if x == k then
        1
    else
        find_index_k (drop 1 a) k + 1

--prewritten code: https://github.com/antma/algo
{-# LANGUAGE BangPatterns #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char
import Data.List(minimum,maximum)

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

test' :: [Int] -> Int
test' a = minimum [res1, res2, res3]
  where
    n = length a
    f g = snd $ head $ filter ( (== g). fst) $ zip a [0 ..]
    u = f $ minimum a
    v = f $ maximum a
    u' = min u v
    v' = max u v
    res1 = 1 + v'
    res2 = n - u'
    res3 = 1 + u' + n - v'

nl = char7 '\r' <> char7 '\n'
test :: Builder -> Int -> [Int] -> Builder
test buf 0 _ = buf
test buf nt (n:a) = test (buf <> intDec (test' b) <> nl) (pred nt) c
  where
    (b, c) = splitAt n a

solve :: [Int] -> Builder
solve (nt:xs) = test mempty nt xs

main :: IO ()
main = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents


import Control.Monad( replicateM)
import Control.Applicative( (<$>))

main = do
    n_ <- readLn
    let
	readPair = do
	    [before, after] <- map read . words <$> getLine
	    return (before, after)

    pairs_ <- replicateM n_ readPair::IO [(Int,Int)]
    let
	isDesc [] = True
	isDesc [_] = True
	isDesc (a:tl@(b:rem))	| a>=b	    = isDesc tl
				| otherwise = False

	(befores, afters) = unzip pairs_

	sames = and $ zipWith (==) befores afters

    putStr $ if sames
		then if isDesc befores
			then "maybe"
			else "unrated"
		else "rated"

module Main where

import Data.Functor
import Control.Applicative

main = do
    n <- read <$> getLine :: IO Int
    ps <- sequence $ replicate n $ (\[a, b] -> (read a, read b)) . words <$> getLine :: IO [(Int, Int)]
    if any (uncurry (/=)) ps then
        putStr "rated"
    else if and $ zipWith (>=) ps $ tail ps then
        putStr "maybe"
    else
        putStr "unrated"
    return ()

f::[String]->Bool
f []=True
f (s:str)=let (a:b:[])=words s
          in if a==b then f str else False

f2::[String]->Bool
f2 (s:[])=True
f2 (s:s2:str)=let (a:b:[])=map read (words s)::[Int]
                  (c:d:[])=map read (words s2)::[Int]
              in if a<c then False else f2 (s2:str)

main = do
       e<-getLine
       es<-getContents
       let xs=lines es
       putStrLn $ if (f xs) && ((f2 xs)==False) then "unrated"
                          else if (f xs) && (f2 xs) then "maybe" else "rated"

module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

solve bas = if any (\(b, a) -> b /= a) bas
  then Just True
  else if any (\((_, a1), (_, a2)) -> a1 < a2) $ zip bas (tail bas) then Just False else Nothing

main = do
  n <- readInt <$> B.getLine
  bas <- replicateM n ((\(b:a:_) -> (b,a)) . readInts <$> B.getLine)
  putStr $ maybe "maybe" (\b -> if b then "rated" else "unrated") $ solve bas

{-# OPTIONS_GHC -O2 -optc-O2 #-}
module Main where

import Control.Applicative
import Control.Monad

data Status = Rated | Unrated | Unknown
              deriving (Show, Eq)

ratingChanged :: (Int, Int) -> Bool
ratingChanged (x, y) = x /= y

tails :: [a] -> [[a]]
tails [x] = [[x]]
tails xss@(x:xs) = xss : tails xs

solve :: [(Int, Int)] -> Status
solve rs | haveChanges = Rated
         | haveMisplaces = Unrated
         | otherwise = Unknown
    where haveChanges = not . null . filter id $ map ratingChanged rs
          haveMisplaces = not . null . concat $ [filter (> x) ys | (x:ys) <- tails bs]
          bs = map fst rs

test0 = [(3060,  3060)
        , (2194, 2194)
        , (2876, 2903)
        , (2624, 2624)
        , (3007, 2991)
        , (2884, 2884)
        ] :: [(Int, Int)]

test1 = [ (1500, 1500)
        , (1300, 1300)
        , (1200, 1200)
        , (1400, 1400)
        ] :: [(Int, Int)]

test2 = [ (3123, 3123)
        , (2777, 2777)
        , (2246, 2246)
        , (2246, 2246)
        , (1699, 1699)
        ] :: [(Int, Int)]

main :: IO ()
main = do
  n <- read <$> getLine
  rs <- replicateM n $ do
          [a, b] <- map read . words <$> getLine
          return (a, b)
  putStrLn $ case solve rs of
    Rated -> "rated"
    Unrated -> "unrated"
    Unknown -> "maybe"


main = interact $ unlines . map solve . tail . lines

solve s = show $ foldl max 0 [ a * y
                             , b * x
                             , a * (b-y-1)
                             , b * (a-x-1) ]
      where [a, b, x, y] = map (read :: String -> Int) (words s)

import Control.Arrow
import Data.List

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

solve :: [Integer] -> Integer
solve [a, b, x, y] = max ((max x (a - x - 1)) * b)
                        ((max y (b - y - 1)) * a)

pop :: [a] -> (a, [a])
pop ([x]) = (x, [])
pop (x:xs) = (x, xs)
pop _ = undefined

cal :: Int -> IO ()
cal 0 = return ()
cal n = do
  line <- getLine
  let xs = map (read :: String -> Int) $ words line
  let (a, x1) = pop xs
  let (b, x2) = pop x1
  let (x, x3) = pop x2
  let (y, x4) = pop x3
  let (x1, x2) = (x, a - 1 - x)
  let (y1, y2) = (y, b - 1 - y)
  let area = maximum [calArea (x1, b), calArea (x2, b),calArea (a, y1), calArea (a, y2)]
  putStrLn $ show area
  cal (n - 1)
  where calArea (w, h) =  w * h

main :: IO ()
main = do
  a <- getLine
  let n = (read a) :: Int
  cal n

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

routine :: IO ()
routine = do
  [a,b,x,y] <- (map read.words) <$> getLine
  print $ solve a b x y

solve :: Int -> Int -> Int -> Int -> Int
solve a b x y = max (xm*b) (ym*a)
  where
    x1=x
    x2=a-x-1
    xm=max x1 x2
    y1=y
    y2=b-y-1
    ym=max y1 y2

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

onecase = do
		[r,c,x,y]<- map read <$> words <$> getLine ::IO [Int]
		let ml = max x (r-x-1)
		let mw = max y (c-y-1)
		print $ max (ml*c) (mw*r)

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

maxOkayArea :: Int -> Int -> Int -> Int -> Int
maxOkayArea a b x y = max ((max x x') * b) ((max y y') * a)
    where
        x' = a - 1 - x
        y' = b - 1 - y

readInt :: String -> Int
readInt = read

main = do
    n <- fmap readInt getLine
    s <- fmap (map (map readInt.words).lines) getContents
    putStrLn.unlines.map show.map (\[a,b,x,y] -> maxOkayArea a b x y) $ s

import Control.Monad

data Rect = Rect { l :: Int,  r :: Int, b :: Int, t :: Int } deriving (Show)

main :: IO ()
main = do
  examples <- read <$> getLine :: IO Int
  _ <- forM (replicate examples ()) $ \_ -> do
     [xMax, yMax, x, y] <- (\str -> read <$> words str) <$> getLine :: IO [Int]
     putStrLn $ show $ solve xMax yMax x y
  return ()

area :: Rect -> Int
area (Rect l r b t)
  | (l <= r) && (b <= t) = (r - l + 1) * (t - b + 1)
  | otherwise = 0

solve :: Int -> Int -> Int -> Int -> Int
solve xMax yMax x y = foldl1 max $ area <$>
  [ Rect 0 (xMax-1) 0 (y-1) -- bottom to Y
  , Rect 0 (x-1) 0 (yMax-1) -- left to X
  , Rect (x+1) (xMax-1) 0 (yMax-1) -- right to X
  , Rect 0 (xMax-1) (y+1) (yMax-1) -- top to Y
  ]

import Control.Monad

data Rect = Rect { l :: Int,  r :: Int, b :: Int, t :: Int }

main :: IO ()
main = do
  examples <- read <$> getLine :: IO Int
  _ <- forM (replicate examples ()) $ \_ -> do
     [xMax, yMax, x, y] <- (\str -> read <$> words str) <$> getLine :: IO [Int]
     putStrLn $ show $ solve xMax yMax x y
  return ()

area :: Rect -> Int
area (Rect l r b t)
  | (l < r) && (b < t) = (r - l + 1) * (t - b + 1)
  | otherwise = 0

solve :: Int -> Int -> Int -> Int -> Int
solve xMax yMax x y = foldl1 max $ area <$>
  [ Rect 0 (xMax-1) 0 (y-1)
  , Rect 0 (x-1) 0 (yMax-1)
  , Rect (x+1) (xMax-1) 0 (yMax-1)
  , Rect 0 (xMax-1) (y+1) (yMax-1)
  ]


import Data.List
c=cycle[1>0,0>1]
z h l=length$filter(all(\(a,c)->a=='.'||c==(a`elem`h)).zip l)[c,tail c]
s s=foldr1(((`mod`1000003).).(*))$z"14"`map`transpose s++z"12"`map`s
main=interact$show.s.tail.lines

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph

parseInput = do
    n <- readInt
    m <- readInt
    grid <- replicateM n (BS.unpack <$> readString)
    return (n, m, grid)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

main = print =<< solve . evalState parseInput <$> BS.getContents

modulo = 1000003

newtype ModP = ModP Integer deriving Eq

instance Show ModP where
    show (ModP a) = show a

instance Num ModP where
    ModP a + ModP b = ModP $ (a + b) `mod` modulo
    ModP a - ModP b = ModP $ (a - b) `mod` modulo
    ModP a * ModP b = ModP $ (a * b) `mod` modulo
    signum = undefined
    abs = undefined
    fromInteger = ModP . (`mod` modulo)

solve (n, m, grid)
    | isConflict = 0
    | otherwise  = fromInteger 2 ^ frees :: ModP
  where
    lst = concat [ map (process (i, j)) (getD cij)
                 | (i, row) <- zip [0..] grid
                 , (j, cij) <- zip [0..] row
                 ]

    process (x, y) L = (x, even y)
    process (x, y) R = (x, odd y)
    process (x, y) U = (n + y, even x)
    process (x, y) D = (n + y, odd x)

    arr = accumArray merge None (0, n + m - 1) lst :: Array Int Info

    answer = elems arr

    isConflict = any (==Conflict) answer
    frees = length $ filter (==None) answer

    merge (Unique bool) b
        | bool == b = Unique bool
        | otherwise = Conflict

    merge Conflict _ = Conflict
    merge None x = Unique x

data Direction = L | R | U | D deriving (Show, Eq)

data Info = None
          | Unique Bool
          | Conflict deriving (Show, Eq)

getD '1' = [L, U]
getD '2' = [L, D]
getD '3' = [R, D]
getD '4' = [R, U]
getD _   = []

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

class (Monad m) => MonadState s m | m -> s where
	get :: m s
	put :: s -> m ()

modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
	s <- get
	put (f s)

gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
	s <- get
	return (f s)

newtype State s a = State { runState :: s -> (a, s) }

instance Functor (State s) where
	fmap f m = State $ \s -> let
		(a, s') = runState m s
		in (f a, s')

instance Applicative (State s) where
    pure = return
    (<*>) = ap

instance Monad (State s) where
	return a = State $ \s -> (a, s)
	m >>= k  = State $ \s -> let
		(a, s') = runState m s
		in runState (k a) s'

instance MonadState s (State s) where
	get   = State $ \s -> (s, s)
	put s = State $ \_ -> ((), s)

evalState :: State s a -> s -> a
evalState m s = fst (runState m s)

execState :: State s a -> s -> s
execState m s = snd (runState m s)

mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m

withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f

state = State

import Data.List
import Control.Applicative

newtype I=I Int deriving (Show, Eq, Ord)
mmm :: Integral a => a -> a
mmm x=x `mod` 1000003

instance Num I where
  I x+I y=I(mmm$x+y)
  I x*I y|y<10^3 || x < 10^3 = I $ mmm $ x * y
   | otherwise = I $ fromInteger $ mmm $
                   (fromIntegral x :: Integer) * fromIntegral y
  fromInteger n = I $ fromInteger $ mmm n

instance Real I
instance Enum I
instance Integral I where
  toInteger (I i) = toInteger i

s1 :: (Char -> Bool) -> [Char] -> I
s1 is1 l = goN l where
  goN [] = 2
  goN ('.':t) = goN t
  goN (some:t) = goS (not $ is1 some) t
  goS need1 [] = 1
  goS need1 ('.':t) = goS (not need1) t
  goS need1 (some:t) | is1 some /= need1 = 0
   | 1>0 = goS (not need1) t

solve s = product (map (s1 ((||) <$> (=='1') <*>  (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2')))  s)

ss = show . toInteger . solve
main=interact$ss.tail.lines

import Data.List
import Control.Applicative

newtype I=I Int deriving (Show, Eq, Ord)
mmm :: Integral a => a -> a
mmm x=x `mod` 1000003

instance Num I where
  I x+I y=I(mmm$x+y)
  I x*I y|y<10^3 || x < 10^3 = I $ mmm $ x * y
   | otherwise = I $ mmm $ fromInteger $
                   (fromIntegral x :: Integer) * fromIntegral y
  fromInteger n = I $ fromInteger $ mmm n

instance Real I
instance Enum I
instance Integral I where
  toInteger (I i) = toInteger i

s1 :: (Char -> Bool) -> [Char] -> I
s1 is1 l = goN l where
  goN [] = 2
  goN ('.':t) = goN t
  goN (some:t) = goS (not $ is1 some) t
  goS need1 [] = 1
  goS need1 ('.':t) = goS (not need1) t
  goS need1 (some:t) | is1 some /= need1 = 0
   | 1>0 = goS (not need1) t

solve s = product (map (s1 ((||) <$> (=='1') <*>  (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2')))  s)

main=interact$show . toInteger . solve . tail . lines

import Data.List
import Control.Applicative

newtype I=I Int deriving (Show, Eq)
mmm :: Integral a => a -> a
mmm x=x `mod` 1000003

instance Num I where
  I x+I y=I(mmm$x+y)
  I x*I y|y<10^3 || x < 10^3 = I $ mmm $ x * y
   | otherwise = I $ mmm $ fromInteger $
                   (fromIntegral x :: Integer) * fromIntegral y
  fromInteger n = I $ fromInteger $ mmm n

s1 :: (Char -> Bool) -> [Char] -> I
s1 is1 l = goN l where
  goN [] = 2
  goN ('.':t) = goN t
  goN (some:t) = goS (not $ is1 some) t
  goS need1 [] = 1
  goS need1 ('.':t) = goS (not need1) t
  goS need1 (some:t) | is1 some /= need1 = 0
   | 1>0 = goS (not need1) t

solve s = product (map (s1 ((||) <$> (=='1') <*>  (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2')))  s)

main=interact$show . solve . tail . lines

import Data.List
import Control.Applicative

s1 is1 l = goN l where
  goN [] = 2
  goN ('.':t) = goN t
  goN (some:t) = goS (not $ is1 some) t
  goS need1 [] = 1
  goS need1 ('.':t) = goS (not need1) t
  goS need1 (some:t) | is1 some /= need1 = 0
   | 1>0 = goS (not need1) t

solve s = product (map (s1 ((||) <$> (=='1') <*>  (=='4'))) $ transpose s) * product (map (s1 ((||) <$> (=='1') <*> (=='2')))  s)

main=interact$show . solve . tail . lines

import Data.List
c=cycle[1>0,0>1]
z h l = length$filter(o l)[c,tail c]where o=(all g.).zip;g(a,c)=a=='.'||c==(a`elem`h)
s s=foldr1((.(`mod`1000003)).(*))$z"14"`map`transpose s++z"12"`map`s
main=interact$show.s.tail.lines


xor :: Bool -> Bool -> Bool
xor a b = a && not b || b && not a

doit :: [Int] -> Bool -> Bool
doit [] last = not last
doit (x:xs) last
	| last && x == 0 = False
	| otherwise = doit xs $ last `xor` (x `mod` 2 == 1)

main = do
	getLine
	a <- getLine >>= return . map read . words
	putStrLn $ if doit a False then "YES" else "NO"

import Data.List
import Data.Array

main = do
  getLine
  aStr <- getLine
  putStrLn $
    if solve $ map (read :: String -> Int) (words aStr)
      then "YES"
      else "NO"

solve a = dp n 0
  where
        n = length a
        a' = listArray (1, n) a

        dp :: Int -> Int -> Bool
        dp 0 0 = True
        dp 0 1 = False
        dp i 0 = dps ! (i-1, (a' ! i) `mod` 2)
        dp i 1 = if (a' ! i) `mod` 2 == 0
                    then (if (a' ! i) /= 0 then dps ! (i-1, 1) else False)
                    else dps ! (i-1, 0)

        dps = listArray bounds [dp i j | (i, j) <- range bounds]
        bounds = ((0, 0), (n, 1))

import Data.List.Split

solve :: [Int] -> Bool
solve [] = True
solve [x] = even x && x >= 0
solve (x:y:nums)
  | x < 0 = False
  | even x = solve (y:nums)
  | otherwise = solve ((y-1):nums)

main :: IO ()
main = do
    _ <- getLine
    line <- getLine
    let nums = map read $ splitOn " " line
    putStrLn $ if solve nums then "YES" else "NO"

module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

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

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  elemSet :: (Ord a) => a -> S.Set a -> Bool
  elemSet elem sets =
    let found = elem `S.lookupIndex` sets
        in toBool found
        where
          toBool :: Maybe Int -> Bool
          toBool (Just _) = True
          toBool Nothing = False

  solve :: Bool -> [Int] -> Bool
  solve acc  [] = acc
  solve True (x:xs)
    | x `mod` 2 == 0 = solve True xs
    | x `mod` 2 == 1 = solve False xs
  solve False (0:xs) = False
  solve False (1:xs) = solve True xs
  solve False (x:xs)
    | x `mod` 2 == 0 = solve False xs
    | x `mod` 2 == 1 = solve True xs

  getOutput :: Bool -> String
  getOutput True = "YES"
  getOutput False = "NO"

  main :: IO()
  main = do
    n <- getLine
    xs <- getLine >>= return . map readInt .  words
    let canDo = solve True xs
    putStrLn $ getOutput canDo

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

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

main = do
  _ <- getLine
  xs <- map readInt.B.words <$> B.getLine
  putStrLn.bool"NO""YES" $ solve xs

solve :: [Int] -> Bool
solve xs = all isValid $ split xs
  where
    isValid (x:xs) | even x = isValid xs
    isValid (x:y:xs) = isValid $ (y-1):xs
    isValid (_:_) = False
    isValid [] = True

split :: [Int] -> [[Int]]
split xs = case span (0/=) xs of
  (ys, 0:zs) -> ys : split zs
  (ys, []) -> [ys]
  _ -> undefined


{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as C
import qualified Data.IntMap as M
import Control.Monad (replicateM_, replicateM)
import Data.Maybe (fromMaybe, fromJust)

inf = 2*10^9

accTemp :: [Integer] -> [Integer]
accTemp acs = [] where
  calcTemp minprev ac = min (minprev + 1) ac

solve :: Int -> M.IntMap Integer -> [Integer]
solve n acMap = zipWith min l r where
  find x = M.findWithDefault inf x acMap
  acs = map find [1..n]
  calcTemp minprev ac = min (minprev + 1) ac
  l = scanl1 calcTemp acs
  r = reverse $ scanl1 calcTemp $ reverse acs

-- IO from https://github.com/byorgey/comprog-hs/blob/master/Scanner.hs
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

str :: Scanner C.ByteString
str = get >>= \case s : ss -> put ss >> return s

int :: Scanner Int
int = fst . fromJust . C.readInt <$> str

integer :: Scanner Integer
integer = read . C.unpack <$> str

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

solveCase :: Scanner [Integer]
solveCase = do
  (n, k) <- pair int int
  pos <- replicateM k int
  temp <- replicateM k integer
  return $ solve n $ M.fromList (zip pos temp)

main :: IO ()
main = C.interact $ runScanner (numberOf (C.pack . unwords . map show <$> solveCase)  ) >>> C.unlines

-- main :: IO ()
-- main = do
--   q <- readLn
--   replicateM_ q $ do
--     getLine
--     [n, _] <- map read . words <$> getLine :: IO [Int]
--     pos <- map read . words <$> getLine :: IO [Int]
--     temp <- map read . words <$> getLine :: IO [Integer]
--     let ans = solve n $ M.fromList (zip pos temp)
--     putStrLn $ unwords $ map show ans

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as C
import qualified Data.IntMap as M
import Control.Monad (replicateM)
import Data.List (sort)
import Data.Maybe (fromMaybe, fromJust)

inf = 2*10^9

accTemp :: [Integer] -> [Integer]
accTemp acs = [] where
  calcTemp minprev ac = min (minprev + 1) ac

fillList :: Ord a => Int -> a ->  [(Int, a)] -> [a]
fillList n fillVal = go n . sort where
  go 0 _ = []
  go i [] = fillVal : go (i - 1) []
  go i vals@((j, x) : xs) = if n - i + 1 == j
    then x : go (i - 1) xs
    else fillVal : go (i - 1) vals

solve :: Int -> [Int] -> [Integer ] -> [Integer]
solve n pos temp = zipWith min l r where
  acs = fillList n inf $ zip pos temp
  calcTemp minprev ac = min (minprev + 1) ac
  l = scanl1 calcTemp acs
  r = reverse $ scanl1 calcTemp $ reverse acs

-- IO from https://github.com/byorgey/comprog-hs/blob/master/Scanner.hs
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

str :: Scanner C.ByteString
str = get >>= \case s : ss -> put ss >> return s

int :: Scanner Int
int = fst . fromJust . C.readInt <$> str

integer :: Scanner Integer
integer = read . C.unpack <$> str

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

solveCase :: Scanner [Integer]
solveCase = do
  (n, k) <- pair int int
  pos <- replicateM k int
  temp <- replicateM k integer
  return $ solve n pos temp

main :: IO ()
main = C.interact $ runScanner (numberOf (C.pack . unwords . map show <$> solveCase)  ) >>> C.unlines

-- main :: IO ()
-- main = do
--   q <- readLn
--   replicateM_ q $ do
--     getLine
--     [n, _] <- map read . words <$> getLine :: IO [Int]
--     pos <- map read . words <$> getLine :: IO [Int]
--     temp <- map read . words <$> getLine :: IO [Integer]
--     let ans = solve n $ M.fromList (zip pos temp)
--     putStrLn $ unwords $ map show ans

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as C
import Data.List (sort)
import Data.Maybe (fromMaybe, fromJust)

-- https://github.com/byorgey/comprog-hs/blob/master/ScannerBS.hs
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

str :: Scanner C.ByteString
str = get >>= \case s : ss -> put ss >> return s

int :: Scanner Int
int = fst . fromJust . C.readInt <$> str

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts

main :: IO ()
main = C.interact $ runScanner (numberOf (C.pack . unwords . map show <$> testCase)) >>> C.unlines

testCase :: Scanner [Int]
testCase = do
  (n, k) <- pair int int
  as <- replicateM k int
  ts <- replicateM k int
  return $ solve [[n, k], as, ts]

solve :: [[Int]] -> [Int]
solve [[n, k], as, ts] = zipWith min (compute xs) (reverse . compute . reverse $ xs)
  where
    xs = tail . snd . foldr upd (n + 1, []) . sort $ ((0, 0) : zip as ts)
    upd (a, t) (i, xs) = (a, t : replicate (i - a - 1) inf ++ xs)
    inf = 2 * 10 ^ 9

compute :: [Int] -> [Int]
compute = scanl1 (\p x -> min (p + 1) x)


import Control.Monad

readInts :: IO [Int]
readInts = do
    ls <- fmap words getLine
    return $ map read ls

main = do
    [n] <- readInts
    replicateM_ n $ do
        [a,b] <- readInts
        print $ solve a b

solve a b
    | a == b = 0
    | a > b  = if mod (a-b) 2 == 0 then 1 else 2
    | a < b  = if mod (b-a) 2 == 1 then 1 else 2

module Main where

import Control.Monad
import Data.List

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

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

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [x, y] <- getIntList
        print $ f x y

f :: Int -> Int -> Int
f x y
    | x == y = 0
    | or [(sameP x y) && (x > y), not (sameP x y) && (x < y)] = 1
    | otherwise = 2

sameP :: Int -> Int -> Bool
sameP x y = odd x == odd y

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

main = getLine >>= test.read
test 0 = return ()
test n = getLine >>= print.(\(a:b:_) -> solve a b).map read.words >> test (n - 1)

solve a b
	| a == b = 0
	| even (a - b) = 1 + fromEnum (a < b)
	| otherwise = 1 + fromEnum (a > b)

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

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

solve :: Int -> Int
solve 0 = 0
solve n
  {-|n>=8 = (n `div` 8) + solve (n `mod` 8)
  |n<=(-9) = (n `div` (-9)) + solve (n `mod` (-9))-}
  |(n>0) && even n = 1
  |(n<0) && odd n = 1
  |otherwise = 2

{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import Data.Ord
import Data.Int
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if s then
                aux s
            else
                return id
        else
            liftM ((.) $ showChar x) $ aux False
    in liftM (flip ($) []) $ aux True

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

class IOInteract a where
    convertEither :: String -> Either String a
    toShowS :: a -> String -> String
    toShow :: a -> String
    toShow x = toShowS x []

instance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where
    convertEither = convertEitherp (undefined :: flag)
    toShowS = toShowSp (undefined :: flag)

type family IOType x where
    IOType String = HString
    IOType [x] = HList
    IOType x = HNormal

class IOInteractp flag a where
    convertEitherp :: flag -> String -> Either String a
    toShowSp :: flag -> a -> String -> String

instance (Show a, Read a) => IOInteractp HNormal a where
    convertEitherp _ x = readEither x
    toShowSp _ x = shows x

instance IOInteractp HString String where
    convertEitherp _ x = Right x
    toShowSp _ x = showString x

instance (IOInteract a) => IOInteractp HList [a] where
    convertEitherp _ x = mapM convertEither $ words x
    toShowSp _ [] = id
    toShowSp _ (x : []) = toShowS x
    toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

main :: IO ()
main = do
    o <- runExceptT main_
    case o of
        Right () -> return ()
        Left s -> putStrLn s

main_ :: EIO ()
-- template --
main_ = do
    t <- get
    replicateM_ t f1

f1 :: EIO ()
f1 = do
    (a, b) <- liftM2 (,) get get
    putln $ f2 a b

f2 :: Int64 -> Int64 -> Int
f2 a b =    if b > a then
                if (mod (b - a) 2) == 1 then
                    1
                else
                    2
            else
                if b < a then
                    if (mod (b - a) 2) == 1 then
                        2
                    else
                        1
                else
                    0

import Control.Monad (replicateM_)

solve :: Int -> Int -> Int
solve x y | x == y = 0
          | x < y && x `mod` 2 /= y `mod` 2 = 1
          | x > y && x `mod` 2 == y `mod` 2 = 1
          | otherwise = 2

main :: IO ()
main = readLn >>= flip replicateM_ (getLine >>= print . (\[x,y] -> solve x y) . map read . words)

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

process a b | a==b = 0
            | b>a && odd (b-a) =1
	    | b>a = 2
	    | a>b && even (b-a) = 1
	    | otherwise = 2

onecase = do
		[a,b]<- map read <$> words <$> getLine:: IO [Int]
		print $ process a b

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

--ghc 7.10

countMoves :: (Integral a) => (a,a) -> a
countMoves (a,b)
    | a < b = 1 + e
    | a > b = 2 - e
    | otherwise = 0
    where e = if even (a-b) then 1 else 0

readPair :: String -> (Int,Int)
readPair str = (a,b)
    where [a,b] = map read . words $ str

main = do
    nStr <- getLine
    contents <- getContents
    let qPairs = map readPair . lines $ contents
    sequence . map print $ map countMoves qPairs

solve :: Int -> Int -> Int
solve a b
  | a == b = 0
  | b > a && odd (b-a) = 1
  | b > a && even (b-a) = 2
  | b < a && odd (a-b) = 2
  | b < a && even (a-b) = 1

parse :: String -> String
parse line = show $ solve a b
  where [a, b] = map (\x -> read x :: Int) $ words line

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

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

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

solve :: Int -> Int
solve 0 = 0
solve n
  |n>=8 = (n `div` 8) + solve (n `mod` 8)
  |n<=(-9) = (n `div` (-9)) + solve (n `mod` (-9))
  |(n>0) && even n = 1
  |(n<0) && odd n = 1
  |otherwise = 2

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

process a b | a==b = 0
            | even a && b>a = 1
	    | even a = 2
	    | odd a && a<b = 1
	    | otherwise = 2

onecase = do
		[a,b]<- map read <$> words <$> getLine:: IO [Int]
		print $ process a b

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


{-# LANGUAGE BangPatterns #-}

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

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

mp [ a, b ] = ( a, b )

main = do
	[ h, w ] <- getInts
	rows <- replicateM h getInts

	let
		mirrors rs
			| length rs < h = mirrors $ rs ++ reverse rs
			| otherwise = rs

	print $ head $ filter ( ( == rows ) . mirrors . ( flip take rows ) ) [ 1 .. h ]

input :: Int -> [String] -> IO ([String])
input 0 acc = return acc
input n acc = do
              r <- getLine
              input (n-1) (r:acc)

symmetric matrix | odd (length matrix) = False
                 | otherwise = (top == reverse bottom)
                 where
                     top = take (div n 2) matrix
                     bottom = drop (div n 2) matrix
                     n = length matrix

fold :: [String] -> Int
fold matrix | symmetric matrix = fold (take (div (length matrix) 2) matrix)
            | otherwise        = length matrix

main = do
  s <- getLine
  let n = read (head (words s)) ::Int
  matr <- (input n [])
  print (fold matr)

import Control.Monad

solve :: [[Int]] -> Int

solve m | odd rowCount = rowCount
        | upperPart == reverse lowerPart = solve upperPart
        | otherwise = rowCount

    where rowCount = length m
          upperPart = take (rowCount `div` 2) m
          lowerPart = drop (rowCount `div` 2) m

main = do
    [n,m] <- fmap (map read . words) getLine
    as <- forM [1..n] (\_ -> fmap (map read . words) getLine)
    print $ solve as

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

hash :: [Int] -> Integer
hash [] = 0
hash (x:xs) = (fi x + 12347 * hash xs) `mod` 0x3de1f1ed

solve :: (Eq a) => [a] -> Int
solve xs = case n `quotRem` 2 of
	(k,0) -> let (x1, x2) = splitAt k xs in
		if reverse x1 == x2 then solve x2 else n
	_ -> n
	where n = length xs

main :: IO ()
main = do
	[n,_] <- inputInts
	mat <- replicateM n (hash <$> inputInts)
	print $ solve mat


import Control.Monad (liftM)

solve :: Int -> Int -> String
solve 0 m  =  replicate m 'G'
solve n 0  =  replicate n 'B'
solve n m
  | n > m  =  'B' : 'G' : solve (n - 1) (m - 1)
  | otherwise  =  'G' : 'B' : solve (n - 1) (m - 1)

main :: IO ()
main  =  do
    [n, m]  <-  liftM (map read . words) (readFile "input.txt")
    writeFile "output.txt" $ solve n m

import Control.Applicative
import Control.Monad
import System.IO

main = do

  hin  <- openFile "input.txt"  ReadMode
  hout <- openFile "output.txt" WriteMode

  [n,m] <- map read.words <$> hGetLine hin

  if n>m
     then hPutStrLn hout $ ([1..m]>>"BG")++replicate (n-m) 'B'
     else hPutStrLn hout $ ([1..n]>>"GB")++replicate (m-n) 'G'

  hClose hin
  hClose hout

import Control.Applicative
import Control.Monad
import System.IO

main = do

  hin  <- openFile "input.txt"  ReadMode
  hout <- openFile "output.txt" WriteMode

  [n,m] <- map read.words <$> hGetLine hin

  if n>m
     then hPutStrLn hout $ ([1..m]>>"BG")++replicate (n-m) 'B'
     else hPutStrLn hout $ ([1..n]>>"GB")++replicate (n-m) 'G'

  hClose hin
  hClose hout


{-# LANGUAGE BangPatterns, Strict #-}

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go !i !l !r "" !ms
      | 2 * (max r l) == i = ""
      | otherwise = ms
    go !i !l !r !s@(c : cs) !ms
    --  | 2 * (max l r) == length ms = ""
      | i `mod` 2 == 0 && r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | i `mod` 2 /= 0 && r > 0 && i == 2 * r + 1 && l < r + 1 = go i (r + 1) r s ms --(repXL i ms)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve !str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    !str' = '(' : (init $ tail str) ++ ")"

main = do
    getLine
    interact solveAll

{-# LANGUAGE BangPatterns, Strict #-}

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go !i !l !r "" !ms
      | 2 * r == i = ""
      | 2 * l == i = ""
      | otherwise = ms
    go !i !l !r !s@(c : cs) !ms
    --  | 2 * (max l r) == length ms = ""
      | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | r > 0 && i == 2 * r + 1 && l < r + 1 = go i (r + 1) r s ms --(repXL i ms)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve !str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    !str' = '(' : (init $ tail str) ++ ")"

main = do
    getLine
    interact solveAll

{-# LANGUAGE BangPatterns #-}

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go !i !l !r "" !ms
      | 2 * r == i = ""
      | 2 * l == i = ""
      | otherwise = ms
    go !i !l !r !s@(c : cs) !ms
    --  | 2 * (max l r) == length ms = ""
      | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | r > 0 && i == 2 * r + 1 && l < r + 1 = go i (r + 1) r s ms --(repXL i ms)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve !str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    !str' = '(' : (init $ tail str) ++ ")"

main = do
    getLine
    interact solveAll

{-# LANGUAGE BangPatterns #-}

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go i l r "" ms
      | 2 * r == i = ""
      | 2 * l == i = ""
      | otherwise = ms
    go !i !l !r s@(c : cs) !ms
    --  | 2 * (max l r) == length ms = ""
      | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | r > 0 && i == 2 * r + 1 && l < r + 1 = go i (r + 1) r s ms --(repXL i ms)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    str' = '(' : (init $ tail str) ++ ")"

main = do
    getLine
    interact solveAll

{-# LANGUAGE BangPatterns #-}

nLRXT :: String -> (Int, Int, Int, Int)
nLRXT str = go (0, 0, 0, 0) str
  where
    go t "" = t
    go (!l, !r, !x, !t) (c : cs) = case c of
        '(' -> go (l + 1, r, x, t + 1) cs
        ')' -> go (l, r + 1, x, t + 1) cs
        '?' -> go (l, r, x + 1, t + 1) cs

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go _ _ r "" ms
      | 2 * r == length ms = ""
      | otherwise = ms
    go !i !l !r s@(c : cs) ms
      | 2 * (max l r) == length ms = ""
      | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    str' = '(' : (init $ tail str) ++ ")"

p str = (lines str) !! 111

main = do
    s <- getLine
    let n = read s :: Int
    if n < 500 then interact solveAll else interact p
    --interact solveAll

--s = take 3000000 $ cycle "?()"

{-# LANGUAGE BangPatterns #-}

nLRXT :: String -> (Int, Int, Int, Int)
nLRXT str = go (0, 0, 0, 0) str
  where
    go t "" = t
    go (!l, !r, !x, !t) (c : cs) = case c of
        '(' -> go (l + 1, r, x, t + 1) cs
        ')' -> go (l, r + 1, x, t + 1) cs
        '?' -> go (l, r, x + 1, t + 1) cs

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go _ _ r "" ms
      | 2 * r == length ms = ""
      | otherwise = ms
    go !i !l !r s@(c : cs) ms
      | 2 * (max l r) == length ms = ""
      | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | r > 0 && i == 2 * r + 1 && l < r + 1 = go i r (r + 1) s (repXL i ms)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    str' = '(' : (init $ tail str) ++ ")"

repXL :: Int -> String -> String
repXL i str = (map conv (take i str)) ++ (drop i str)
  where
    conv '?' = '('
    conv x = x

main = do
    getLine
    interact solveAll

--s = take 3000000 $ cycle "?()"

{-# LANGUAGE BangPatterns #-}

nLRXT :: String -> (Int, Int, Int, Int)
nLRXT str = go (0, 0, 0, 0) str
  where
    go t "" = t
    go (!l, !r, !x, !t) (c : cs) = case c of
        '(' -> go (l + 1, r, x, t + 1) cs
        ')' -> go (l, r + 1, x, t + 1) cs
        '?' -> go (l, r, x + 1, t + 1) cs

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go _ _ r "" ms
      | 2 * r == length ms = ""
      | otherwise = ms
    go !i !l !r s@(c : cs) ms
      | 2 * (max l r) == length ms = ""
      | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | r > 0 && i == 2 * r + 1 && i < r + 1 = go i r (r + 1) s (repXL i ms)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    str' = '(' : (init $ tail str) ++ ")"

repXL :: Int -> String -> String
repXL i str = (map conv (take i str)) ++ (drop i str)
  where
    conv '?' = '('
    conv x = x

main = do
    getLine
    interact solveAll

--s = take 3000000 $ cycle "?()"

{-# LANGUAGE BangPatterns #-}

nLRXT :: String -> (Int, Int, Int, Int)
nLRXT str = go (0, 0, 0, 0) str
  where
    go t "" = t
    go (!l, !r, !x, !t) (c : cs) = case c of
        '(' -> go (l + 1, r, x, t + 1) cs
        ')' -> go (l, r + 1, x, t + 1) cs
        '?' -> go (l, r, x + 1, t + 1) cs

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go _ _ r "" ms
      | 2 * r == length ms = ""
      | otherwise = ms
    go !i !l !r s@(c : cs) ms
      | 2 * (max l r) == length ms = ""
      | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    str' = '(' : (init $ tail str) ++ ")"

p str = (lines str) !! 85

main = do
    s <- getLine
    let n = read s :: Int
    if n < 500 then interact solveAll else interact p
    --interact solveAll

--s = take 3000000 $ cycle "?()"

{-# LANGUAGE BangPatterns #-}

nLRXT :: String -> (Int, Int, Int, Int)
nLRXT str = go (0, 0, 0, 0) str
  where
    go t "" = t
    go (!l, !r, !x, !t) (c : cs) = case c of
        '(' -> go (l + 1, r, x, t + 1) cs
        ')' -> go (l, r + 1, x, t + 1) cs
        '?' -> go (l, r, x + 1, t + 1) cs

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go _ _ r "" ms
      | 2 * r == length ms = ""
      | otherwise = ms
    go !i !l !r s@(c : cs) ms
      | 2 * (max l r) == length ms = ""
      | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    str' = '(' : (init $ tail str) ++ ")"

p str = (lines str) !! 86

main = do
    s <- getLine
    let n = read s :: Int
    if n < 500 then interact solveAll else interact p
    --interact solveAll

--s = take 3000000 $ cycle "?()"

{-# LANGUAGE BangPatterns #-}

nLRXT :: String -> (Int, Int, Int, Int)
nLRXT str = go (0, 0, 0, 0) str
  where
    go t "" = t
    go (!l, !r, !x, !t) (c : cs) = case c of
        '(' -> go (l + 1, r, x, t + 1) cs
        ')' -> go (l, r + 1, x, t + 1) cs
        '?' -> go (l, r, x + 1, t + 1) cs

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go _ _ r "" ms
      | 2 * r == length ms = ""
      | otherwise = ms
    go !i !l !r s@(c : cs) ms
      | 2 * (max l r) == length ms = ""
      | r > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | r > 0 && i == 2 * r + 1 = go i r (r + 1) s (repXL i ms)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    str' = '(' : (init $ tail str) ++ ")"

repXL :: Int -> String -> String
repXL i str = (map conv (take i str)) ++ (drop i str)
  where
    conv '?' = '('
    conv x = x

main = do
    getLine
    interact solveAll

--s = take 3000000 $ cycle "?()"

{-# LANGUAGE BangPatterns #-}

nLRXT :: String -> (Int, Int, Int, Int)
nLRXT str = go (0, 0, 0, 0) str
  where
    go t "" = t
    go (!l, !r, !x, !t) (c : cs) = case c of
        '(' -> go (l + 1, r, x, t + 1) cs
        ')' -> go (l, r + 1, x, t + 1) cs
        '?' -> go (l, r, x + 1, t + 1) cs

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go _ _ r "" ms
      | 2 * r == length ms = ""
      | otherwise = ms
    go !i !l !r s@(c : cs) ms
      | 2 * (max l r) == length ms = ""
      | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | i > 0 && i == 2 * r + 1 = go i r (r + 1) s (repXL i ms)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    str' = '(' : (init $ tail str) ++ ")"

repXL :: Int -> String -> String
repXL i str = (map conv (take i str)) ++ (drop i str)
  where
    conv '?' = '('
    conv x = x

main = do
    getLine
    interact solveAll

--s = take 3000000 $ cycle "?()"

{-# LANGUAGE BangPatterns #-}

nLRXT :: String -> (Int, Int, Int, Int)
nLRXT str = go (0, 0, 0, 0) str
  where
    go t "" = t
    go (!l, !r, !x, !t) (c : cs) = case c of
        '(' -> go (l + 1, r, x, t + 1) cs
        ')' -> go (l, r + 1, x, t + 1) cs
        '?' -> go (l, r, x + 1, t + 1) cs

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go _ _ r "" ms
      | 2 * r == length ms = ""
      | otherwise = ms
    go !i !l !r s@(c : cs) ms
      | 2 * (max l r) == length ms = ""
      | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    str' = '(' : (init $ tail str) ++ ")"

p str = (lines str) !! 451

main = do
    s <- getLine
    let n = read s :: Int
    if n < 500 then interact solveAll else interact p
    --interact solveAll

--s = take 3000000 $ cycle "?()"

{-# LANGUAGE BangPatterns #-}

nLRXT :: String -> (Int, Int, Int, Int)
nLRXT str = go (0, 0, 0, 0) str
  where
    go t "" = t
    go (!l, !r, !x, !t) (c : cs) = case c of
        '(' -> go (l + 1, r, x, t + 1) cs
        ')' -> go (l, r + 1, x, t + 1) cs
        '?' -> go (l, r, x + 1, t + 1) cs

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go _ _ r "" ms
      | 2 * r == length ms = ""
      | otherwise = ms
    go !i !l !r s@(c : cs) ms
      | 2 * (max l r) == length ms = ""
      | i > 0 && i == 2 * r = go 0 0 0 ('(' : cs) ('(' : cs)
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    str' = '(' : (init $ tail str) ++ ")"

main = do
    getLine
    interact solveAll

--s = take 3000000 $ cycle "?()"

{-# LANGUAGE BangPatterns #-}

nLRXT :: String -> (Int, Int, Int, Int)
nLRXT str = go (0, 0, 0, 0) str
  where
    go t "" = t
    go (!l, !r, !x, !t) (c : cs) = case c of
        '(' -> go (l + 1, r, x, t + 1) cs
        ')' -> go (l, r + 1, x, t + 1) cs
        '?' -> go (l, r, x + 1, t + 1) cs

maxFI :: String -> String
maxFI str = go 0 0 0 str str
  where
    go _ _ r "" ms
      | 2 * r == length ms = ""
      | otherwise = ms
    go !i !l !r s@(c : cs) ms
      | 2 * (max l r) == length ms = ""
      | i + 1 == 2 * r = go 0 0 0 s s
      | otherwise = case c of
          '(' -> go (i + 1) (l + 1) r cs ms
          ')' -> go (i + 1) l (r + 1) cs ms
          _   -> go (i + 1) l r cs ms

solveAll :: String -> String
solveAll = unlines . (map solve) . lines

solve :: String -> String
solve "" = "YES"
solve str = if b then "YES" else "NO"
  where
    --(tL, tR, tX, tT) = nLXRT str
    b = maxFI str' == ""
    str' = '(' : (init $ tail str) ++ ")"

main = do
    getLine
    interact solveAll

--s = take 3000000 $ cycle "?()"


import Control.Monad (forM_)

main = do
  t <- read <$> getLine
  forM_ [1 .. t] $ \_ -> do
    [x, n] <- map read . words <$> getLine
    let n' = case n `mod` 4 of
          0 -> 0
          1 -> n
          2 -> -1
          _ -> - n - 1
    let x' = if even x then x - n' else x + n'
    print x'

import Data.Char
import qualified Data.Map as M
import System.IO

split :: Eq a => a -> [a] -> [[a]]
split d l = takeWhile (/= d) l : [dropWhile (/= d) l]

jump' :: Integer -> Integer -> Integer
jump' pos 0 = pos
jump' pos 1 = if even pos then pos -1 else pos + 1
jump' pos step
  | m2 == 0 =
    if even pos
      then
        if m4 == 0
          then pos
          else pos + 1
      else
        if m4 == 0
          then pos
          else pos - 1
  | even pos = if (step -1) `mod` 4 == 0 then pos - step else pos + step + 1
  | otherwise = if (step -1) `mod` 4 == 0 then pos + step else pos - step - 1
  where
    m2 = step `mod` 2
    m4 = step `mod` 4

jump :: String -> Integer
jump [] = 0
jump xs = jump' (read start) (read step)
  where
    start = head $ split ' ' xs
    step = last $ split ' ' xs

solve :: [String] -> [String]
solve [] = []
solve xs = map (show . jump) xs

main :: IO ()
main = do
  inputs <- getContents
  let lns = lines inputs
  putStr $ unlines $ solve $ tail lns

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

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

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

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

process 0 = return ()
process t = do
    [a,b] <- getIntList
    let c = mod b 4
    let tmp = if c==0 then 0 else if c==1 then b else if c==2 then -1 else -b-1
    let res = if odd a then tmp else -tmp
    print (a+res)
    process (t-1)

main = do
    t <- getInt
    process t

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

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

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

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

process 0 = return ()
process t = do
    x <- getIntList
    let a = head x
    let b = head $ tail x
    let c = mod b 4
    let tmp = if c==0 then 0 else if c==1 then b else if c==2 then -1 else -b-1
    let res = if odd a then tmp else -tmp
    print (a+res)
    process (t-1)

main = do
    t <- getInt
    process t

solve :: Int -> Int -> Int
solve start n
  | even start =
    if mod n 4 == 0 then start
    else if mod n 4 == 1 then start - 1 - 4 * div n 4
    else if mod n 4 == 2 then start + 1
    else if mod n 4 == 3 then start + 4 + 4 * div n 4 else 0
  | mod n 4 == 0 = start
  | mod n 4 == 1 = start + 1 + 4 * div n 4
  | mod n 4 == 2 = start - 1
  | mod n 4 == 3 = start - 4 - 4 * div n 4
  | otherwise = 0

run 0 = return 0
run count = do
    line <- getLine
    let start = read (head (words line))
    let n = read (words line!!1)
    print(solve start n)
    run (count-1)
main = do
    n <- getLine
    let n' = read n
    run n'

import Data.Foldable (for_)
next :: Int -> Int -> Int
next position jumpSize
  | even position = position - jumpSize
  | otherwise = position + jumpSize

solve :: Int -> Int -> Int
solve start jumps
  | m == 0 = start
  | otherwise = foldl next start [(jumps - m + 1)..jumps]
  where m = mod jumps 4

testCase :: IO ()
testCase = do
  line <- getLine;
  let [start, jumps] = map read (words line);
  print $ solve start jumps;

main = do
  line <- getLine
  let nTestCases = read line :: Integer
  for_ [1..nTestCases] (const testCase)

import Control.Monad (replicateM_)

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [x_0, n] <- map read . words <$> getLine
    let m = n - n `rem` 4
    print $ foldl next x_0 [m + 1 .. n]
  where
    next x i = if even x then x - i else x + i

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

solve :: IO ()
solve = do
    ~[x, n] <- readInt64s
    let (p, q) = n `divMod` 4
        ans = case q of
            0 -> 0
            1 -> -4 * p - 1
            2 -> 1
            _ -> 4 * (p + 1)
    print $ x + if even x then ans else -ans

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

readInt64s :: IO [Int64]
readInt64s = map (fromInteger . fst . fromJust . C.readInteger) . C.words <$> C.getLine

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

import Data.Char
import qualified Data.Map as M
import System.IO

split :: Eq a => a -> [a] -> [[a]]
split d l = takeWhile (/= d) l : [dropWhile (/= d) l]

jump' :: Integer -> Integer -> Integer
jump' pos 0 = pos
jump' pos 1 = if even pos then pos -1 else pos + 1
jump' pos step
  | m2 == 0 = if m4 == 0 then pos else pos + 1
  | even pos = if (step -1) `mod` 4 == 0 then pos - step else pos + step + 1
  | otherwise = if (step -1) `mod` 4 == 0 then pos + step else pos - step - 1
  where
    m2 = step `mod` 2
    m4 = step `mod` 4

jump :: String -> Integer
jump [] = 0
jump xs = jump' (read start) (read step)
  where
    start = head $ split ' ' xs
    step = last $ split ' ' xs

solve :: [String] -> [String]
solve [] = []
solve xs = map (show . jump) xs

main :: IO ()
main = do
  inputs <- getContents
  let lns = lines inputs
  putStr $ unlines $ solve $ tail lns


import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import Control.Applicative ((<$>), liftA)
import Control.Monad (sequence, replicateM)
import Data.Map.Strict (Map, lookupLE, lookupGE)
import qualified Data.Map.Strict as M
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8

type Roll = Map Int Int -> Map Int Int -> [Int]

solve :: Int -> [(Int, Int, Char)] -> [Int]
solve n a = foldr loop (\_ _ -> []) a zero zero
    where
    zero = M.fromList [(0, n + 1), (n + 1, 0)] :: Map Int Int

    loop :: (Int, Int, Char) -> Roll -> Roll
    loop (c, r, 'U') f row col = x:f row col'
        where (x, col') = inner r c row col

    loop (c, r, 'L') f row col = x:f row' col
        where (x, row') = inner c r col row

    inner :: Int -> Int -> Map Int Int -> Map Int Int -> (Int, Map Int Int)
    inner r c row col
        | jkey == c = (0, col)
        | otherwise = (out, col')
        where
        (ikey, ival) = fromJust $ lookupLE r row :: (Int, Int)
        (jkey, jval) = fromJust $ lookupGE c col :: (Int, Int)
        out = if n + 1 < jkey + ival + ikey then r - ikey else jkey + jval - c
        col' = M.insert c out col :: Map Int Int

parse :: ByteString -> (Int, Int, Char)
parse line = (readInt c, readInt r, C8.head d)
    where
    [c, r, d] = C8.words line :: [ByteString]
    readInt :: ByteString -> Int
    readInt = fst . fromJust . C8.readInt

main = fromJust . sequence . fmap (liftA fst . C8.readInt) .C8.words <$>
    B.getLine >>= \[n, q] -> replicateM q B.getLine >>= \a ->
    mapM_ print . solve n $ parse <$> a

import Data.Maybe (fromJust)
import Control.Applicative ((<$>), liftA)
import Control.Monad (sequence, replicateM)
import Data.ByteString (ByteString)
import Data.Map (Map, lookupLE, lookupGE)
import qualified Data.Map as M
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8

type Roll = Map Int Int -> Map Int Int -> [Int]

solve :: Int -> [(Int, Int, Char)] -> [Int]
solve n a = foldr loop (\_ _ -> []) a zero zero
    where
    zero = M.fromList [(0, n + 1), (n + 1, 0)] :: Map Int Int

    loop :: (Int, Int, Char) -> Roll -> Roll
    loop (c, r, 'U') f row col = x:f row col'
        where (x, col') = inner r c row col

    loop (c, r, 'L') f row col = x:f row' col
        where (x, row') = inner c r col row

    inner :: Int -> Int -> Map Int Int -> Map Int Int -> (Int, Map Int Int)
    inner r c row col
        | jkey == c = (0, col)
        | otherwise = (out, col')
        where
        (ikey, ival) = fromJust $ lookupLE r row :: (Int, Int)
        (jkey, jval) = fromJust $ lookupGE c col :: (Int, Int)
        out = if n + 1 < jkey + ival + ikey then r - ikey else jkey + jval - c
        col' = M.insert c out col :: Map Int Int

parse :: ByteString -> (Int, Int, Char)
parse line = (readInt c, readInt r, C8.head d)
    where
    [c, r, d] = C8.words line :: [ByteString]
    readInt :: ByteString -> Int
    readInt = fst . fromJust . C8.readInt

main = sequence . fmap (liftA fst . C8.readInt) .C8.words <$> B.getLine >>=
    \(Just [n, q]) -> replicateM q B.getLine >>=
    \a -> mapM_ print . solve n $ parse <$> a


import Data.Bits
-- import Debug.Trace
import qualified Data.Map as M
import qualified Data.Int as I
main = do
    line <- getLine
    let nk = words line
    let ans = solve (read (nk!!0)::I.Int64) (read (nk!!1)::Int)
    putStrLn (if (fst ans) then "Yes\n" ++ (printList $ snd ans) else "No")

printList :: (Show a) => [a] -> String
printList (x:[]) = show x
printList (x:xs) = (show x) ++ " " ++ printList xs

solve :: I.Int64 -> Int -> (Bool, [Int])
solve 0 _ = (False, [])
solve n k
    | popCount n > k = (False, [])
    | otherwise = (True, toList (let dbg = expand 0 k (genList 0 n) in dbg) (0,0))

genList :: Int -> I.Int64 -> (M.Map Int Int)
genList p n = case n of
    0 -> M.empty
    n -> case (n .&. 1::I.Int64) of
        0 -> genList (p+1) (shiftR n 1)
        1 -> M.insert p 1 $ genList (p+1) (shiftR n 1)

expand :: Int -> Int -> M.Map Int Int -> M.Map Int Int
expand 0 k m = expand (M.size m) k m
expand s k m
    | k == s = m
    | otherwise = let num = M.findMax m in
                    if (s + snd num) <= k then
                        if M.member ((fst num)-1) m
                        then expand (s+(snd num)) k $ M.adjust (+2*(snd num)) ((fst num)-1) (M.deleteMax m)
                        else expand (s+(snd num)) k $ M.insert ((fst num)-1) (2*(snd num)) (M.deleteMax m)
                    else let num2 = M.findMin m in
                        if M.member ((fst num2)-1) m
                        then expand (s+1) k $ M.adjust (+ 2) ((fst num2)-1) $ M.adjust (\x->x-1) (fst num2) m
                        else expand (s+1) k $ M.insert ((fst num2)-1) 2 $ M.adjust (\x->x-1) (fst num2) m

toList :: M.Map Int Int -> (Int, Int) -> [Int]
toList m (_, 0) = if M.size m == 0 then [] else toList (M.deleteMax m) (M.findMax m)
toList m (k, x) = k:toList m (k, x-1)

import Data.Bits
import Data.Maybe
-- import Debug.Trace
import qualified Data.Map as M
import qualified Data.Int as I
main = do
    line <- getLine
    let nk = words line
    let ans = solve (read (nk!!0)::I.Int64) (read (nk!!1)::Int)
    putStrLn (if (fst ans) then "Yes\n" ++ (printList $ snd ans) else "No")

printList :: (Show a) => [a] -> String
printList (x:[]) = show x
printList (x:xs) = (show x) ++ " " ++ printList xs

solve :: I.Int64 -> Int -> (Bool, [Int])
solve 0 _ = (False, [])
solve n k = if (popCount n) > k then (False, [])
            else (True, toList (expand 0 k (genList 0 n) ) (0,0))

genList :: Int -> I.Int64 -> (M.Map Int Int)
genList _ 0 = M.empty
genList p n = if (n .&. 1::I.Int64)==0 then genList (p+1) (shiftR n 1) else M.insert p 1 $ genList (p+1) (shiftR n 1)

expand :: Int -> Int -> M.Map Int Int -> M.Map Int Int
expand 0 k m = expand (M.size m) k m
expand s k m = if k == s then m
                else let num = M.findMax m
                         newVal n x = if isNothing x then Just (2*n) else fmap (+2*n) x in
                    if (s + snd num) <= k then
                        expand (s+(snd num)) k $ M.alter (newVal (snd num)) ((fst num)-1) (M.deleteMax m)
                    else let num2 = M.findMin m in
                        expand (s+1) k $ M.alter (newVal 1) ((fst num2)-1) $ M.adjust (\x->x-1) (fst num2) m

toList :: M.Map Int Int -> (Int, Int) -> [Int]
toList m (_, 0) = if M.size m == 0 then [] else toList (M.deleteMax m) (M.findMax m)
toList m (k, x) = k:toList m (k, x-1)

import Data.Bits
-- import Debug.Trace
import qualified Data.Map as M
import qualified Data.Int as I
main = do
    line <- getLine
    let nk = words line
    let ans = solve (read (nk!!0)::I.Int64) (read (nk!!1)::Int)
    putStrLn (if (fst ans) then "Yes\n" ++ (printList $ snd ans) else "No")

printList :: (Show a) => [a] -> String
printList (x:[]) = show x
printList (x:xs) = (show x) ++ " " ++ printList xs

solve :: I.Int64 -> Int -> (Bool, [Int])
solve 0 _ = (False, [])
solve n k
    | popCount n > k = (False, [])
    | otherwise = (True, toList (let dbg = expand 0 k (genList 0 n) in dbg) (0,0))

genList :: Int -> I.Int64 -> (M.Map Int Int)
genList p n = case n of
    0 -> M.empty
    n -> case (n .&. 1::I.Int64) of
        0 -> genList (p+1) (shiftR n 1)
        1 -> M.insert p 1 $ genList (p+1) (shiftR n 1)

expand :: Int -> Int -> M.Map Int Int -> M.Map Int Int
expand 0 k m = expand (M.size m) k m
expand s k m
    | k == s = m
    | otherwise = let num = M.findMax m in
                    if (s + snd num) <= k then
                        if M.member ((fst num)-1) m
                        then expand (s+(snd num)) k $ M.adjust (+2*(snd num)) ((fst num)-1) (M.deleteMax m)
                        else expand (s+(snd num)) k $ M.insert ((fst num)-1) (2*(snd num)) (M.deleteMax m)
                    else let num2 = M.findMin m in
                        if (s + snd num2) <= k then
                            if M.member ((fst num2)-1) m
                            then expand (s+(snd num2)) k $ M.adjust (+2*(snd num2)) ((fst num2)-1) (M.deleteMin m)
                            else expand (s+(snd num2)) k $ M.insert ((fst num2)-1) (2*(snd num2)) (M.deleteMin m)
                        else let dif = k-s in
                            if M.member ((fst num2)-1) m
                            then expand (s+dif) k $ M.adjust (+ 2*dif) ((fst num2)-1) $ M.adjust (\x->x-dif) (fst num2) m
                            else expand (s+dif) k $ M.insert ((fst num2)-1) (2*dif) $ M.adjust (\x->x-dif) (fst num2) m

toList :: M.Map Int Int -> (Int, Int) -> [Int]
toList m (_, 0) = if M.size m == 0 then [] else toList (M.deleteMax m) (M.findMax m)
toList m (k, x) = k:toList m (k, x-1)

import Data.Bits
-- import Debug.Trace
import qualified Data.Map as M
import qualified Data.Int as I
main = do
    line <- getLine
    let nk = words line
    let ans = solve (read (nk!!0)::I.Int64) (read (nk!!1)::Int)
    putStrLn (if (fst ans) then "Yes\n" ++ (printList $ snd ans) else "No")

printList :: (Show a) => [a] -> String
printList (x:[]) = show x
printList (x:xs) = (show x) ++ " " ++ printList xs

solve :: I.Int64 -> Int -> (Bool, [Int])
solve 0 _ = (False, [])
solve n k
    | popCount n > k = (False, [])
    | otherwise = (True, toList (let dbg = expand 0 k (genList 0 n) in dbg) (0,0))

genList :: Int -> I.Int64 -> (M.Map Int Int)
genList p n = case n of
    0 -> M.empty
    n -> case (n .&. 1::I.Int64) of
        0 -> genList (p+1) (shiftR n 1)
        1 -> M.insert p 1 $ genList (p+1) (shiftR n 1)

expand :: Int -> Int -> M.Map Int Int -> M.Map Int Int
expand 0 k m = expand (M.size m) k m
expand s k m
    | k == s = m
    | otherwise = let num = M.findMax m in
                    if (s + snd num) <= k then
                        if M.member ((fst num)-1) m
                        then expand (s+(snd num)) k $ M.adjust (+2*(snd num)) ((fst num)-1) (M.deleteMax m)
                        else expand (s+(snd num)) k $ M.insert ((fst num)-1) (2*(snd num)) (M.deleteMax m)
                    else let num2 = M.findMin m in
                        if (s + snd num2) <= k then
                            if M.member ((fst num)-1) m
                            then expand (s+(snd num2)) k $ M.adjust (+2*(snd num2)) ((fst num2)-1) (M.deleteMin m)
                            else expand (s+(snd num2)) k $ M.insert ((fst num2)-1) (2*(snd num2)) (M.deleteMin m)
                        else let dif = k-s in
                            if M.member ((fst num2)-1) m
                            then expand (s+dif) k $ M.adjust (+ 2*dif) ((fst num2)-1) $ M.adjust (\x->x-dif) (fst num2) m
                            else expand (s+dif) k $ M.insert ((fst num2)-1) (2*dif) $ M.adjust (\x->x-dif) (fst num2) m

toList :: M.Map Int Int -> (Int, Int) -> [Int]
toList m (_, 0) = if M.size m == 0 then [] else toList (M.deleteMax m) (M.findMax m)
toList m (k, x) = k:toList m (k, x-1)

import Data.Bits
-- import Debug.Trace
import qualified Data.Map as M
import qualified Data.Int as I
main = do
    line <- getLine
    let nk = words line
    let ans = solve (read (nk!!0)::I.Int64) (read (nk!!1)::Int)
    putStrLn (if (fst ans) then "Yes\n" ++ (printList $ snd ans) else "No")

printList :: (Show a) => [a] -> String
printList (x:[]) = show x
printList (x:xs) = (show x) ++ " " ++ printList xs

solve :: I.Int64 -> Int -> (Bool, [Int])
solve 0 _ = (False, [])
solve n k
    | popCount n > k = (False, [])
    | otherwise = (True, toList (expand 0 k (let dbg=genList 0 n in dbg)) (0,0))

genList :: Int -> I.Int64 -> (M.Map Int Int)
genList p n = case n of
    0 -> M.empty
    n -> case (n .&. 1::I.Int64) of
        0 -> genList (p+1) (shiftR n 1)
        1 -> M.insert p 1 $ genList (p+1) (shiftR n 1)

expand :: Int -> Int -> M.Map Int Int -> M.Map Int Int
expand 0 k m = expand (M.size m) k m
expand s k m
    | k == s = m
    | otherwise = let num = M.findMax m in
                    if (s + snd num) <= k then
                        if M.member ((fst num)-1) m
                        then expand (s+(snd num)) k $ M.adjust (+2*(snd num)) ((fst num)-1) (M.deleteMax m)
                        else expand (s+(snd num)) k $ M.insert ((fst num)-1) (2*(snd num)) (M.deleteMax m)
                    else let dif = k-s in
                        if M.member ((fst num)-1) m
                        then expand (s+dif) k $ M.adjust (+ 2*dif) ((fst num)-1) $ M.adjust (\x->x-dif) (fst num) m
                        else expand (s+dif) k $ M.insert ((fst num)-1) (2*dif) $ M.adjust (\x->x-dif) (fst num) m

toList :: M.Map Int Int -> (Int, Int) -> [Int]
toList m (_, 0) = if M.size m == 0 then [] else toList (M.deleteMax m) (M.findMax m)
toList m (k, x) = k:toList m (k, x-1)


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

import GHC.TypeLits

newtype ModVal a (n :: Nat)= ModVal { unMod :: a} deriving (Show, Eq)

modBase :: KnownNat n => ModVal a n -> Integer
{-# INLINE modBase #-}
modBase v = natVal v

instance (Integral a, KnownNat n) => Num (ModVal a n) where
  ma@(ModVal a) + (ModVal b) =
    let
      m = fromIntegral $ modBase ma
      c = a + b
    in ModVal $ if c >= m then c - m else c
  ma@(ModVal a) - (ModVal b) =
    let
      m = fromIntegral $ modBase ma
      c = a - b
    in ModVal $ if c < 0 then c + m else c
  ma@(ModVal a) * (ModVal b) =
    let m = fromIntegral $ modBase ma in ModVal$ (a * b) `mod` m
  negate ma@(ModVal a) = let m = fromIntegral $ modBase ma in ModVal (m - a)
  abs = id
  signum _ = ModVal 1
  fromInteger x = toMod (ModVal 0) $ fromIntegral x
    where
      toMod :: (Integral a, KnownNat n) => ModVal a n -> a -> ModVal a n
      toMod m x = ModVal $ mod x $ fromIntegral $ modBase m
  {-# INLINE (+) #-}
  {-# INLINE (-) #-}
  {-# INLINE (*) #-}
  {-# INLINE abs #-}
  {-# INLINE signum #-}
  {-# INLINE fromInteger #-}

type MI = ModVal Int 998244353

pmod = 998244353
tableSize :: Int
tableSize = 10^5
fac :: Array Int MI
fac = listArray (0, tableSize) $ scanl' (*) (fromIntegral 1) $ map fromIntegral $ [1..tableSize]
invMod = (^(pmod-2))

data CountChess = CC !Int !Int deriving (Show, Eq, Ord)

countChess s c@(CC x y) = case s of
  [] -> c
  ('1':'1':xs) -> countChess xs $ CC x (y + 1)
  (k:xs) -> countChess xs $ CC (if k == '0' then x + 1 else x)  y

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    n <- getInts 1
    ~[s] <- getNext 1
    let (CC n m) = countChess (P.unpack s) (CC 0 0)
    pure $! putInts . (:[]) $! unMod $ (fac!(n+m)) * (invMod $ fac!m) * (invMod $ fac!(n))

type SP = State [P.ByteString]

readInt :: P.ByteString -> Int
readInt = fst . fromJust . P.readInt

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

getInts :: Int -> SP [Int]
getInts k = map readInt <$> getNext k

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

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

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

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

import Data.Int

data ZPos = ZPos !Int ![Int]

step :: ZPos -> Char -> ZPos
step (ZPos ix li) '0' = ZPos (ix + 1) (ix : li)
step (ZPos ix li) '1' = ZPos (ix + 1) li
step _ _ = error "invalid input"

compress :: Int -> Int -> Int
compress x y = if  even (fromIntegral y - x)
  then  x + 2
  else  x + 1

p :: Int
p = 998244353

p64 :: Int64
p64 = fromIntegral p

newtype ModP = ModP Int

instance Num ModP where
  (ModP x) * (ModP y) = ModP $ fromIntegral
    $ rem (fromIntegral x * fromIntegral y) p64

inv :: ModP -> ModP
inv = (^ (p-2))

choose :: Int -> Int -> ModP
choose n k = let
  cstep w x = w * ModP (n + 1 - x) * inv (ModP x)
  in  foldl' cstep (ModP 1) [1..k]

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n] <- readInts
    s <- readLine
    let
      ZPos _n zpos = P.foldl' step (ZPos 1 []) s
      nzeros = length zpos
      cstop = foldl' compress 0 $ reverse zpos
      wiggle = div (n - cstop) 2
      ModP ans = choose (nzeros + wiggle) wiggle
    putInts [ans]

type SIO = StateT P.ByteString IO

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

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

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

{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict              #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE BangPatterns #-}

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             guard, join, replicateM,
                                             replicateM_)
import qualified Control.Monad.ST.Strict    as ST
import qualified Control.Monad.State.Strict as S
import qualified Data.Array                 as A
import qualified Data.Array.IO.Safe         as IOA
import qualified Data.Array.MArray.Safe     as MA
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.Function              (on)
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             intersect, isPrefixOf, nub, sort,
                                             sortOn, foldl')
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM, for)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             hFlush, openFile, stdin, stdout)
import           Text.Printf                (printf)

import           Debug.Trace                (trace, traceM, traceShowM)
import           GHC.IO.Handle              (hDuplicateTo)

debug :: c -> String -> c
debug = flip trace
traced x = trace (show x) x
withTrace s x = trace (s ++ " -> " ++ show x) x

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

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

powerMd :: Int64 -> Int64 -> Int64 -> Int64
powerMd md _ 0 = 1 `mod` md
powerMd md a 1 = a `mod` md
powerMd md a k
    | even k =
        let
            half :: Int64
            !half = powerMd md a (k `div` 2)

            sqrMd :: Int64 -> Int64 -> Int64
            sqrMd md x = (x ^ 2) `mod` md
        in
            sqrMd md half
    | odd k =
        let
            rest :: Int64
            !rest = powerMd md a (k - 1)
        in
            (a * rest) `mod` md

factorialMd :: Int64 -> Int64 -> Int64
factorialMd md 0 = 1 `mod` md
factorialMd md n = (`mod` md) . foldl' (\a b -> (a * b) `mod` md) 1 $ [1 .. n]

calcCombinationsMd :: Int64 -> Int64 -> Int64 -> Int64
calcCombinationsMd md n k =
        (nFactorial * denominatorMdInv) `mod` md
    where
        nFactorial :: Int64
        nFactorial = factorialMd md n

        kFactorial :: Int64
        kFactorial = factorialMd md k

        n_kFactorial :: Int64
        n_kFactorial = factorialMd md (n - k)

        denominatorMdInv :: Int64
        denominatorMdInv = powerMd md ((kFactorial * n_kFactorial) `mod` md) (md - 2)

solve :: Int -> String -> Int64
solve n s =
        calcCombinationsMd md (zeroGroupsCnt + oneGroupsCnt) zeroGroupsCnt
    where
        md :: Int64
        md = 998_244_353

        oneGroupsCnt :: Int64
        oneGroupsCnt = fromIntegral . length . filter (== "11") $ sGroups

        zeroGroupsCnt :: Int64
        zeroGroupsCnt = fromIntegral . length . filter (== "0") $ sGroups

        sGroups :: [String]
        sGroups = calcGroups s

        calcGroups :: String -> [String]
        calcGroups ('1':'1':rest) = "11" : calcGroups rest
        calcGroups (x:rest) = [x] : calcGroups rest
        calcGroups [] = []

main :: IO ()
main = do
    tests <- B8.getLine <&> readIntB8
    replicateM_ tests $ do
        n <- B8.getLine <&> readIntB8
        s <- B8.getLine <&> B8.unpack . head . B8.words

        let answer = solve n s

        printf "%lld\n" answer