A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.A fixed point of a function is a point that is mapped to itself by the function. A permutation can be regarded as a bijective function. We'll get a definition of a fixed point in a permutation. An integer i is a fixed point of permutation a0, a1, ..., an - 1 if and only if ai = i. For example, permutation [0, 2, 1] has 1 fixed point and permutation [0, 1, 2] has 3 fixed points.You are given permutation a. You are allowed to swap two elements of the permutation at most once. Your task is to maximize the number of fixed points in the resulting permutation. Note that you are allowed to make at most one swap operation.

The first line contains a single integer n (1 ≤ n ≤ 105). The second line contains n integers a0, a1, ..., an - 1 — the given permutation.

Print a single integer — the maximum possible number of fixed points in the permutation after at most one swap operation.

import Control.Monad (liftM)
import Data.Array ((!), bounds, listArray)
import Data.List (intercalate)
import Prelude hiding (reads)

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

solve :: [Int] -> Int
solve xs  =  min n (k + l)
  where
    n  =  length xs
    a  =  listArray (0, n-1) xs
    k  =  length [0 | i <- [0 .. n-1], i == a ! i]
    l  =  if null [0 | i <- [0 .. n-1], i /= a ! i, i == a ! (a ! i)]
                 then 1 else 2

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

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

import Data.IntMap (IntMap, (!), foldlWithKey, fromList)

boolToInt :: Bool -> Integer
boolToInt True  = 1
boolToInt False = 0

stationaryCount :: IntMap Int -> Integer
stationaryCount = foldlWithKey (\z k x -> z + (boolToInt (k == x))) 0

hasTransp :: IntMap Int -> Bool
hasTransp perm = foldlWithKey (\z k x -> z || ((k /= x) && (perm ! x == k))) False perm

solve :: Integer -> [Int] -> Integer
solve n xs = case (hasTransp xs') of
                True  -> s + 2
                False -> s + (boolToInt $ n - s > 1)
         where xs' = fromList $ zip [0..] xs
               s = stationaryCount xs'
main = do
    [n] <- (map (read :: String -> Integer) . words) `fmap` getLine
    seq <- (map (read :: String -> Int) . words) `fmap` getLine
    print $ solve n seq

import Control.Applicative ((<$>), (<*>))
import Data.Array ((!), listArray)
import Data.List (sortBy)
import Data.Maybe (listToMaybe)

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

solve :: Int -> [Int] -> Int
solve n as = length [ a | (i, a) <- zip [0..] as, i == a ]
         + maybe 0 succ (listToMaybe (sortBy (flip compare) [ fromEnum (as' ! a == i) | (i, a) <- zip [0..] as, i /= a ]))
         where as' = listArray (0, n - 1) as

module Main where

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

main = do
    n <- read <$> getLine
    ns <- map read <$> words <$> getLine
    print $ solve n ns

solve :: Int -> [Int] -> Int
solve 1 _ = 1
solve 2 _ = 2
solve n ns =
    let arr = listArray (0, n-1) ns
        res = foldl' (\(m, b) i ->
                        if arr ! i == i
                        then (m + 1, b)
                        else (m, b || arr ! (arr ! i) == i)
                    ) (0, False) [0 .. n-1]
    in case res of
        (m, False) -> min n (m + 1)
        (m, _)     -> m + 2

module Main where

import Control.Applicative
import Data.Array

main = do
    n <- read <$> getLine
    ns <- map read <$> words <$> getLine
    print $ solve n ns

solve :: Int -> [Int] -> Int
solve 1 _ = 1
solve 2 _ = 2
solve n ns =
    let arr = listArray (0, n-1) ns
        res = foldl (\(m, b) i ->
                        if arr ! i == i
                        then (m + 1, b)
                        else (m, b || arr ! (arr ! i) == i)
                    ) (0, False) [0 .. n-1]
    in case res of
        (m, False) -> min n (m + 1)
        (m, _)     -> m + 2

module Main where

import Control.Applicative
import Data.Array

main = do
    n <- read <$> getLine
    ns <- map read <$> words <$> getLine
    print $ solve n ns

solve :: Int -> [Int] -> Int
solve 1 _ = 1
solve 2 _ = 2
solve n ns =
    let arr = listArray (0, n-1) ns
        res = foldr (\i (m, b) ->
                        if arr ! i == i
                        then (m + 1, b)
                        else (m, b || arr ! (arr ! i) == i)
                    ) (0, False) [0 .. n-1]
    in case res of
        (m, False) -> min n (m + 1)
        (m, _)     -> m + 2

main = do
    input <- getLine
    let n = read (input) :: Int
    input <- getLine
    let input' = zip [0..] (f $ split ' ' input)
    let orig = sum [ 1 | (a, b) <- input', a == b ]
    let swap = qsort [ (b, a) | (a, b) <- input' ]
    let count = sum [ 1 | ((a, b), (c, d)) <- (zip input' swap), b == d ]

    print (if orig == n then orig else (if orig < count then orig + 2 else orig + 1))

f :: [String] -> [Int]
f x = map read x

qsort :: (Ord a) => [a] -> [a]
qsort [] = []
qsort (x:xs) = qsort [ a | a <- xs, a <= x ] ++ [x] ++ qsort [ a | a <- xs, a > x ]

split' :: (Eq a) => a -> [a] -> [a] -> [[a]]
split' _ [] l = [l]
split' v (x:xs) l
   | x /= v = split' v xs (l ++ [x])
   | otherwise = [l] ++ split' v xs []

split :: (Eq a) => a -> [a] -> [[a]]
split v xs = split' v xs []

import Control.Monad (liftM, unless, when)
import Data.List (group, intercalate, sort)
import Data.Array
import Prelude hiding (reads)

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

main :: IO ()
main = do
  n <- getLine
  vals <- reads
  putStrLn $ show $ solve (read n) vals

foldla :: (b -> Int -> a -> b) -> b -> Array Int a -> b
foldla f z0 ar = go z0 lo
  where go z i
          | i > hi = z
          | otherwise = go (f z i (ar ! i)) $ i + 1
        (lo, hi) = bounds ar

samePos :: Array Int Int -> Int
samePos a = foldla (\acc idx val -> if idx == val then acc + 1 else acc) 0 a

improvement :: Array Int Int -> Int
improvement perm
  = foldla (\best idx val -> if idx == val then best
                             else if perm ! val == idx then 2
                                  else max 1 best) 0 perm

solve :: Int -> [Int] -> Int
solve n xs = (samePos perm) + (improvement perm)
  where
    dim = (0, n - 1)
    perm = array dim $ zip (range dim) xs

import Control.Monad (liftM)
import Data.Array ((!), bounds, listArray)
import Data.List (intercalate)
import Prelude hiding (reads)

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

solve :: [Int] -> Int
solve xs  =  min n (k + l)
  where
    n  =  length xs
    a  =  listArray (0, n-1) xs
    k  =  length [0 | i <- [0 .. n-1], i == a ! i]
    l  =  if null [0 | i <- [0, n-1], i /= a ! i, i == a ! (a ! i)]
                 then 1 else 2

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

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

module Main where

import Control.Applicative
import Data.Array

main = do
    n <- read <$> getLine
    ns <- map read <$> words <$> getLine
    print $ solve n ns

solve :: Int -> [Int] -> Int
solve n ns =
    let arr = listArray (0 :: Int,n-1) ns
        res = foldr (\i (m, b) ->
                        if arr ! i == i
                        then (m + 1, b)
                        else (m, arr ! (arr ! i) == i)
                    ) (0, False) [0 .. n-1]
    in case res of
        (m, False) -> min n (m + 1)
        (m,_) -> m + 2

module Main where

import Control.Applicative
import Data.Array

main = do
    n <- read <$> getLine
    ns <- map read <$> words <$> getLine
    print $ solve n ns

solve :: Int -> [Int] -> Int
solve 1 _ = 1
solve 2 _ = 2
solve n ns =
    let arr = listArray (0, n-1) ns
        res = foldr (\i (m, b) ->
                        if arr ! i == i
                        then (m + 1, b)
                        else (m, arr ! (arr ! i) == i)
                    ) (0, False) [0 .. n-1]
    in case res of
        (m, False) -> min n (m + 1)
        (m, _)     -> m + 2

module Main where

import Control.Applicative
import Data.Array

main = do
    n <- read <$> getLine
    ns <- map read <$> words <$> getLine
    print $ solve n ns

solve :: Int -> [Int] -> Int
solve 1 _ = 1
solve 2 _ = 2
solve n ns =
    let arr = listArray (0 :: Int,n-1) ns
        res = foldr (\i (m, b) ->
                        if arr ! i == i
                        then (m + 1, b)
                        else (m, arr ! (arr ! i) == i)
                    ) (0, False) [0 .. n-1]
    in case res of
        (m, False) -> min n (m + 1)
        (m,_) -> m + 2

main = do
    input <- getLine
    let n = read (input) :: Int
    input <- getLine
    let input' = zip [0..] (f $ split ' ' input)
    let orig = sum [ 1 | (a, b) <- input', a == b ]
    let swap = qsort [ (b, a) | (a, b) <- input' ]
    let count = sum [ 1 | ((a, b), (c, d)) <- (zip input' swap), b == d ]

    print (if count == n then orig else (if orig < count then orig + 2 else orig + 1))

f :: [String] -> [Int]
f x = map read x

qsort :: (Ord a) => [a] -> [a]
qsort [] = []
qsort (x:xs) = qsort [ a | a <- xs, a <= x ] ++ [x] ++ qsort [ a | a <- xs, a > x ]

split' :: (Eq a) => a -> [a] -> [a] -> [[a]]
split' _ [] l = [l]
split' v (x:xs) l
   | x /= v = split' v xs (l ++ [x])
   | otherwise = [l] ++ split' v xs []

split :: (Eq a) => a -> [a] -> [[a]]
split v xs = split' v xs []

main = do
    input <- getLine
    let n = read (input) :: Int
    input <- getLine
    let input' = zip [0..] (f $ split ' ' input)
    print (sum [1 | (a, b) <- input', a == b] + swap input' 0)

swap [] m = m
swap [_] m = m
swap ((x1,y1):x@(x2,y2):xs) m = swap (x:xs) (max m v)
    where v = (if x1 == y1 then -1 else 0) + (if x2 == y2 then -1 else 0) + (if x1 == y2 then 1 else 0) + (if x2 == y1 then 1 else 0)

f :: [String] -> [Int]
f x = map read x

split' :: (Eq a) => a -> [a] -> [a] -> [[a]]
split' _ [] l = [l]
split' v (x:xs) l
   | x /= v = split' v xs (l ++ [x])
   | otherwise = [l] ++ split' v xs []

split :: (Eq a) => a -> [a] -> [[a]]
split v xs = split' v xs []


Let's call a number a binary decimal if it's a positive integer and all digits in its decimal notation are either $$$0$$$ or $$$1$$$. For example, $$$1\,010\,111$$$ is a binary decimal, while $$$10\,201$$$ and $$$787\,788$$$ are not.Given a number $$$n$$$, you are asked to represent $$$n$$$ as a sum of some (not necessarily distinct) binary decimals. Compute the smallest number of binary decimals required for that.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$), denoting the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^9$$$), denoting the number to be represented.

For each test case, output the smallest number of binary decimals required to represent $$$n$$$ as a sum.

NoteIn the first test case, $$$121$$$ can be represented as $$$121 = 110 + 11$$$ or $$$121 = 111 + 10$$$.In the second test case, $$$5$$$ can be represented as $$$5 = 1 + 1 + 1 + 1 + 1$$$.In the third test case, $$$1\,000\,000\,000$$$ is a binary decimal itself, thus the answer is $$$1$$$.

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

module Main where

import           Data.Char
import           Data.List
import           Data.Functor
import           Control.Monad

main :: IO ()
main =
  getLine
    <&> read @Int
    >>= flip replicateM (getLine <&> map digitToInt)
    >>= mapM_ (print . maximum)

import Control.Monad

lgst :: [Char] -> Char -> [Char]
lgst [a] b = if a > b then [a] else [b]
lgst (a:xs) mx = if a>mx then lgst xs a else lgst xs mx

main = do
    times <- readLn
    replicateM_ times $ do
        n <- getLine
        let l = lgst n '0'
        putStrLn l

module Main where

main = interact solve

solve inp =
    let
        linp = lines inp
        t = read $ head linp :: Int
        xs = take t . tail $ linp
        logic x = maximum x
    in
        unlines . map ((\x -> x : "") . logic) $ xs

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

main :: IO ()
main = do
    s <- getLine
    let n = read s :: Int
    r <- forM [1..n] $ \_ -> do
        z <- getLine
        return (maximum z) :: IO Char
    putStrLn $ intersperse '\n' r

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.Int (Int64)
import Data.List as L
import qualified Data.Bits as Bits
import qualified Data.Char as Char
import qualified System.IO as Io

import Data.Word (Word8)
import qualified Data.ByteString as B
--import Data.IntSet

convert :: [Int] -> [[Int]]
convert xs
  | null xs || all (==0) xs = []
  | otherwise = nextnum : convert nextxs
  where nextnum = map (\x -> if x > 0 then 1 else 0) xs
        nextxs = map (\x -> if x > 0 then x-1 else 0) xs

solve :: IO ()
solve = do
  s <- getLine
  let dig = map Char.digitToInt $ s
      res = convert dig
    in putStrLn $ show $ length res

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

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

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

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    s <- readLine
    let  ans = P.foldl' max minBound s
    lift $ B.hPutBuilder stdout (B.char7 ans <> B.char7 '\n')

type SIO = StateT P.ByteString IO

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

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

import Control.Monad

solve 0 = 0
solve n = max (mod n 10) $ solve (div n 10)

printResult = do
    n <- readLn :: IO Int
    let r = solve n
    print r

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

module Main where

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

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

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

printList :: (Show a) => [a] -> IO ()
printList = putStrLn . list2Str

list2Str :: (Show a) => [a] -> String
list2Str = concat . intersperse " " . fmap show

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

tCase :: IO () -> IO ()
tCase x = do
    t <- readLn
    replicateM_ t $ x

main :: IO ()
main = tCase process

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

process :: IO ()
process = do
    s <- getLine
    putChar $ foldl max '1' s
    putChar '\n'

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE Strict #-}

import Control.Applicative (liftA2)
import Control.Monad (replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust)

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

testCase :: Scanner String
testCase = (: "") . maximum <$> str

-------------------------- Template ------------------------------------------
type Scanner = State [C.ByteString]

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

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

peek :: Scanner C.ByteString
peek = gets head

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

str :: Scanner String
str = C.unpack <$> bstr

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

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

double :: Scanner Double
double = read . C.unpack <$> bstr

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

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

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t
    then return []
    else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

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


The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.Find any longest k-good segment.As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The first line contains two integers n, k (1 ≤ k ≤ n ≤ 5·105) — the number of elements in a and the parameter k. The second line contains n integers ai (0 ≤ ai ≤ 106) — the elements of the array a.

Print two integers l, r (1 ≤ l ≤ r ≤ n) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in a are numbered from 1 to n from left to right.

{-# LANGUAGE FlexibleContexts #-}

import Control.Applicative ((<$>), (<*>))
import Control.Monad (replicateM, forM_, forM, when)
import Control.Monad.ST.Safe (ST, runST)
import Control.Applicative ((<$>), (<*>))
import Data.Array.IArray (accumArray, listArray, (!), elems)
import Data.Array.MArray.Safe (newArray, readArray, writeArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
import Data.Array.Unboxed (UArray)
import Data.ByteString.Char8 (readInt, words, unpack, getLine, getContents, lines)
import Data.List (maximumBy)
import Data.Maybe (fromJust)
import Data.Ord (comparing)
import Prelude hiding (words, getLine)

main = do
  [n, k] <- map (fst . fromJust . readInt) . words <$> getLine
  as' <- map (fst . fromJust . readInt) . words <$> getLine

  let
    as = listArray (1, n) as' :: UArray Int Int

    (l, r) = maximumBy (comparing (\(l, r) -> r-l+1)) ps
    ps = runST $ do
      cs <- newArray (0, 10^6) 0 :: ST s (STUArray s Int Int)

      let
        -- scan :: Int -> Int -> Int -> ST s [(Int, Int)]
        scan i r z
          | i == n = return [(n, n)]
          | otherwise = do
            z' <- if i /= 1
                    then do
                      let a = as ! (i-1)
                      c <- readArray cs a
                      writeArray cs a (c-1)
                      return $ if c == 1 then (z-1) else z
                    else return z

            let
              extend r z
                | r == n = return (r, z)
                | r < n = do
                  let a = as ! (r + 1)
                  c <- readArray cs a
                  if c == 0
                    then
                      if z < k
                        then do
                          writeArray cs a (c + 1)
                          extend (r + 1) (z + 1)
                        else return (r, z)
                    else do
                      writeArray cs a (c + 1)
                      extend (r + 1) z

            (r', z'') <- extend r z'

            ps <- scan (i+1) r' z''
            return $ ((i, r'):ps)

      writeArray cs (as ! 1) 1
      scan 1 1 1

  putStrLn $ show l ++ " " ++ show r


A rectangle with its opposite corners in $$$(0, 0)$$$ and $$$(w, h)$$$ and sides parallel to the axes is drawn on a plane.You are given a list of lattice points such that each point lies on a side of a rectangle but not in its corner. Also, there are at least two points on every side of a rectangle.Your task is to choose three points in such a way that:   exactly two of them belong to the same side of a rectangle;  the area of a triangle formed by them is maximum possible. Print the doubled area of this triangle. It can be shown that the doubled area of any triangle formed by lattice points is always an integer.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The first line of each testcase contains two integers $$$w$$$ and $$$h$$$ ($$$3 \le w, h \le 10^6$$$) — the coordinates of the corner of a rectangle. The next two lines contain the description of the points on two horizontal sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$x_1 < x_2 < \dots < x_k$$$ ($$$0 < x_i < w$$$) — the $$$x$$$ coordinates of the points in the ascending order. The $$$y$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$h$$$. The next two lines contain the description of the points on two vertical sides. First, an integer $$$k$$$ ($$$2 \le k \le 2 \cdot 10^5$$$) — the number of points. Then, $$$k$$$ integers $$$y_1 < y_2 < \dots < y_k$$$ ($$$0 < y_i < h$$$) — the $$$y$$$ coordinates of the points in the ascending order. The $$$x$$$ coordinate for the first line is $$$0$$$ and for the second line is $$$w$$$. The total number of points on all sides in all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print a single integer — the doubled maximum area of a triangle formed by such three points that exactly two of them belong to the same side.

{-#LANGUAGE Strict #-}

import Control.Monad(replicateM)

data Point = Point Int Int

main :: IO ()
main = do
    t <- read <$> getLine
    res <- replicateM t $ do
        [w, h] <- map read . words <$> getLine -- :: IO [Int]
        bottom <- breadth . fAndL . tail . map read . words <$> getLine -- :: IO [Int]
        top <- breadth . fAndL . tail . map read . words <$> getLine -- :: IO [Int]
        left <- breadth . fAndL . tail . map read . words <$> getLine -- :: IO [Int]
        right <- breadth . fAndL . tail . map read . words <$> getLine -- :: IO [Int]
        return $ solve (Point w h) bottom top left right
    putStrLn $ unlines . map show $ res
    return ()

solve :: Point -> Int -> Int -> Int -> Int -> Int
solve p@(Point w h) b t l r = max (horz * h) (vert * w)
    where
        horz    = max t b
        vert    = max l r
        -- top     = last t - head t
        -- bottom  = last b - head b
        -- left    = last l - head l
        -- right   = last r - head r

fAndL :: [a] -> (a, a)
fAndL xs = (head xs, last xs)

breadth :: Num a => (a, a) -> a
breadth (f, l) = abs (l - f)

{-#LANGUAGE Strict #-}

import Control.Monad(replicateM)

data Point = Point Int Int

main :: IO ()
main = do
    t <- read <$> getLine
    res <- replicateM t $ do
        [w, h] <- map read . words <$> getLine :: IO [Int]
        bottom <- tail . map read . words <$> getLine :: IO [Int]
        top <- tail . map read . words <$> getLine :: IO [Int]
        left <- tail . map read . words <$> getLine :: IO [Int]
        right <- tail . map read . words <$> getLine :: IO [Int]
        return $ solve (Point w h) bottom top left right
    putStrLn $ unlines . map show $ res
    return ()

solve :: Point -> [Int] -> [Int] -> [Int] -> [Int] -> Int
solve p@(Point w h) b t l r = max (horz * h) (vert * w)
    where
        horz    = max top bottom
        vert    = max left right
        top     = last t - head t
        bottom  = last b - head b
        left    = last l - head l
        right   = last r - head r

{-# LANGUAGE TypeApplications #-}

module Main where

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

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

main = do
  n <- read @Int <$> getLine
  replicateM n $ do
    [w,h] <- fmap (read @Integer) . words <$> getLine
    let getPs = fmap (read @Integer) .  tail . words <$> getLine
    let getMaxLen l = last l - head l
    lowHoriz <- getPs
    upHoriz <- getPs
    leftVert <- getPs
    rightVert <- getPs
    print @Integer $ maximum [getMaxLen lowHoriz * h,
                             getMaxLen upHoriz * h,
                             getMaxLen leftVert * w,
                             getMaxLen rightVert * w]


Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i-th task, she needs to be in the house number ai and complete all tasks with numbers less than i. Initially, Xenia is in the house number 1, find the minimum time she needs to complete all her tasks if moving from a house to a neighboring one along the ringroad takes one unit of time.

The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ n). Note that Xenia can have multiple consecutive tasks in one house.

Print a single integer — the time Xenia needs to complete all tasks. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first test example the sequence of Xenia's moves along the ringroad looks as follows: 1 → 2 → 3 → 4 → 1 → 2 → 3. This is optimal sequence. So, she needs 6 time units.

import Data.List (sort)
import Control.Applicative

main = do
  [n,m] <- map read . words <$> getLine :: IO [Integer]
  ls <- (1:) . map read . words <$> getLine
  print . sum . map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)

import Data.List

solve n xs = fst $ foldl' moveToHouse (0, 1) xs
  where moveToHouse (time, position) destination
          | position <= destination = (time + destination - position,
                                       destination)
          | position > destination = (time + n - position + destination,
                                      destination)

main = do [n, _] <- fmap (map read . words) getLine
          xs <- fmap (map read . words) getLine
          putStrLn $ show $ solve n xs

import Data.List

solve n xs = fst $ foldl moveToHouse (0, 1) xs
  where moveToHouse (time, position) destination
          | position <= destination = (time + destination - position,
                                       destination)
          | position > destination = (time + n - position + destination,
                                      destination)

main = do [n, _] <- fmap (map read . words) getLine
          xs <- fmap (map read . words) getLine
          putStrLn $ show $ solve n xs

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.Text as T
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

dist :: Int -> Int -> Int -> Int
dist n a b = if b >= a then b - a else n + b - a

solve :: Int -> [Int] -> Int64
solve n a = sum $ map fromIntegral $ zipWith (dist n) (1:a) a

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

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

process [] _ _ cou = cou
process (a:as) n cu cou |  a>=cu = process as n a (cou + a-cu)
                        |  otherwise = process as n a (cou +n-cu+a )

main=do

   [n,m]<- map read <$> words <$> getLine ::IO [Integer]
   a<- map read <$> words <$> getLine ::IO [Integer]

   print $  process a n 1 0

import Data.List (foldl')

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

solve :: [[Integer]] -> Integer
solve [[n, _], as] = snd $ foldl' (\(a, b) c -> (c, b + (c + n - a) `mod` n)) (1, 0) as
solve _ = undefined

main = do
  [n,m] <- fmap (map read . words) getLine
  as <- fmap (map read . words) getLine
  let d a b = (b-a) `mod` n
  print . sum $ zipWith d (1:as) as

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

import Data.Int

dist :: Int -> Int -> Int -> Int
dist n a b = if b >= a then b - a else n + b - a

solve :: Int -> [Int] -> Int64
solve n a = sum $ map fromIntegral $ zipWith (dist n) (1:a) a

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

module Main where
import Data.List
import Data.Char
import Data.Maybe
import System.Environment
import qualified Data.ByteString.Char8 as C

main = do
	params <- readInts
	a <- readInts
	print $ gao (map fromIntegral a) (fromIntegral (params!!0))

--	let a = take 100000 [1, 2, 1 ..]
--		in print $ gao (map fromIntegral a) (fromIntegral (params!!0))

gao :: [Integer] -> Integer -> Integer
gao xs n = ((fromIntegral $ length (groupBy' (<=) xs)) - 1) * n + last xs - 1

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

groupBy'                 :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy' _  []           = []
groupBy' _	(x:[])		 = [[x]]
groupBy' eq (x:y:zs)     | eq x y = (x:(head tmp)) : (tail tmp)
						 | otherwise = (x:[]):tmp
						 where tmp = (groupBy' eq (y:zs))

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

path (n:_:ls) = fst $ foldl (\(s,p) e -> (s + diff n p e, e)) (0,1) ls

diff n p e = if e<p then n+e-p else e-p

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

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

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

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

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

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

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

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

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

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

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

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

til :: Integer -> Integer -> Integer -> Integer
til n x1 x2 = if x2 >= x1 then x2 - x1 else x2 + n - x1

main :: IO ()
main = do
	[n, _] <- inputIntegers
	xs <- inputIntegers
	print . sum $ zipWith (til n) (1 : xs) xs

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

main=do
	[n,m]<- map read. words <$>  getLine  ::IO [Integer]
	s<- map (fst.fromJust.C.readInteger). C.words <$>  C.getLine  ::IO [Integer]
	print $   sum $ zipWith (\a b-> mod (a-b) n) s (1:s)

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

main :: IO ()
main = do
	line1 <- getLine
	line2 <- getLine
	let
		[n, m] = map (\x->read x::Integer). words $ line1
		arr = map (\x->x-1). map (\x->read x::Integer). words $ line2
		solve _ [] = 0
		solve p (x:xs) = ((x-p)`mod`n + n)`mod`n + (solve x xs)
	print$ solve 0 arr

process :: [Integer] -> Integer -> Integer
process xs n = sum $ zipWith f xs' (0:xs')
    where
        f x y = (x - y) `mod` n
        xs' = map (subtract 1) xs

readInt :: String -> Integer
readInt = read

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

module Main where
import Data.List (foldl')

main :: IO ()
main = do
  n:_ <- fmap (map read . words) getLine
  ts <- fmap (map read . words) getLine
  print $ rush n ts

rush :: Integer -> [Integer] -> Integer
rush n = snd . foldl' (\(b,acc) t -> (t, (if t >= b then t - b else n + t - b) + acc)) (1, 0)

import Data.Int

time :: Int64 -> [Int64] -> Int64
time n xs = sum $ zipWith d (1:xs) xs
    where d a b = (b - a) `mod` n

solve :: String -> String
solve s = show $ time  n  xs
    where l:ls = lines s
          n:_ = fmap read.words $ l
          xs = fmap read.words.head $ ls

main :: IO ()
main = interact $ solve

import Data.Int

f :: Int64 -> (Int64, Int64) -> Int64 -> (Int64, Int64)
f n (currentHouse, elapsedTime) nextHouse = (nextHouse, elapsedTime + newTime)
    where newTime = (nextHouse + n - currentHouse) `rem` n

solve :: String -> String
solve s = show $ snd $ foldl (f n) (1, 0)  xs
    where l:ls = lines s
          n:_ = fmap read.words $ l
          xs = fmap read.words.head $ ls

main :: IO ()
main = interact $ solve

calc n t
  | t < 0 = t+n
  | otherwise = t
count c n h [] = c
count c n h (m:ms)
  | h == m = count c n h ms
  | otherwise = count (c+(calc n (m-h))) n m (m:ms)
parse=(map (map read)).(map words).lines
main=interact$ show.(\[x, y]->count 0 (head x) 1 y).parse

module Main (main)
    where

import Control.Monad (replicateM)

main :: IO ()
main = print . solve . map (map read . words) =<< replicateM 2 getLine
    where solve [[n,_],xs] = go n 1 0 xs
          go _ _ t [] = t
          go n c t (x:xs)
            | x >= c    = go n x (t + x - c) xs
            | otherwise = go n x (t + n - c + x) xs

main = do
	s<-getLine
	rest<-getLine
	putStrLn $ show $ solve (read (head (words s))) (map read (words rest)) 1
solve::Integer->[Integer]->Integer->Integer
solve n [] c = 0
solve n w c = travel n c (head w) + solve n (tail w) (head w)

travel n a b | b >= a = (b-a)
             | otherwise = n-a+b

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

solve :: [Integer] -> Integer
solve (n:m:a) = solve' a 1
    where
        solve' :: [Integer] -> Integer -> Integer
        solve' []     _    = 0
        solve' (a:ax) last | a >= last = a - last + (solve' ax a)
                           | otherwise = a - last + n + (solve' ax a)

import Data.Int

solution :: Int64 -> [Int64] -> [Int64]
solution n [] = []
solution n [k] = []
solution n [a, b]
    | a > b = [n + b - a]
    | otherwise = [b - a]
solution n xs = (solution n [xs!!0, xs!!1]) ++ (solution n $ tail xs)

main :: IO ()
main = do
    line1 <- getLine
    line2 <- getLine
    let n = head $ map (\x -> read x :: Int64) $ words line1
        args = map (\x -> read x :: Int64) $ words line2
    print $ sum $ solution n (1:args)

main = do
  [n, m] <- fmap (map read . words) getLine
  xs <- fmap (map read . words) getLine

  let
    a = 1:xs
    s = sum $ zipWith (\x y -> if x <= y then y-x else n-(x-y)) a (tail a)
  print 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.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

main = do
    n:m:l <- map readInt . B.words <$> B.getContents
    print $ solve n m l

solve :: Int -> Int -> [Int] -> Integer
solve n m l = sum $ zipWith f (1:l) l
    where
    f a b = fromIntegral $ (b + n - a) `mod` n

import Control.Applicative

main :: IO ()
main = do
        [n,_] <- (map read . words) <$> getLine
        ts <- (map read . words) <$> getLine
        print . snd $ foldl (h n) (1,0) ts

-- |
-- >>> length $ g (f 4) [3,2,3]
--6
-- >>> length $ g (f 4) [2,3,3]
--2
--
---- prop> \n xs -> length (g (f n) xs) == foldl (h n) 0 xs

f :: Integer -> [Integer]
f n = cycle [1..n]

g :: [Integer] -> [Integer] -> [Integer]
g _ [] = []
g (x:xs) (t:ts) | x == t = g (x:xs) ts
                | otherwise = x : g xs (t:ts)
g _ _ = []

-- |
-- >>> snd $ foldl (h 4) (1,0) [3,2,3]
--6
-- >>> snd $ foldl (h 4) (1,0) [2,3,3]
--2
h :: Integer -> (Integer,Integer) -> Integer -> (Integer,Integer)
h n (c,r) t | t < c = (t,r + n - c + t)
            | otherwise = (t,r + t - c)

import Data.List
import Data.Maybe
import Data.Char
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve. (\(a:b:bs)->a:1:bs).concat.map (map read.words).take 2.lines
solve :: [Integer]->String
solve xs = show $ fst $ slv1 xs
slv1 (x:xs)=foldr f (0,0) xs where
  f a (0,0) = (0,a)
  f a (b1,b2) = if b2-a>=0 then (b1+b2-a,a) else (b1+b2+x-a,a)

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

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

solve :: Integer -> [Integer] -> Integer
solve n as  =  snd $ foldl' solve' (1, 0) as
  where
  	solve' (m, s) a
  	  | a >= m  =  (a, s + a - m)
  	  | a <  m  =  (a, s + (n - m + a))

main :: IO ()
main  =  do
	[n, m]  <-  reads
	as  <-  reads
	print $ solve n as

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

readInt :: B.ByteString -> Integer
readInt = B.foldl' (\x c -> 10 * x + fromIntegral (ord c) - 48) 0

main = do
  [n,m] <- map read . words <$> getLine :: IO [Integer]
  ls <- (1:) . map readInt . B.words <$> B.getContents
  print . sum . map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)

import Data.List (sort)
import Control.Applicative
import Data.Int (Int64)

main = do
  [n,m] <- map read . words <$> getLine :: IO [Int64]
  ls <- (1:) . map read . words <$> getLine
  print . sum . map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)

import Data.List (sort)
import Control.Applicative

main = do
  [n,m] <- map read . words <$> getLine :: IO [Integer]
  ls <- (1:) . map read . words <$> getLine
  let m = map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)
  print . sum $ m

import Data.List

solve :: [Int] -> Int
solve (n:_:xs) = fst $ foldl' moveToHouse (0, 1) xs
  where moveToHouse (time, position) destination
          | position <= destination = (time + destination - position,
                                       destination)
          | position > destination = (time + n - position + destination,
                                      destination)

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

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.Text as T
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

dist :: Int -> Int -> Int -> Int
dist n a b = if b >= a then b - a else n + b - a

solve :: Int -> [Int] -> Int
solve n a = sum $ zipWith (dist n) (1:a) a

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

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

process [] _ _ cou = cou
process (a:as) n cu cou |  a>=cu = process as n a (cou + a-cu)
                        |  otherwise = process as n a (cou +n-cu+a )

main=do

   [n,m]<- map read <$> words <$> getLine ::IO [Int]
   a<- map read <$> words <$> getLine ::IO [Int]

   print $  process a n 1 0

module Main where
import Data.List
import Data.Char
import Data.Maybe
import System.Environment
import qualified Data.ByteString.Char8 as C

main = do
	params <- readInts
	a <- readInts
	print $ gao a (params!!0)

gao :: [Int] -> Int -> Int
gao xs n = (length (groupBy (<) xs) - 1) * n + last xs - 1

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

module Main where
import Data.List
import Data.Char
import Data.Maybe
import System.Environment
import qualified Data.ByteString.Char8 as C

main = do
	params <- readInts
	a <- readInts
	print $ gao (map fromIntegral a) (fromIntegral (params!!0))

gao :: [Integer] -> Integer -> Integer
gao xs n = ((fromIntegral $ length (groupBy (<=) xs)) - 1) * n + last xs - 1

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

module Main where
import Data.List
import Data.Char
import Data.Maybe
import System.Environment
import qualified Data.ByteString.Char8 as C

main = do
	params <- readInts
	a <- readInts
	print $ gao a (params!!0)

gao :: [Int] -> Int -> Int
gao xs n = (length (groupBy (<=) xs) - 1) * n + last xs - 1

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

import Control.Applicative
import Data.List

main=do
	[n,m]<- map read. words <$>  getLine  ::IO [Int]
	s<- map read. words <$>  getLine  ::IO [Int]
	print $   sum $ zipWith (\a b-> mod (a-b) n) s (1:s)

process :: [Int] -> Int -> Int
process xs n = sum $ zipWith f xs' (0:xs')
    where
        f x y = (x - y) `mod` n
        xs' = map (subtract 1) xs

readInt :: String -> Int
readInt = read

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

f :: Int -> (Int, Int) -> Int -> (Int, Int)
f n (currentHouse, elapsedTime) nextHouse = (nextHouse, elapsedTime + newTime)
    where newTime = (nextHouse + n - currentHouse) `rem` n

solve :: String -> String
solve s = show $ snd $ foldl (f n) (1, 0)  xs
    where l:ls = lines s
          n:_ = fmap read.words $ l
          xs = fmap read.words.head $ ls

main :: IO ()
main = interact $ solve

main = do
	s<-getLine
	rest<-getLine
	putStrLn $ show $ solve (read (head (words s))) (map read (words rest)) 1
solve::Int->[Int]->Int->Int
solve n [] c = 0
solve n w c = travel n c (head w) + solve n (tail w) (head w)

travel n a b | b >= a = (b-a)
             | otherwise = n-a+b

solution :: Int -> [Int] -> [Int]
solution n [] = []
solution n [k] = []
solution n [a, b]
    | a > b = [n + b - a]
    | otherwise = [b - a]
solution n xs = (solution n [xs!!0, xs!!1]) ++ (solution n $ tail xs)

main :: IO ()
main = do
    line1 <- getLine
    line2 <- getLine
    let n = head $ map (\x -> read x :: Int) $ words line1
        args = map (\x -> read x :: Int) $ words line2
    print $ sum $ solution n (1:args)

import Control.Applicative

main :: IO ()
main = do
        [n,_] <- (map read . words) <$> getLine
        ts <- (map read . words) <$> getLine
        print . snd $ foldl (h n) (1,0) ts

-- |
-- >>> length $ g (f 4) [3,2,3]
--6
-- >>> length $ g (f 4) [2,3,3]
--2
--
---- prop> \n xs -> length (g (f n) xs) == foldl (h n) 0 xs

f :: Int -> [Int]
f n = cycle [1..n]

g :: [Int] -> [Int] -> [Int]
g _ [] = []
g (x:xs) (t:ts) | x == t = g (x:xs) ts
                | otherwise = x : g xs (t:ts)
g _ _ = []

-- |
-- >>> snd $ foldl (h 4) (1,0) [3,2,3]
--6
-- >>> snd $ foldl (h 4) (1,0) [2,3,3]
--2
h :: Int -> (Int,Int) -> Int -> (Int,Int)
h n (c,r) t | t < c = (t,r + n - c + t)
            | otherwise = (t,r + t - c)

import Data.List (sort)
import Control.Applicative

main = do
  [n,m] <- map read . words <$> getLine :: IO [Int]
  ls <- (1:) . map read . words <$> getLine
  let m = map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)
  print m
  print . sum $ m

import Data.List (sort)
import Control.Applicative

main = do
  [n,m] <- map read . words <$> getLine :: IO [Int]
  ls <- (1:) . map read . words <$> getLine
  print . sum . map ((`mod`4) . uncurry (flip (-))) $ zip ls (drop 1 ls)

import Data.List (sort)
import Control.Applicative
import Data.Word

main = do
  [n,m] <- map read . words <$> getLine :: IO [Word64]
  ls <- (1:) . map read . words <$> getLine
  print . sum . map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)

import Data.List (sort)
import Control.Applicative

main = do
  [n,m] <- map read . words <$> getLine :: IO [Int]
  ls <- (1:) . map read . words <$> getLine
  let m = map ((`mod`n) . uncurry (flip (-))) $ zip ls (drop 1 ls)
  print . sum $ m


A permutation of length $$$n$$$ is a sequence of integers from $$$1$$$ to $$$n$$$ such that each integer appears in it exactly once.Let the fixedness of a permutation $$$p$$$ be the number of fixed points in it — the number of positions $$$j$$$ such that $$$p_j = j$$$, where $$$p_j$$$ is the $$$j$$$-th element of the permutation $$$p$$$.You are asked to build a sequence of permutations $$$a_1, a_2, \dots$$$, starting from the identity permutation (permutation $$$a_1 = [1, 2, \dots, n]$$$). Let's call it a permutation chain. Thus, $$$a_i$$$ is the $$$i$$$-th permutation of length $$$n$$$.For every $$$i$$$ from $$$2$$$ onwards, the permutation $$$a_i$$$ should be obtained from the permutation $$$a_{i-1}$$$ by swapping any two elements in it (not necessarily neighboring). The fixedness of the permutation $$$a_i$$$ should be strictly lower than the fixedness of the permutation $$$a_{i-1}$$$.Consider some chains for $$$n = 3$$$:  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$ — that is a valid chain of length $$$2$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$.  $$$a_1 = [2, 1, 3]$$$, $$$a_2 = [3, 1, 2]$$$ — that is not a valid chain. The first permutation should always be $$$[1, 2, 3]$$$ for $$$n = 3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [1, 3, 2]$$$, $$$a_3 = [1, 2, 3]$$$ — that is not a valid chain. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped but the fixedness increase from $$$1$$$ to $$$3$$$.  $$$a_1 = [1, 2, 3]$$$, $$$a_2 = [3, 2, 1]$$$, $$$a_3 = [3, 1, 2]$$$ — that is a valid chain of length $$$3$$$. From $$$a_1$$$ to $$$a_2$$$, the elements on positions $$$1$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$3$$$ to $$$1$$$. From $$$a_2$$$ to $$$a_3$$$, the elements on positions $$$2$$$ and $$$3$$$ get swapped, the fixedness decrease from $$$1$$$ to $$$0$$$. Find the longest permutation chain. If there are multiple longest answers, print any of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 99$$$) — the number of testcases. The only line of each testcase contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the required length of permutations in the chain.

For each testcase, first, print the length of a permutation chain $$$k$$$. Then print $$$k$$$ permutations $$$a_1, a_2, \dots, a_k$$$. $$$a_1$$$ should be an identity permutation of length $$$n$$$ ($$$[1, 2, \dots, n]$$$). For each $$$i$$$ from $$$2$$$ to $$$k$$$, $$$a_i$$$ should be obtained by swapping two elements in $$$a_{i-1}$$$. It should also have a strictly lower fixedness than $$$a_{i-1}$$$.

import Control.Monad(replicateM)

getPermutation :: Int -> Int -> [Int]
getPermutation n i = enumFromTo 2 (succ i) ++ 1 : enumFromTo (i+2) n

getAns :: Int -> (Int, [[Int]])
getAns n = (n, map (getPermutation n) [0..pred n])

printAns :: (Int, [[Int]]) -> IO()
printAns (n, lst) = do
  print n
  mapM_ (putStrLn . showLn) lst

showLn :: [Int] -> String
showLn [] = []
showLn [x] = show x
showLn (x:xs) = show x ++ ' ' : showLn xs

main :: IO()
main = do
  t <- readLn
  ns <- replicateM t readLn
  let solution = getAns <$> ns
  mapM_ printAns solution

import Control.Monad(replicateM)

getPermutation :: Int -> Int -> [Int]
getPermutation n i = enumFromTo 2 (succ i) ++ 1 : enumFromTo (i+2) n

getAns :: Int -> (Int, [[Int]])
getAns n = (n, map (getPermutation n) [0..pred n])

printAns :: (Int, [[Int]]) -> IO()
printAns (n, lst) = do
  print n
  mapM_ print lst

main :: IO()
main = do
  t <- readLn
  ns <- replicateM t readLn
  let solution = getAns <$> ns
  mapM_ printAns solution


In this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully.A string is a bHTML table, if it satisfies the grammar: TABLE ::=
ROWS
ROWS ::= ROW | ROW ROWSROW ::=
CELLS
CELLS ::= CELL | CELL CELLSCELL ::= 	 | TABLE	Blanks in the grammar are only for purposes of illustration, in the given data there will be no spaces. The bHTML table is very similar to a simple regular HTML table in which meet only the following tags : "table", "tr", "td", all the tags are paired and the table contains at least one row and at least one cell in each row. Have a look at the sample tests as examples of tables.As can be seen, the tables may be nested. You are given a table (which may contain other(s)). You need to write a program that analyzes all the tables and finds the number of cells in each of them. The tables are not required to be rectangular.

For convenience, input data can be separated into non-empty lines in an arbitrary manner. The input data consist of no more than 10 lines. Combine (concatenate) all the input lines into one, to get a text representation s of the specified table. String s corresponds to the given grammar (the root element of grammar is TABLE), its length does not exceed 5000. Only lower case letters are used to write tags. There are no spaces in the given string s.

Print the sizes of all the tables in the non-decreasing order.

import Text.ParserCombinators.ReadP
import List

main = interact $ unwords.map show.solve.concat.lines

solve :: String -> [Int]
solve = sort.fst.head.readP_to_S table

table :: ReadP [Int]
table = do
      { string "
"
      ; xss <- manyTill row (string "
")
      ; return $ ((length $ concat xss):) $ concat $ filter(not.null) $ concat xss
      }

row :: ReadP [[Int]]
row = do
      { string "
"
      ; xs <- manyTill cell (string "
")
      ; return xs
      }

cell :: ReadP [Int]
cell = do
      { string ""
      ; xs <- option [] table
      ; string "	"
      ; return xs
      }

import Control.Monad
import Data.List

main = do
    s <- getContents >>= return . concat . lines
    mapM (\x -> putStr (show x ++ " ")) $ solve s
    putStrLn ""

solve s = sort $ count $ preproc s

preproc s = foldl replaceStr s [("
","["),("
", "]"),("
", ""),("
", ""),("", "."),("	", "")]

replaceStr [] _ = []
replaceStr xs@(y:ys) p@(from, to) = case stripPrefix from xs of
    Nothing  -> y:replaceStr ys p
    Just ys' -> to ++ replaceStr ys' p

count s = count' s [] [] where
    count' []     _  acc = acc
    count' (s:ss) st acc = case s of
        '[' -> count' ss (0:st) acc
        '.' -> count' ss ((head st + 1):(tail st)) acc
        ']' -> count' ss (tail st) ((head st):acc)

import List
main = interact solve
solve input = output where
  input0 = concat $ lines input
  output = unwords $ map show $ sort $ map count $ divide (translate input0) []
translate [] = []
translate xs
  | take 7 xs == "
"  = 'a':(translate $ drop 7 xs)
  | take 8 xs == "
" = 'b':(translate $ drop 8 xs)
  | take 4 xs == "
"     = 'c':(translate $ drop 4 xs)
  | take 5 xs == "
"    = 'd':(translate $ drop 5 xs)
  | take 4 xs == ""     = 'e':(translate $ drop 4 xs)
  | take 5 xs == "	"    = 'f':(translate $ drop 5 xs)
divide [] _ = []
divide (x:xs) ys
  | x=='a'    = divide xs ([]:ys)
  | x=='b'    = y:(divide xs ys')
  | otherwise = divide xs ((x:y):ys')
   where y = head ys
         ys' = tail ys
count xs = length $ filter (=='e') xs

import Text.ParserCombinators.ReadP
import List

main = interact $ unwords.map show.solve.concat.lines

solve :: String -> [Int]
solve = fst.head.readP_to_S table

table :: ReadP [Int]
table = do
      { string "
"
      ; xss <- manyTill row (string "
")
      ; return $ ((length $ concat xss):) $ concat $ filter(not.null) $ concat xss
      }

row :: ReadP [[Int]]
row = do
      { string "
"
      ; xs <- manyTill cell (string "
")
      ; return xs
      }

cell :: ReadP [Int]
cell = do
      { string ""
      ; xs <- option [] table
      ; string "	"
      ; return xs
      }

import Control.Monad
import Data.List

main = do
    s <- getContents >>= return . concat . lines
    mapM (\x -> putStr (show x ++ " ")) $ solve s
    putStrLn ""

solve s = count $ preproc s

preproc s = foldl replaceStr s [("
","["),("
", "]"),("
", ""),("
", ""),("", "."),("	", "")]

replaceStr [] _ = []
replaceStr xs@(y:ys) p@(from, to) = case stripPrefix from xs of
    Nothing  -> y:replaceStr ys p
    Just ys' -> to ++ replaceStr ys' p

count s = count' s [] [] where
    count' []     _  acc = acc
    count' (s:ss) st acc = case s of
        '[' -> count' ss (0:st) acc
        '.' -> count' ss ((head st + 1):(tail st)) acc
        ']' -> count' ss (tail st) ((head st):acc)


We have an array of length $$$n$$$. Initially, each element is equal to $$$0$$$ and there is a pointer located on the first element.We can do the following two kinds of operations any number of times (possibly zero) in any order: If the pointer is not on the last element, increase the element the pointer is currently on by $$$1$$$. Then move it to the next element. If the pointer is not on the first element, decrease the element the pointer is currently on by $$$1$$$. Then move it to the previous element.But there is one additional rule. After we are done, the pointer has to be on the first element.You are given an array $$$a$$$. Determine whether it's possible to obtain $$$a$$$ after some operations or not.

The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(1\le n\le 2 \cdot 10^5)$$$  — the size of array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print "Yes" (without quotes) if it's possible to obtain $$$a$$$ after some operations, and "No" (without quotes) otherwise. You can output "Yes" and "No" in any case (for example, strings "yEs", "yes" and "Yes" will be recognized as a positive response).

NoteIn the first test case we can obtain the array after some operations, but the pointer won't be on the first element.One way of obtaining the array in the second test case is shown below.$$$\langle \underline{0}, 0, 0, 0\rangle \to \langle 1, \underline{0}, 0, 0 \rangle \to \langle \underline{1}, -1, 0, 0\rangle \to \langle 2, \underline{-1}, 0, 0\rangle \to \langle 2, 0, \underline{0}, 0\rangle \to \langle 2, \underline{0}, -1, 0\rangle \to \langle \underline{2}, -1, -1, 0\rangle$$$

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String ( IsString(fromString) )
import qualified Data.ByteString.Char8 as C
import Data.List (dropWhileEnd)

-- solve :: [Integer] -> Bool
-- solve xs = null ys || all (<0) (tail ys) && head ys == 0
--   where ys = scanr1 (+) $ dropWhileEnd (==0) xs

solve :: [Integer] -> Bool
solve xs = null ys || all (>0) (init ys) && last ys == 0
  where ys = scanl1 (+) $ dropWhileEnd (==0) xs

-- solve :: [Integer] -> Bool
-- solve [] = True
-- solve [0] = True
-- solve [_] = False
-- solve (x:y:xs)
--   | z == 0 = all (==0) (xs)
--   | z > 0 = solve (z:xs)
--   | otherwise = False
--   where z = x + y

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String
import qualified Data.ByteString.Char8 as C
import Data.List (dropWhileEnd)

solve :: [Integer] -> Bool
solve xs = all (==0) xs || all (<0) (tail ys) && head ys == 0
  where ys = scanr1 (+) $ dropWhileEnd (==0) xs

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

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

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

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

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

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

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

solve xs = not (headFail||negPSumFail||finSumFail||splitFail)
  where
    psums = scanl1 (+) xs
    psumsNozeros = reverse . dropWhile (==0) . reverse $ psums
    headFail = (not.null) psumsNozeros && head psumsNozeros <= 0
    negPSumFail = isJust . L.find (<0) $ psumsNozeros
    finSumFail = (last psums /= 0)
    splitFail = isJust . L.find (==0) $ psumsNozeros

{-# LANGUAGE BangPatterns #-}

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

obtainable :: [Int] -> Bool
obtainable = go . reverse where
  go [0] = True
  go [_] = False
  go (0:xs) = go xs
  go (x1:x2:xs)
    | x1 > 0 = False
    | (-x1) == x2 && not (null xs) = False
    | otherwise = go (x2+x1:xs)

main = do
  [!t] <- readInts
  replicateM_ t $ do
    readInts
    as <- readInts
    putStrLn (if obtainable as then "Yes" else "No")

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

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String ( IsString(fromString) )
import qualified Data.ByteString.Char8 as C
import Data.List (dropWhileEnd)

-- solve :: [Integer] -> Bool
-- solve xs = null ys || all (<0) (tail ys) && head ys == 0
--   where ys = scanr1 (+) $ dropWhileEnd (==0) xs

solve :: [Integer] -> Bool
solve xs = null ys || all (>0) (init ys) && last ys == 0
  where ys = scanl1 (+) xs

-- solve :: [Integer] -> Bool
-- solve [] = True
-- solve [x] = x == 0
-- solve (x:y:xs)
--   | z == 0 = all (==0) xs
--   | z > 0 = solve (z:xs)
--   | otherwise = False
--   where z = x + y

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String ( IsString(fromString) )
import qualified Data.ByteString.Char8 as C
import Data.List (dropWhileEnd)

-- solve :: [Integer] -> Bool
-- solve xs = null ys || all (<0) (tail ys) && head ys == 0
--   where ys = scanr1 (+) $ dropWhileEnd (==0) xs

-- solve :: [Integer] -> Bool
-- solve xs = null ys || all (>0) (init ys) && last ys == 0
--   where ys = scanl1 (+) $ dropWhileEnd (==0) xs

solve :: [Integer] -> Bool
solve [] = True
solve [x] = x == 0
solve (x:y:xs)
  | z == 0 = all (==0) xs
  | z > 0 = solve (z:xs)
  | otherwise = False
  where z = x + y

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String ( IsString(fromString) )
import qualified Data.ByteString.Char8 as C
import Data.List (dropWhileEnd)

-- solve :: [Integer] -> Bool
-- solve xs = null ys || all (<0) (tail ys) && head ys == 0
--   where ys = scanr1 (+) $ dropWhileEnd (==0) xs

solve :: [Integer] -> Bool
solve xs = null ys || all (>0) (tail ys) && last ys == 0
  where ys = scanl1 (+) $ dropWhileEnd (==0) xs

-- solve :: [Integer] -> Bool
-- solve [] = True
-- solve [0] = True
-- solve [_] = False
-- solve (x:y:xs)
--   | z == 0 = all (==0) (xs)
--   | z > 0 = solve (z:xs)
--   | otherwise = False
--   where z = x + y

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String ( IsString(fromString) )
import qualified Data.ByteString.Char8 as C
import Data.List (dropWhileEnd)

-- solve :: [Integer] -> Bool
-- solve xs = null ys || all (<0) (tail ys) && head ys == 0
--   where ys = scanr1 (+) $ dropWhileEnd (==0) xs

solve :: [Integer] -> Bool
solve [] = True
solve [0] = True
solve [_] = False
solve (x:y:xs)
  | z == 0 = all (==0) (xs)
  | z > 0 = solve (z:xs)
  | otherwise = False
  where z = x + y

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String
import qualified Data.ByteString.Char8 as C

solve :: [Integer] -> Bool
solve xs = all (==0) xs || all (<0) (tail ys) && head ys == 0
  where ys = scanr1 (+) xs

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String
import qualified Data.ByteString.Char8 as C

solve :: [Integer] -> Bool
solve [] = False
solve [0] = True
solve [_] = False
solve (x:y:xs)
  | x == 0 = all (==0) (y:xs)
  | z >= 0 = solve (z:xs)
  | otherwise = False
  where z = x + y

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String
import qualified Data.ByteString.Char8 as C

solve :: [Integer] -> Bool
solve [] = False
solve [0] = True
solve [_] = False
solve (x:y:xs)
  | z == 0 = all (==0) xs
  | z > 0 = solve (z:xs)
  | otherwise = False
  where z = x + y

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String
import qualified Data.ByteString.Char8 as C

solve :: [Integer] -> Bool
solve [] = False
solve [0] = True
solve [_] = False
solve (x:y:xs)
  | x + y == 0 = all (==0) xs
  | x + y > 0 = solve (x+y : xs)
  | otherwise = False

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String
import qualified Data.ByteString.Char8 as C

solve :: [Integer] -> Bool
solve [] = True
solve [0] = True
solve [_] = False
solve (x:y:xs)
  | x + y == 0 = all (==0) xs
  | x + y > 0 = solve (x+y : xs)
  | otherwise = False

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String
import qualified Data.ByteString.Char8 as C

solve :: [Integer] -> Bool
solve [] = True
solve [0] = True
solve [_] = False
solve (x:y:xs)
  | x == 0 = all (==0) (y:xs)
  | x + y > 0 = solve (x+y : xs)
  | otherwise = False

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
-- import Debug.Trace
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String
import qualified Data.ByteString.Char8 as C

solve :: [Integer] -> Bool
solve [] = True
solve [0] = True
solve [_] = False
solve (x:y:xs)
  | x == 0 = all (==0) (y:xs)
  | x + y >= 0 = solve (x+y : xs)
  | otherwise = False

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

parseIntegerList :: String -> [Integer]
parseIntegerList = map parseInteger . words

printAns :: Bool -> IO ()
printAns True = putStrLn "YES"
printAns False = putStrLn "NO"

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (printAns <$> solve =<< (parseIntegerList <$> (getLine >> getLine)))


Ashishgup and FastestFinger play a game. They start with a number $$$n$$$ and play in turns. In each turn, a player can make any one of the following moves:  Divide $$$n$$$ by any of its odd divisors greater than $$$1$$$.  Subtract $$$1$$$ from $$$n$$$ if $$$n$$$ is greater than $$$1$$$. Divisors of a number include the number itself.The player who is unable to make a move loses the game.Ashishgup moves first. Determine the winner of the game if both of them play optimally.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$)  — the number of test cases. The description of the test cases follows. The only line of each test case contains a single integer  — $$$n$$$ ($$$1 \leq n \leq 10^9$$$).

For each test case, print "Ashishgup" if he wins, and "FastestFinger" otherwise (without quotes).

FastestFinger
Ashishgup
Ashishgup
FastestFinger
Ashishgup
FastestFinger
Ashishgup

NoteIn the first test case, $$$n = 1$$$, Ashishgup cannot make a move. He loses.In the second test case, $$$n = 2$$$, Ashishgup subtracts $$$1$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the third test case, $$$n = 3$$$, Ashishgup divides by $$$3$$$ on the first move. Now $$$n = 1$$$, FastestFinger cannot make a move, so he loses.In the last test case, $$$n = 12$$$, Ashishgup divides it by $$$3$$$. Now $$$n = 4$$$, FastestFinger is forced to subtract $$$1$$$, and Ashishgup gets $$$3$$$, so he wins by dividing it by $$$3$$$.

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

main = getLine >>= flip replicateM_ test . read

test = do
  n <- read <$> getLine
  putStrLn $ bool "FastestFinger" "Ashishgup" $ solve n

solve n
  | p == 0, x == 1 = False
  | p == 0 = True
  | p == 1, x == 1 = True
  | p == 1 = any ((== 0) . (x `mod`)) $ takeWhile (<= floor (sqrt $ fromIntegral x)) [3, 5 ..]
  | x == 1 = False
  | otherwise = True
  where
    (p, x) = powerTwo n

powerTwo = f . (,) 0
  where
    f (p, n)
      | odd n = (p, n)
      | otherwise = f (p + 1, n `div` 2)

import Control.Monad

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

routine :: IO ()
routine = do
  n <- readLn
  putStrLn $ if solve n then "Ashishgup" else "FastestFinger"

solve :: Int -> Bool
solve n
  | n == 1 = False
  | odd n = True
  | n == 2 = True
  | pow2 n = False
  | otherwise = not $ isPrime (n `div` 2)

isPrime :: Int -> Bool
isPrime n = not $ any (\x -> n `mod` x == 0) [2..sq]
  where
    sq = floor $ sqrt $ fromIntegral n

pow2 :: Int -> Bool
pow2 n = x == n
  where
      x = until (>=n) (*2) 1

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

main = getLine >>= flip replicateM_ test . read

test = do
  n <- read <$> getLine
  putStrLn $ bool "FastestFinger" "Ashishgup" $ solve n

solve n
  | p == 0, x == 1 = False
  | p == 0 = True
  | p == 1, x == 1 = True
  | p == 1 = any ((== 0) . (x `div`)) $ takeWhile (<= floor (sqrt $ fromIntegral x)) [1, 3 ..]
  | x == 1 = False
  | otherwise = True
  where
    (p, x) = powerTwo n

powerTwo = f . (,) 0
  where
    f (p, n)
      | odd n = (p, n)
      | otherwise = f (p + 1, n `div` 2)

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

main = getLine >>= flip replicateM_ test . read

test = do
  n <- read <$> getLine
  putStrLn $ bool "FastestFinger" "Ashishgup" $ solve n

solve n
  | p == 0, x == 1 = False
  | p == 0 = True
  | p == 1, x == 1 = True
  | p == 1 = any ((== 0) . (x `div`)) $ takeWhile (<= floor (sqrt $ fromIntegral x)) [3, 5 ..]
  | x == 1 = False
  | otherwise = True
  where
    (p, x) = powerTwo n

powerTwo = f . (,) 0
  where
    f (p, n)
      | odd n = (p, n)
      | otherwise = f (p + 1, n `div` 2)

import Control.Monad

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

routine :: IO ()
routine = do
  n <- readLn
  putStrLn $ if solve n then "Ashishgup" else "FastestFinger"

solve :: Int -> Bool
solve n
  | n == 1 = False
  | odd n = True
  | n == 2 = True
  | otherwise = not $ isPrime (n `div` 2)

isPrime :: Int -> Bool
isPrime n = not $ any (\x -> n `mod` x == 0) [2..sq]
  where
    sq = floor $ sqrt $ fromIntegral n


We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7.The string "ab" appears as a substring if there is a letter 'b' right after the letter 'a' somewhere in the string.

The first line contains the initial string consisting of letters 'a' and 'b' only with length from 1 to 106.

Print the minimum number of steps modulo 109 + 7.

NoteThe first example: "ab"  →  "bba".The second example: "aab"  →  "abba"  →  "bbaba"  →  "bbbbaa".

main = getLine >>= print . solve 0 1

solve ans _ [] = ans
solve ans a ('a':cs) = solve ans (a * 2 `mod` 1000000007) cs
solve ans a ('b':cs) = solve ((ans + a - 1) `mod` 1000000007) a cs

module Main where
import Control.Monad
import Control.Applicative
import Data.List
import Data.Bits

solve :: String -> Int
solve = snd . foldl' (\(a, b) c -> if c == 'b' then (a, b +% a +% (base - 1)) else (a *% 2, b)) (1, 0)
  where
    base = 1000000007
    a +% b = (a + b) `mod` base

    a *% b = (a * b) `mod` base

main = solve <$> getLine >>= print

-- abbaaabaabaaaaabbbbaababaaaaabaabbaaaaabbaabbaaaabbbabbbabb
-- bbaba
-- bbbbaa
-- aab
-- abba
-- bbab a
-- bbbbaa

-- X'abbaY
-- X'bbabaY
-- ab  b
-- bba b
-- aab
-- ab -> bba

-- aa ab
-- aa bba  1
-- a ab ba
-- a bba ba 2
-- abb ab a
-- abb bba a 3
-- ab bbbaa
-- bba bbbaa 4
-- bb ab bb aa
-- bb bba bb aa 5
-- bbbb ab baa
-- bbbb bba baa 6

-- first takes 1, add 2  -> 2
-- second takes 2, add 2 -> 4
-- third takes 4, add 4 -> 8
-- 1 + 2 + 4
-- bbbbbbb aaa

module Main where
import Control.Monad
import Control.Applicative
import Data.List
import Data.Bits

solve :: String -> Int
solve = snd . foldl' (\(a, b) c -> if c == 'b' then (a, if a == 0 then b else b +% ((2 `shiftL` (a - 1) - 1) `mod` base)) else (a +% 1, b)) (0, 0)
  where
    base = 1000000007
    a +% b = (a + b) `mod` base

main = solve <$> getLine >>= print

-- aab
-- abba
-- bbab a
-- bbbbaa

-- X'abbaY
-- X'bbabaY
-- ab  b
-- bba b
-- aab
-- ab -> bba

-- aa ab
-- aa bba  1
-- a ab ba
-- a bba ba 2
-- abb ab a
-- abb bba a 3
-- ab bbbaa
-- bba bbbaa 4
-- bb ab bb aa
-- bb bba bb aa 5
-- bbbb ab baa
-- bbbb bba baa 6

-- first takes 1, add 2  -> 2
-- second takes 2, add 2 -> 4
-- third takes 4, add 4 -> 8
-- 1 + 2 + 4
-- bbbbbbb aaa


Polycarpus develops an interesting theory about the interrelation of arithmetic progressions with just everything in the world. His current idea is that the population of the capital of Berland changes over time like an arithmetic progression. Well, or like multiple arithmetic progressions.Polycarpus believes that if he writes out the population of the capital for several consecutive years in the sequence a1, a2, ..., an, then it is convenient to consider the array as several arithmetic progressions, written one after the other. For example, sequence (8, 6, 4, 2, 1, 4, 7, 10, 2) can be considered as a sequence of three arithmetic progressions (8, 6, 4, 2), (1, 4, 7, 10) and (2), which are written one after another.Unfortunately, Polycarpus may not have all the data for the n consecutive years (a census of the population doesn't occur every year, after all). For this reason, some values of ai may be unknown. Such values are represented by number -1.For a given sequence a = (a1, a2, ..., an), which consists of positive integers and values -1, find the minimum number of arithmetic progressions Polycarpus needs to get a. To get a, the progressions need to be written down one after the other. Values -1 may correspond to an arbitrary positive integer and the values ai > 0 must be equal to the corresponding elements of sought consecutive record of the progressions.Let us remind you that a finite sequence c is called an arithmetic progression if the difference ci + 1 - ci of any two consecutive elements in it is constant. By definition, any sequence of length 1 is an arithmetic progression.

The first line of the input contains integer n (1 ≤ n ≤ 2·105) — the number of elements in the sequence. The second line contains integer values a1, a2, ..., an separated by a space (1 ≤ ai ≤ 109 or ai =  - 1).

Print the minimum number of arithmetic progressions that you need to write one after another to get sequence a. The positions marked as -1 in a can be represented by any positive integers.

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
import Control.Applicative
import Data.Int (Int64)
import Data.Maybe
import qualified Data.ByteString.Char8 as C

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

gao :: Int64 -> Int64 -> [(Int64, Int64)] -> Int -> Int
gao s t [] res = res + if s < t then 1 else 0
gao _ _ [_] res = res + 1
gao s t a@((i, _): _) res | s > i = gao i t a res
gao s t ((i, x): (j, y): a) res
  | m /= 0 || lval <= 0 = gao j t ((j, y): a) $ res + 1
  | otherwise = gao ridx t a' $ res + 1
  where
  (d, m) = (y - x) `quotRem` (j - i)
  lval = x - (i - s) * d
  ridx = if d >= 0 then t else j + (y-1) `quot` (-d) + 1
  a' = dropWhile (\(k, z) -> z == y + (k - j) * d) a

main :: IO ()
main = do
  n <- readInt <$> C.getLine
  a <- map readInt . C.words <$> C.getLine
  print $ gao 0 n [ie | ie@(_, e) <- zip [0..] a, e > 0] 0

import Control.Applicative
import Control.Monad
import Data.Int (Int64)
import Data.Maybe
import Debug.Trace
import qualified Data.ByteString.Char8 as C

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

getInts :: IO [Int64]
getInts = map readInt . C.words <$> C.getLine

getInt :: IO Int64
getInt = readInt <$> C.getLine

gao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int
gao s [] n res = res + if s < n then 1 else 0
gao _ [_] _ res = res + 1
gao s all@((i,x) : (j,y) : xs) n res
  | s > i = gao i all n res
  | m /= 0 || l <= 0 = gao j ((j,y) : xs) n $ res + 1
  | otherwise = gao next xs' n $ res + 1
  where
  (d,m) = (y - x) `quotRem` (j - i)
  l = x - (i - s) * d
  next = if d >= 0 then n else j + (y-1) `quot` (-d) + 1
  xs' = dropWhile (\(k,z) -> z == (k-j)*d + y) xs

main :: IO ()
main = do
  n <- getInt
  array <- getInts
  print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0

import Control.Applicative
import Control.Monad
import Data.Int (Int64)
import Data.Maybe
import Debug.Trace
import qualified Data.ByteString.Char8 as C

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

getInts :: IO [Int64]
getInts = map readInt . C.words <$> C.getLine

getInt :: IO Int64
getInt = readInt <$> C.getLine

gao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int
gao s [] n res = res + if s < n then 1 else 0
gao _ [_] _ res = res + 1
gao s all@((i,x) : (j,y) : xs) n res
  | lval <= 0.0 = gao i all n $ res + 1
  | cant = gao n xs n $ res + 1
  | otherwise = gao j ((j,y):xs) n $ res
  where
  dif = fromIntegral $ y - x :: Double
  dis = fromIntegral $ j - i :: Double
  x' = fromIntegral $ x :: Double
  y' = fromIntegral $ y :: Double
  dis' = if i <= s then 0.0 else fromIntegral $ i - s :: Double
  d = dif / dis :: Double
  lval = x' - dis' * d
  next = if d >= 0 then n else ceiling $ y' / (-d)
  calc (t1,t2) (t3,t4) = (t4 - t2) `quotRem` (t3 - t1)
  cant = if null xs then True else calc (j,y) (i,x) /= calc (head xs) (j,y)

main :: IO ()
main = do
  n <- getInt
  array <- getInts
  print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0

import Control.Applicative
import Control.Monad
import Data.Int (Int64)
import Data.Maybe
import Debug.Trace
import qualified Data.ByteString.Char8 as C

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

getInts :: IO [Int64]
getInts = map readInt . C.words <$> C.getLine

getInt :: IO Int64
getInt = readInt <$> C.getLine

gao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int
gao s [] n res = res + if s < n then 1 else 0
gao _ [_] _ res = res + 1
gao s all@((i,x) : (j,y) : xs) n res
  | m /= 0 || l <= 0 = if s < i then gao i all n (res+1) else gao next xs n (res+2)
  | cant = gao next xs n $ res + 1
  | otherwise = gao i ((j,y):xs) n res
  where
  (d,m) = (y - x) `quotRem` (j - i)
  l = x - (i - s) * d
  cant = if null xs then True else (snd $ head xs) /= (y + d * ((fst $ head xs) - j))
  next = if null xs then n else fst $ head xs

main :: IO ()
main = do
  n <- getInt
  array <- getInts
  print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0

import Control.Applicative
import Control.Monad
import Data.Int (Int64)
import Data.Maybe
import Debug.Trace
import qualified Data.ByteString.Char8 as C

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

getInts :: IO [Int64]
getInts = map readInt . C.words <$> C.getLine

getInt :: IO Int64
getInt = readInt <$> C.getLine

gao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int
gao s [] n res = res + if s < n then 1 else 0
gao _ [_] _ res = res + 1
gao s all@((i,x) : (j,y) : xs) n res
  | m /= 0 || l <= 0 = if x > i - s then gao j ((j,y):xs) n (res+1) else gao i xs n (res+1)
  | cant = gao next xs n $ res + 1
  | otherwise = gao i ((j,y):xs) n res
  where
  (d,m) = (y - x) `quotRem` (j - i)
  l = x - (i - s) * d
  cant = if null xs then True else (snd $ head xs) /= (y + d * ((fst $ head xs) - j))
  next' = if d >= 0 then n else j + (y-1) `quot` (-d) + 1
  next = if null xs then next' else fst $ head xs

main :: IO ()
main = do
  n <- getInt
  array <- getInts
  print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0

import Control.Applicative
import Control.Monad
import Data.Int (Int64)
import Data.Maybe
import Debug.Trace
import qualified Data.ByteString.Char8 as C

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

getInts :: IO [Int64]
getInts = map readInt . C.words <$> C.getLine

getInt :: IO Int64
getInt = readInt <$> C.getLine

gao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int
gao s [] n res = res + if s < n then 1 else 0
gao _ [_] _ res = res + 1
gao s all@((i,x) : (j,y) : xs) n res
  | m /= 0 || l <= 0 = gao j ((j,y) : xs) n $ res + 1
  | otherwise = gao next xs' n $ res + 1
  where
  (d,m) = (y - x) `quotRem` (j - i)
  l = x - (i - s) * d
  next = if d >= 0 then n else j + (y-1) `quot` (-d) + 1
  xs' = dropWhile (\(k,z) -> z == (k-j)*d + y) xs

main :: IO ()
main = do
  n <- getInt
  array <- getInts
  print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0

import Control.Applicative
import Control.Monad
import Data.Int (Int64)
import Data.Maybe
import Debug.Trace
import qualified Data.ByteString.Char8 as C

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

getInts :: IO [Int64]
getInts = map readInt . C.words <$> C.getLine

getInt :: IO Int64
getInt = readInt <$> C.getLine

gao :: Int64 -> [(Int64, Int64)] -> Int64 -> Int -> Int
gao s [] n res = res + if s < n then 1 else 0
gao _ [_] _ res = res + 1
gao s all@((i,x) : (j,y) : xs) n res
  | m /= 0 || l <= 0 = if s < i then gao j ((j,y):xs) n (res+1) else gao next xs n (res+2)
  | cant = gao next xs n $ res + 1
  | otherwise = gao i ((j,y):xs) n res
  where
  (d,m) = (y - x) `quotRem` (j - i)
  l = x - (i - s) * d
  cant = if null xs then True else (snd $ head xs) /= (y + d * ((fst $ head xs) - j))
  next = if null xs then n else fst $ head xs

main :: IO ()
main = do
  n <- getInt
  array <- getInts
  print $ gao 0 [k | k@(_,i) <- zip [0..] array, i > 0] n 0


Mocha is a young girl from high school. She has learned so much interesting knowledge from her teachers, especially her math teacher. Recently, Mocha is learning about binary system and very interested in bitwise operation.This day, Mocha got a sequence $$$a$$$ of length $$$n$$$. In each operation, she can select an arbitrary interval $$$[l, r]$$$ and for all values $$$i$$$ ($$$0\leq i \leq r-l$$$), replace $$$a_{l+i}$$$ with $$$a_{l+i} \,\&\, a_{r-i}$$$ at the same time, where $$$\&$$$ denotes the bitwise AND operation. This operation can be performed any number of times.For example, if $$$n=5$$$, the array is $$$[a_1,a_2,a_3,a_4,a_5]$$$, and Mocha selects the interval $$$[2,5]$$$, then the new array is $$$[a_1,a_2\,\&\, a_5, a_3\,\&\, a_4, a_4\,\&\, a_3, a_5\,\&\, a_2]$$$.Now Mocha wants to minimize the maximum value in the sequence. As her best friend, can you help her to get the answer?

Each test contains multiple test cases.  The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the sequence. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \le a_i \le 10^9$$$).

For each test case, print one integer — the minimal value of the maximum value in the sequence.

NoteIn the first test case, Mocha can choose the interval $$$[1,2]$$$, then the sequence becomes $$$[ 0, 0]$$$, where the first element is $$$1\,\&\,2$$$, and the second element is $$$2\,\&\,1$$$.In the second test case, Mocha can choose the interval $$$[1,3]$$$, then the sequence becomes $$$[ 1,1,1]$$$, where the first element is $$$1\,\&\,3$$$, the second element is $$$1\,\&\,1$$$, and the third element is $$$3\,\&\,1$$$.

{-# LANGUAGE BangPatterns #-}

module Main where

import qualified Data.ByteString.Char8 as C8
import           Data.Maybe (fromJust)
import           Control.Monad.Reader (replicateM_)
import           Data.Bits (Bits((.&.)))
import           Data.List (sort)

readInput :: C8.ByteString -> [[Int]]
readInput = map
  (map
     (\str -> let (Just (i, _)) = C8.readInt str
              in i)
   . C8.words)
  . C8.lines

main :: IO ()
main = do
  t <- readLn :: IO Int
  replicateM_ t
    $ do
      n <- readLn :: IO Int
      sequence <- map (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine
      print $ solve sequence

solve :: [Int] -> Int
solve [x] = x
solve xs = foldr (.&.) (2 ^ 31-1) xs
{->>>solve [1,2]
0
-}

import Control.Arrow ((>>>))
import Data.Bits ((.&.))

solve :: [Int] -> Int
solve = foldl1 (.&.)

process [] = []
process (x:y:ys) = show (solve ((map read . words) y)) : process ys

main = interact $ lines >>> drop 1 >>> process >>> unlines

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

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    unused <- getLine
    line <- getLine
    let numbers = map read $ words line :: [Int]
    putStrLn $ show $ foldl1 (.&.) numbers

import Data.Bits ((.&.))

main = do
    t <- read <$> getLine :: IO Int
    mapM_ solve [1..t]

solve :: Int -> IO ()
solve _ = do
    getLine
    a <- map read . words <$> getLine :: IO [Int]
    print $ foldr1 (.&.) a

import Control.Arrow ((>>>))
import Data.Bits ((.&.))

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

solve :: [Int] -> Int
solve = foldl1 (.&.)

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

-- import Debug.Trace
import Data.Bits

type InType  = [Int]
type OutType = Int

inpLines :: Int
inpLines = 2

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf x l  = take x l : chunksOf x (drop x l)

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

solve :: InType -> OutType
solve = foldr (.&.) all_bits
    where all_bits = 2 ^ 31 - 1

receive :: [String] -> InType
receive [n, a] = toArr a
receive _      = undefined

main :: IO ()
main = interact $
  unlines . map (show . solve . receive) . chunksOf inpLines . tail . lines
    where showb True = "YES"
          showb False = "NO"

{-# LANGUAGE BangPatterns #-}

module Main where

import qualified Data.ByteString.Char8 as C8
import           Data.Maybe (fromJust)
import           Control.Monad.Reader (replicateM_)
import           Data.Bits (Bits((.&.)))
import           Data.List (sort)

readInput :: C8.ByteString -> [[Int]]
readInput = map
  (map
     (\str -> let (Just (i, _)) = C8.readInt str
              in i)
   . C8.words)
  . C8.lines

main :: IO ()
main = do
  t <- readLn :: IO Int
  replicateM_ t
    $ do
      n <- readLn :: IO Int
      sequence <- map (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine
      print $ solve sequence

solve :: [Int] -> Int
solve [x] = x
solve xs = maximum xs .&. minimum xs
{->>>solve [3,11,3,7]
3
-}

{-# LANGUAGE BangPatterns #-}

module Main where

import qualified Data.ByteString.Char8 as C8
import           Data.Maybe (fromJust)
import           Control.Monad.Reader (replicateM_)
import           Data.List (sort)

readInput :: C8.ByteString -> [[Int]]
readInput = map
  (map
     (\str -> let (Just (i, _)) = C8.readInt str
              in i)
   . C8.words)
  . C8.lines

main :: IO ()
main = do
  t <- readLn :: IO Int
  replicateM_ t
    $ do
      n <- readLn :: IO Int
      sequence <- map (fst . fromJust . C8.readInt) . C8.words <$> C8.getLine
      print $ solve sequence

solve :: [Int] -> Int
solve [x] = x
solve xs = y - z - 1
  where
    (y:z:ys) = reverse $ sort xs
{->>>solve [3,11,3,7]
3
-}


This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers $$$a_1, a_2, \dots, a_n$$$.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers $$$f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q)$$$, where $$$a_1 \dots a_p$$$ and $$$b_1 \dots b_q$$$ are digits of two integers written in the decimal notation without leading zeros.In other words, the function $$$f(x, y)$$$ alternately shuffles the digits of the numbers $$$x$$$ and $$$y$$$ by writing them from the lowest digits to the older ones, starting with the number $$$y$$$. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: $$$$$$f(1111, 2222) = 12121212$$$$$$ $$$$$$f(7777, 888) = 7787878$$$$$$ $$$$$$f(33, 44444) = 4443434$$$$$$ $$$$$$f(555, 6) = 5556$$$$$$ $$$$$$f(111, 2222) = 2121212$$$$$$Formally,  if $$$p \ge q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$;  if $$$p < q$$$ then $$$f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q$$$. Mishanya gives you an array consisting of $$$n$$$ integers $$$a_i$$$, your task is to help students to calculate $$$\sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j)$$$ modulo $$$998\,244\,353$$$.

The first line of the input contains a single integer $$$n$$$ ($$$1 \le n \le 100\,000$$$) — the number of elements in the array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the elements of the array.

Print the answer modulo $$$998\,244\,353$$$.

import Control.Monad
import Data.List
import qualified Data.Map as M
import qualified Data.Sequence as S

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

output :: Show a => [a] -> IO ()
output = putStrLn <$> unwords <$> map show

_MOD = 998244353

pad x 0 = x
pad x k = x`mod`10 + 100 * pad (x`div`10) (k-1)

digits 0 = 0
digits x = 1 + digits (x`div`10)

main = do
  getLine --n
  a <- input :: IO [Integer]
  let step digits count r x = (r + count * (pad x digits + 10 * pad x (digits-1))) `mod` _MOD
  print
    $ (`mod`_MOD)
    $ sum
    $ map (\xs -> foldl' (step (head xs) (fromIntegral $ length xs)) 0 a)
    $ group
    $ sort
    $ map digits
    $ a


You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times:  if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;  ...  remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.

The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.

Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).

readTokens :: Read a => IO [a]
readTokens = getLine >>= (return . map read . words)

dropMax :: Eq a => a -> Int -> [a] -> (Int, [a])
dropMax _ k []  = (k, [])
dropMax _ 0 lst = (0, lst)
dropMax v k (x:t)
  | x == v = dropMax v (k - 1) t
  | otherwise = (k', (x: t')) where
      (k', t') = dropMax v k t

solve :: Int -> String -> String
solve k s = solve' k 'a' s
  where solve' 0 _  s = s
        solve' k ch s = solve' k' ch' s'
          where (k', s') = dropMax ch k s
                ch' = succ ch

main :: IO()
main = do
  [_, k] <- (readTokens::IO [Int])
  l <- getLine
  putStrLn $ solve k l