-- Vicfred
-- https://codeforces.com/problemset/problem/492/B

import Data.List

solve :: Int -> [Int] -> Double
solve l a = max (fromIntegral (max (head sa) (l - last sa))) x
    where sa = sort a
          x  = (fromIntegral . maximum $ 0 : zipWith (-) (tail sa) sa) / 2

main :: IO ()
main = do
    [_, l] <- fmap (map read . words) getLine
    a <- fmap (map read . words) getLine
    print $ solve l a

import Data.List
import Control.Applicative

main :: IO ()
main = interact solve

solve :: String -> String
solve s = show $ maximum [start, end, middle / 2]
    where (_:l:as) = read <$> words  s :: [Double]
          (start:xs) = sort as
          end = l - last (start:xs)
          middle
            |null xs = 0
            |otherwise = maximum $ zipWith (-) xs (start:xs)

import Data.List (sort, foldl')

light :: [Integer] -> Double
light ys = ((/ 2) . fromIntegral) $ fst $ foldl' func (2*x, x) xs
    where (x:xs) = sort ys
          func (m, prev) next = (max m $ next-prev, next)

readInt :: String -> Integer
readInt = read

main = do
    [_, f] <- fmap (map readInt) $ fmap words $ getLine
    second <- fmap (map readInt) $ fmap words $ getLine
    let sorted = sort second
    let l = last sorted
    let t = f + (f - l)*2
    let i = init sorted
    print $ light $ (f:l:t:i)

import Data.List

dist (x:xs) | xs /= [] = (head xs - x) : dist xs
            | otherwise = []

solve l xs = fromIntegral (maximum ds) / 2.0 where
--solve l xs = ys where
    ys = if head xs == 0 then xs else -(head xs) : xs
    zs = if last ys == l then ys else ys ++ [l + (l - last ys)]
    ds = dist zs

main = do
    line <- getLine
    let [n, l] = map read $ words line :: [Int]
    line <- getLine
    let xs = map read $ words line :: [Int]
    print $ solve l (sort xs)

{-# LANGUAGE BangPatterns #-}

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

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

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

main = do
	[ n, l ] <- getInts
	as <- sort <$> getInts

	printf "%.12f\n" $ ( maximum :: [Double] -> Double ) [ fromIntegral $ head as, fromIntegral $ ( l - last as ), fromIntegral ( maximum $ 0 : diffs as ) / 2.0 ]

diffs ( a : as )
	| null as = []
	| otherwise = ( head as - a ) : diffs as

import Data.List

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

solve :: [Int] -> Double
solve (n:l:a) =
    let sa = sort a
    in (fromIntegral (max ((head sa) * 2) (solve' sa))) * 0.5
    where
        solve' :: [Int] -> Int
        solve' [a] = (l - a) * 2
        solve' (a:b:x) = max (b - a) (solve' (b:x))

import Data.List

biggap lst max
  | (length lst) == 1 = max
  | otherwise = biggap (tail lst) (maximum [max, (head (drop 1 lst)) - (head lst)])

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

main = do
  ff <- getLine
  let n = (read (head (words ff)))::Int
      d = (read (last (words ff)))::Int
  gg <- getLine

  let aa = (conv (words gg) [])
      srted = sort aa

  let cc = (biggap srted 0)

      mx = (maximum [ realToFrac ( ((head srted) - 0)), realToFrac ( (d - (last srted))), ( (realToFrac cc) / (realToFrac 2))])
  putStrLn (show mx)

  -- putStrLn ("\n\n\n\n")
  -- putStrLn (show (cc / (realToFrac 2)))

import Data.List

main = do
  [n, l] <- fmap (map read . words) getLine
  xs <- fmap (map head . group . sort . map read . words) getLine

  let
    d = (head xs):(l - last xs):(zipWith (\a b -> (a+b)/2 - a) xs (tail xs))

  print $ maximum d

import Data.List
main = interact $ show . (/2) . h . g . map read . tail . words
f [l, x] = (l - x) * 2
f (l:x:y:z) = max (y - x) $ f (l:y:z)
g (a:b) = (a:sort b)
h (l:x:y) = max (x * 2) $ f(l:x:y)

import Control.Applicative
import Control.Monad.ST
import Data.Array.ST
import Data.List
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as B
showBI :: Int -> B.ByteString
showBI = B.pack . show
readBI :: B.ByteString -> Int
readBI = fst . fromJust . B.readInt
smap :: ((a,b) -> (c,b)) -> b -> [a] -> [c]
smap f s (l:ls) = (fst app):(smap f (snd app) ls)
                  where app = f (l,s)
smap _ _ [] = []

main = interact $ show . rd . lines
rd :: [String] -> Double
rd [nl,as] = go (read . last . words $ nl) (map read . words $ as)
go :: Double -> [Double] -> Double
go l as = maximum $ [frst,scnd,thrd]
          where frst = (/2) . maximum . smap (\(x,y) -> (x-y,x)) (head lst) $ lst
                scnd = head lst
                thrd = l-(last lst)
                lst = sort as

import Data.List
import Data.Maybe
import Data.Char
import Data.Function
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve. tail.concat.map (map read.words). take 2. lines
solve :: [Integer]->String
solve (x:xs) = show $ (/2) $ fromIntegral $ maximum $ zipWith (\a b->a-b) (s1:s1s) (s1:init (s1:s1s))
  where
  (s:ss)=sort  xs
  (s1:s1s)=(-s):(s:ss)++(x+x-last (s:ss)):[]

import           Data.List                      ( sort )

split :: Eq a => a -> [a] -> [[a]]
split _    [] = []
split cond xs = x : split cond (drop 1 y) where (x, y) = span (/= cond) xs

process :: Double -> [Double] -> Double
process _ [] = 0.0
process l xs =
  let xs' = zipWith (-) (xs ++ [l]) (0.0 : xs)
  in  maximum $ (minimum xs - 0.0) : (l - maximum xs) : (map (/ 2.0) xs')

main :: IO ()
main = do
  input <- getLine
  lamps <- getLine
  let xs = map (read :: String -> Integer) (split ' ' input)
  let ys = map (read :: String -> Double) (split ' ' lamps)
  let l  = xs !! 1
  print $ process (fromInteger l) (sort ys)

import Control.Monad
import Data.Array
import Data.Char
import Data.Functor
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import qualified Data.ByteString.Char8 as B
getList :: Read a => IO [a]
getList = map (read . B.unpack) . B.words <$> B.getLine
getIntList :: IO [Int]
getIntList = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

toD :: Int -> Double
toD = fromIntegral

solve :: Int -> [Int] -> Double
solve l a = max (toD (max (head sa) (l - last sa))) x
    where sa = sort a
          x  = (toD . maximum $ 0 : zipWith (-) (tail sa) sa) / 2

main :: IO ()
main = do
    [_, l] <- getIntList
    a <- getIntList
    print $ solve l a

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

process s q = maximum [(fromIntegral x ) /2 ,fromIntegral(s- maximum q), fromIntegral(minimum q)]
  where x1 = zipWith (-) (tail q) q
        x = if x1==[] then 0 else ( maximum x1)

main=do
     [n,s]<-map read <$> words <$>getLine ::IO [Int]
     q<- (sort <$> map read <$> words <$>getLine )::IO [Int]
     print $ process s q

import Data.List (sort)

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

solve :: [Double] -> Double
solve (_:l:as) = maximum (head bs : (l - last bs) : map (/2) (zipWith (-) (tail bs) bs))
  where bs = sort as
solve _ = undefined

import Data.List (group,sort)
readNums = fmap (map read . words) getLine
main = do
  [n,l] <- readNums
  as <- fmap (map ((*2) . head) . group . sort) readNums
  print $ fromIntegral (bsearch as 0 (2*l)) / 2
bsearch as l road = go l road
  where go l r | l + 1 == r = r
               | v m = go l m
               | otherwise = go m r
          where m = (l + r) `div` 2
        v r = all (uncurry cover) (zip as' (tail as'))
          where cover a b = b - a <= 2 * r
                as' = (-r) : as ++ [road+r]

import Data.List
import System.IO

readInput :: Read a => IO [a]
readInput = fmap (map read . words) getLine

getNLine :: Int -> IO [String]
getNLine n
    | n <= 0 = return []
    | otherwise = do
        x <- getLine
        xs <- getNLine $ n-1
        let ret = (x:xs)
        return ret

main :: IO ()
main = do
    n <- readInput :: IO [Int]
    l <- readInput :: IO [Int]
    let xs = reverse (last n : reverse (0 : sort l))
    let dis = zipWith (-) (tail xs)  xs
    -- print dis
    print $ solve dis
    -- putStrLn xs

solve :: [Int] -> Double
solve li =  max max_dis end_point
    where
        max_dis = fromIntegral (maximum li) / 2
        end_point = fromIntegral (max (head li) (last li))

import Control.Applicative
import Data.List

main= do
	[x1,b1]<- map read. words <$> getLine ::IO [Int]
	s<-sort .map read. words <$> getLine ::IO [Int]
	let s1= (head s ): s
	let sm = maximum $ zipWith (-) (tail s1) s1
	print $ maximum [ (fromIntegral sm)/2.0, fromIntegral (head s) , fromIntegral (b1-(last s))]

import Data.List
main = do
  [n, l] <- getLine >>= return. map read. words :: IO [Int]
  a <- getLine >>= return. Data.List.sort. map read. words :: IO [Double]
  print. maximum $ [head a, fromIntegral l - last a] ++ (map (/2).zipWith (-) (tail a) $ a)

import Data.List

answer :: [Integer] ->Int
answer xs =   if length xs == ans && odd (head xs - last xs) then ans +1 else ans
        where ans = snd $ foldl1 (\old@(e,ind) new@(ne, nin)-> if even (e - ne) then old else new ) (zip xs [1..])

readnl ::String-> [Double]
readnl  = fmap read .  words

distance ::[Double]->Double
distance [x] = x
distance (x:xs) =  maximum (zipWith (-) xs (x : xs))  / 2

someFunc :: IO ()
someFunc = do
    fl <- getLine
    let [n,l] = readnl fl
    sl <- getLine
    let coords = sort $ readnl sl
    let min =  head coords
    let max =  last coords
    print $ maximum [min, l-max, distance coords]

main :: IO ()
main = someFunc

import Data.List (sort)
import Text.Printf (printf)

process :: [Int] -> Int -> Double
process xs@(_:ys) l
    | ys == [] = max d0 dl
    | otherwise = maximum [d0, di/2, dl]
    where
        xs' = sort xs
        d0 = fromIntegral $ head xs'
        dl = fromIntegral $ l - last xs'
        di = fromIntegral $ maximum $ zipWith (-) (tail xs') xs'

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    [n,l] <- fmap (map readInt.words) getLine
    as <- fmap (map readInt.words) getLine
    printf "%.10f" $ process as l

import           Data.List                      ( elemIndex )
import           Data.Maybe                     ( fromJust )

split :: Eq a => a -> [a] -> [[a]]
split _    [] = []
split cond xs = x : split cond (drop 1 y) where (x, y) = span (/= cond) xs

process :: Double -> [Double] -> Double
process _ [] = 0.0
process l xs =
  let xs' =
          [ x - y
          | x <- xs
          , y <- xs
          , y /= x && fromJust (elemIndex x xs) - fromJust (elemIndex y xs) == 1
          ]
      xs'' = (minimum xs - 0) : (l - maximum xs) : (map (\x -> x / 2.0) xs')
  in  abs $ (maximum xs'')

main :: IO ()
main = do
  input <- getLine
  lamps <- getLine
  let xs = map (read :: String -> Integer) (split ' ' input)
  let ys     = map (read :: String -> Double) (split ' ' lamps)
  let (_, l) = (xs !! 0, xs !! 1)
  print $ process (fromInteger l) ys

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

process s q = (fromIntegral y ) /2
  where x = maximum $ zipWith (-) (tail q) q
        y = maximum [x, s- maximum q, minimum q]
main=do
     [s,n]<-map read <$> words <$>getLine ::IO [Int]
     q<- (sort <$> map read <$> words <$>getLine )::IO [Int]
     print $ process s q

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

process s q = maximum [(fromIntegral x ) /2 ,fromIntegral(s- maximum q), fromIntegral(minimum q)]
  where x = maximum $ zipWith (-) (tail q) q

main=do
     [s,n]<-map read <$> words <$>getLine ::IO [Int]
     q<- (sort <$> map read <$> words <$>getLine )::IO [Int]
     print $ process s q

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

process q = (fromIntegral x ) /2
  where x = maximum $ zipWith (-) (tail q) q
main=do
     [s,n]<-map read <$> words <$>getLine ::IO [Int]
     q<- (sort <$> map read <$> words <$>getLine )::IO [Int]
     print $ process q

import Data.List (group,sort)
readNums = fmap (map read . words) getLine
main = do
  [n,l] <- readNums
  as <- fmap (map ((*2) . head) . group . sort) readNums
  print $ fromIntegral (bsearch l as 0 (2*l)) / 2
bsearch road as l r = go l r
  where go l r | l + 1 == r = r
               | v m = go l m
               | otherwise = go m r
          where m = (l + r) `div` 2
        v r = all (uncurry cover) (zip as' (tail as'))
          where cover a b = b - a <= 2 * r
                as' = (-r) : as ++ [road+r]

import Data.List (group,sort)
readNums = fmap (map read . words) getLine
main = do
  [n,l] <- readNums
  as <- fmap (map ((*2) . head) . group . sort) readNums
  print $ fromIntegral (bsearch as 0 (2*l)) / 2
bsearch as l r = go l r
  where go l r | l + 1 == r = r
               | v m = go l m
               | otherwise = go m r
          where m = (l + r) `div` 2
        v r = all (uncurry cover) (zip as' (tail as'))
          where cover a b = b - a <= 2 * r
                as' = (-r) : as ++ [l+r]

import Data.List
import System.IO

readInput :: Read a => IO [a]
readInput = fmap (map read . words) getLine

getNLine :: Int -> IO [String]
getNLine n
    | n <= 0 = return []
    | otherwise = do
        x <- getLine
        xs <- getNLine $ n-1
        let ret = (x:xs)
        return ret

main :: IO ()
main = do
    n <- readInput :: IO [Int]
    l <- readInput :: IO [Int]
    let xs = reverse (last n : reverse (0 : sort l))
    let dis = zipWith (-) (tail xs)  xs
    print dis
    print $ solve dis
    -- putStrLn xs

solve :: [Int] -> Double
solve li =  max max_dis end_point
    where
        max_dis = fromIntegral (maximum li) / 2
        end_point = fromIntegral (max (head li) (last li))

import Data.List
eps = 1e-8
bin :: (Double -> Bool) -> Double -> Double -> Double
bin f l r
  | r - l < eps   = mid
  | f mid         = bin f l mid
  | otherwise     = bin f mid r
  where mid = (l + r) / 2
isOk :: [Double] -> Double -> Double -> Bool
go :: [(Double, Double)] -> Double -> Double -> Bool
go [] l r = r <= l
go cur l r
  | l < s     = False
  | otherwise = go state (max e l) r
  where (s, e):state = cur
isOk a l d =
  go state 0 l
  where state = Data.List.sort  [(x - d, x + d) | x <- a]
main = do
  [n, l] <- getLine >>= return. map read. words :: IO [Int]
  a <- getLine >>= return. map read. words :: IO [Double]
  let ll = fromIntegral l :: Double in print $ bin (isOk a ll) 0 ll

import Data.List (sort)
import Text.Printf (printf)

process :: [Int] -> Int -> Float
process xs l = maximum [d0, di/2, dl]
    where
        xs' = sort xs
        d0 = fromIntegral $ head xs'
        dl = fromIntegral $ l - last xs'
        di = fromIntegral $ maximum $ zipWith (-) (tail xs') xs'

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    [n,l] <- fmap (map readInt.words) getLine
    as <- fmap (map readInt.words) getLine
    printf "%.10f" $ process as l

import Data.List (sort)

process :: [Int] -> Int -> Float
process xs l = maximum [d0, di/2, dl]
    where
        xs' = sort xs
        d0 = fromIntegral $ head xs'
        dl = fromIntegral $ l - last xs'
        di = fromIntegral $ maximum $ zipWith (-) (tail xs') xs'

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    [n,l] <- fmap (map readInt.words) getLine
    as <- fmap (map readInt.words) getLine
    print $ process as l

import Data.List (sort, foldl')

light :: [Int] -> Double
light ys = ((/ 2) . fromIntegral) $ fst $ foldl' func (2*x, x) xs
    where (x:xs) = sort ys
          func (m, prev) next = (max m $ next-prev, next)

readInt :: String -> Int
readInt = read

main = do
    [_, f] <- fmap (map readInt) $ fmap words $ getLine
    second <- fmap (map readInt) $ fmap words $ getLine
    let l = last second
    let t = f + (f - l)*2
    let i = init second
    print $ light $ (f:l:t:i)

import Data.List (sort, foldl')

light :: [Int] -> Float
light ys = ((/ 2) . fromIntegral) $ fst $ foldl' func (2*x, x) xs
    where (x:xs) = sort ys
          func (m, prev) next = (max m $ next-prev, next)

main = do
    [_, f] <- fmap (map read) $ fmap words $ getLine
    second <- fmap (map read) $ fmap words $ getLine
    print $ light $ (f:second)

import Data.List (sort, foldl')

light :: [Int] -> Double
light ys = ((/ 2) . fromIntegral) $ fst $ foldl' func (2*x, x) xs
    where (x:xs) = sort ys
          func (m, prev) next = (max m $ next-prev, next)

main = do
    [_, f] <- fmap (map read) $ fmap words $ getLine
    second <- fmap (map read) $ fmap words $ getLine
    print $ light $ (f:second)

import Data.List (sort, foldl')

light :: [Int] -> Double
light ys = ((/ 2) . fromIntegral) $ fst $ foldl' func (2*x, x) xs
    where (x:xs) = sort ys
          func (m, prev) next = (max m $ next-prev, next)

readInt :: String -> Int
readInt = read

main = do
    [_, f] <- fmap (map readInt) $ fmap words $ getLine
    second <- fmap (map readInt) $ fmap words $ getLine
    let sorted = sort second
    let l = last sorted
    let t = f + (f - l)*2
    let i = init sorted
    print $ light $ (f:l:t:i)


import Control.Arrow ((>>>))

main :: IO ()
main = interact $ lines >>> drop 1 >>> process >>> map show >>> unlines

process :: [String] -> [Int]
process [] = []
process (nl:s:xs) = solve c0 c1 h s : process xs
  where
    [_, c0, c1, h] = map read . words $ nl

solve :: Int -> Int -> Int -> String -> Int
solve c0 c1 h s = min c0 (h + c1) * count '0' + min c1 (h + c0) * count '1'
  where
    count d = length (filter (== d) s)

module Main where

{-
calculatePrices :: Int -> [Int]
calculatePrices 0 = []
calculatePrices n = price:(calculatePrices $ n - 1)
    where price = 1
-}

calculatePrices :: Int -> IO ()

calculatePrice :: (Int, Int, Int) -> [Bool] -> Int -> Int

-- Helper functions

extractMeta :: String -> (Int, Int, Int)

convertString :: String -> [Bool]

split :: (Eq a) => a -> [a] -> [[a]]

calculatePrices 0 = return ()
calculatePrices n = do
    meta <- getLine
    string <- getLine
    putStrLn $ show $ calculatePrice (extractMeta meta) (convertString string) 0
    calculatePrices (n - 1)

calculatePrice _ [] acc = acc
calculatePrice (c0, c1, h) (True:ss) acc
    | c1 > h + c0 = calculatePrice (c0, c1, h) ss (acc + h + c0)
    | otherwise = calculatePrice (c0, c1, h) ss (acc + c1)

calculatePrice (c0, c1, h) (False:ss) acc
    | c0 > h + c1 = calculatePrice (c0, c1, h) ss (acc + h + c1)
    | otherwise = calculatePrice (c0, c1, h) ss (acc + c0)

extractMeta source = (read $ tokens !! 1, read $ tokens !! 2, read $ tokens !! 3)
    where tokens = split ' ' source

convertString [] = []
convertString ('0':ss) = False:(convertString ss)
convertString ('1':ss) = True:(convertString ss)

split _ [] = [[]]
split d (c:cs)
    | d == c = []:(split d cs)
    | otherwise = let (h:t) = split d cs in (c:h):t

main = do
    testCases <- getLine
    calculatePrices $ read testCases
    -- foldl (>>) (return ()) (map (putStrLn . show) $ calculatePrices (read testCases :: Int))


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

query :: [Int] -> Builder
query li = string7 "? " <> putInts li <> flush

finishSoln :: Int -> Int -> Int -> Int -> SP Builder
finishSoln currw x1 x2 x3 = let
  xs = [x1, x2, x3]
  y : _ = [1..4] \\ xs
  qs = map (flip delete $ y : xs) xs
  in  (foldMap query qs <>) <$> do
  nxs <- replicateM 3 getInt
  let  (z1, _) : (z2, _) : _ = sortOn snd $ zip (y : xs) (currw : nxs)
  pure $ string7 "! " <> putInts [z1, z2] <> flush

solnStep :: Int -> Int -> Int -> Int -> Int -> Int -> SP Builder
solnStep n i currw x1 x2 x3 = if  i > n
  then  finishSoln currw x1 x2 x3
  else  (<>) (query [x2, x3, i] <> query [x1, x3, i]) <$> do
  no1 <- getInt
  no2 <- getInt
  case  ()  of
    () | no1 >= max no2 currw  -> solnStep n (i + 1) no1 x2 x3 i
       | no2 >= max no1 currw  -> solnStep n (i + 1) no2 x1 x3 i
       | otherwise -> solnStep n (i + 1) currw x1 x2 x3

solve :: Int -> SP Builder
solve n = (query [1, 2, 3] <>) <$> do
  initw <- getInt
  solnStep n 4 initw 1 2 3

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    solve n

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

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

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

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

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

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

{-# LANGUAGE BangPatterns #-}
import Data.Bits
import Data.List
import Control.Monad
import System.IO
import qualified System.Exit as Exit

solve4 :: Int -> Int -> Int -> Int -> (Int, Int)
solve4 xa xb xc xd = case maxes of
  [x] -> (x, x)
  [x, y] -> (x, y)
  _ -> error $ "ambiguous: " ++ show maxes
  where
    m = maximum [xa, xb, xc, xd]
    maxes = filter ((/=0) . (.&. maxmap) . (1 `shiftL`)) [0..3]
    maxmap = foldl' (.&.) 0xf $ map snd $ filter ((==m) . fst)
      [ (xa, 0xe::Int)
      , (xb, 0xd)
      , (xc, 0xb)
      , (xd, 0x7)
      ]

query :: Int -> Int -> Int -> IO Int
query i j k = do
  putStrLn $ "? " ++ show (i+1) ++ " " ++ show (j+1) ++ " " ++ show (k+1)
  w <- readLn
  when (w == -1) Exit.exitSuccess
  return w

solve :: Int -> IO ()
solve n = do
  w2 <- query 0 1 2
  phase0 2 w2 3
  where
    phase0 best bestW !i
      | i >= n = phase1 best 9999 (-1) 2
      | otherwise = do
        wi <- query 0 1 i
        if wi > bestW
          then phase0 i wi (i+1)
          else phase0 best bestW (i+1)

    phase1 p best bestW i
      | i >= n = phase2 p best bestW
      | i == p = phase1 p best bestW (i+1)
      | otherwise = do
        wi <- query 0 p i
        if wi > bestW
          then phase1 p i wi (i+1)
          else phase1 p best bestW (i+1)

    phase2 p q w0pq = do
      --putStrLn $ "phase2: " ++ show (p, q)
      w01p <- query 0 1 p
      w01q <- query 0 1 q
      w1pq <- query 1 p q
      let !(ix, iy) = solve4 w1pq w0pq w01q w01p
      let [x, y] = map ([0, 1, p, q]!!) [ix, iy]
      putStrLn $ "! " ++ show (x+1) ++ " " ++ show (y+1)

main :: IO ()
main = do
  hSetBuffering stdout LineBuffering
  t <- readLn
  replicateM_ t $ do
    n <- readLn
    solve n

{-# LANGUAGE BangPatterns #-}
import Data.Bits
import Data.List
import Control.Monad
import System.IO
import qualified System.Exit as Exit

solve4 :: Int -> Int -> Int -> Int -> (Int, Int)
solve4 xa xb xc xd = case maxes of
  [x] -> (x, x)
  [x, y] -> (x, y)
  _ -> error $ "ambiguous: " ++ show maxes
  where
    m = maximum [xa, xb, xc, xd]
    maxes = filter ((/=0) . (.&. maxmap) . (1 `shiftL`)) [0..3]
    maxmap = foldl' (.&.) 0xf $ map snd $ filter ((==m) . fst)
      [ (xa, 0xe::Int)
      , (xb, 0xd)
      , (xc, 0xb)
      , (xd, 0x7)
      ]

query :: Int -> Int -> Int -> IO Int
query i j k = do
  putStrLn $ "? " ++ show (i+1) ++ " " ++ show (j+1) ++ " " ++ show (k+1)
  w <- readLn
  when (w == -1) Exit.exitSuccess
  return w

solve :: Int -> IO ()
solve n = do
  w2 <- query 0 1 2
  phase0 2 w2 3
  where
    phase0 best bestW !i
      | i >= n = do
        w2 <- query 0 best 2
        phase1 best 2 w2 3
      | otherwise = do
        wi <- query 0 1 i
        if wi > bestW
          then phase0 i wi (i+1)
          else phase0 best bestW (i+1)

    phase1 p best bestW i
      | i >= n = phase2 p best bestW
      | i == p = phase1 p best bestW (i+1)
      | otherwise = do
        wi <- query 0 p i
        if wi > bestW
          then phase1 p i wi (i+1)
          else phase1 p best bestW (i+1)

    phase2 p q w0pq = do
      --putStrLn $ "phase2: " ++ show (p, q)
      w01p <- query 0 1 p
      w01q <- query 0 1 q
      w1pq <- query 1 p q
      let !(ix, iy) = solve4 w1pq w0pq w01q w01p
      let [x, y] = map ([0, 1, p, q]!!) [ix, iy]
      putStrLn $ "! " ++ show (x+1) ++ " " ++ show (y+1)

main :: IO ()
main = do
  hSetBuffering stdout LineBuffering
  t <- readLn
  replicateM_ t $ do
    n <- readLn
    solve n


module Main where

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

import Data.Time.Calendar

main = interact (show . solve . map read . words . (!! 1) . lines)

divisors :: Int -> [Int]
divisors n = concat [[x, n `div` x] | x <- [1..((+1) $ ceiling $ sqrt $ fromIntegral n)], n `mod` x == 0]

solve :: [Int] -> Int
solve values = let n = length values in maximum $ map (score values) (filter (<= (n `div` 3)) $ divisors n)

score :: [Int] -> Int -> Int
score values k = maximum $ map sum $ getGroups values k

getGroups :: [Int] -> Int -> [[Int]]
getGroups xs k = transpose $ fixedGroups [] xs k where
    fixedGroups result [] _ = result
    fixedGroups result xs k = let (h, t) = splitAt k xs in fixedGroups (h : result) t k

import Data.Function (fix)

main = do
    n <- fmap read getLine
    t <- fmap (map read . words) getLine
    let count k = toList $ foldl (\zipper ti -> next $ update (+ti) zipper) (fromList $ replicate k 0) t
    print $ maximum $ concatMap count $ filter ((>= 3) . (n `div`)) $ divisors n

type Zipper a = ([a], [a])

next :: Zipper a -> Zipper a
next ([], [])   = error "next: Empty zipper"
next (xs, [])   = ([], reverse xs)
next (xs, y:ys) = (y:xs, ys)

update :: (a -> a) -> Zipper a -> Zipper a
update f ([], [])   = error "update: Empty zipper"
update f (xs, [])   = update f ([], reverse xs)
update f (xs, y:ys) = (xs, f y:ys)

fromList :: [a] -> Zipper a
fromList [] = error "fromList: Empty zipper"
fromList xs = ([], xs)

toList :: Zipper a -> [a]
toList (xs, ys) = reverse xs ++ ys

divisors n = filter ((==0) . (n `mod`)) [1..n-1]

import Data.List

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

solve (n:xss) = maximum (map solve' divisors) where
    xs = take n xss
    divisors = [x | x <- [3..n], n `mod` x == 0]
    solve' y = maximum (map sum (transpose (splitter (n `div` y) xs)))

splitter n xs = splitter' xs [] where
    splitter' [] acc = acc
    splitter' ls acc = splitter' ys (h:acc) where
        (h, ys) = splitAt n ls

import Array

getWords :: IO [String]
getWords = getLine >>= return . words

reads :: Read a => IO [a]
reads = getWords >>= return . (map read)

readArray :: Read e => IO (Array Int e)
readArray = do
    xs <- Main.reads
    return (listArray (0, length xs - 1) xs)

solve :: Array Int Int -> Int
solve array  =  maximum $ map sum (map getList [(s, r) | r <- remainders, s <- [0 .. n `div` r - 1]])
  where
    n  =  rangeSize $ bounds array
    remainders  =  filter (\m -> n `rem` m == 0) [3..n]

    getList :: (Int, Int) -> [Int]
    getList (s, r)  =  [array ! (s + i * (n `div` r)) | i <- [0 .. r - 1]]

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

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

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

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

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

solve (n, a) = maximum [ calc a (n `div` i)
                       | i <- [3..n]
                       , n `mod` i == 0
                       ]
  where
    calc a m = let arr = accumArray (+) 0 (1, m) (zip (cycle [1..m]) a) :: UArray Int Int
               in maximum (elems arr)

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

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

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

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

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

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

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

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

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

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

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

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

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

state = State

import Control.Applicative ((<$>), (<*>))
import Data.List (transpose, unfoldr)

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

solve :: Int -> [Int] -> Int
solve n ts = maximum [ maximum $ map sum $ transpose $ splitN (n `div` m) ts | m <- [3..n], n `mod` m == 0 ]

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

import Control.Applicative ((<$>), (<*>))
import Data.Maybe (fromJust)
import qualified Data.ByteString.Char8 as B
import Data.List (transpose, unfoldr)

main :: IO ()
main = solve <$> readLn <*> (map (fst . fromJust . B.readInt) . B.words <$> B.getLine) >>= print

solve :: Int -> [Int] -> Int
solve n ts = maximum [ maximum $ map sum $ transpose $ splitN (n `div` m) ts | m <- [3..n], n `mod` m == 0 ]

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

import Data.Array

divisors :: Int -> [Int]
divisors n = filter (\x -> n `mod` x == 0) [1..n]

getIndexes :: Int -> Int -> Int -> [Int]
getIndexes n period offset = take (n `div` period) $ map (\x -> x * period + offset) [0..]

getAllIndexes :: Int -> [[Int]]
getAllIndexes n = [getIndexes n period offset | period <- (divisors n), offset <- [0..period - 1], n `div` period >= 3]

solve :: Int -> [Int] -> Int
solve n bl = maximum $ map (sum . map (arr !)) $ getAllIndexes n
	where arr = listArray (0, n - 1) bl

main = do
	n <- readLn
	str <- getLine
	print $ solve n (map read $ words $ str)

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

solve' n list a = maximum . elems $
        (accumArray (+) 0 (0, a-1) [ (i `mod` a, num) | (i, num) <- list ] :: UArray Int Int)

solve :: Int -> [(Int, Int)] -> Int
solve n list = maximum [solve' n list (n `div` a) | a <- [3..n], n `mod` a == 0]

readInt = (\(Just (x,_)) -> x) . BS.readInt

main = do
    n <- liftM readInt BS.getLine
    list <- liftM (map readInt . BS.words) BS.getLine

    print $ solve n (zip [1..] list)

import Data.List
divisors :: Int -> [Int]
divisors n = filter (\x -> n `mod` x == 0) [3..n]
solve :: [Int] -> Int
solve (num:ts) = maximum . map solve' . divisors $ num
    where solve' y = maximum . map sum . transpose . split (num `div` y) $ ts
split :: Int -> [Int] -> [[Int]]
split n xs = split' [] xs
    where split' ps [] = ps
          split' ps qs = let (h, ys) = splitAt n qs in split' (h:ps) ys
main = putStrLn . show . solve . map read . words =<< getContents

module Main where

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

import Data.Time.Calendar

main = interact (show . solve . map read . words . (!! 1) . lines)

divisors :: Int -> [Int]
divisors n = concat [[x, n `div` x] | x <- [1..((+1) $ ceiling $ sqrt $ fromIntegral n)], n `mod` x == 0]

solve :: [Int] -> Int
solve values = maximum $ map (score values) (divisors $ length values)

score :: [Int] -> Int -> Int
score values k = maximum $ map sum $ getGroups values k

getGroups :: [Int] -> Int -> [[Int]]
getGroups xs k = transpose $ fixedGroups [] xs k where
    fixedGroups result [] _ = result
    fixedGroups result xs k = let (h, t) = splitAt k xs in fixedGroups (h : result) t k

import Control.Applicative ((<$>), (<*>))

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

solve :: Integer -> [Integer] -> Integer
solve n ts = maximum [ sum [ t | (i, t) <- zip [0..] ts, i `mod` k == l ] | k <- factors n, l <- [0..k-1] ]

factors :: Integral t => t -> [t]
factors n = [ m | m <- [1..n], n `mod` m == 0 ]

import Control.Applicative ((<$>), (<*>))

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

solve :: Integer -> [Integer] -> Integer
solve n ts = maximum [ sum [ t | (i, t) <- zip [0..] ts, i `mod` k == l ] | k <- factors n, k > 2, l <- [0..k-1] ]

factors :: Integral t => t -> [t]
factors n = [ m | m <- [1..n], n `mod` m == 0 ]


{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

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

main :: IO ()
main = do
  Just (n,_) <- BS.readInt <$> BS.getLine
  xs <- getLine
  let b = head xs
      xs1 = reverse xs
      e = head xs1
      prefixlen = fromIntegral $ length $ takeWhile (== b) xs
      suffixlen = fromIntegral $ length $ takeWhile (== e) xs1
      ans = if b == e then
              ((prefixlen + 1) * (suffixlen + 1)) `mod` modulus
            else
              (prefixlen + suffixlen + 1) `mod` modulus
  print ans

modulus :: Int64
modulus = 998244353

import Data.Int

heads s = (+1) . length . takeWhile id $ zipWith (==) s (tail s)

fromIntToInt64 :: Int -> Int64
fromIntToInt64 = fromIntegral

fromInt64toInt :: Int64 -> Int
fromInt64toInt = fromIntegral

cnt :: Int -> Int -> Int -> Int
cnt x y n | x + y <= n = fromInt64toInt $ (fromIntToInt64 (x + 1)) * (fromIntToInt64 (y + 1)) `mod` (fromIntToInt64 b)
          | otherwise = x * (x + 1) `div` 2 `mod` b
          where b = 998244353

solve :: String -> Int
solve s | (head rs) == (head s) = cnt (heads s) (heads rs) (length s)
        | otherwise             = (heads s) + (heads rs) + 1
        where rs = reverse s

main = do
    _ <- getLine
    s <- getLine
    -- print $ heads s
    print $ solve s

heads s = (+1) . length . takeWhile id $ zipWith (==) s (tail s)

cnt :: Int -> Int -> Int -> Int
cnt x y n | x + y < n = (x + 1) * (y + 1) `mod` b
          | otherwise = x * (x + 1) `div` 2 `mod` b
          where b = 998244353

solve :: String -> Int
solve s | (head rs) == (head s) = cnt (heads s) (heads rs) (length s)
        | otherwise             = (heads s) + (heads rs) + 1
        where rs = reverse s

main = do
    _ <- getLine
    s <- getLine
    -- print $ heads s
    print $ solve s

heads s = (+1) . length . takeWhile id $ zipWith (==) s (tail s)

cnt :: Int -> Int -> Int -> Int
cnt x y n | x + y <= n = (x + 1) * (y + 1) `mod` b
          | otherwise = x * (x + 1) `div` 2 `mod` b
          where b = 998244353

solve :: String -> Int
solve s | (head rs) == (head s) = cnt (heads s) (heads rs) (length s)
        | otherwise             = (heads s) + (heads rs) + 1
        where rs = reverse s

main = do
    _ <- getLine
    s <- getLine
    -- print $ heads s
    print $ solve s

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

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

main :: IO ()
main = do
  Just (n,_) <- BS.readInt <$> BS.getLine
  xs <- BS.getLine
  let beg = BS.head xs
      end = BS.last xs
      prefixlen = fromIntegral $ BS.length $ BS.takeWhile (== beg) xs
      suffixlen = fromIntegral $ BS.length $ snd $ BS.spanEnd (== end) xs
      ans = if beg == end then
              ((prefixlen + 1) * (suffixlen + 1)) `mod` modulus
            else
              (prefixlen + suffixlen + 1) `mod` modulus
  print ans

modulus :: Int64
modulus = 998244353

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

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

main :: IO ()
main = do
  Just (n,_) <- BS.readInt <$> BS.getLine
  xs <- BS.getLine
  let beg = BS.head xs
      end = BS.last xs
      prefixlen = BS.length $ BS.takeWhile (== beg) xs
      suffixlen = BS.length $ snd $ BS.spanEnd (== end) xs
      ans = if beg == end then
              ((prefixlen + 1) * (suffixlen + 1)) `mod` modulus
            else
              (prefixlen + suffixlen + 1) `mod` modulus
  print ans

modulus :: Int
modulus = 998244353

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

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

main :: IO ()
main = do
  Just (n,_) <- BS.readInt <$> BS.getLine
  xs <- BS.getLine
  let b = BS.head xs
      e = BS.last xs
      prefixlen = fromIntegral $ BS.length $ BS.takeWhile (== b) xs
      suffixlen = fromIntegral $ BS.length $ snd $ BS.spanEnd (== e) xs
      ans = if b == e then
              ((prefixlen + 1) * (suffixlen + 1)) `mod` modulus
            else
              (prefixlen + suffixlen + 1) `mod` modulus
  print ans

modulus :: Int64
modulus = 998244353

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

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

main :: IO ()
main = do
  Just (n,_) <- BS.readInt <$> BS.getLine
  xs <- BS.getLine
  let beg = BS.head xs
      end = BS.last xs
      prefixlen = BS.length $ BS.takeWhile (== beg) xs
      suffixlen = BS.length $ snd $ BS.spanEnd (== end) xs
      ans = if beg == end then
              ((prefixlen + 1) * (suffixlen + 1)) `mod` modulus
            else if suffixlen + prefixlen == n then
              n `mod` modulus
            else
              (prefixlen + suffixlen + 1) `mod` modulus
  print ans

modulus :: Int
modulus = 998244353


import Control.Monad (liftM, replicateM, when)
import Data.Char (ord)
import Data.List (intercalate, sortBy)
import Prelude hiding (reads)
import System.IO (hPutStrLn, stderr)
import System.CPUTime (getCPUTime)

timeout :: Bool
timeout  =  False

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

data Command  =  Go Int Char | Take | Destroy

solve :: [[Int]] -> [Command]
solve bombs  =  concatMap solve'
     $ sortBy compareBombs bombs
  where
   solve' [0, y]  =
    [
      Go (abs y) (goY y),
      Take,
      Go (abs y) (reverseY y),
      Destroy
    ]
   solve' [x, 0]  =
    [
      Go (abs x) (goX x),
      Take,
      Go (abs x) (reverseX x),
      Destroy
    ]
   solve' [x, y]  =
    [
      Go (abs x) (goX x),
      Go (abs y) (goY y),
      Take,
      Go (abs x) (reverseX x),
      Go (abs y) (reverseY y),
      Destroy
    ]
   goX a  =  if a > 0 then 'R' else 'L'
   goY a  =  if a > 0 then 'U' else 'D'
   reverseX a  =  if a > 0 then 'L' else 'R'
   reverseY a  =  if a > 0 then 'D' else 'U'
   compareBombs [x1, y1] [x2, y2]
     =  compare (abs x1 + abs y1) (abs x2 + abs y2)

print' :: Command -> String
print' (Go k c)  =  "1 " ++ show k ++ " " ++ [c]
print' Take  =  "2"
print' Destroy  =  "3"

main :: IO ()
main  =  do
    t0  <-  getCPUTime
    n  <-  readLn
    bombs  <-  replicateM n reads
    let commands  =  solve bombs
    --print $ length commands
    let zero  =  length $ filter (\[x,y] -> x == 0 || y == 0) bombs
    print (6 * (n - zero) + 4 * zero)
    mapM_ (putStrLn . print') commands
    t1 <- getCPUTime
    when timeout $
     hPutStrLn stderr $ concat ["Time = ", show (fromIntegral (t1 - t0) * 1e-12), " sec."]

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

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

calc :: [(Int, Int)] -> [[String]]
calc [] = []
calc ((x, y) : xs) = goX ++ goY ++ [["2"]] ++ backX ++ backY ++ [["3"]] ++ calc xs
	where
		goX
			| x < 0 = [["1", show (-x), "L"]]
			| x > 0 = [["1", show x, "R"]]
			| otherwise = []
		goY
			| y < 0 = [["1", show (-y), "D"]]
			| y > 0 = [["1", show y, "U"]]
			| otherwise = []
		backX
			| x < 0 = [["1", show (-x), "R"]]
			| x > 0 = [["1", show x, "L"]]
			| otherwise = []
		backY
			| y < 0 = [["1", show (-y), "U"]]
			| y > 0 = [["1", show y, "D"]]
			| otherwise = []

zipXY :: [Int] -> [(Int, Int)]
zipXY [] = []
zipXY (x : y : xs) = (x, y) : zipXY xs

handle :: [Char8.ByteString] -> [[String]]
handle (_ : xs) = [show $ length res] : res
	where
		px = sortBy (comparing (\(x, y) -> (abs x) + (abs y))) $ zipXY $ map readInt xs
		res = calc px

main :: IO ()
main = do
	input <-ByteString.getContents
	putStr $ unlines $ map unwords $ handle $ Char8.words input

import Data.List (sortBy)

main = interact $ encompase . map (map read) . map words . tail . lines

f = sortBy (\(d1, _, _) (d2, _, _) -> compare d1 d2) . map (\(x:y:[]) -> (x^2 + y^2, x, y))

encompase y = show (h x) ++ "\n" ++ g x
  where x = f y

g = unlines . concat . map g'
g' (_, x, y) = filter (/="") [gx x, gy y, "2", gx' x, gy' y, "3"]

gx x
  | x > 0 = "1 " ++ show(x) ++ " R"
  | x < 0 = "1 " ++ show (abs x) ++ " L"
  | otherwise = ""

gy y
  | y > 0 = "1 " ++ show(y) ++ " U"
  | y < 0 = "1 " ++ show (abs y) ++ " D"
  | otherwise = ""

gx' x
  | x > 0 = "1 " ++ show(x) ++ " L"
  | x < 0 = "1 " ++ show (abs x) ++ " R"
  | otherwise = ""

gy' y
  | y > 0 = "1 " ++ show(y) ++ " D"
  | y < 0 = "1 " ++ show (abs y) ++ " U"
  | otherwise = ""

h = sum . map h'
h' (_, x, y) = 2*(x'+y') + 2
  where x' = fromEnum ((abs x) /= 0)
        y' = fromEnum ((abs y) /= 0)

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

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

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

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

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

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

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

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

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

data Op = Move Int Dir | PickUp | Destroy
data Dir = R | L | U | D deriving(Show,Eq)

instance Show Op where
    show (Move i d) = "1 "++show i ++ " " ++ show d
    show PickUp = "2"
    show Destroy = "3"

main = B.interact $ B.words >>> map readInt >>> process

process (n:l) = B.unlines $ ((B.pack $ show m):)$ map (B.pack . show) $ solve points
    where
    points = go l []
    go [] !acc = acc
    go (x:y:l) !acc = go l ((x,y):acc)
    ans = solve points
    m = length ans

solve ps = concat $ map doit ps'
    where
    ps' = map snd $ sort [ (d,(x,y)) | (x,y) <- ps , let d = abs x + abs y]

doit (x,y) = move x y ++ [PickUp] ++ move (-x) (-y) ++ [Destroy]
move x y = moveH x ++ moveV y
moveH 0 = []
moveH x = [Move (abs x) (if x > 0 then R else L)]
moveV 0 = []
moveV y = [Move (abs y) (if y > 0 then U else D)]

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

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Ord

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

toPairs (x:y:xys) = (x,y) : toPairs xys
toPairs _ = []

data Operation = Op1 !Int !Dir
               | Op2
               | Op3

instance Show Operation where
  show (Op1 k dir) = unwords ["1",show k, show dir]
  show Op2 = "2"
  show Op3 = "3"

data Dir = R | L | U | D deriving Show

main :: IO ()
main = do
  n <- readLn :: IO Int
  xys <- sortBy (comparing $ \(x,y)->(abs x,abs y)).toPairs.map readInt.B.words <$> B.getContents
  let ops = filter (not.isStay) $ solve xys
  print $ length ops
  putStr.unlines $ map show ops

isStay :: Operation -> Bool
isStay (Op1 0 _) = True
isStay _ = False

solve :: [(Int,Int)] -> [Operation]
solve ((x,y):xys)
  | x>=0, y>=0 = Op1 x    R : Op1 y U    : Op2 : Op1 x L    : Op1 y D    : Op3 : solve xys
  | x<=0, y>=0 = Op1 (-x) L : Op1 y U    : Op2 : Op1 (-x) R : Op1 y D    : Op3 : solve xys
  | x<=0, y<=0 = Op1 (-x) L : Op1 (-y) D : Op2 : Op1 (-x) R : Op1 (-y) U : Op3 : solve xys
  | x>=0, y<=0 = Op1 x    R : Op1 (-y) D : Op2 : Op1 x L    : Op1 (-y) U : Op3 : solve xys
solve [] = []

module Main where
import System.IO
import Data.Maybe
import Data.List
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

solve :: Int -> [[Int]] -> [String]
solve n xs = (show steps):(printMoves xs)
	where steps = sum $ map moves xs

norm :: [Int] -> Int
norm [x,y] = abs x + abs y

moves :: [Int] -> Int
moves [0,0] = 0
moves [_,0] = 4
moves [0,_] = 4
moves [_,_] = 6

printMoves :: [[Int]] -> [String]
printMoves [] = []
printMoves (x:xs) = (printMove x) ++ (printMoves xs)

printMove :: [Int] -> [String]
printMove [x,0] = [ "1 " ++ (show $ abs x) ++ " " ++ h
                  , "2"
                  , "1 " ++ (show $ abs x) ++ " " ++ h'
                  , "3"]
	where (h,h') = if x > 0 then ("R","L") else ("L","R")
printMove [0,y] = [ "1 " ++ (show $ abs y) ++ " " ++ v
                  , "2"
                  , "1 " ++ (show $ abs y) ++ " " ++ v'
                  , "3"]
	where (v,v') = if y > 0 then ("U","D") else ("D","U")
printMove [x,y] = [ "1 " ++ (show $ abs x) ++ " " ++ h
                  , "1 " ++ (show $ abs y) ++ " " ++ v
                  , "2"
                  , "1 " ++ (show $ abs y) ++ " " ++ v'
                  , "1 " ++ (show $ abs x) ++ " " ++ h'
                  , "3"]
	where (h,h') = if x > 0 then ("R","L") else ("L","R")
	      (v,v') = if y > 0 then ("U","D") else ("D","U")

main :: IO ()
main = do
	n <- readInt `fmap` B.getLine
	xs <- (map (map readInt . C.words) . C.lines) `fmap` B.getContents
	putStr . unlines $ solve n (sortBy (\x y -> compare (norm x) (norm y)) xs)

readInteger :: C.ByteString -> Integer
readInteger = fst . fromJust . C.readInteger

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

import Control.Monad (liftM, replicateM, when)
import Data.Char (ord)
import Data.List (intercalate, sortBy)
import Prelude hiding (reads)
import System.IO (hPutStrLn, stderr)
import System.CPUTime (getCPUTime)

timeout :: Bool
timeout  =  False

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

data Command  =  Go Int Char | Take | Destroy

solve :: [[Int]] -> [Command]
solve bombs  =  concatMap solve'
     $ sortBy compareBombs bombs
  where
   solve' [0, y]  =
    [
      Go (abs y) (goY y),
      Take,
      Go (abs y) (reverseY y),
      Destroy
    ]
   solve' [x, 0]  =
    [
      Go (abs x) (goX x),
      Take,
      Go (abs x) (reverseX x),
      Destroy
    ]
   solve' [x, y]  =
    [
      Go (abs x) (goX x),
      Go (abs y) (goY y),
      Take,
      Go (abs x) (reverseX x),
      Go (abs y) (reverseY y),
      Destroy
    ]
   goX a  =  if a > 0 then 'R' else 'L'
   goY a  =  if a > 0 then 'U' else 'D'
   reverseX a  =  if a > 0 then 'L' else 'R'
   reverseY a  =  if a > 0 then 'D' else 'U'
   compareBombs [x1, y1] [x2, y2]
     =  compare (abs x1 + abs y1) (abs x2 + abs y2)

print' :: Command -> String
print' (Go k c)  =  "1 " ++ show k ++ " " ++ [c]
print' Take  =  "2"
print' Destroy  =  "3"

main :: IO ()
main  =  do
    t0  <-  getCPUTime
    n  <-  readLn
    bombs  <-  replicateM n reads
    let commands  =  solve bombs
    --print $ length commands
    let zero  =  length $ filter (\[x,y] -> x == 0 || y == 0) bombs
    print (6 * (n - zero) + 4 * zero)
    mapM_ (putStrLn . print') commands
    t1 <- getCPUTime
    when timeout $
     hPutStrLn stderr $ concat ["Time = ", show (fromIntegral (t1 - t0) * 1e-12), " sec."]

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

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Ord

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

data Operation = Op1 !Int !Dir
               | Op2
               | Op3

instance Show Operation where
  show (Op1 k dir) = unwords ["1",show k, show dir]
  show Op2 = "2"
  show Op3 = "3"

data Dir = R | L | U | D deriving Show

main :: IO ()
main = do
  n <- readLn :: IO Int
  xs <- map readInt.B.words <$> B.getContents
  let ops = filter (not.isStay) $ solve xs
  print $ length ops
  putStr.unlines $ map show ops

isStay :: Operation -> Bool
isStay (Op1 0 _) = True
isStay _ = False

solve :: [Int] -> [Operation]
solve (x:y:xys)
  | x>=0, y>=0 = Op1 x    R : Op1 y U    : Op2 : Op1 x L    : Op1 y D    : Op3 : solve xys
  | x<=0, y>=0 = Op1 (-x) L : Op1 y U    : Op2 : Op1 (-x) R : Op1 y D    : Op3 : solve xys
  | x<=0, y<=0 = Op1 (-x) L : Op1 (-y) D : Op2 : Op1 (-x) R : Op1 (-y) U : Op3 : solve xys
  | x>=0, y<=0 = Op1 x    R : Op1 (-y) D : Op2 : Op1 x L    : Op1 (-y) U : Op3 : solve xys
solve [] = []

module Main where
import System.IO
import Data.Maybe
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

solve :: Int -> [[Int]] -> [String]
solve n xs = (show steps):(printMoves xs)
	where steps = sum $ map moves xs

norm :: [Int] -> [Int] -> Int
norm [x1,y1] [x2,y2] = abs (x2-x1) + abs (y2-y1)

moves :: [Int] -> Int
moves [0,0] = 0
moves [_,0] = 4
moves [0,_] = 4
moves [_,_] = 6

printMoves :: [[Int]] -> [String]
printMoves [] = []
printMoves (x:xs) = (printMove x) ++ (printMoves xs)

printMove :: [Int] -> [String]
printMove [x,0] = [ "1 " ++ (show $ abs x) ++ " " ++ h
                  , "2"
                  , "1 " ++ (show $ abs x) ++ " " ++ h'
                  , "3"]
	where (h,h') = if x > 0 then ("R","L") else ("L","R")
printMove [0,y] = [ "1 " ++ (show $ abs y) ++ " " ++ v
                  , "2"
                  , "1 " ++ (show $ abs y) ++ " " ++ v'
                  , "3"]
	where (v,v') = if y > 0 then ("U","D") else ("D","U")
printMove [x,y] = [ "1 " ++ (show $ abs x) ++ " " ++ h
                  , "1 " ++ (show $ abs y) ++ " " ++ v
                  , "2"
                  , "1 " ++ (show $ abs y) ++ " " ++ v'
                  , "1 " ++ (show $ abs x) ++ " " ++ h'
                  , "3"]
	where (h,h') = if x > 0 then ("R","L") else ("L","R")
	      (v,v') = if y > 0 then ("U","D") else ("D","U")

main :: IO ()
main = do
	n <- readInt `fmap` B.getLine
	xs <- (map (map readInt . C.words) . C.lines) `fmap` B.getContents
	putStr . unlines $ solve n xs

readInteger :: C.ByteString -> Integer
readInteger = fst . fromJust . C.readInteger

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

calc :: [Int] -> [[String]]
calc [] = []
calc (x : y : xs) = goX ++ goY ++ [["2"]] ++ backX ++ backY ++ [["3"]] ++ calc xs
	where
		goX
			| x < 0 = [["1", show (-x), "L"]]
			| x > 0 = [["1", show x, "R"]]
			| otherwise = []
		goY
			| y < 0 = [["1", show (-y), "D"]]
			| y > 0 = [["1", show y, "U"]]
			| otherwise = []
		backX
			| x < 0 = [["1", show (-x), "R"]]
			| x > 0 = [["1", show x, "L"]]
			| otherwise = []
		backY
			| y < 0 = [["1", show (-y), "U"]]
			| y > 0 = [["1", show y, "D"]]
			| otherwise = []

handle :: [String] -> [[String]]
handle (sn : xs) = [show $ length res] : res
	where
		px = map read xs
		res = calc px

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

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

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

calc :: [(Int, Int)] -> [[String]]
calc [] = []
calc ((x, y) : xs) = goX ++ goY ++ [["2"]] ++ backX ++ backY ++ [["3"]] ++ calc xs
	where
		goX
			| x < 0 = [["1", show (-x), "L"]]
			| x > 0 = [["1", show x, "R"]]
			| otherwise = []
		goY
			| y < 0 = [["1", show (-y), "D"]]
			| y > 0 = [["1", show y, "U"]]
			| otherwise = []
		backX
			| x < 0 = [["1", show (-x), "R"]]
			| x > 0 = [["1", show x, "L"]]
			| otherwise = []
		backY
			| y < 0 = [["1", show (-y), "U"]]
			| y > 0 = [["1", show y, "D"]]
			| otherwise = []

zipXY :: [Int] -> [(Int, Int)]
zipXY [] = []
zipXY (x : y : xs) = (x, y) : zipXY xs

handle :: [Char8.ByteString] -> [[String]]
handle (_ : xs) = [show $ length res] : res
	where
		px = sortBy (comparing (\(x, y) -> x + y)) $ zipXY $ map readInt xs
		res = calc px

main :: IO ()
main = do
	input <-ByteString.getContents
	putStr $ unlines $ map unwords $ handle $ Char8.words input


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

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

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

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

main = do
    (n,m) <- readIntPair
    if m == 0 then
        putStrLn "YES"
    else do
        l <- sort <$> readInts
        let a = head l
        let b = last l
        if a == 1 || b == n then
            putStrLn "NO"
        else if all (\(k,a) -> a /= 1 || k <= 1) $ map (length &&& head) $ group $ zipWith (-) (tail l) l then
            putStrLn "YES"
        else
            putStrLn "NO"

import Control.Applicative
import Data.List

solve n a = if c then "YES" else "NO"
    where xs = sort a
          f xs = length xs < 3 || not ((xs!!0)+1 == xs!!1 && (xs!!1)+1 == xs!!2)
          c = null xs || (head xs /= 1 && last xs /= n && all f (tails xs))

main = do
    n:m:a <- map read . words <$> getContents
    putStrLn $ solve n a

import Control.Monad (liftM)
import Data.Char (ord)
import Data.List (intercalate, sort)

(<?>) :: a -> a -> Bool -> a
(<?>) a b p  =  if p then a else b

solve :: Int -> [Int] -> Bool
solve n as
  | 1 `elem` as  =  False
  | n `elem` as  =  False
  | otherwise  =  not $ threeInOrder $ sort as
  where
    threeInOrder (a:b:c:as)
      | a+1 == b && b+1 == c  =  True
      | otherwise  =  threeInOrder (b:c:as)
    threeInOrder _  =  False

main :: IO ()
main  =  do
    [n, m]  <-  reads
    if m == 0 then
        putStrLn "YES"
    else
      do
        as  <-  reads
        putStrLn $ ("YES" <?> "NO") $ solve n as

  where

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


import Control.Monad
import qualified Data.ByteString.Char8 as B

solve :: Int -> [Int] -> Integer
solve n b = fst $ foldl f (fromIntegral $ abs $ head b, head b) $ tail b
  where
    f :: (Integer, Int) -> Int -> (Integer, Int)
    f (opsCount, arrVal) elem = (opsCount + fromIntegral (abs $ arrVal - elem), elem)

main :: IO ()
main = do
  n <- liftM (maybe 0 fst . B.readInt) B.getLine
  b <- liftM (map (maybe 0 fst . B.readInt) . B.words) B.getLine
  print $ solve n b

--fast read
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Control.Applicative
readInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words a
readLists = readInts $ B.getLine
readLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.lines $ B.getContents
readMatrix = fmap readInts $ fmap B.lines $ B.getContents
answer [] res = 0
answer (a:as) res = abs (a-res) + answer as a
main = do
  n <- readLn::IO Int
  a <- map read <$>words <$> getLine ::IO [Integer]
  print $ answer a 0

import Control.Applicative

solve :: [Integer] -> Integer
solve [_] = 0
solve (x:y:ys) = abs (y-x) + solve (y:ys)

main :: IO ()
main = do
    n <- readLn :: IO Int
    bs <- map read . words <$> getLine
    print . solve $ 0 : bs

import Data.Int

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

solve :: Int64 -> [Int64] -> Int64
solve x [] = 0
solve x (y:ys) = abs (y-x) + solve y ys

import Data.Int

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

solve :: Integer -> [Integer] -> Integer
solve x [] = 0
solve x (y:ys) = abs (y-x) + solve y ys

module Main where

main :: IO ()
main = do
	n <- getInt
	as <- getInts
	print $ process as

getInt :: IO Integer
getInt = readLn

getInts :: IO [Integer]
getInts = do
	s <- getLine
	let ws = words s
	return $ map read ws

process :: [Integer] -> Integer
process = process' 0

process' :: Integer -> [Integer] -> Integer
process' start [] = 0
process' start (a : as) = if start < a
	then a - start + process' a as
	else start - a + process' a as

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

solve :: Integer -> [Integer] -> Integer
solve _ []    = 0
solve l (a:x) = (abs (a - l)) + (solve a x)

solve :: [Integer] -> Integer
solve (x:y:xs) = abs(x - y) + solve (y:xs)
solve _ = 0

main :: IO ()
main = do
    n <- getLine
    input <- getLine
    let arr = map read $ words input
    putStrLn $ show $ solve (0:arr)

import Data.Int

solve :: [Int64] -> Int64
solve (x:y:xs) = abs(x - y) + solve (y:xs)
solve _ = 0

main :: IO ()
main = do
    n <- getLine
    input <- getLine
    let arr = map read $ words input
    putStrLn $ show $ solve (0:arr)

import Data.List

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

solve :: Int -> [Int] -> Int
solve x [] = 0
solve x (y:ys) = abs (y-x) + solve y ys

main :: IO ()
main = do
    n <- getLine
    input <- getLine
    let arr = map read $ words input :: [Int]
    putStrLn $ show $ foldl (\acc x -> acc + abs (x - acc)) 0 arr

solve :: [Int] -> Int
solve (x:y:xs) = abs(x - y) + solve (y:xs)
solve _ = 0

main :: IO ()
main = do
    n <- getLine
    input <- getLine
    let arr = map read $ words input
    putStrLn $ show $ solve (0:arr)

--fast read
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Control.Applicative
readInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words a
readLists = readInts $ B.getLine
readLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.lines $ B.getContents
readMatrix = fmap readInts $ fmap B.lines $ B.getContents
answer [] res = 0
answer (a:as) res = abs (a-res) + answer as a
main = do
  n <- readLn::IO Int
  a <- readLists
  print $ answer a 0

--fast read
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Control.Applicative
readInts a = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.words a
readLists = readInts $ B.getLine
readLLists = fmap (map (fst . fromJust)) $ fmap (map B.readInt) $ fmap B.lines $ B.getContents
readMatrix = fmap readInts $ fmap B.lines $ B.getContents
main = do
  n <- readLn::IO Int
  a <- readLists
  print $ (a !! 0)  + (sum $ map abs $ zipWith (-) a (tail a))

import Control.Monad
import qualified Data.ByteString.Char8 as B

solve n b = foldl (\c x -> abs (x - c) + c) (abs $ head b) $ tail b

main :: IO ()
main = do
  n <- liftM (maybe 0 fst . B.readInt) B.getLine
  b <- liftM (map (maybe 0 fst . B.readInt) . B.words) B.getLine
  print $ solve n b

import Control.Applicative

solve :: [Int] -> Int
solve [_] = 0
solve (x:y:ys) = abs (y-x) + solve (y:ys)

main :: IO ()
main = do
    n <- readLn :: IO Int
    bs <- map read . words <$> getLine
    print . solve $ 0 : bs


main = getLine >> (interact $ unlines . map (solve . map read . words) . lines)

solve [a,b,n,s]
    | r <= b = "YES"
    | otherwise = "NO"
    where r = s - n * (min a $ s `div` n)

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

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

main = readInt >>= flip replicateM solve >>= mapM_ ( putStrLn . which "YES" "NO" )

solve = do
	[ a, b, n, s ] <- readInts
	let
		x = min a $ s `div` n
		remaining = s - x * n
	return $ remaining <= b

import Control.Monad

solve :: Integer -> Integer -> Integer -> Integer -> Bool
solve a b n s = rest<=b
  where
    rest = max (s-n*a) (mod s n)

routine :: IO ()
routine = do
  [a,b,n,s] <- fmap (map read.words) getLine
  putStrLn (if solve a b n s then "YES" else "NO")

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

-- http://codeforces.com/contest/1256/problem/A

data Case = Case { ns :: Int
                 , ones :: Int
                 , nValue :: Int
                 , total :: Int
                 }

data Answer = YES | NO deriving (Show)

toCase :: String -> Case
toCase line = do
  let ints = map read $ words line :: [Int]
  Case { ns = ints !! 0
       , ones = ints !! 1
       , nValue = ints !! 2
       , total = ints !! 3
       }

getUsedNs :: Case -> Int
getUsedNs (Case ns _ nValue total) = do
    let requiredNs = total `div` nValue
    min ns requiredNs

getUsedOnes :: Int -> Int -> Int -> Int
getUsedOnes totalN ones total = do
    let requiredOnes = total - totalN
    min ones requiredOnes

toAnswer :: Bool -> Answer
toAnswer boolean
  | boolean = YES
  | otherwise = NO

solve :: Case -> Answer
solve (Case ns ones nValue total) = do
  toAnswer (totalN + usedOnes == total)
  where usedNs = getUsedNs (Case ns ones nValue total)
        totalN = usedNs * nValue
        usedOnes = getUsedOnes totalN ones total

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

main = interact main'
main' =
    unlines . map (f . map read . words) . drop 1 . lines

f [a, b, n, s]
    =
        if not enough
        then "NO"
        else "YES"
    where
        req_a = min (s `div` n) a
        req_b = s - n * req_a
        enough = req_b <= b

import Control.Monad

solve :: Int -> Int -> Int -> Int -> Bool
solve a b n s = rest<=b
  where
    rest = max (s-n*a) (mod s n)

routine :: IO ()
routine = do
  [a,b,n,s] <- fmap (map read.words) getLine
  putStrLn (if solve a b n s then "YES" else "NO")

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

import Control.Monad

solve :: Int -> Int -> Int -> Int -> Bool
solve a b n s = rest<=b
  where
    rest = max (s-n*a) (mod s n)

routine :: IO ()
routine = do
  [a,b,n,s] <- fmap (map read.words) getLine
  putStrLn (if solve a b n s then "YES" else "NO")

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

-- http://codeforces.com/contest/1256/problem/A

data Case = Case { ns :: Int
                 , ones :: Int
                 , nValue :: Int
                 , total :: Int
                 }

data Answer = YES | NO deriving (Show)

toCase :: String -> Case
toCase line = do
  let ints = map read $ words line :: [Int]
  Case { ns = ints !! 0
       , ones = ints !! 1
       , nValue = ints !! 2
       , total = ints !! 3
       }

toAnswer :: Bool -> Answer
toAnswer boolean
  | boolean = YES
  | otherwise = NO

solve :: Case -> Answer
solve (Case ns ones nValue total)
  | ones >= total = YES
  | otherwise = toAnswer (intDivision <= ns && modValue <= ones)
  where intDivision = total `div` nValue
        modValue = total `mod` nValue

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

-- http://codeforces.com/contest/1256/problem/A

data Case = Case { ns :: Int
                 , ones :: Int
                 , nValue :: Int
                 , total :: Int
                 }

data Answer = YES | NO deriving (Show)

toCase :: String -> Case
toCase line = do
  let ints = map read $ words line :: [Int]
  Case { ns = ints !! 0
       , ones = ints !! 1
       , nValue = ints !! 2
       , total = ints !! 3
       }

toAnswer :: Bool -> Answer
toAnswer boolean
  | boolean = YES
  | otherwise = NO

solve :: Case -> Answer
solve (Case ns ones nValue total) =
  toAnswer (intDivision <= ns && modValue <= ones)
  where intDivision = total `div` nValue
        modValue = total `mod` nValue

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


import Data.List
import Data.Array
import Data.Char

vow 'a' = True
vow 'e' = True
vow 'i' = True
vow 'o' = True
vow 'u' = True
vow _ = False

solve [] _ _ _ = []
solve (x:xs) c last diff
	|(not (vow x)) && (c>=2) && ((x/=last) || diff) = ' ':x:(solve xs 1 x False)
	|(not (vow x)) && ((x/=last) || diff)= x:solve xs (c+1) x True
	|(not (vow x)) = x:solve xs (c+1) x diff
	|otherwise = x:solve xs 0 (head xs) False

main=do
	l<- getLine
	putStrLn (solve l 0 (head l) False)

is_vowel :: Char -> Bool
is_vowel 'a' = True
is_vowel 'e' = True
is_vowel 'i' = True
is_vowel 'o' = True
is_vowel 'u' = True
is_vowel ch  = False

f :: String -> String
f ""                            = ""
f (a:"")                        = a : ""
f (a:rema)                      = a : s' ++ sub_ans
                                where s  = takeWhile (\x -> x == a) rema
                                      t  = dropWhile (\x -> x == a) rema
                                      l = length s
                                      s' = if l == 0 then [head rema] else s
                                      t' = if l == 0 then tail rema else t
                                      sub_ans = if null t' then "" else ' ' : f t'

g :: String -> String
g ""                        = ""
g (a:rema) | is_vowel a     = a : g rema
           | otherwise      = f (a:s) ++ g t
                            where s = takeWhile (not . is_vowel) rema
                                  t = dropWhile (not . is_vowel) rema

main :: IO ()
main = do
    line <- getLine
    putStrLn $ g line

import Data.List
import Data.Array
import Data.Char

vow 'a' = True
vow 'e' = True
vow 'i' = True
vow 'o' = True
vow 'u' = True
vow _ = False

solve [] _ = []
solve (x:xs) c
	|(not (vow x)) && (c==2) = ' ':x:(solve xs 0)
	|(not (vow x)) = x:solve xs (c+1)
	|vow x = x:solve xs 0
	|otherwise = x:solve xs c

main=do
	l<- getLine
	putStrLn (solve l 0)

import Data.List
import Data.Array
import Data.Char

vow 'a' = True
vow 'e' = True
vow 'i' = True
vow 'o' = True
vow 'u' = True
vow _ = False

solve [] _ = []
solve (x:xs) c
	|(not (vow x)) && (c==2) = ' ':x:(solve xs 0)
	|(not (vow x)) = x:solve xs (c+1)
	|otherwise = x:solve xs c

main=do
	l<- getLine
	putStrLn (solve l 0)

is_vowel :: Char -> Bool
is_vowel 'a' = True
is_vowel 'e' = True
is_vowel 'i' = True
is_vowel 'o' = True
is_vowel 'u' = True
is_vowel ch  = False

f :: String -> String
f ""                            = ""
f (a:"")                        = a : ""
f (a:b:"")                      = a : b : ""
f (a:rema)                      = a : s' ++ (' ' : f t')
                                where s  = takeWhile (\x -> x == a) rema
                                      t  = dropWhile (\x -> x == a) rema
                                      l = length s
                                      s' = if l == 0 then [head rema] else s
                                      t' = if l == 0 then tail rema else t

g :: String -> String
g ""                        = ""
g (a:rema) | is_vowel a     = a : g rema
           | otherwise      = f (a:s) ++ g t
                            where s = takeWhile (not . is_vowel) rema
                                  t = dropWhile (not . is_vowel) rema

main :: IO ()
main = do
    line <- getLine
    putStrLn $ g line

is_vowel :: Char -> Bool
is_vowel 'a' = True
is_vowel 'e' = True
is_vowel 'i' = True
is_vowel 'o' = True
is_vowel 'u' = True
is_vowel ch  = False

f :: String -> String
f ""                            = ""
f (a:"")                        = a : ""
f (a:rema)      | is_vowel a    = a : f rema
                | otherwise  = let s'' = takeWhile is_vowel t'
                                   t'' = dropWhile is_vowel t'
                                   in a : s' ++ s'' ++ (' ' : f t'')
                where s  = takeWhile (\x -> x == a) rema
                      t  = dropWhile (\x -> x == a) rema
                      l = length s
                      s' = if l == 0 then [head rema] else s
                      t' = if l == 0 then tail rema else t

main :: IO ()
main = do
    line <- getLine
    putStrLn $ f line


import Control.Monad
-- import Data.List

getStrList :: IO [String]
getStrList = fmap words getLine

getIntList :: IO [Integer]
getIntList = fmap (map read) getStrList

f :: Integer -> Integer -> Integer
f c s
    | r == 0 = c * d * d
    | otherwise = r * (d + 1) * (d + 1) + (c - r) * d * d
    where r = s `mod` c
          d = s `div` c

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

import Control.Monad

solve :: Int -> Int -> Int
solve x y = (n^2)*(x-m)+((n+1)^2)*m
  where
    n = y `div` x
    m = y `mod` x

routine :: IO ()
routine = do
   l <- fmap ((map read).words) getLine
   print $ solve (l!!0) (l!!1)

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


import qualified Data.Map as M
import Control.Applicative
import Data.List
import Data.Function

f _ m [] = fst $ minimumBy (compare `on` snd) $ M.assocs m
f i m (a:as) = f (i+1) (M.alter (\_ -> Just i) a m) as

main = do
    n <- readLn :: IO Int
    as <- map (read :: String -> Int ) . words <$> getLine
    let b = f 0 M.empty as
    print b

import qualified Data.IntMap as M
import Data.List
import Data.Function
main = getLine >> getLine >>= print . fst . minimumBy (compare `on` snd) . M.assocs . foldl' (\m (i, c) -> M.insert c i m) M.empty . zip [1..] . map read . words

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU
{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as C
import qualified Data.IntMap as I
import Data.List (foldl')
import Data.Maybe

readI = fst . fromJust . C.readInt

main = C.interact $ C.pack . solve . map readI . C.words

solve (n:xs) = show $ ans
    where
        ans = snd $ minimum $ I.elems mp
        ys = zip [0..] xs
        mp = foldl' f I.empty ys
        f m v@(_,k) = I.insert k v m

import qualified Data.Map.Strict as M
import qualified Data.ByteString.Char8 as B
import Control.Applicative
import Data.List
import Data.Function
import Data.Maybe

f _ m [] = fst $ minimumBy (compare `on` snd) $ M.assocs m
f i m (a:as) = f (i+1) (M.alter (\_ -> Just i) a m) as

main = do
    n <- readLn :: IO Int
    as <- map (fst . fromJust . B.readInt ) . B.words <$> B.getLine
    let b = f 0 M.empty as
    print b


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

main = getLine >>= test.read
test :: Integer -> IO ()
test 0 = return ()
test t = do
  (n:x:_) <- map read.words <$> getLine
  as <- map read.words <$> getLine
  let m = maximum as
  print (if any (== x) as then 1 else max 2 $ div x m + fromEnum (mod x m /= 0))
  test (t - 1)

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

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

solve :: Int -> [Int] -> Int
solve x l
  | x `elem` l = 1
  |otherwise = max 2 (ceiling (x % max1))
  where
    max1 = maximum l

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

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

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

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

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

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

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

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

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

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

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

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

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

f1 :: EIO ()
f1 = do
    (n, x) <- liftM2 (,) get get
    as <- replicateM n get
    putln $ f2 as x

f2 :: [Int64] -> Int64 -> Int64
f2 as x = minimum $ fmap (\k -> if (mod x k) == 0 then (div x k) else max (div (x + k - 1) k) 2) as

import Control.Monad

doit :: IO ()
doit = do
  [_, x] <- fmap (map read . words) getLine
  tmp <- fmap (map read . words) getLine
  print $ if x `elem` tmp then 1 else
          let y = maximum tmp
          in 2 `max` ((x + y - 1) `div` y)

main = readLn >>= flip replicateM_ doit

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

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

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

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

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

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

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

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

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

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

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

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

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

f1 :: EIO ()
f1 = do
    (n, x) <- liftM2 (,) get get
    as <- replicateM n get
    putln $ f2 as x

f2 :: [Int64] -> Int64 -> Int64
f2 as x =   let k = maximum as
            in
            if (mod x k) == 0 then (div x k) else max (div (x + k - 1) k) 2


import Data.List (sort)
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Ratio (Ratio, (%), numerator, denominator)

solve :: Integer -> [Integer] -> Ratio Integer
solve n a = inc + sum out
    where
    dist = zipWith (-) (tail a) a :: [Integer]
    out = zipWith (\d k -> 2 * k * (n - k) * d % n) dist [1..]
    inc = sum $ (% n) <$> a :: Ratio Integer

wrap :: Int -> [Int] -> [String]
wrap n a = [show i, " ", show j]
    where
    out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Integer
    [i, j] = ($ out) <$> [numerator, denominator] :: [Integer]

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = parse <$> B.getLine >>= \[n] -> parse <$> B.getLine >>= \a ->
    mapM_ putStr $ wrap n a

import Data.Int (Int64)
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString.Char8 as C
import Data.Ratio (Ratio, (%), numerator, denominator)

solve :: Int64 -> [Int64] -> Ratio Int64
solve n a = (sum a + x + y) % n
    where
    x = (2*) . sum . zipWith (\i j -> (2 * i + 1 - n) * j) [1..n - 2] $ tail a
    y = 2 * (n - 1) * (last a - head a)

wrap :: Int -> [Int] -> [String]
wrap n a = [show i, " ", show j]
    where
    out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Int64
    [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = parse <$> B.getLine >>= \[n] -> parse <$> B.getLine >>= \a ->
    mapM_ putStr $ wrap n a

import Data.List
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

main :: IO()
main = putStrLn . unwords . map show . solve . map (fst . fromJust . C.readInteger) . C.words =<< B.getContents

solve :: [Integer] -> [Integer]
solve (n:a) = let sorted = sort a
                  relativeDist = sum $ calcRelativeDist 1 (head sorted) 0 (tail sorted)
                  absoluteDist = sum a
                  totalDist = 2 * relativeDist + absoluteDist
                  common = gcd totalDist n
              in  [div totalDist common, div n common]

calcRelativeDist :: Integer -> Integer -> Integer -> [Integer] -> [Integer]
calcRelativeDist i last dist []    = [dist]
calcRelativeDist i last dist (a:s) = dist : calcRelativeDist (i + 1) a (dist + i * (a - last)) s

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

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

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

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

casti = fromIntegral

main = do
    n <- readInt <$> B.getLine
    l <- map readInt . B.words <$> B.getLine
    let r = solve n l
    putStrLn $ show (numerator r) ++ " "++ show (denominator r)

solve :: Int -> [Int] -> Rational
solve n l = foldl' f s1 (zip3 (tail l') sums [1..])
    where
    l' = map casti (sort l)
    sums = scanl1 (+) $ zipWith (*) l' [ 4*i-1 | i <- [1..]]
    s1 = head l'
    f a (b,s,n) = a +( (2*n+1)*b - s/n) / (n+1)

import Data.Int (Int64)
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString.Char8 as C
import Data.Ratio (Ratio, (%), numerator, denominator)

solve :: Int64 -> [Int64] -> Ratio Int64
solve n a = inc + 2 * sum out
    where
    dist = zipWith (-) (tail a) a :: [Int64]
    out = zipWith (\d k -> k * (n - k) * d % n) dist [1..] :: [Ratio Int64]
    inc = sum a % n :: Ratio Int64

wrap :: Int -> [Int] -> [String]
wrap n a = [show i, " ", show j]
    where
    out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Int64
    [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = parse <$> B.getLine >>= \[n] -> parse <$> B.getLine >>= \a ->
    mapM_ putStr $ wrap n a

import Data.Int (Int64)
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Ratio (Ratio, (%), numerator, denominator)

solve :: Int64 -> [Int64] -> Ratio Int64
solve n a = inc + sum out
    where
    dist = zipWith (-) (tail a) a :: [Int64]
    out = zipWith (\d k -> 2 * k * (n - k) * d % n) dist [1..] :: [Ratio Int64]
    inc = sum a % n :: Ratio Int64

wrap :: Int -> [Int] -> [String]
wrap n a = [show i, " ", show j]
    where
    out = solve (fromIntegral n) (fromIntegral <$> 0:sort a) :: Ratio Int64
    [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = parse <$> B.getLine >>= \[n] -> parse <$> B.getLine >>= \a ->
    mapM_ putStr $ wrap n a

import Data.Int (Int64)
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import Control.Applicative (liftA, (<$>))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Ratio (Ratio, (%), numerator, denominator)

solve :: Int64 -> [Int64] -> Ratio Int64
solve n a = inc + sum out
    where
    dist = zipWith (-) (tail a) a :: [Int64]
    out = zipWith (\d k -> 2 * k * (n - k) * d % n) dist [1..] :: [Ratio Int64]
    inc = sum a % n :: Ratio Int64

wrap :: Int -> [Int] -> [String]
wrap n a = [show i, " ", show j]
    where
    out = solve (fromIntegral n) (fromIntegral <$> sort a) :: Ratio Int64
    [i, j] = ($ out) <$> [numerator, denominator] :: [Int64]

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = parse <$> B.getLine >>= \[n] -> parse <$> B.getLine >>= \a ->
    mapM_ putStr $ wrap n a


{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.List as L
import Data.Int (Int64)
--import Data.Char as C
--import Data.IntSet as S

test :: Int64 -> Int64 -> Int64 -> Int64 -> Bool
test n a b acc
  | acc > n = False
  | not good && a == 1 = False
  | otherwise = if good then True else test n a b $ a*acc
  where good = (mod (n-acc) b == 0)

solve :: String -> String
solve s = let [n, a, b] = map read $ words s  :: [Int64]
              res = test n a b 1
          in (if test n a b 1 then "Yes" else "No")

main = do
  t <- readLn :: IO Int
  lines <- sequence $ replicate t getLine
  let res = map solve lines
    in putStrLn $ L.intercalate "\n" res

import Control.Monad (replicateM_)

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

belongsToSet n a b pow
  | pow > n = False
  | (n - pow) `rem` b == 0 = True
  | a == 1 = False
  | otherwise = belongsToSet n a b (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet n a b 1 then "Yes" else "No"

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

import Control.Monad (replicateM_)

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

belongsToSet n a b = go 1 where
  go pow  | pow > n = False
          | (n - pow) `rem` b == 0 = True
          | a == 1 = False
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet n a b then "Yes" else "No"

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

import Control.Monad (replicateM_)

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

belongsToSet :: (Integer, Integer) -> Integer -> Bool
belongsToSet (a, b) n = go 1 where
  go pow  | pow > n = False
          | (n - pow) `mod` b == 0 = True
          | a == 1 = False
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet (a, b) n then "Yes" else "No"

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

import Control.Monad (replicateM_)

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

belongsToSet :: (Integer, Integer) -> Integer -> Bool
belongsToSet (a, b) n = go 1 where
  go pow  | pow > n = False
          | (n - pow) `rem` b == 0 = True
          | a == 1 = False
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet (a, b) n then "Yes" else "No"

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

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.List as L
import Data.Int (Int64)
--import Data.Char as C
--import Data.IntSet as S

test :: Int64 -> Int64 -> Int64 -> Int64 -> Bool
test n a b acc
  | acc > n = False
  | not good && a == 1 = False
  | otherwise = if good then True else test n a b $ a*acc
  where good = (mod (n-acc) b == 0)

solve :: IO ()
solve = do
  s <- getLine
  let [n, a, b] = map read $ words s  :: [Int64]
      res = test n a b 1
    in putStrLn (if test n a b 1 then "Yes" else "No")

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

import Control.Arrow ((>>>))
import Data.Bool (bool)

main :: IO ()
main = interact $
  lines
    >>> drop 1
    >>> map (words >>> map read >>> solve >>> bool "No" "Yes")
    >>> unlines

solve :: [Integer] -> Bool
solve [n, 1, b] = b == 1 || n `mod` b == 1
solve [n, a, b] = any ((== 0) . (`mod` b) . (n -)) $ takeWhile (<= n) $ iterate (a *) 1

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

solve n a b x
            | x > n = False
            | mod (n-x) b == 0 = True
            | a == 1 = False
            | otherwise =  solve n a b (x*a)

printResult = do
    [n,a,b] <- readInts
    putStrLn $ if solve n a b 1 then "Yes" else "No"

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

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

readInts = fmap (map read.words) getLine :: IO [Integer]
solve n a b temp r
    | temp > n = putStrLn"No"
    | (((mod temp b) == r) && (temp <= n)) = putStrLn"Yes"
    | otherwise = solve n a b (temp*a) r
printS = do
    [n,a,b]<-readInts
    let r = mod n b
    if ( (b==1) || (r == 1) || ((a==1) && (r==1)) ) then putStrLn"Yes"
    else do
        if a==1 then putStrLn"No"
        else solve n a b a r

main = do
    t<-readLn
    replicateM_ t printS

import Control.Monad (replicateM_)

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

belongsToSet :: (Integer, Integer) -> Integer -> Bool
belongsToSet (a, b) n = a /= 1 && go 1 where
  go pow  | pow > n = False
          | (n - pow) `rem` b == 0 = True
          | a == 1 = False
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet (a, b) n then "Yes" else "No"

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

import Control.Monad (replicateM_)

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

belongsToSet :: (Integer, Integer) -> Integer -> Bool
belongsToSet (a, b) n = a /= 1 && go 1 where
  go pow  | pow > n = False
          | (n - pow) `rem` b == 0 = True
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet (a, b) n then "Yes" else "No"

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

import Control.Monad (replicateM_)

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

belongsToSet :: (Int, Int) -> Int -> Bool
belongsToSet (a, b) n = go 1 where
  go pow  | a == 1 || pow > n = False
          | (n - pow) `rem` b == 0 = True
          | otherwise = go (a * pow)

solve :: IO ()
solve = do
  [n, a, b] <- readInts
  putStrLn $ if belongsToSet (a, b) n then "Yes" else "No"

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

import Control.Arrow ((>>>))
import Data.Bool (bool)

main :: IO ()
main = interact $
  lines
    >>> drop 1
    >>> map (words >>> map read >>> solve >>> bool "No" "Yes")
    >>> unlines

solve :: [Integer] -> Bool
solve [n, 1, b] = n `mod` b == 1
solve [n, a, b] = any ((== 0) . (`mod` b) . (n -)) $ takeWhile (<= n) $ iterate (a *) 1

import Control.Arrow ((>>>))
import Data.Bool (bool)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromMaybe)
import Data.List (unfoldr)

main :: IO ()
main = interact $
  lines
    >>> drop 1
    >>> map (words >>> map read >>> solve >>> bool "No" "Yes")
    >>> unlines

solve :: [Integer] -> Bool
solve [n, 1, b] = n `mod` b == 1
solve [n, a, b] = any ((== 0) . (`mod` b) . (n -)) $ takeWhile (<= n) $ iterate (a *) 1

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

solve n a b x
            | mod (n-x) b == 0 = True
            | x > n || a == 1 = False
            | otherwise =  solve n a b (x*a)

printResult = do
    [n,a,b] <- readInts
    putStrLn $ if solve n a b 1 then "Yes" else "No"

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