import Data.List

groupOn :: Int -> [a] -> [[a]]
groupOn _ [] = []
groupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds
-------------------------------------------------------------------------------

main = interact $ unlines . parse . lines

parse [_, perm'] = sol perm
  where
    perm = fn $ words perm'
    fn :: [String] -> [Int]
    fn xs = map read xs

sol :: [Int] -> [String]
sol perm = [ show $ select list ]
  where
    list' = recc 0 0 perm
    list = 1 : list' ++ list'
    select xs = head $ maximumBy cmplen $ group $ sortBy (flip compare) xs
    cmplen x y = compare (length x) (length y)

recc _ _ [] = []
recc nd st (x:xs)
  | st < x    = recc st x xs
  | nd < x    = st : x : recc x st xs
  | otherwise = x : recc nd st xs

list = [4,4,3,3,1,0,3,4]

#!/usr/bin/env stack
{- stack
  --resolver lts-2.22
  script
  --optimize
  --package aeson
  --package array
  --package base
  --package bytestring
  --package containers
  --package hashmap
  --package hashtables
  --package lens
  --package logict
  --package mtl
  --package mwc-random
  --package parsec
  --package pipes
  --package time
  --package vector
-}
{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}
module Main
( main
) where

import           Prelude hiding (interact, lines, unlines, words, unwords,
                                 sequence, foldr)
import           Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,
                                        unlines, unwords, interact, readInt,
                                        readInteger)
import qualified Data.ByteString.Char8 as BS
import           Data.List (foldl', sort, sortBy, group, groupBy, inits, tails,
                            unfoldr)
import qualified Data.List as L
import qualified Data.IntSet as IS
import           Data.IntSet (IntSet)
import qualified Data.IntMap.Strict as IM
import           Data.IntMap.Strict (IntMap)
import qualified Data.Map.Strict as M
import           Data.Map.Strict (Map)
import qualified Data.Set as S
import           Data.Set (Set)
import qualified Data.Array.IArray as A
import           Data.Array.IArray ((!), Array, listArray, array)
import           Data.Array.Unboxed (UArray)
import           Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,
                             catMaybes)
import           Data.Either (either)
import           Control.Applicative (Applicative, pure,
                                      (<$>), (<*>), (<|>), liftA2, liftA3)
import           Control.Monad (unless, when, void, filterM, ap, forM_)
import           Control.Arrow ((***), (&&&), first, second)
import           Data.Traversable (sequence, sequenceA, traverse,
                                   Traversable)
import           Data.Ord (comparing, Down(..))
import           Data.Function (on)
import           Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,
                            bit, shiftR, shiftL, Bits)
import qualified Data.Bits as B
import           Data.Word (Word32)
import           Control.Monad.State (State, get, put, gets, modify,
                                      evalState, execState, runState)
import           Text.Parsec (char, space, parse, Parsec)
import qualified Text.Parsec as P
import           Data.Tuple (swap)
import           Data.Foldable (Foldable, foldr)
import           Data.Monoid ((<>), Monoid, mappend, mempty)
import           Data.Time.Clock
import           System.IO (stderr)

type N = Int
toNum = toInt

fromDown :: Down a -> a
fromDown (Down a) = a

-- answer :: [(Int, Int)] -> Int
answer xs = incs' $$ IM.toList .- L.maximumBy (comparing snd <> comparing (fst .- Down))
         .- fst
  where
    seens = scanl' (flip S.insert) S.empty xs
    greaters = zipWith S.split xs seens $$ map snd .- map toTwos
    isRec = greaters $$ map null
    zs = zip xs isRec
    incs = greaters $$ concatMap toOnes .- sort .- group .- map (head &&& length)
                    .- IM.fromList
    incs' = foldl' doOne incs zs
    toTwos = S.toList .- take 2
    toOnes [_, _] = []
    toOnes ys = ys
    doOne m (x, rec'')  = let rec' = toChange rec''
                              alt Nothing = Just $ rec'
                              alt (Just v) = Just $ v + rec'
                           in IM.alter alt x m
    toChange True = -1
    toChange _ = 0

handleInput :: ByteString -> ByteString
handleInput = words .- drop 1 .- map toNum
            .- answer
            .- show .- pack
            -- .- map (show .- pack) .- unlines

toInt = readInt .- fromJust .- fst
toInte = readInteger .- fromJust .- fst
toX :: Read a => ByteString -> a
toX = unpack .- read

coerceInput f (a:b:xs) = f a b xs
coerceInput _ _ = error "invalid input"

main :: IO ()
main = do
  st <- getCurrentTime
  st `seq` interact handleInput
  ed <- getCurrentTime
  BS.hPutStrLn stderr $ pack ""
  BS.hPutStrLn stderr . pack $ show (ed `diffUTCTime` st)

-- Util stuff --
(.-) :: (a -> b) -> (b -> c) -> a -> c
(.-) = flip (.)
infixl 9 .-

($$) :: a -> (a -> b) -> b
($$) = flip ($)
infixl 0 $$

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral

scanl' :: (b -> a -> b) -> b -> [a] -> [b]
scanl' f !z [] = [z]
scanl' f !z (x:xs) = z : scanl' f (f z x) xs

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

main = B.interact exec
exec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words
solve xs = case maximum $ map (liftM2 (,) (subtract 1 . sum . map (\(m, m2, x) -> fromEnum $ x /= m && x > m2)) ((\(m, _, _) -> -m) . head)) $ groupBy (\(m, _, _) (m', _, _) -> m == m') $ zip3 pmaxs (0:pmax2s) xs of
  (d, _) | d <= 0 -> maybe (minimum xs) id $ minimumMay $ map fst $ filter (uncurry (/=)) $ zip xs pmaxs
  (_, x) -> -x
  where
  pmaxs = scanl1 max xs
  pmax2s = snd $ mapAccumL (\p (pm, cm, x) -> if cm /= pm then (pm, pm) else if p < x && x < cm then (x, x) else (p, p)) 0 $ zip3 (0:pmaxs) pmaxs xs

minimumMay [] = Nothing
minimumMay xs = Just $ minimum xs

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

main = B.interact exec
exec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words
solve xs = fst $ maximumBy (comparing snd) $ map (liftM2 (,) ((\(m, _, _) -> m) . head) (sum . map (\(_, m2, x) -> fromEnum $ x > m2))) $ groupBy (\(m, _, _) (m', _, _) -> m == m') $ zip3 pmaxs (0:pmax2s) xs
  where
  pmaxs = scanl1 max xs
  pmax2s = snd $ mapAccumL (\p (pm, cm, x) -> if cm /= pm then (pm, pm) else if p < x && x < cm then (x, x) else (p, p)) 0 $ zip3 (0:pmaxs) pmaxs xs

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

main = B.interact exec
exec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words
solve xs = case maximum $ map (liftM2 (,) (subtract 1 . sum . map (\(m, m2, x) -> fromEnum $ x /= m && x > m2)) ((\(m, _, _) -> -m) . head)) $ groupBy (\(m, _, _) (m', _, _) -> m == m') $ zip3 pmaxs (0:pmax2s) xs of
  (d, _) | d <= 0 -> minimum xs
  (_, x) -> -x
  where
  pmaxs = scanl1 max xs
  pmax2s = snd $ mapAccumL (\p (pm, cm, x) -> if cm /= pm then (pm, pm) else if p < x && x < cm then (x, x) else (p, p)) 0 $ zip3 (0:pmaxs) pmaxs xs

minimumMay [] = Nothing
minimumMay xs = Just $ minimum xs

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

main = B.interact exec
exec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words
solve xs = case maximum $ map (liftM2 (,) (subtract 1 . sum . map (\(m, m2, x) -> fromEnum $ x /= m && x > m2)) ((\(m, _, _) -> -m) . head)) $ groupBy (\(m, _, _) (m', _, _) -> m == m') $ zip3 pmaxs (0:pmax2s) xs of
  (d, x) | d <= 0 -> maybe (-x) id $ minimumMay $ filter (/= (-x)) xs
  (_, x) -> -x
  where
  pmaxs = scanl1 max xs
  pmax2s = snd $ mapAccumL (\p (pm, cm, x) -> if cm /= pm then (pm, pm) else if p < x && x < cm then (x, x) else (p, p)) 0 $ zip3 (0:pmaxs) pmaxs xs

minimumMay [] = Nothing
minimumMay xs = Just $ minimum xs

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

main = B.interact exec
exec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . tail . B.words
solve xs = case maximum $ map (liftM2 (,) (subtract 1 . sum . map (\(m, m2, x) -> fromEnum $ x /= m && x > m2)) ((\(m, _, _) -> -m) . head)) $ groupBy (\(m, _, _) (m', _, _) -> m == m') $ zip3 pmaxs (0:pmax2s) xs of
  (0, x) -> minimum $ map fst $ filter (\(x', m) -> x' /= m && x' < -x) $ zip xs pmaxs
  (_, x) -> -x
  where
  pmaxs = scanl1 max xs
  pmax2s = snd $ mapAccumL (\p (pm, cm, x) -> if cm /= pm then (pm, pm) else if p < x && x < cm then (x, x) else (p, p)) 0 $ zip3 (0:pmaxs) pmaxs xs

#!/usr/bin/env stack
{- stack
  --resolver lts-2.22
  script
  --optimize
  --package aeson
  --package array
  --package base
  --package bytestring
  --package containers
  --package hashmap
  --package hashtables
  --package lens
  --package logict
  --package mtl
  --package mwc-random
  --package parsec
  --package pipes
  --package time
  --package vector
-}
{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}
module Main
( main
) where

import           Prelude hiding (interact, lines, unlines, words, unwords,
                                 sequence, foldr)
import           Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,
                                        unlines, unwords, interact, readInt,
                                        readInteger)
import qualified Data.ByteString.Char8 as BS
import           Data.List (foldl', sort, sortBy, group, groupBy, inits, tails,
                            unfoldr)
import qualified Data.List as L
import qualified Data.IntSet as IS
import           Data.IntSet (IntSet)
import qualified Data.IntMap.Strict as IM
import           Data.IntMap.Strict (IntMap)
import qualified Data.Map.Strict as M
import           Data.Map.Strict (Map)
import qualified Data.Set as S
import           Data.Set (Set)
import qualified Data.Array.IArray as A
import           Data.Array.IArray ((!), Array, listArray, array)
import           Data.Array.Unboxed (UArray)
import           Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,
                             catMaybes)
import           Data.Either (either)
import           Control.Applicative (Applicative, pure,
                                      (<$>), (<*>), (<|>), liftA2, liftA3)
import           Control.Monad (unless, when, void, filterM, ap, forM_)
import           Control.Arrow ((***), (&&&), first, second)
import           Data.Traversable (sequence, sequenceA, traverse,
                                   Traversable)
import           Data.Ord (comparing, Down(..))
import           Data.Function (on)
import           Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,
                            bit, shiftR, shiftL, Bits)
import qualified Data.Bits as B
import           Data.Word (Word32)
import           Control.Monad.State (State, get, put, gets, modify,
                                      evalState, execState, runState)
import           Text.Parsec (char, space, parse, Parsec)
import qualified Text.Parsec as P
import           Data.Tuple (swap)
import           Data.Foldable (Foldable, foldr)
import           Data.Monoid ((<>), Monoid, mappend, mempty)
import           Data.Time.Clock
import           System.IO (stderr)

type N = Int
toNum = toInt

fromDown :: Down a -> a
fromDown (Down a) = a

-- answer :: [(Int, Int)] -> Int
answer xs = greaters $$ sort .- group .- map (length &&& head)
         .- ((0, 1) :) .- L.maximumBy (comparing fst <> comparing (snd .- Down))
         .- snd
  where
    seens = scanl' (flip S.insert) S.empty xs
    greaters = zipWith S.split xs seens $$ map snd .- concatMap toOnes
    toOnes x
      | S.size x == 1 = S.toList x
      | otherwise = []

handleInput :: ByteString -> ByteString
handleInput = words .- drop 1 .- map toNum
            .- answer
            .- show .- pack
            -- .- map (show .- pack) .- unlines

toInt = readInt .- fromJust .- fst
toInte = readInteger .- fromJust .- fst
toX :: Read a => ByteString -> a
toX = unpack .- read

coerceInput f (a:b:xs) = f a b xs
coerceInput _ _ = error "invalid input"

main :: IO ()
main = do
  st <- getCurrentTime
  st `seq` interact handleInput
  ed <- getCurrentTime
  BS.hPutStrLn stderr $ pack ""
  BS.hPutStrLn stderr . pack $ show (ed `diffUTCTime` st)

-- Util stuff --
(.-) :: (a -> b) -> (b -> c) -> a -> c
(.-) = flip (.)
infixl 9 .-

($$) :: a -> (a -> b) -> b
($$) = flip ($)
infixl 0 $$

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral

scanl' :: (b -> a -> b) -> b -> [a] -> [b]
scanl' f !z [] = [z]
scanl' f !z (x:xs) = z : scanl' f (f z x) xs

#!/usr/bin/env stack
{- stack
  --resolver lts-2.22
  script
  --optimize
  --package aeson
  --package array
  --package base
  --package bytestring
  --package containers
  --package hashmap
  --package hashtables
  --package lens
  --package logict
  --package mtl
  --package mwc-random
  --package parsec
  --package pipes
  --package time
  --package vector
-}
{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}
module Main
( main
) where

import           Prelude hiding (interact, lines, unlines, words, unwords,
                                 sequence, foldr)
import           Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,
                                        unlines, unwords, interact, readInt,
                                        readInteger)
import qualified Data.ByteString.Char8 as BS
import           Data.List (foldl', sort, sortBy, group, groupBy, inits, tails,
                            unfoldr)
import qualified Data.List as L
import qualified Data.IntSet as IS
import           Data.IntSet (IntSet)
import qualified Data.IntMap.Strict as IM
import           Data.IntMap.Strict (IntMap)
import qualified Data.Map.Strict as M
import           Data.Map.Strict (Map)
import qualified Data.Set as S
import           Data.Set (Set)
import qualified Data.Array.IArray as A
import           Data.Array.IArray ((!), Array, listArray, array)
import           Data.Array.Unboxed (UArray)
import           Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,
                             catMaybes)
import           Data.Either (either)
import           Control.Applicative (Applicative, pure,
                                      (<$>), (<*>), (<|>), liftA2, liftA3)
import           Control.Monad (unless, when, void, filterM, ap, forM_)
import           Control.Arrow ((***), (&&&), first, second)
import           Data.Traversable (sequence, sequenceA, traverse,
                                   Traversable)
import           Data.Ord (comparing, Down(..))
import           Data.Function (on)
import           Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,
                            bit, shiftR, shiftL, Bits)
import qualified Data.Bits as B
import           Data.Word (Word32)
import           Control.Monad.State (State, get, put, gets, modify,
                                      evalState, execState, runState)
import           Text.Parsec (char, space, parse, Parsec)
import qualified Text.Parsec as P
import           Data.Tuple (swap)
import           Data.Foldable (Foldable, foldr)
import           Data.Monoid ((<>), Monoid, mappend, mempty)
import           Data.Time.Clock
import           System.IO (stderr)

type N = Int
toNum = toInt

fromDown :: Down a -> a
fromDown (Down a) = a

-- answer :: [(Int, Int)] -> Int
answer xs = incs' $$ IM.toList .- L.maximumBy (comparing snd <> comparing (fst .- Down))
         .- fst
  where
    seens = scanl' (flip S.insert) S.empty xs
    greaters = zipWith S.split xs seens $$ map snd .- map toTwos
    isRec = greaters $$ map null
    zs = zip xs isRec
    incs = greaters $$ concatMap toOnes .- sort .- group .- map (head &&& length)
                    .- IM.fromList
    incs' = foldl' doOne incs zs
    toTwos x
      | S.size x <= 2 = S.toList x
      | otherwise = []
    toOnes [_, _] = []
    toOnes ys = ys
    doOne m (x, rec'')  = let rec' = toChange rec''
                              alt Nothing = Just $ rec'
                              alt (Just v) = Just $ v + rec'
                           in IM.alter alt x m
    toChange True = -1
    toChange _ = 0

handleInput :: ByteString -> ByteString
handleInput = words .- drop 1 .- map toNum
            .- answer
            .- show .- pack
            -- .- map (show .- pack) .- unlines

toInt = readInt .- fromJust .- fst
toInte = readInteger .- fromJust .- fst
toX :: Read a => ByteString -> a
toX = unpack .- read

coerceInput f (a:b:xs) = f a b xs
coerceInput _ _ = error "invalid input"

main :: IO ()
main = do
  st <- getCurrentTime
  st `seq` interact handleInput
  ed <- getCurrentTime
  BS.hPutStrLn stderr $ pack ""
  BS.hPutStrLn stderr . pack $ show (ed `diffUTCTime` st)

-- Util stuff --
(.-) :: (a -> b) -> (b -> c) -> a -> c
(.-) = flip (.)
infixl 9 .-

($$) :: a -> (a -> b) -> b
($$) = flip ($)
infixl 0 $$

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral

scanl' :: (b -> a -> b) -> b -> [a] -> [b]
scanl' f !z [] = [z]
scanl' f !z (x:xs) = z : scanl' f (f z x) xs

import Data.List

groupOn :: Int -> [a] -> [[a]]
groupOn _ [] = []
groupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds
-------------------------------------------------------------------------------

main = interact $ unlines . parse . lines

parse [_, perm'] = sol perm
  where
    perm = fn $ words perm'
    fn :: [String] -> [Int]
    fn xs = map read xs

sol :: [Int] -> [String]
sol perm = [ show $ select list ]
  where
    list' = recc 0 0 perm
    list = 1 : list' ++ list'
    select xs = head $ maximumBy cmplen $ group $ sortBy (flip compare) xs
    cmplen x y = compare (length x) (length y)

recc _ _ [] = []
recc nd st (x:xs)
  | st < x    = recc st x xs
  | nd < x    = st : recc x st xs
  | otherwise = recc nd st xs

list = [4,4,3,3,1,0,3,4]

import Data.List

groupOn :: Int -> [a] -> [[a]]
groupOn _ [] = []
groupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds
-------------------------------------------------------------------------------

main = interact $ unlines . parse . lines

parse [_, perm'] = sol perm
  where
    perm = fn $ words perm'
    fn :: [String] -> [Int]
    fn xs = map read xs

sol :: [Int] -> [String]
sol perm = [ show $ select list ]
  where
    list' = recc 0 0 perm
    list = 1 : list' ++ list'
    select xs = head $ maximumBy cmplen $ group $ sortBy (flip compare) xs
    cmplen x y = compare (length x) (length y)

recc _ _ [] = []
recc nd st (x:xs)
  | st < x    = recc st x xs
  | nd < x    = st : x : recc x st xs
  | otherwise = recc nd st xs

list = [4,4,3,3,1,0,3,4]


import Control.Monad (replicateM_)

solve :: String -> String
solve (a:[]) = [a, a]
solve (a:b:xs) =
  if b >= a
    then [a, a]
    else iter [a] a (b:xs)
  where
    iter acc a [] = reverse acc ++ acc
    iter acc a (b:xs) =
      if b <= a
        then iter (b:acc) b xs
        else reverse acc ++ acc

main :: IO ()
main = do
  tc <- readInt <$> getLine
  replicateM_ tc gao
  where
    readInt s = read s :: Int
    gao = do
      n <- readInt <$> getLine
      s <- getLine
      putStrLn $ solve s

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

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

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    ~[s] <- getNext 1
    let
      sLi = P.unpack s
      s2 = toEnum 255 : sLi
      toUse = case  sLi  of
        x : y : zs | x <= y  -> [x]
        _ -> map fst $ takeWhile (uncurry (<=)) $ zip sLi s2
    pure $ string7 $ toUse ++ reverse toUse ++ "\n"

type SP = State [P.ByteString]

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

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

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

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

{-# LANGUAGE TypeApplications #-}

module Main where

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

removeElem :: Int -> [a] -> [a]
removeElem i xs = take i xs <> tail (drop i xs)

main = do
  n <- read @Int <$> getLine
  replicateM n $ do
    void getLine
    str <- getLine
    let go (x:xs) c = if x < c || (x == c && head str > x)
                      then x : go xs x
                      else []
        go [] c = []
    let res = go str maxBound
    putStrLn $ res ++ reverse res

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    _ <- getInts
    str <- filter (not . isSpace) . C.unpack <$> C.getLine
    let (g : gs) = group str
        result
          | length g >= 2 = [head g]
          | otherwise = concat $ either id id $ foldM acc [g] gs
          where acc ts xs
                  | head (head ts) > head xs = Right $ xs : ts
                  | otherwise = Left ts
    return $ string8 (reverse result ++ result) `mappend` charUtf8 '\n'
  hPutBuilder stdout output

import Control.Monad (replicateM_)

solve :: String -> String
solve s =
  iter [head s] (head s) (tail s)
  where
    iter acc curr "" = reverse acc ++ acc
    iter acc curr rem =
      let
        next_ = head rem
      in
        if curr > next_
          then iter (next_:acc) next_ (tail rem)
          else reverse acc ++ acc

main :: IO ()
main = do
  tc <- readInt <$> getLine
  replicateM_ tc gao
  where
    readInt s = read s :: Int
    gao = do
      n <- readInt <$> getLine
      s <- getLine
      putStrLn $ solve s

{-# LANGUAGE OverloadedStrings #-}
import Control.Monad (replicateM_)
import qualified Data.ByteString.Char8 as C

solve :: Int -> C.ByteString -> String
solve 1 s = [C.head s, C.head s]
solve _ s =
  iter [C.head s] (C.head s) (C.tail s)
  where
    iter acc curr "" = reverse acc ++ acc
    iter acc curr rem =
      let
        next_ = C.head rem
      in
        if curr > next_
          then iter (next_:acc) next_ (C.tail rem)
          else reverse acc ++ acc

main :: IO ()
main = do
  tc <- readInt <$> C.getLine
  replicateM_ tc gao
  where
    readInt s = let Just (i, _) = C.readInt s in i
    gao = do
      n <- readInt <$> C.getLine
      s <- C.getLine
      putStrLn $ solve n s

{-# LANGUAGE OverloadedStrings #-}
import Control.Monad (replicateM_)
import qualified Data.ByteString.Char8 as C

solve :: Int -> C.ByteString -> String
solve 1 s = [C.head s, C.head s]
solve _ s =
  iter [C.head s] (C.head s) (C.tail s)
  where
    iter acc curr "" = reverse acc ++ acc
    iter acc curr rem =
      let
        next = C.head rem
      in
        if curr > next
          then iter (next:acc) next (C.tail rem)
          else reverse acc ++ acc

main :: IO ()
main = do
  tc <- readInt <$> C.getLine
  replicateM_ tc gao
  where
    readInt s = let Just (i, _) = C.readInt s in i
    gao = do
      n <- readInt <$> C.getLine
      s <- C.getLine
      putStrLn $ solve n s

{-# LANGUAGE OverloadedStrings #-}
import Control.Monad (replicateM_)
import qualified Data.ByteString.Char8 as C

solve :: Int -> C.ByteString -> C.ByteString
solve 1 s = C.append s s
solve _ s =
  iter (C.singleton $ C.head s) (C.head s) (C.tail s)
  where
    iter acc curr "" = C.append (C.reverse acc) acc
    iter acc curr rem =
      let
        next = C.head rem
      in
        if curr > next
          then iter (C.cons next acc) next (C.tail rem)
          else C.append (C.reverse acc) acc

main :: IO ()
main = do
  tc <- readInt <$> C.getLine
  replicateM_ tc gao
  where
    readInt s = let Just (i, _) = C.readInt s in i
    gao = do
      n <- readInt <$> C.getLine
      s <- C.getLine
      C.putStrLn $ solve n s

{-# LANGUAGE OverloadedStrings #-}
import Control.Monad (replicateM_)
import qualified Data.ByteString.Char8 as C

solve :: Int -> C.ByteString -> C.ByteString
solve 1 s = s
solve _ s =
  iter (C.singleton $ C.head s) (C.head s) (C.tail s)
  where
    iter acc curr "" = C.append (C.reverse acc) acc
    iter acc curr rem =
      let
        next = C.head rem
      in
        if curr > next
          then iter (C.cons next acc) next (C.tail rem)
          else C.append (C.reverse acc) acc

main :: IO ()
main = do
  tc <- readInt <$> C.getLine
  replicateM_ tc gao
  where
    readInt s = let Just (i, _) = C.readInt s in i
    gao = do
      n <- readInt <$> C.getLine
      s <- C.getLine
      C.putStrLn $ solve n s

{-# LANGUAGE TypeApplications #-}

module Main where

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

removeElem :: Int -> [a] -> [a]
removeElem i xs = take i xs <> tail (drop i xs)

main = do
  n <- read @Int <$> getLine
  replicateM n $ do
    void getLine
    str <- getLine
    let go (x:xs) c = if x < c
                      then x : go xs x
                      else []
        go [] c = []
    let res = go str maxBound
    putStrLn $ res ++ reverse res


main = fmap (\x -> show (length (filter odd [1..x]) ^ 2 + (length (filter even [1..x]) ^ 2)) : f 1 x) readLn >>= mapM putStrLn
f a b = if a > b then [] else map (\x -> if even (a + x) then 'C' else '.') [1..b] : f (a + 1) b

{-# 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
    ls = [[if even i == even j then 'C' else '.' | j <- [1..n]] | i <- [1..n]]

  print $ length $ filter (== 'C') $ concat ls
  putStrLn $ unlines ls

main = fmap (\x -> show (div (x * x + 1) 2) : f 1 x) readLn >>= mapM putStrLn
f a b = if a > b then [] else map (\x -> if even (a + x) then 'C' else '.') [1..b] : f (a + 1) b

main = fmap f readLn >>= mapM putStrLn
f x = show (div (x * x + 1) 2) : g [g "C.", g ".C"]
  where g xs = take x $ concat $ repeat xs

main = readLn >>= mapM putStrLn . f
f x = show (div (x * x + 1) 2) : g [g "C.", g ".C"]
  where g xs = take x $ cycle xs

import Control.Monad (forM_)

main = do
  n <- fmap read getLine
  let total = case n `divMod` 2 of
                (q,0) -> n*q
                (q,1) -> (q+1) + q*n
  let row1 = take n $ cycle "C."
      row2 = take n $ cycle ".C"
      rows = take n $ cycle [row1,row2]
  print total
  forM_ rows $ putStrLn

import Data.List
import qualified Data.Map as Map

main = do
    n <- fmap (read) getLine :: IO Int
    let table = take n $ cycle [ take n $ cycle [1, 0], take n $ cycle [0, 1] ]
    print $ sum $ fmap sum table
    mapM_ (putStrLn . (fmap ((Map.fromList [(0, '.'), (1, 'C')]) Map.!))) table

module Main where

import Data.List
-- https://codeforces.com/problemset/problem/384/A
main :: IO ()
main = do
    n <- getLine >>= pure . (read :: String -> Int)
    let res = solve n
    putStrLn . show . length . filter (=='C') $ res
    putStrLn res
    pure ()

solve :: Int -> String
solve n =
    let n' = (n+1) `div` 2
        cs = f "." . intercalate "." . take n' $ (repeat "C")
        dot = f "C" . intercalate "C" . take n' $ (repeat ".")
    in intercalate "\n" . take n $ cycle [cs, dot]
    where
        f s = if even n then ( <> s )
                else ( <> mempty )

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

solve :: Int -> [String]
solve n = show ((n * n + 1) `div` 2) : take n (cycle [ take n $ cycle "C.", take n $ cycle ".C" ])

main = do
  n <- readLn
  print $ (n^2 + 1) `div` 2
  mapM_ putStrLn $ take n $ map (take n . flip drop (cycle "C.")) (cycle [0,1])

import Control.Applicative
import Data.List

main=do
	n<-    read   <$> getLine:: IO  Int
	let s1 = take n $ cycle ['C','.']
	let s2 = take n $ cycle ['.','C']
	print $ (+) (if odd n then 1 else 0) $ div (n*n) 2
	putStrLn $ intercalate "\n" $ take n $ cycle [s1,s2]

process :: Int -> (Int,[[Char]])
process n = (nc,map (\i -> take n (f (odd i))) [1..n])
    where
        nc = (n^2-1)`div`2+1
        f :: Bool -> [Char]
        f b = map (\x -> if x then 'C' else '.') $ iterate not b

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    let (nc,board) = process n
    print nc
    mapM_ putStrLn board

sol :: Int -> [Char]
sol n = take ((n+1)*n) (cycle ((take n (cycle "C.") ++ ['\n']) ++ (take n (cycle ".C") ++ ['\n'])))

main = do
        input <- getLine
        let n = read input
        putStrLn $ show $ (ceiling ((fromIntegral n^2) / 2))
        putStrLn $ sol n

main = getLine>>=(\x->putStr(solve (read x)))
solve n = res n ++ "\n" ++ (unlines (tb n))
res n = show ((n*n)`div`2+n`mod`2)
tb n = take n (concat (map (map (take n)) (replicate 1000 [concat (replicate 1000 "C."),concat (replicate 1000 ".C")])))

module Main where

import Data.List
-- https://codeforces.com/problemset/problem/384/A
main :: IO ()
main = do
    n <- getLine >>= pure . (read :: String -> Int)
    putStrLn $ solve n
    pure ()

solve :: Int -> String
solve n =
    let n' = (n+1) `div` 2
        cs = f "." . intercalate "." . take n' $ (repeat "C")
        dot = f "C" . intercalate "C" . take n' $ (repeat ".")
    in intercalate "\n" . take n $ cycle [cs, dot]
    where
        f s = if even n then ( <> s )
                else ( <> mempty )

import Control.Applicative
import Data.List

main=do
	n<-    read   <$> getLine:: IO  Int
	let s1 = take n $ cycle ['C','.']
	let s2 = take n $ cycle ['.','C']
	putStrLn $ intercalate "\n" $ take n $ cycle [s1,s2]

import Control.Applicative
import Data.List

main=do
	n<-    read   <$> getLine:: IO  Int
	let s1 = take n $ cycle ['C','.']
	let s2 = take n $ cycle ['.','C']
	print n
	putStrLn $ intercalate "\n" $ take n $ cycle [s1,s2]

{-# 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
    ls = [[if even i == even j then 'C' else '.' | j <- [1..n]] | i <- [1..n]]

  print $ length $ filter (== '.') $ concat ls
  putStrLn $ unlines ls

{-# 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
    ls = [[if even i == even j then 'C' else '.' | j <- [1..n]] | i <- [1..n]]

  putStrLn $ unlines ls

main = fmap (\x -> show (x * x + 1 `div` 2) : f 1 x) readLn >>= mapM putStrLn
f a b = if a > b then [] else map (\x -> if even (a + x) then 'C' else '.') [1..b] : f (a + 1) b

main = fmap f readLn >>= mapM putStrLn
f x = show (div (x * x + 1) 2) : g [g "C.", g ".C"]
  where g xs = take 5 $ concat $ repeat xs

main = fmap (f 1) readLn >>= mapM putStrLn
f a b = if a > b then [] else map (\x -> if x == a then 'C' else '.') [1..b] : f (a + 1) b


import System.IO
import Data.List
import Data.Bits

toint s = (read s) :: Int

doit::Int->Int->Int->Int->[Int]->String
doit d t a b s =
  if t == t then
    if d < 0 then
      "! "++show(a)++" "++show(b)++"\n"
    else
      if t == 0 then
        let w = head s in
        let aa = if w == 1 then a else (xor a $ shift 1 d) in
        let bb = if w == 1 then b else (xor b $ shift 1 d) in
        "? "++show(xor a $ shift 1 d)++" "++show(b)++"\n"++(doit (d-1) 0 aa bb $ tail s)
      else
        let q = "? "++show(xor a $ shift 1 d)++" "++show(xor b $ shift 1 d)++"\n" in
        let w = head s in
        q++(if w == t then (doeq d t a b $ tail s) else (doneq d t a b $ tail s))
  else
    "pingo"

doeq d t a b s =
  if t == t then
    let q = "? "++show(xor a $ shift 1 d)++" "++show(b)++"\n" in
    let w = head s in
    let aa = if w == 1 then a else (xor a $ shift 1 d) in
    let bb = if w == 1 then b else (xor b $ shift 1 d) in
    q++(doit (d-1) t aa bb $ tail s)
  else
    "pingo"

doneq d t a b s =
  if t == t then
    let aa = if t == 1 then (xor a $ shift 1 d) else a in
    let bb = if t == 1 then b else (xor b $ shift 1 d) in
    let q = "? "++show(aa)++" "++show(bb)++"\n" in
    let w = head s in
    q++(doit (d-1) w aa bb $ tail s)
  else
    "pingo"

solve::String -> String
solve ss =
  let s = map toint $ words ss in
  let t = head s in
  "? 0 0\n"++(doit 29 t 0 0 $ tail s)

main = do
  hSetBuffering stdout LineBuffering
  interact $ solve

{-# LANGUAGE BangPatterns #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
{-
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import System.IO

main :: IO ()
main = do
  (x, y) <- first
  putStrLn $ ("! "++) $ shows x $ ' ' : show y

putQuery :: Int -> Int -> IO Ordering
putQuery c d = do
  putStrLn $ ("? "++) $ shows c $ ' ' : show d
  hFlush stdout
  (`compare` (0::Int)) . read <$> getLine

first :: IO (Int, Int)
first =  (putQuery 0 0 >>=) $ neqLoop (bit 29) 0 0

neqLoop :: Int -> Int -> Int -> Ordering -> IO (Int, Int)
neqLoop 0 !a !b !ord = return (a,b)
neqLoop !lev !a !b EQ = eqLoop lev a b
neqLoop !lev !a !b !ord = do
  flippedOrd <- putQuery (a .|. lev) (b .|. lev)
  if ord == flippedOrd then do
    thisBit <- putQuery a (b .|. lev)
    let (newA, newB) = case thisBit of
                         LT -> (a,b)
                         _  -> (a .|. lev, b .|. lev)
    neqLoop (lev `shiftR` 1) newA newB ord
  else do
    let (newA, newB) = case ord of
                         GT -> (a .|. lev, b)
                         _  -> (a, b .|. lev)
    newOrd <- putQuery newA newB
    neqLoop (lev `shiftR` 1) newA newB newOrd

eqLoop :: Int -> Int -> Int -> IO (Int, Int)
eqLoop 0 !a !b = return (a, b)
eqLoop !lev !a !b = do
  ord <- putQuery a (b .|. lev)
  case ord of
    LT -> eqLoop (lev `shiftR` 1) a b
    _  -> eqLoop (lev `shiftR` 1) (a .|. lev) (b .|. lev)

{-# LANGUAGE BangPatterns #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
{-
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import System.IO

main :: IO ()
main = do
  (x, y) <- first
  putStrLn $ ("! "++) $ shows x $ ' ' : show y

putQuery :: Int -> Int -> IO Ordering
putQuery c d = do
  putStrLn $ ("? "++) $ shows c $ ' ' : show d
  hFlush stdout
  (`compare` (0::Int)) . read <$> getLine

first :: IO (Int, Int)
first =  (putQuery 0 0 >>=) $ neqLoop (bit 29) 0 0 (bit 30 - 1)

neqLoop :: Int -> Int -> Int -> Int -> Ordering -> IO (Int, Int)
neqLoop 0 !a !b !unk !ord = eqLoop (bit 29) a b unk
neqLoop !lev !a !b !unk EQ = eqLoop (bit 29) a b unk
neqLoop !lev !a !b !unk !ord = do
  flippedOrd <- putQuery (a .|. lev) (b .|. lev)
  if ord == flippedOrd then
    neqLoop (lev `shiftR` 1) a b unk ord
  else do
    let (newA, newB) = case ord of
                         GT -> (a .|. lev, b)
                         _  -> (a, b .|. lev)
    newOrd <- putQuery newA newB
    neqLoop (lev `shiftR` 1) newA newB (unk .&. complement lev) newOrd

eqLoop :: Int -> Int -> Int -> Int -> IO (Int, Int)
eqLoop 0 !a !b !unk = return (a, b)
eqLoop !lev !a !b !unk | lev .&. unk == 0
  = eqLoop (lev `shiftR` 1) a b unk
eqLoop !lev !a !b !unk = do
  ord <- putQuery a (b .|. lev)
  case ord of
    LT -> eqLoop (lev `shiftR` 1) a b unk
    _  -> eqLoop (lev `shiftR` 1) (a .|. lev) (b .|. lev) unk

{-# LANGUAGE BangPatterns #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
{-
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import System.IO

main :: IO ()
main = do
  (x, y) <- first
  putStrLn $ ("! "++) $ shows x $ ' ' : show y

putQuery :: Int -> Int -> IO Ordering
putQuery c d = do
  putStrLn $ ("? "++) $ shows c $ ' ' : show d
  hFlush stdout
  (`compare` (0::Int)) . read <$> getLine

data Status = Status { level :: {-# UNPACK #-} !Int,
                       bitsA :: {-# UNPACK #-} !Int,
                       bitsB :: {-# UNPACK #-} !Int,
                       unknown :: {-# UNPACK #-} !Int }

first :: IO (Int, Int)
first =  (putQuery 0 0 >>=) $ neqLoop $ Status (bit 29) 0 0 (bit 30 - 1)

neqLoop :: Status -> Ordering -> IO (Int, Int)
neqLoop st@Status{ level = 0 } !ord = eqLoop st{ level = bit 29 }
neqLoop !st EQ = eqLoop st{ level = bit 29 }
neqLoop !st !ord = do
  flippedOrd <- putQuery (bitsA st .|. level st) (bitsB st .|. level st)
  if ord == flippedOrd then
    neqLoop st{level = level st `shiftR` 1} ord
  else do
    let (newA, newB) = case ord of
                         GT -> (bitsA st .|. level st, bitsB st)
                         _  -> (bitsA st, bitsB st .|. level st)
        !newSt = Status { level = level st `shiftR` 1,
                          bitsA = newA,
                          bitsB = newB,
                          unknown = unknown st `xor` level st}
    newOrd <- putQuery newA newB
    neqLoop newSt newOrd

eqLoop :: Status -> IO (Int, Int)
eqLoop st@Status{ level = 0 } = return (bitsA st, bitsB st)
eqLoop st | level st .&. unknown st == 0
  = eqLoop st{level = level st `shiftR` 1}
eqLoop !st = do
  ord <- putQuery (bitsA st) (bitsB st .|. level st)
  case ord of
    LT -> eqLoop st{ level = level st `shiftR` 1 }
    _  -> eqLoop st{ bitsA = bitsA st .|. level st,
                     bitsB = bitsB st .|. level st,
                     level = level st `shiftR` 1}

import System.IO
import Data.List
import Data.Bits

toint s = (read s) :: Int

doit::Int->Int->Int->Int->[Int]->String
doit d t a b s =
  if t == t then
    if d < 0 then
      "! "++show(a)++" "++show(b)++"\n"
    else
      if t == 0 then
        let w = head s in
        let aa = if w == 1 then a else (xor a $ shift 1 d) in
        "? "++show(xor a $ shift 1 d)++" "++show(b)++"\n"++(doit (d-1) 0 aa aa $ tail s)
      else
        let q = "? "++show(xor a $ shift 1 d)++" "++show(xor b $ shift 1 d)++"\n" in
        let w = head s in
        q++(if w == t then (doeq d t a b $ tail s) else (doneq d t a b $ tail s))
  else
    "pingo"

doeq d t a b s =
  if t == t then
    let q = "? "++show(xor a $ shift 1 d)++" "++show(b)++"\n" in
    let w = head s in
    let aa = if w == 1 then a else (xor a $ shift 1 d) in
    let bb = if w == 1 then b else (xor b $ shift 1 d) in
    q++(doit (d-1) t aa bb $ tail s)
  else
    "pingo"

doneq d t a b s =
  if t == t then
    let aa = if t == 1 then (xor a $ shift 1 d) else a in
    let bb = if t == 1 then b else (xor b $ shift 1 d) in
    let q = "? "++show(aa)++" "++show(bb)++"\n" in
    let w = head s in
    q++(doit (d-1) w aa bb $ tail s)
  else
    "pingo"

solve::String -> String
solve ss =
  let s = map toint $ words ss in
  let t = head s in
  "? 0 0\n"++(doit 29 t 0 0 $ tail s)

main = do
  hSetBuffering stdout LineBuffering
  interact $ solve


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

import Control.Applicative
import Control.DeepSeq (deepseq)
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 Data.STRef
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.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
-- import Debug.Trace
import System.IO
import System.Random

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

main = do
  [x1, y1, x2, y2, x3, y3] <- map read . words <$> getLine

  let
    options a [] = [a]
    options a b = concat $ map f b
      where
        f p@(x, y, i) = options (a ++ [(x, y, i)]) (b \\ [p]) ++ options (a ++ [(y, x, i)]) (b \\ [p])

    rs = catMaybes $ map try $ options [] [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]
      where
        try [(x1, y1, i1), (x2, y2, i2), (x3, y3, i3)]
          | x1 == x2 && x2 == x3 && y1+y2+y3 == x1 =
            Just $ replicate y1 (replicate x1 i1) ++ replicate y2 (replicate x1 i2) ++ replicate y3 (replicate x1 i3)
          | x2 == x3 && x1+x2 == y1 && x1+x2 == y2+y3 =
            Just $ replicate y2 (replicate x1 i1 ++ replicate x2 i2) ++ replicate y3 (replicate x1 i1 ++ replicate x3 i3)
          | otherwise = Nothing

  if null rs
    then
      print (-1)
    else do
      print $ length $ head rs
      putStr $ unlines $ head rs

import Data.List
hanten::[(Int,Int,Char)] -> [[(Int,Int,Char)]]
hanten [a0,a1,a2] = [a0,a1,a2]:[fp a0,a1,a2]:[a0,fp a1,a2]:[a0,a1,fp a2]:[fp a0,fp a1,a2]:[a0,fp a1,fp a2]:[fp a0,a1,fp a2]:[fp a0,fp a1,fp a2]:[]
fp::(Int,Int,Char) -> (Int,Int,Char)
fp (a,b,c) = (b,a,c)
perm:: [(Int,Int,Char)] -> [[(Int,Int,Char)]]
perm a = permutations a
isOk:: [(Int,Int,Char)] -> Int
isOk [(x0,y0,_),(x1,y1,_),(x2,y2,_)] | (x0 == x1+x2) && (y1 == y2) && (x0 == y0 + y1) = 1
                               | (x0 == x1) && (x1 == x2) && (x0 == y0+y1+y2)= 2
                               | otherwise = 0
takeIsOk ::[[(Int,Int,Char)]] -> ([(Int,Int,Char)],Int)
takeIsOk [] = ([],0)
takeIsOk (a:as) | io > 0 = (a,io)
                | otherwise = takeIsOk as
   where io = isOk a
toString::([(Int,Int,Char)],Int) -> String
toString ([],0) = "-1"
toString (a@[(x0,y0,_),(x1,y1,_),(x2,y2,_)],1) = toString0 getC1 a 0 0 x0 (y0+y1)
toString (a@[(x0,y0,_),(x1,y1,_),(x2,y2,_)],2) = toString0 getC2 a 0 0 x0 (y0+y1+y2)
toString0::([(Int,Int,Char)] -> Int -> Int -> Char) -> [(Int,Int,Char)]-> Int -> Int -> Int -> Int  -> String
toString0 getC a@[(x0,y0,_),(x1,y1,_),(x2,y2,_)] i j si sj
                                                | i == si = []
                                                | j == sj -1 = [getC a i j]++"\n"++(toString0 getC a (i+1) 0 si sj)
                                                | otherwise = (getC a i j):(toString0 getC a i (j+1) si sj)
getC1::[(Int,Int,Char)] -> Int -> Int -> Char
getC1 a@[(x0,y0,c0),(x1,y1,c1),(x2,y2,c2)] i j | i < y0 = c0
                                               | i >= y0 && j < x1 = c1
                                               | otherwise = c2
getC2::[(Int,Int,Char)] -> Int -> Int -> Char
getC2 a@[(x0,y0,c0),(x1,y1,c1),(x2,y2,c2)] i j | i < y0 = c0
                                               | i < y0+y1 = c1
                                               | otherwise = c2

main = do
  w0 <- getLine
  let [x0,y0,x1,y1,x2,y2] = [read n::Int| n<-(words w0)]
  let a = [[(x0,y0,'A'),(x1,y1,'B'),(x2,y2,'C')]]
  let allPattern = concatMap perm $ concatMap hanten a
  let ok = takeIsOk allPattern
  let t = snd ok
  if t == 0
    then putStrLn "-1"
    else do
          let ([(xn0,yn0,_),(xn1,yn1,_),(xn2,yn2,_)],_) = ok
          putStr ((show xn0) ++ "\n"++ (toString ok))

import Control.Monad
import Data.List
import qualified Data.Array as Array
import qualified Data.Array.ST as ST

place :: (Num a, Array.Ix a, Ord a, Enum a) => [(a, a, c)] -> Array.Array (a, a) c
place xs =
    let m = maximum $ map (\(l, r, c) -> max l r) xs
        xs' = fit (m, m) xs
    in if length xs' == length xs then ST.runSTArray $ produce xs' m
    else Array.array ((0, 0), (-1, -1)) []
        where produce vs sz = do
                    ar <- ST.newArray ((0, 0), (sz-1, sz-1)) (third $ head vs)
                    foldM_ (\p (l, r, v) -> do writeBlock ar p (l, r) v; return $ advance p (l, r) sz) (0, 0) vs
                    return ar
              writeBlock ar (r, c) (rows, columns) value =
                  mapM_ (\(or, oc) -> ST.writeArray ar (r+or, c+oc) value) [(i, j) | i <- [0..rows-1], j <- [0..columns-1]]

advance (r, c) (br, bc) sz =
    if (c+bc) == sz then (r+br, c)
    else (r, c+bc)

fit target values = fit' target [] [] values
    where fit' target rs ns [] | fst target == 0 || snd target == 0 = reverse rs
            | otherwise = []
          fit' target@(l, r) rs ns (x@(l', r', c):xs) =
              if l == l' && r >= r' then fit' (l', r-r') (x:rs) [] (ns ++ xs)
              else if l == r' && r >= l' then fit' (r', r-l') ((r', l', c):rs) [] (ns ++ xs)
              else if r == l' && l >= r' then fit' (l-r', l') ((r', l', c):rs) [] (ns ++ xs)
              else if r == r' && l >= l' then fit' (l-l', r') ((l', r', c):rs) [] (ns ++ xs)
              else fit' target rs (x:ns) xs

second (_, v, _) = v
third (_, _, v) = v

main = do
    inp <- getContents
    let values = map read $ words inp :: [Int]
        d = zip3 (snd $ unzip $ filter (\v -> odd $ fst v) $ zip [0..] values)
            (snd $ unzip $ filter (\v -> even $ fst v) $ zip [0..] values) ['A', 'B', 'C']
        r = map (map snd) $ groupBy (\((l, _), _) ((r, _), _) -> l == r) (Array.assocs $ place d)
    if length r /= 0 then do
        putStrLn $ show $ length r
        putStrLn $ unlines $ r
    else
        putStrLn "-1"

import Data.Maybe
import Data.List ((\\), find)
import Debug.Trace (trace)

main = do
	[x1, y1, x2, y2, x3, y3] <- (map read . words) `fmap` getLine

	let
		try [(x, y, c)] = [[(x, y, c)], [(y, x, c)]]
		try bs = concatMap next bs
			where
				next b@(x, y, c) =
						(map ((x, y, c) :) bs') ++ (map ((y, x, c) :) bs')
					where
						bs' = try $ bs \\ [b]

		check [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =
			x1 == x2 && x2 == x3 && y1 + y2 + y3 == x1 || x1 == x2 && y1 + y2 == y3 && x1 + x3 == y3

		opts = try [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]
		ans = find check opts

		printAns [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =
			if x1 == x2 && x2 == x3 && y1 + y2 + y3 == x1 then do
				print x1
				putStr $ unlines $ replicate y1 $ replicate x1 c1
				putStr $ unlines $ replicate y2 $ replicate x1 c2
				putStr $ unlines $ replicate y3 $ replicate x1 c3
			else  do
				print y3
				putStr $ unlines $ replicate y1 $ replicate x1 c1 ++ replicate x3 c3
				putStr $ unlines $ replicate y2 $ replicate x2 c2 ++ replicate x3 c3

	if isNothing ans
		then print (-1)
		else printAns $ fromJust ans

import Data.Maybe
import Data.List ((\\), find)
import Debug.Trace (trace)

main = do
	[x1, y1, x2, y2, x3, y3] <- (map read . words) `fmap` getLine

	let
		try [(x, y, c)] = [[(x, y, c)], [(y, x, c)]]
		try bs = concatMap next bs
			where
				next b@(x, y, c) =
						(map ((x, y, c) :) bs') ++ (map ((y, x, c) :) bs')
					where
						bs' = try $ bs \\ [b]

		check [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =
			x1 == x2 && x3 == x3 && y1 + y2 + y3 == x1 || x1 == x2 && y1 + y2 == y3 && x1 + x3 == y3

		opts = try [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]
		ans = find check opts

		printAns [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =
			if x1 == x2 && x2 == x3 then do
				print x1
				putStr $ unlines $ replicate y1 $ replicate x1 c1
				putStr $ unlines $ replicate y2 $ replicate x1 c2
				putStr $ unlines $ replicate y3 $ replicate x1 c3
			else if x1 == x2 && y1 + y2 == y3 then do
				print y3
				putStr $ unlines $ replicate y1 $ replicate x1 c1 ++ replicate x3 c3
				putStr $ unlines $ replicate y2 $ replicate x2 c2 ++ replicate x3 c3
			else
				return ()

	if isNothing ans
		then print (-1)
		else printAns $ fromJust ans

import Data.Maybe
import Data.List ((\\), find)
import Debug.Trace (trace)

main = do
	[x1, y1, x2, y2, x3, y3] <- (map read . words) `fmap` getLine

	let
		try [(x, y, c)] = [[(x, y, c)], [(y, x, c)]]
		try bs = concatMap next bs
			where
				next b@(x, y, c) =
						(map ((x, y, c) :) bs') ++ (map ((y, x, c) :) bs')
					where
						bs' = try $ bs \\ [b]

		check [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =
			x1 == x2 && x2 == x3 && y1 + y2 + y3 == x1 || x1 == x2 && y1 + y2 == y3 && x1 + x3 == y3

		opts = try [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]
		ans = find check opts

		printAns [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =
			if x1 == x2 && x2 == x3 then do
				print x1
				putStr $ unlines $ replicate y1 $ replicate x1 c1
				putStr $ unlines $ replicate y2 $ replicate x1 c2
				putStr $ unlines $ replicate y3 $ replicate x1 c3
			else if x1 == x2 && y1 + y2 == y3 then do
				print y3
				putStr $ unlines $ replicate y1 $ replicate x1 c1 ++ replicate x3 c3
				putStr $ unlines $ replicate y2 $ replicate x2 c2 ++ replicate x3 c3
			else
				return ()

	if isNothing ans
		then print (-1)
		else printAns $ fromJust ans

import Data.Maybe
import Data.List ((\\), find)
import Debug.Trace (trace)

main = do
	[x1, y1, x2, y2, x3, y3] <- (map read . words) `fmap` getLine

	let
		try [(x, y, c)] = [[(x, y, c)], [(y, x, c)]]
		try bs = concatMap next bs
			where
				next b@(x, y, c) =
						(map ((x, y, c) :) bs') ++ (map ((y, x, c) :) bs')
					where
						bs' = try $ bs \\ [b]

		check [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =
			x1 == x2 && x3 == x3 || x1 == x2 && y1 + y2 == y3

		opts = try [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]
		ans = find check opts

		printAns [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =
			if x1 == x2 && x2 == x3 then do
				putStr $ unlines $ replicate y1 $ replicate x1 'A'
				putStr $ unlines $ replicate y2 $ replicate x1 'B'
				putStr $ unlines $ replicate y3 $ replicate x1 'C'
			else if x1 == x2 && y1 + y2 == y3 then do
				putStr $ unlines $ replicate y1 $ replicate x1 'A' ++ replicate x3 'C'
				putStr $ unlines $ replicate y2 $ replicate x2 'B' ++ replicate x3 'C'
			else
				return ()

	if isNothing ans
		then print (-1)
		else printAns $ fromJust ans

import Data.Maybe
import Data.List ((\\), find)
import Debug.Trace (trace)

main = do
	[x1, y1, x2, y2, x3, y3] <- (map read . words) `fmap` getLine

	let
		try [(x, y, c)] = [[(x, y, c)], [(y, x, c)]]
		try bs = concatMap next bs
			where
				next b@(x, y, c) =
						(map ((x, y, c) :) bs') ++ (map ((y, x, c) :) bs')
					where
						bs' = try $ bs \\ [b]

		check [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =
			x1 == x2 && x3 == x3 && y1 + y2 + y3 == x1 || x1 == x2 && y1 + y2 == y3 && x1 + x3 == y3

		opts = try [(x1, y1, 'A'), (x2, y2, 'B'), (x3, y3, 'C')]
		ans = find check opts

		printAns [(x1, y1, c1), (x2, y2, c2), (x3, y3, c3)] =
			if x1 == x2 && x2 == x3 then do
				print x1
				putStr $ unlines $ replicate y1 $ replicate x1 'A'
				putStr $ unlines $ replicate y2 $ replicate x1 'B'
				putStr $ unlines $ replicate y3 $ replicate x1 'C'
			else if x1 == x2 && y1 + y2 == y3 then do
				print y3
				putStr $ unlines $ replicate y1 $ replicate x1 'A' ++ replicate x3 'C'
				putStr $ unlines $ replicate y2 $ replicate x2 'B' ++ replicate x3 'C'
			else
				return ()

	if isNothing ans
		then print (-1)
		else printAns $ fromJust ans

import Control.Monad
import Data.List
import qualified Data.Array as Array
import qualified Data.Array.ST as ST

place :: (Num a, Array.Ix a, Ord a, Enum a) => [(a, a, c)] -> Array.Array (a, a) c
place xs =
    let m = maximum $ map (\(l, r, c) -> max l r) xs
        xs' = fit (m, m) xs
    in if length xs' == length xs then ST.runSTArray $ produce xs' m
    else Array.array ((0, 0), (-1, -1)) []
        where produce vs sz = do
                    ar <- ST.newArray ((0, 0), (sz-1, sz-1)) (third $ head vs)
                    foldM_ (\p (l, r, v) -> do writeBlock ar p (l, r) v; return $ advance p (l, r) sz) (0, 0) vs
                    return ar
              writeBlock ar (r, c) (rows, columns) value =
                  mapM_ (\(or, oc) -> ST.writeArray ar (r+or, c+oc) value) [(i, j) | i <- [0..rows-1], j <- [0..columns-1]]

advance (r, c) (br, bc) sz =
    if (c+bc) == sz then (r+br, c)
    else (r, c+bc)

fit target values = fit' target [] values
    where fit' target ns [] = []
          fit' target@(l, r) ns (x@(l', r', c):xs) =
              if l == l' && r >= r' then x:(fit' (l', r-r') [] (ns ++ xs))
              else if l == r' && r >= l' then (r', l', c):(fit' (r', r-l') [] (ns ++ xs))
              else if r == l' && l >= r' then (r', l', c):(fit' (l-r', l') [] (ns ++ xs))
              else if r == r' && l >= l' then (l', r', c):(fit' (l-l', r') [] (ns ++ xs))
              else fit' target (x:ns) xs

second (_, v, _) = v
third (_, _, v) = v

main = do
    inp <- getContents
    let values = map read $ words inp :: [Int]
        d = zip3 (snd $ unzip $ filter (\v -> odd $ fst v) $ zip [0..] values)
            (snd $ unzip $ filter (\v -> even $ fst v) $ zip [0..] values) ['A', 'B', 'C']
        r = map (map snd) $ groupBy (\((l, _), _) ((r, _), _) -> l == r) (Array.assocs $ place d)
    if length r /= 0 then do
        putStrLn $ show $ length r
        putStrLn $ unlines $ r
    else
        putStrLn "-1"


main = do
  inputjar <- getLine
  let n = read inputjar :: Int
  solve n

solve :: Int -> IO ()
solve 0 = putStr ""
solve n = do
  input <- getLine
  let list = read ("[" ++ map (\x -> if x == ' ' then ',' else x) input ++ "]") :: [Int]
  solveCase list
  solve (n - 1)

solveCase :: [Int] -> IO ()
solveCase (x : y : n : [])
  | tmp <= n = print tmp
  | otherwise = print $ tmp - x
  where
    tmp = n - (n `mod` x) + y

solve :: [Int] -> Int
solve [x, y, n]
  | (n - n `mod` x + y) <= n = (n - n `mod` x + y)
  | otherwise                = (n - n `mod` x - (x - y))

splitEvery :: Int -> [a] -> [[a]]
splitEvery _ [] = []
splitEvery n xs = as : splitEvery n bs
  where (as,bs) = splitAt n xs

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

main :: IO ()
main = interact $ unlines . map show . map solve . splitEvery 3 . map read . tail . words

import Control.Monad (replicateM_)

main = readLn >>= flip replicateM_ (getLine >>= print . (\[a,b,c] -> f a b c) . map read . words)

f :: Int -> Int -> Int -> Int
f x y n | n `mod` x >= y = n - ((n `mod` x) - y)
        | otherwise = f x y $ n - (n `mod` x) - 1

{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Monad (replicateM_)

main = do
  n <- readLn
  replicateM_ n $ do
    input :: [Word] <- map read  . words <$> getLine
    let x = input !! 0;
        y = input !! 1;
        n = input !! 2;
        i = n - n `mod` x + y; in
      print $ if i > n then i - x else i

{-# LANGUAGE Safe #-}

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

main :: IO ()
main =  interact $  lines >>> drop 1 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (l : rest) = (itoline . solve . linetois) l : tcio rest
  linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois
  itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

solve :: [Int]  -> Int
solve (x: y: n: []) | r >= y = n - (r-y)
                    | otherwise = n + (y-r) - x where
  r = n `mod` x

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

process x y n | a==y = n
	      | a>y = n-a+y
              | otherwise = n-x-a+y
	where a = mod n x

onecase = do
		[x,y,n]<- map read <$> words <$> getLine ::IO [Integer]
		print $ process x y n

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

import Control.Monad

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [x,y,n] <- map read . words <$> getLine
    print $ n - (n - y) `mod` x


import Control.Monad

solve :: Double -> Double
solve n
    | n > 1 = (1.0 / n) + solve (n - 1)
    | otherwise = 1

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

solve :: Integer -> Double
solve n = sum $ map (\x -> 1.0 / (fromInteger x)) [1..n]

main = interact (show . solve . (\x -> read x :: Integer))

import Control.Monad

solve :: Double -> Int -> Double
solve ans 0 = ans
solve ans n = solve (ans + (1 / (fromIntegral n))) (n - 1)

main :: IO ()
main = do
    n <- read <$> getLine
    putStrLn $ show . solve 0.0 $ n

import Control.Monad

solve :: Double -> Double
solve n = sum $ map (\x -> 1.0 / x) [1..n]

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

module Main where

main :: IO()
main = do
    x <- getLine
    let y = read x :: Int
    let s = sum [1 / fromIntegral(i) | i <- [1..y]]
    print s

solve :: Int -> Double
solve n
  | n == 1 = 1.0
  | otherwise = r + solve n'
    where
      n' = n - 1
      r =  (1.0) / (fromIntegral n)

main = do
  n <- readLn :: IO Int
  print $ solve n

solve :: Int -> Double
solve n
  | n == 1 = 1.0
  | otherwise = r + solve n'
    where
      n' = n - t
      t = (n `div` 2)
      r =  (fromIntegral t) / (fromIntegral n)

main = do
  n <- readLn :: IO Int
  print $ solve n

solve :: Int -> Double
solve n
  | n == 1 = 1.0
  | otherwise = r + solve n'
    where
      n' = n - t
      t = (n `div` 2) + n `mod` 2
      r =  (fromIntegral t) / (fromIntegral n)

main = do
  n <- readLn :: IO Int
  print $ solve n

solve :: Int -> Double
solve n
  | n == 1 = 1.0
  | otherwise = r + solve n'
    where
      n' = n - t
      t = n - 1
      r =  (fromIntegral t) / (fromIntegral n)

main = do
  n <- readLn :: IO Int
  print $ solve n


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

check a b c = and $ map ( \(a1,b1,c1)-> a1==c1 || b1==c1) x
	where x = zip3 a b c

onecase = do
		[a,b,c]<-replicateM 3 getLine
		putStrLn $ if check a b c then "YES" else "NO"

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

import Data.List (zip3)

process :: [Char] -> [Char] -> [Char] -> Bool
process as bs cs = all (\(a,b,c) -> a==c || b==c) $ zip3 as bs cs

readInt :: String -> Int
readInt = read

run :: Int -> IO ()
run 0 = return ()
run t = do
    as <- getLine
    bs <- getLine
    cs <- getLine
    if process as bs cs
        then putStrLn "YES"
        else putStrLn "NO"
    run (t-1)

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

solve :: String -> String -> String -> Bool
solve "" "" "" = True
solve (a:as) (b:bs) (c:cs) = if (c == b || c == a ) then solve as bs cs
                                                    else False

parse :: (String, String, String) -> String
parse (a, b, c)
  | solve a b c = "YES"
  | otherwise = "NO"

takeLines :: [String] -> [(String, String, String)]
takeLines [] = []
takeLines (a:b:c:rest) = (a, b, c):takeLines rest

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


import Control.Arrow

main = interact $
  lines >>> drop 1
  >>> map (words >>> map read)
  >>> process
  >>> map (\b -> if b then "Yes" else "No") >>> unlines

process :: [[Int]] -> [Bool]
process [] = []
process ([n,a,b,c,d]:ps) = (check n a b c d) : process ps

check n a b c d =
  c - d <= n * (a + b) && n * (a - b) <= c + d

module Main where

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

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

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

printStrList :: [String] -> IO ()
printStrList = putStrLn . intercalate " "

printList :: (Show a) => [a] -> IO ()
printList = printStrList . map show

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

(-->) :: a -> (a -> b) -> b
(-->) = flip ($)

count :: (Eq a) => a -> [a] -> Int
count x = length . filter (== x)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, a, b, c, d] <- getIntList
        let minW = (a - b) * n
            maxW = (a + b) * n
            minV = (c - d)
            maxV = (c + d)
        putStrLn $ yesOrNo $ not $ or [minW > maxV, maxW < minV]

import Control.Monad

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

routine :: IO ()
routine = do
    [n,a,b,c,d] <- (map read.words) <$> getLine
    let big = (a+b)*n :: Int
        small = (a-b)*n
        in if big < c-d || small > c+d
            then putStrLn "No"
            else putStrLn "Yes"

hasOverlap :: (Int, Int) -> (Int, Int) -> Bool
hasOverlap (a,b) (x,y)
    | a > y     = False
    | b < x     = False
    | otherwise = True

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

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

solve :: String -> String
solve s =
    hasOverlap (n*(a-b), n*(a+b)) (c-d, c+d)
    |> decorate
    where
        (n:a:b:c:d:_) = parse s

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

infixr 0 |>

(|>) :: a -> (a -> b) -> b
(|>) = flip ($)

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

onecase = do
		[n,a,b,c,d]<-map read <$> words <$> getLine ::IO [Integer]
		putStrLn $ if (a+b)*n <(c-d) || (a-b)*n >(c+d) then "No" else "Yes"

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

process :: Int -> Int -> Int -> Int -> Int -> Bool
process n a b c d = (max ln lp) <= (min rn rp)
    where
        ln = n * (a - b)
        rn = n * (a + b)
        lp = c - d
        rp = c + d

readInt :: String -> Int
readInt = read

run :: Int -> IO ()
run 0 = return ()
run t = do
    [n,a,b,c,d] <- fmap (map readInt.words) getLine
    if process n a b c d
        then putStrLn "YES"
        else putStrLn "NO"
    run (t-1)

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

import Control.Monad

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

routine :: IO ()
routine = do
    [n,a,b,c,d] <- (map read.words) <$> getLine
    let big = (a+b)*n
        small = (a-b)*n
        in if (big <= c+d && c-d <= big) || (small <= c+d && c-d <= small)
            then putStrLn "Yes"
            else putStrLn "No"

import Control.Monad.ST

main = print "hello"


expand :: String -> String
expand s
	| p !! 0 == "" && p !! 1 == "" = bindColon (map (grow (10 - (length p))) (tail p))
	| otherwise = bindColon (map (grow (9 - (length p))) p)
		where p = parseColon s

grow :: Int -> String -> String
grow 0 []	= ""
grow n []	= (copyString (n - 1) "0000:") ++ "0000"
grow _ s	= (copyString (4 - (length s)) "0") ++ s

copyString :: Int -> String -> String
copyString 0 s = ""
copyString n s = s ++ (copyString (n - 1) s)

bindColon :: [String] -> String
bindColon (x:(y:xs)) = x ++ ":" ++ (bindColon (y:xs))
bindColon (x:xs)	= x
bindColon _	= ""

parseColon :: String -> [String]
parseColon (a:b)
	| null prev && a == ':'	= [""]
	| null prev && a /= ':'	= [a:""]
	| a == ':'				= "":prev
	| otherwise				= (a:(head prev)):(tail prev)
		where prev = parseColon b
parseColon _ = []

printAns :: [String] -> IO()
printAns (x:xs) = do
	putStrLn x
	printAns xs
printAns _ = do
	putStr ""

main :: IO()
main = do
	str <- getContents
	printAns (map expand (tail (words str)))

import Control.Monad
import Data.List

split c = map (takeWhile (/=c) . tail) . filter ((==c) . head) . init . tails . (c:)

main = do
  n <- fmap read getLine
  replicateM_ n $ do
    (a, b) <- fmap (break (=="") . split ':') getLine
    let b' = filter (/="") b
        s = a ++ replicate (8 - length a - length b') "" ++ b'
    putStrLn $ intercalate ":" $ map (until ((>=4) . length) ('0':)) s

import Data.List

main = do
    getLine
    ips <- fmap lines getContents
    mapM_ (putStrLn . resolveIpv6) ips

data Block = Number String | Empty
    deriving Eq

resolveIpv6 ip = let blocks = split ip ""
                     zeros  = 8 - (length $ filter (/= Empty) blocks)
                 in  tail $ showIpv6 zeros blocks
    where
        split "" ""       = []
        split "" b        = [Number $ addZeros $ reverse b]
        split (':':ip) "" = Empty:(split ip "")
        split (':':ip) b  = (Number $ addZeros $ reverse b):(split ip "")
        split (c:ip) b    = split ip $ c:b
        addZeros b = (replicate (4 - length b) '0') ++ b
        showIpv6 _ [] = ""
        showIpv6 exp (Number b:xs) = ":" ++ b ++ (showIpv6 exp xs)
        showIpv6 exp (Empty:xs) = showIpv6 0 $ (replicate exp (Number "0000")) ++ xs

import Control.Monad (liftM)
import Data.List (intercalate, isInfixOf)

solve :: String -> String
solve s  =  intercalate ":" $ solve' "" s
  where
    n  =  length $ filter (== ':') s
    m  =  if isInfixOf "::" s then n else n + 1

    solve' b ""  =  [addZero b]
    solve' b (':' : ':' : s)
      =  addZero b : (replicate (8 - m) "0000") ++ solve' "" s
    solve' b (':' : s)  =  addZero b : solve' "" s
    solve' b (c : s)  =  solve' (b ++ [c]) s

    addZero s  =  replicate (4 - length s) '0' ++ s

main :: IO ()
main  =  do
    n  <-  readLn
    ls  <-  liftM (take n . lines) getContents
    mapM_ (putStrLn . solve) ls

main=interact$unlines.map f.tail.lines
f cs = tail.concatMap ff $ parse cs
   where
     g ':' = ' '
     g c = c
     n = length.words.map g $ cs
     ff "" = [1..8-n]>>":0000"
     ff ds = (':':) $ reverse $ take 4 $ reverse $ "0000"++ds

parse (':':':':rest) = "" : parse rest
parse (':':rest) = xs : parse ys
   where
     (xs,ys) = span (':'/=) rest
parse "" = []
parse cs =  xs : parse ys
   where
     (xs,ys) = span (':'/=) cs

import Data.List

split :: (Eq a) => a -> [a] -> [[a]]
split _ [] = []
split t xs
    | b == []   = [a]
    | otherwise = a : (split t $ tail b)
    where (a, b) = break (== t) xs

foo str = concat $ intersperse ":" $ map (\t -> (replicate (4 - length t) '0') ++ t) $ xs'
    where xs     = split ':' str
          xs'    = if b == [] then a ++ (replicate (8 - length xs) "")
                   else a ++ (replicate (9 - length xs) "") ++ tail b
          (a, b) = break (== "") xs

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

import Data.List

split :: (Eq a) => a -> [a] -> [[a]]
split _ [] = []
split t xs
    | b == []   = [a]
    | otherwise = a : (split t $ tail b)
    where (a, b) = break (== t) xs

foo str = concat $ intersperse ":" $ map (\t -> (replicate (4 - length t) '0') ++ t) $ xs'
    where xs     = split ':' str
          xs'    = a ++ (replicate (8 - length xs) "") ++ b
          (a, b) = break (== "") xs

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


import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Char

process :: [Char] -> [Char] -> [(Char, Char)]
process [] [] = []
process [] (x: xs) = (' ' , x) : process [] xs
process (x: xs) [] = (x, ' ') : process xs []
process (x:xs) (y:ys)
 | x == y = process xs ys
 | otherwise = (x, y) : process xs ys

main :: IO ()
main = do
	w1 <- getLine
	w2 <- getLine
	let
		arr = process w1 w2
	if length arr == 2 && fst (arr !! 0) == snd (arr !! 1) && snd (arr!!0) == fst (arr!!1) then
		putStrLn "YES"
		else
			putStrLn "NO"

import Data.List

main :: IO()
main = printBool . solve . lines =<< getContents

printBool :: Bool -> IO()
printBool b = putStrLn (if b then "YES" else "NO")

solve :: [String] -> Bool
solve (a:b:_) | (length a) /= (length b) = False
              | otherwise = let (da:db:_) = get_diff a b [[], []]
                            in (length da) == 2 && (sort da) == (sort db)

get_diff :: String -> String -> [[Char]] -> [[Char]]
get_diff []     []     d          = d
get_diff (a:ax) (b:bx) (da:db:dx) | a == b = get_diff ax bx (da:db:dx)
                                  | otherwise = get_diff ax bx ((a:da):(b:db):dx)

solv :: [Char] -> [Char] -> Bool
solv x y = if length x /= length y
              then False
              else let tmp = filter (\(x, y) -> x /= y) $ zip x y in
                       if length tmp /= 2 then False else
                   let [(x1, y1), (x2, y2)] = tmp in
                       (x1 == y2) && (x2 == y1)

main = do
    a <- getLine
    b <- getLine
    putStrLn $ if solv a b then "YES" else "NO"

solve a b
    | length a == length b = let c = zip a b
                                 d = filter (\(x, y) -> x /= y) c
                             in case d of
                                  [(a, b), (c, d)] -> a == d && b == c
                                  otherwise        -> False
    | otherwise            = False

main = do
  a <- getLine
  b <- getLine
  putStrLn $ if solve a b then "YES" else "NO"

{-
import HUnit

testSmallString  =  Test "TestSmallString" $ assertFalse (solve "a" "b")

testInput1  =  Test "TestInput 1" $ assertTrue (solve "ab" "ba")

testInput2  =  Test "TestInput 2" $ assertFalse (solve "aa" "ab")

testDiffLength  =  Test "TestDiffLength" $ assertFalse (solve "ab" "baa")

test  =  mapM_ run
  [
    testSmallString,
    testInput1,
    testInput2,
    testDiffLength
  ]
-}
--------------------------------------------------------------------------------

solve :: String -> String -> Bool
solve a b
  | length a == length b  =  solve' diff
  | otherwise  =  False
  where
    diff  =  getDiff a b
    getDiff [] []  =  []
    getDiff (a:as) (b:bs)
      | a == b  =  getDiff as bs
      | a /= b  =  (a,b) : getDiff as bs
    solve' [(a1, b1), (a2, b2)]  =  a1 == b2 && b1 == a2
    solve' _  =  False

main :: IO ()
main  =  do
    a  <-  getLine
    b  <-  getLine
    putStrLn (if solve a b then "YES" else "NO")

import Data.Char
import Data.List

count :: String -> Char -> Int
count s c = length $ filter (\x -> x == c) s

cs :: String -> String -> Bool
cs s1 s2 = cs' s1 s2 'a' 'z'

cs' :: String -> String -> Char -> Char -> Bool
cs' s1 s2 c to = if c > to then True else
                  if (count s1 c) /= (count s2 c) then False else
                   cs' s1 s2 (toEnum ((fromEnum c) + 1)) to

bad :: String -> String -> Int
bad [] [] = 0
bad [] s = 10
bad s [] = 10
bad s t = (bad (tail s) (tail t)) + (if (head s) == (head t) then 0 else 1)

solve :: String -> String -> String
solve s1 s2 = if ((bad s1 s2) <= 2) && (cs s1 s2) then "YES" else "NO"

main = do s1 <- getLine
          s2 <- getLine
          putStrLn $ solve s1 s2

main=interact$solve.lines

swap (x,y) = (y,x)

solve :: [String] -> String
solve [xs,ys]
  | lx /= ly = "NO"
  | length diff /= 2 = "NO"
  | swap(diff!!0) == diff!!1 = "YES"
  | otherwise = "NO"
  where lx = length xs
        ly = length ys
        diff = filter (\(x,y) -> x/=y) $ zip xs ys

solve :: String -> String -> String
solve [] [] = "NO"
solve gen1 gen2 =
    let
        diffs = filter (\xs -> length xs > 0) $ zipWith (\g1 g2 -> if g1 /= g2 then [g1,g2] else []) gen1 gen2
        lens = length gen1 - length gen2
    in
        if lens /= 0 || length diffs /= 2
        then "NO"
        else
            let
                (a:b:_) = diffs
            in
                if reverse b == a then "YES" else "NO"

main =
    do
        gen1 <- getLine
        gen2 <- getLine
        putStrLn $ solve gen1 gen2

pairCmp :: Eq a => (a,a) -> (a,a) -> Bool
pairCmp x y = fst x == snd y && snd x == fst y

isOk :: Eq b => [(a,(b,b))] -> Bool
isOk pairs
    | l == 0    = True
	| l == 2    = x `pairCmp` y
	| otherwise = False
    where
        l = length pairs
        x = snd $ pairs !! 0
        y = snd $ pairs !! 1

equal :: Char -> Char -> (Bool, (Char, Char))
equal x y = (x == y, (x, y))

cmp :: String -> String -> Bool
cmp a b
    | length a == length b = isOk . filter (not . fst) $ zipWith equal a b
    | otherwise            = False

boolToStr :: Bool -> String
boolToStr x = if x then "YES" else "NO"

main = do
	a <- getLine
	b <- getLine
	putStrLn $ boolToStr $ cmp a b

import Data.Tuple

main :: IO ()
main = do
  a <- getLine
  b <- getLine
  putStrLn $ solve a b

solve :: String -> String -> String
solve xs ys
  | lx /= ly = "NO"
  | length diff /= 2 = "NO"
  | swap(diff !! 0) == diff !! 1 = "YES"
  | otherwise = "NO"
  where
    lx = length xs
    ly = length ys
    diff = filter (\(x, y) -> x/= y) $ zip xs ys

import Data.Function
import Data.List
solve x y =
    (length x == length y) && (verify $ foldl folder [] (zip x y))
    where
      folder acc (a, b) = if a == b
                          then acc
                          else (a,b):acc
      verify [] = True
      verify [(a,b), (c,d)] = (a == d) && (b == c)
      verify _ = False

pprint True = "YES"
pprint False = "NO"

main = do
  foo <- getContents
  let bar = lines foo
  putStrLn . pprint $ solve (bar !! 0) (bar !! 1)

import Data.Tuple

main :: IO ()
main = do
  a <- getLine
  b <- getLine
  putStrLn $ solve a b

solve :: String -> String -> String
solve xs ys
  | lx /= ly = "NO"
  | length diff /= 2 = "NO"
  | swap(diff !! 0) == diff !! 1 = "YES"
  | otherwise = "NO"
  where
    lx = length xs
    ly = length xs
    diff = filter (\(x, y) -> x/= y) $ zip xs ys

import Data.Function
import Data.List
solve x y =
    (length x == length y) && or [cnt == 0, cnt == 2]
    where
      cnt = sum [if a /= b then 1 else 0 | (a, b) <- zip x y]

pprint True = "YES"
pprint False = "NO"

main = do
  foo <- getContents
  let bar = lines foo
  putStrLn . pprint $ solve (bar !! 0) (bar !! 1)

import Data.Function
import Data.List
solve = ((==) `on` sort)

pprint True = "YES"
pprint False = "NO"

main = do
  foo <- getContents
  let bar = lines foo
  putStrLn . pprint $ solve (bar !! 0) (bar !! 1)

import Data.Function
import Data.List
solve x y =
    or [cnt == 0, cnt == 2]
    where
      cnt = sum [if a /= b then 1 else 0 | (a, b) <- zip x y]

pprint True = "YES"
pprint False = "NO"

main = do
  foo <- getContents
  let bar = lines foo
  putStrLn . pprint $ solve (bar !! 0) (bar !! 1)


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

import Control.Monad (foldM_)
import Data.Ix (Ix)
import Data.Array.MArray (MArray, newArray, readArray, writeArray)
import Data.Array.ST (runSTUArray)
import Data.Array.Unboxed (UArray, (!), bounds, elems, listArray)

(?) True  =  const
(?) _  =  flip const

zFunction :: String -> UArray Int Int
zFunction s'  =  runSTUArray $ do
    z  <-  newArray (1, n) 0
    writeArray z 1 n
    foldM_ (iter z) (1, 1) [2..n]
    return z
  where
    n  =  length s'
    s  =  listArray (1, n) s' :: UArray Int Char
    iter z (l, r) i  =  do
        zil  <-  readArray z (i - l + 1)
        let z0  =  (i > r) ? 0 $ min (r - i + 1) zil

        let zi  =  head $ dropWhile (\j -> i + j <= n && s ! (j + 1) == s ! (i + j)) [z0..]
        writeArray z i zi
        return $ (i + zi - 1 > r) ? (i, i + zi - 1) $ (l, r)

solve :: String -> String -> Int
solve s1 s2
  | s1 `isPrefixOf` s2 || s2 `isPrefixOf` s1  =  length $ filter dividerS [1 .. min n1 n2]
  | otherwise  =  0
  where
    n1  =  length s1
    n2  =  length s2
    z1  =  zFunction s1
    z2  =  zFunction s2
    dividerS  i  =  dividerS1 i && dividerS2 i
    dividerS1 i  =  i == n1
        || n1 `mod` i == 0 && z1 ! (i + 1) == (n1 - i)
    dividerS2 i  =  i == n2
        || n2 `mod` i == 0 && z2 ! (i + 1) == (n2 - i)

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

import Control.Monad
import Data.Array.IO
import Data.IORef
import Data.List
check s l =
  let (s1, s2) = splitAt l s
  in null s2 || (isPrefixOf s1 s2 && check s2 l)
main = do
  s1 <- getLine
  s2 <- getLine
  let g = gcd (length s1) (length s2)
  arr <- newArray (1, g) (-1) :: IO (IOArray Int Int)
  cnt <- newIORef 0
  forM_ [1..g] $ \i -> do
    v <- readArray arr i
    if v == -1 && g `mod` i == 0 && check s1 i && check s2 i && take i s1 == take i s2
       then let g' = g `div` i
            in forM_ [1..g'] $ \j -> writeArray arr (i*j) $ if g' `mod` j == 0 then 1 else 0
       else when (v == -1) $ writeArray arr i 0
    readArray arr i >>= \j -> modifyIORef cnt (+j)
  readIORef cnt >>= print

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

import Control.Monad (foldM_, when)
import Data.Ix (Ix)
import Data.Array.MArray (MArray, newArray, readArray, writeArray)
import Data.Array.ST (runSTUArray)
import Data.Array.Unboxed (UArray, (!), bounds, elems, listArray)

while :: Monad m => m Bool -> m () -> m ()
while condition action  =  do
    c  <-  condition
    when c $ do
        action
        while condition action

modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f  =  do
    e  <-  readArray a i
    writeArray a i (f e)

zFunction :: String -> UArray Int Int
zFunction s'  =  runSTUArray $ do
    z  <-  newArray (1, n) 0
    writeArray z 1 n
    foldM_ (iter z) (1, 1) [2..n]
    return z
  where
    n  =  length s'
    s  =  listArray (1, n) s' :: UArray Int Char
    iter z (l, r) i  =  do
        when (i <= r) $ do
            zil  <-  readArray z (i-l+1)
            writeArray z i (min zil (r-i+1))
        while (condition z i) $ modifyArray z i (+1)
        zi  <-  readArray z i
        if (i + zi - 1 > r) then
            return (i, i + zi - 1)
        else
            return (l, r)
    condition z i  =  do
        zi  <-  readArray z i
        return (i + zi <= n && s ! (zi + 1) == s ! (i + zi))

solve :: String -> String -> Int
solve s1 s2
  | s1 `isPrefixOf` s2 || s2 `isPrefixOf` s1  =  length $ filter dividerS [1 .. min n1 n2]
  | otherwise  =  0
  where
    n1  =  length s1
    n2  =  length s2
    z1  =  zFunction s1
    z2  =  zFunction s2
    dividerS  i  =  dividerS1 i && dividerS2 i
    dividerS1 i  =  i == n1
        || n1 `mod` i == 0 && z1 ! (i + 1) == (n1 - i)
    dividerS2 i  =  i == n2
        || n2 `mod` i == 0 && z2 ! (i + 1) == (n2 - i)

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

import Control.Monad
import Data.Array.IO
import Data.IORef
import Data.List
check s l =
  let (s1, s2) = splitAt l s
  in null s2 || (isPrefixOf s1 s2 && check s2 l)
main = do
  s1 <- getLine
  s2 <- getLine
  let g = gcd (length s1) (length s2)
  arr <- newArray (1, g) (-1) :: IO (IOArray Int Int)
  cnt <- newIORef 0
  forM_ [1..g] $ \i -> do
    v <- readArray arr i
    if v == -1 && g `mod` i == 0 && check s1 i && check s2 i && head s1 == head s2
       then let g' = g `div` i
            in forM_ [1..g'] $ \j -> writeArray arr (i*j) $ if g' `mod` j == 0 then 1 else 0
       else when (v == -1) $ writeArray arr i 0
    readArray arr i >>= \j -> modifyIORef cnt (+j)
  readIORef cnt >>= print

import Control.Monad
import Data.Array.IO
import Data.IORef
import Data.List
check s l =
  let (s1, s2) = splitAt l s
  in null s2 || (isPrefixOf s1 s2 && check s2 l)
main = do
  s1 <- getLine
  s2 <- getLine
  let g = gcd (length s1) (length s2)
  arr <- newArray (1, g) (-1) :: IO (IOArray Int Int)
  cnt <- newIORef 0
  forM_ [1..g] $ \i -> do
    v <- readArray arr i
    if v == -1 && g `mod` i == 0 && check s1 i && check s2 i
       then let g' = g `div` i
            in forM_ [1..g'] $ \j -> writeArray arr (i*j) $ if g' `mod` j == 0 then 1 else 0
       else when (v == -1) $ writeArray arr i 0
    readArray arr i >>= \j -> modifyIORef cnt (+j)
  readIORef cnt >>= print

import Control.Monad (liftM2, foldM_, when)
import Data.Ix (Ix)
import Data.Array.MArray (MArray, newArray, readArray, writeArray)
import Data.Array.ST (runSTUArray)
import Data.Array.Unboxed (UArray, (!), bounds, elems, listArray)

while :: Monad m => m Bool -> m () -> m ()
while condition action  =  do
    c  <-  condition
    when c $ do
        action
        while condition action

modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f  =  do
    e  <-  readArray a i
    writeArray a i (f e)

zFunction :: String -> UArray Int Int
zFunction s'  =  runSTUArray $ do
    z  <-  newArray (1, n) 0
    writeArray z 1 n
    foldM_ (iter z) (1, 1) [2..n]
    return z
  where
    n  =  length s'
    s  =  listArray (1, n) s' :: UArray Int Char
    iter z (l, r) i  =  do
        when (i <= r) $ do
            zil  <-  readArray z (i-l+1)
            writeArray z i (min zil (r-i+1))
        while (condition z i) $ modifyArray z i (+1)
        zi  <-  readArray z i
        if (i + zi - 1 > r) then
            return (i, i + zi - 1)
        else
            return (l, r)
    condition z i  =  do
        zi  <-  readArray z i
        return (i + zi <= n && s ! (zi + 1) == s ! (i + zi))

solve :: String -> String -> Int
solve s1 s2  =  length $ filter dividerS [1 .. min n1 n2]
  where
    n1  =  length s1
    n2  =  length s2
    z1  =  zFunction s1
    z2  =  zFunction s2
    dividerS  i  =  dividerS1 i && dividerS2 i
    dividerS1 i  =  i == n1
        || n1 `mod` i == 0 && z1 ! (i + 1) == (n1 - i)
    dividerS2 i  =  i == n2
        || n2 `mod` i == 0 && z2 ! (i + 1) == (n2 - i)

main :: IO ()
main  =  liftM2 solve getLine getLine >>= print

import Control.Monad
import Data.Array.IO
import Data.IORef
import Data.List
check s l =
  let (s1, s2) = splitAt l s
  in null s2 || (isPrefixOf s1 s2 && check s2 l)
main = do
  s1 <- getLine
  s2 <- getLine
  let g = gcd (length s1) (length s2)
  arr <- newArray (1, g) (-1) :: IO (IOArray Int Int)
  cnt <- newIORef 0
  forM_ [1..g] $ \i -> do
    v <- readArray arr i
    if v == -1 && g `mod` i == 0 && check s1 i && check s2 i
       then forM_ [1..(g `div` i)] $ \j -> writeArray arr (i*j) 1
       else when (v == -1) $ writeArray arr i 0
    readArray arr i >>= \j -> modifyIORef cnt (+j)
  readIORef cnt >>= print


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

  let
    max' l' (l, c)
      | l' > l = (l', 1)
      | l == l' = (l, c+1)
      | otherwise = (l, c)

    scan _ [] _ m = m
    scan i ('(':s) st m = scan (i+1) s (i:st) m
    scan i (')':s) [_] m = scan (i+1) s [i] m
    scan i (')':s) (_:j:st) m = scan (i+1) s (j:st) $ max' (i-j) m

    (l, c) = scan 1 s [0] (0, 1)

  putStrLn $ show l ++ " " ++ show c

import Data.List
data St = Open | Close | Sub Int
red st [] =
    let nList = map (\(Sub x) -> x) $ filter (\x -> case x of {Sub _ -> True; _ -> False}) st in
    case nList of
        [] -> [0, 1]
        _ -> let (s:_) = group $ sortBy (flip compare) nList in [head s, length s]
red st                     ('(':inpStr) = red (Open:st)         inpStr
red (Sub n:Open:Sub n1:st) (')':inpStr) = red (Sub (n+n1+2):st) inpStr
red (Sub n:Open:st)        (')':inpStr) = red (Sub (n+2):st)    inpStr
red (Open:Sub n:st)        (')':inpStr) = red (Sub (n+2):st)    inpStr
red (Open:st)              (')':inpStr) = red (Sub 2:st)        inpStr
red st                     (')':inpStr) = red (Close:st)        inpStr
main = (unwords . map show . red []) `fmap` getLine >>= putStrLn

{-# LANGUAGE BangPatterns #-}

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

type Index  = Int
type Depth  = Int
type Stack  = (Depth, Depth, [Index])
type State  = (Stack, (Int, Int))

push :: Index -> State -> State
push i ((d, e, is), best)
  | d == e    = ((d', d', i : is), best)
  | otherwise = ((d', e, is), best)
 where d' = d + 1

pop :: Index -> State -> State
pop i ((!d, !e, is), best@(!longest, !count))
  | d == 0    = ((0, 0, []), best)
  | otherwise = (,) (d - 1, d, is') $ case compare l longest of
    LT -> best
    EQ -> fmap succ best
    GT -> (l, 1)
 where is' = drop (e - d) is
       l = i - head is' + 1

automata :: State -> (Index, Char) -> State
automata state (i, c)
  | c == '('   = push i state
  | otherwise  = pop  i state

solve :: String -> IO ()
solve = uncurry (printf "%d %d\n")
     . snd . foldl automata ((0, 0, []), (0, 1)) . zip [0 ..]

main :: IO ()
main = getLine >>= solve

module Main where

import Data.List (foldl')

main :: IO ()
main = interact solve

solve :: String -> String
solve input = show len <> " " <> show count
  where
    states = foldl' toState [] input
    (len, count) = foldl' foldBest (0, 1) states

data State = Open | Close | Replace !Int deriving (Show)

foldBest :: (Int, Int) -> State -> (Int, Int)
foldBest (l, c) (Replace k) | l == k = (k, c + 1)
foldBest (l, c) (Replace k) | l < k  = (k, 1)
foldBest s      _                    = s

toState :: [State] -> Char -> [State]
toState   s                            '(' = Open:s
toState  (Replace k:Open:Replace n:s)  ')' = Replace (k + n + 2):s
toState  (Open:Replace n:s)            ')' = Replace (n + 2):s
toState  (Replace n:Open:s)            ')' = Replace (n + 2):s
toState  (Open:s)                      ')' = Replace 2:s
toState   s                            ')' = Close:s
toState   s                             _  = s

import Text.Printf

main = do
     line <- getLine
     putStrLn . (\(opt,cnt,_,_,_) -> printf "%d %d" (opt::Int) (cnt::Int))
              . foldl (\(opt,cnt,b,s,i) c ->
              if c == '(' then
                 (opt,cnt,b,i:s,i+1)
              else if null s then
                   (opt,cnt,i,[],i+1)
              else let s' = tail s
                       opt' = i - (if null s' then b else head s')
                   in  if opt' > opt then
                          (opt',1,b,s',i+1)
                       else
                          (opt,cnt+(if opt' == opt then 1 else 0),b,s',i+1)
              ) (0,1,-1,[],0) $ line

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

  let
    max' l' (l, c)
      | l' > l = (l', 1)
      | l == l' = (l, c+1)
      | otherwise = (l, c)

    scan i [] [0] m = max' (i-1) m
    scan _ [] _ m = m
    scan i ('(':s) st m = scan (i+1) s (i:st) m
    scan i (')':s) [] m = scan (i+1) s [] m
    scan i (')':s) (j:st) m = scan (i+1) s st $ max' (i-j+1) m

    (l, c) = scan 1 s [0] (0, 1)

  putStrLn $ show l ++ " " ++ show c

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

  let
    max' l' (l, c)
      | l' > l = (l', 1)
      | l == l' = (l, c+1)
      | otherwise = (l, c)

    scan [] _ l m = m
    scan (c:s) d l m
        | d' < 0 = scan s 0 0 m
        | d' == 0 = scan s d' (l+1) $ max' (l+1) m
        | otherwise = scan s d' (l+1) m
      where
        d' = d + if c == '(' then 1 else -1

    (l, c) = scan s 0 0 (0, 1)

  putStrLn $ show l ++ " " ++ show c

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

  let
    max' l' (l, c)
      | l' > l = (l', 1)
      | l == l' = (l, c+1)
      | otherwise = (l, c)

    scan _ [] _ m = m
    scan i ('(':s) st m = scan (i+1) s (i:st) m
    scan i (')':s) [] m = scan (i+1) s [] m
    scan i (')':s) (j:st) m = scan (i+1) s st $ max' (i-j+1) m

    (l, c) = scan 1 s [] (0, 1)

  putStrLn $ show l ++ " " ++ show c

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

type Index = Int
type Longest = Int
type Count = Int
type State = ([Index], (Longest, Count))

automata :: State -> (Index, Char) -> State
automata state@(stack, best) (i, c)
  | c == '('   = (i : stack, best)
  | null stack = state
  | otherwise  = update state i

update :: State -> Index -> State
update (j : stack, best@(longest, _)) i =
  case compare l longest of
    LT -> (stack, best)
    EQ -> (stack, fmap succ best)
    GT -> (stack, (l, 1))
 where l = i - j + 1

exec :: String -> (Longest, Count)
exec = snd . foldl' automata ([], (0, 1)) . zip [0 ..]

solve :: String -> IO ()
solve = do
  (v, n) <- exec
  return $ printf "%d %d\n" v n

main = getLine >>= solve

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

type Depth = Int
type Score = Int
type Count = Int
type State = ((Depth, Score), (Score, Count))

updateBest :: State -> State
updateBest (state@(d, s), best@(v, n))
  | s < v || s == 0 = (state, best)
  | s == v          = (state, (v, n + 1))
  | s > v           = (state, (s, 1))

automata :: State -> Char -> State
automata ((d, s), best@(v, n)) c
  | c == '('  = ((d + 1, s), best)
  | d > 0     = updateBest ((d - 1, s + 2), best)
  | d == 0    = updateBest ((0, 0), best)
  | d < 0     = error "automata: Never happens!"
 where

exec :: String -> (Score, Count)
exec = snd . foldl' automata ((0, 0), (0, 1))

solve :: String -> IO ()
solve = do
  (v, n) <- exec
  return $ printf "%d %d\n" v n

main = getLine >>= solve

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

type Depth = Int
type Score = Int
type Count = Int
type State = ((Depth, Score), (Score, Count))

automata :: State -> Char -> State
automata ((d, s), best@(v, n)) c
  | c == '\0' = updateBest
  | c == '('  = ((d + 1, s), best)
  | d > 0     = ((d - 1, s + 2), best)
  | d == 0    = updateBest
  | d < 0     = error "automata: Never happens!"
 where
  updateBest
    | s < v || s == 0 = ((0, 0), best)
    | s == v          = ((0, 0), (v, n + 1))
    | s > v           = ((0, 0), (s, 1))

exec :: String -> (Score, Count)
exec = snd . (`automata` '\0') . foldl' automata ((0, 0), (0, 1))

solve :: String -> IO ()
solve = do
  (v, n) <- exec
  return $ printf "%d %d\n" v n

main = getLine >>= solve

import Text.Printf

main = do
     line <- getLine
     putStrLn . (\(opt,cnt,_,_,_) -> printf "%d %d" (opt::Int) (cnt::Int))
              . foldl (\(opt,cnt,b,s,i) c ->
              if c == '(' then
                 (opt,cnt,b,i:s,i+1)
              else if null s then
                   (opt,cnt,i,[],i+1)
              else let s' = tail s
                       opt' = i - (if null s' then b else head s')
                   in  if opt' > opt then
                          (opt',1,b,s',i+1)
                       else
                          (opt,cnt+(if opt' == opt then 1 else 0),b,s',i+1)
              ) (0,0,-1,[],0) $ line

module Main where

import Data.List (foldl')

main :: IO ()
main = interact solve

solve :: String -> String
solve input = show len <> " " <> show count
  where
    states = foldl' toState [] input
    (len, count) = foldl' foldBest (0, 1) states

data State = Open | Close | Replace !Int

foldBest :: (Int, Int) -> State -> (Int, Int)
foldBest (l, c) (Replace k) | l == k = (k, c + 1)
foldBest (l, c) (Replace k) | l < k  = (k, 1)
foldBest s      _                    = s

toState :: [State] -> Char -> [State]
toState   s                            '(' = Open:s
toState  (Replace k:Open:Replace n:s)  _   = Replace (k + n + 2):s
toState  (Open:Replace n:s)            _   = Replace (n + 2):s
toState  (Replace n:Open:s)            _   = Replace (n + 2):s
toState  (Open:s)                      _   = Replace 2:s
toState   s                            _   = Close:s