readInt x = read x :: Int
main = interact $ show . solve' . map readInt . words

solve' (_:xs) = if length xs < 3 then length xs else solve xs
solve xs =
	maximum $ zipWith f ([(0,0)] ++ init ls) (tail rs ++ [(0,0)])
	where
		ls = incLengths xs
		rs = map (\x -> (-fst x,snd x)) (reverse $ incLengths $ map negate $ reverse xs)
		f a b = if (fst a + 2 <= fst b) then (1 + snd a + snd b) else (1 + max (snd a) (snd b))

incLengths (x:xs) = scanl f (x,1) xs
	where f a x = if fst a < x then (x,snd a+1) else (x,1)

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

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

main = do
  getLine
  as <- getInts :: IO [Int]

  let
    xs = scanl (\v (a, b) -> if a < b then v + 1 else 1) 1 $ zip as $ tail as
    ys = scanr (\(a, b) v -> if a < b then v + 1 else 1) 1 $ zip as $ tail as

  print $ maximum $ zipWith3 (\a b f -> if f then a + 1 + b else max (a+1) (b+1)) (0:xs) (tail ys ++ [0]) (zipWith (\a b -> a + 1 < b) (0:as) (tail as ++ [2*10^9]))

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

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

main = do
  getLine
  as <- getInts :: IO [Int]

  let
    xs = scanl (\v (a, b) -> if a < b then v + 1 else 1) 1 $ zip as $ tail as
    ys = scanr (\(a, b) v -> if a < b then v + 1 else 1) 1 $ zip as $ tail as

  print $ maximum $ zipWith3 (\a b f -> if f then a + 1 + b else max (a+1) (b+1)) (0:xs) (tail ys ++ [0]) (zipWith (\a b -> a + 1 < b) (0:as) (tail as ++ [2*10^9]))

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE ViewPatterns        #-}
{-# LANGUAGE BangPatterns        #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IO
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8       as C
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import           Data.Functor
import           Data.Int
import qualified Data.IntMap                 as M
import           Data.IORef
import           Data.List
import           Data.Maybe
import           Data.Monoid
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as S
import           Data.Word
import           Debug.Trace
import           Text.Printf

-- I/O

readInts :: C.ByteString -> [Int]
readInts = map fst . mapMaybe C.readInt . C.words

getInts :: IO [Int]
getInts = readInts <$> C.getLine

readNums :: Num a => C.ByteString -> [a]
readNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words

getNums :: Num a => IO [a]
getNums = readNums <$> C.getLine

cast :: (Integral a, Integral b) => a -> b
cast = fromIntegral

-----

spl (x:y:z)
  | x < y = let (a:as) = spl (y:z) in (x:a):as
  | otherwise = [x] : spl (y:z)
spl [x] = [[x]]
spl [] = []

main :: IO ()
main = do
  _ <- getLine
  ns <- spl <$> getInts
  -- print ns

  let ans = foldl' max 0 $ map length ns ++ zipWith f ns (tail ns)

      f [_] ys = length ys + 1
      f xs [_] = length xs + 1
      f xs ys@(y1:y2:_)
        | y2 - last xs >= 2 = length xs + length ys
        | y1 - last (init xs) >= 2 = length xs + length ys
        | otherwise = max (length xs) (length ys) + 1

  print ans

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Sequence ((<|),(|>),(><),ViewL(..),ViewR(..))
import qualified Data.Sequence as Seq
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
for :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()
for !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)
{-# INLINE for #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  getLine
  xs <- map readInt.B.words <$> B.getLine
  print $ solve xs

solve :: [Int] -> Int
solve xs = go 0 $ splitBy (>=) xs
   where
     go !res (xs:[y]:xss) = go (max res $ length xs + 1) ([y]:xss)
     go !res ([x]:ys:xss) = go (max res $ length ys + 1) (ys:xss)
     go !res (xs:(y:y':ys):xss) = case reverse xs of
        (x:x':xs') | x' + 1 < y || x + 1 < y' -> go (max res $ length xs + length ys + 2) ((y:y':ys):xss)
                   | otherwise -> go (max res $ length xs `max` (length ys + 2) + 1) ((y:y':ys):xss)
     go !res [xs] = max res $ length xs

splitBy :: (a -> a -> Bool) -> [a] -> [[a]]
splitBy p xs = foldr f [] xs
   where
     f x (yys@(y:_):yss)
       | p x y = [x]:yys:yss
       | otherwise = (x:yys):yss
     f x [] = [[x]]

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
import Data.Maybe
import Data.Char
import Data.List
import Data.IORef
import Data.Array.IO
import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map              as Map
import qualified Data.Set              as Set
import Text.Printf

getint :: IO Int
getint  = head <$> getints

getints :: IO [Int]
getints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine

getnums :: Num a => IO [a]
getnums = map (fromIntegral . fst) . mapMaybe BS.readInteger . BS.words <$> BS.getLine

getstr = getLine

solveCont :: Int -> [Int] -> Int -> [Int]
solveCont _ [] _ = []
solveCont prev (a:as) pvc
  | prev < a = (pvc + 1) : (solveCont a as (pvc + 1))
  | otherwise = 1 : (solveCont a as 1)

solveCont' :: Int -> [Int] -> Int -> [Int]
solveCont' _ [] _ = []
solveCont' prev (a:as) pvc
  | prev > a = (pvc + 1) : (solveCont' a as (pvc + 1))
  | otherwise = 1 : (solveCont' a as 1)

solve (f1:f2:f3:fs) (b1:b2:b3:bs) (a1:a2:a3:as)
  | a3 - a1 >= 2 = max (f1 + b3 + 1) nxt
  | otherwise = maximum [f1 + 1, f2, b3 + 1, b2, nxt]
  where nxt = solve (f2:f3:fs) (b2:b3:bs) (a2:a3:as)
solve (f1:f2:fs) (b1:b2:bs) (a1:a2:as) =
  maximum [f1 + 1, f2, b2 + 1, b1]

solve2 (f1:f2:fs) (b1:b2:bs) =
  maximum [f1 + 1, f2, b1, b2 + 1]

main = do
  n <- getint
  as <- getints
  if n == 1
    then do putStrLn "1"
    else do let fwdLen = solveCont (-1) as 0
                bckLen = reverse $ solveCont' (1000000001) (reverse as) 0
            putStrLn (show (max (solve fwdLen bckLen as) (solve2 fwdLen bckLen)))

maxTo = scanl (\(c,n) x-> if x > n then (c+1, x) else (1, x)) (0,-1)
maxFrom = reverse . scanl (\(c,n) x-> if x < n then (c+1, x) else (1, x)) (0,10^9+5) . reverse
s(_:l)=maximum$zipWith f mxt (tail mxf) where
  mxt = maxTo l
  mxf = maxFrom l
  f (c1,a) (c2,b) | a < b-1 = c1+c2+1
    | otherwise = max (c1+1) (c2+1)
main=interact$show.s.map read.words

import Data.Maybe
import Data.List
import Data.Function
import qualified Data.IntSet as IS
import Text.Printf (printf)

subseqs :: [Int] -> [[Int]]
subseqs [] = []
subseqs (x : xs) = go [x] xs
  where
    go acc [] = [reverse acc]
    go acc (x : xs)
      | head acc < x = go (x : acc) xs
      | otherwise    = (reverse acc) : go [x] xs

solve :: [Int] -> Int
solve as = go 0 (map (\s -> (s, reverse s, length s)) $ subseqs as)
  where
    spans _ [] = []
    spans p xs =
      case span p xs of
        ([], []) -> []
        ([], (x : xs')) -> [x] : spans p xs'
        (s, xs')  -> s : spans p xs'

    go best [] = best
    go best [(_, _, l)] = max best l
    go best ((s, z, l) : (x@(s', _, l')) : xs) =
      go (maximum [best,
                   case z of
                     (_ : t : _) | t + 1 < head s' -> l + l'
                     _ -> l' + 1,
                   case s' of
                     (_ : h : _) | head z + 1 < h -> l + l'
                     _ -> l + 1]) (x : xs)

main :: IO ()
main = do
  _ <- getLine
  as <- fmap (map read . words) getLine
  print $ solve as

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.List

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  show `fmap` solve n `fmap` replicateM n poi
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve 1 _ = 1
solve 2 _ = 2
solve n xs = min n $ max (maximum $ map (+1) es) (maximum (zipWith4 (\e x y s -> if y > x + 1 then e + s + 1 else 0) es xs (drop 2 xs) (drop 2 ss)))
  where
    es = scanl (\l (a, b) -> if a < b then l + 1 else 1) (1 :: Int) $ zip xs (tail xs :: [Int])
    ss = concatMap reverse $ groupBy (<) es

{-
_ 7 1 2 3

<= 1
a[i] < a[i + 2]
[1,1,2,1,2,3]
[1,2,1,3,2,1]
-}

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.List

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  show `fmap` solve `fmap` replicateM n poi
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve xs = max (maximum es) (maximum (zipWith4 (\e x y s -> if y > x + 1 then e + s + 1 else 0) (1:es) (minBound:xs) (tail xs) (tail ss)))
  where
    es = scanl (\l (a, b) -> if a < b then l + 1 else 1) (1 :: Int) $ zip xs (tail xs :: [Int])
    ss = concatMap reverse $ groupBy (<) es

{-
_ 7 1 2 3

<= 1
a[i] < a[i + 2]
[1,1,2,1,2,3]
[1,2,1,3,2,1]
-}

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.List

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  show `fmap` solve `fmap` replicateM n poi
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve [_] = 1
solve [_, _] = 2
solve xs = max (maximum $ head ss:map (+1) (tail ss)) (maximum (zipWith4 (\e x y s -> if y > x + 1 then e + s + 1 else 0) es xs (drop 2 xs) (drop 2 ss)))
  where
    es = scanl (\l (a, b) -> if a < b then l + 1 else 1) (1 :: Int) $ zip xs (tail xs :: [Int])
    ss = concatMap reverse $ groupBy (<) es

{-
_ 7 1 2 3

<= 1
a[i] < a[i + 2]
[1,1,2,1,2,3]
[1,2,1,3,2,1]
-}

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

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

main = do
  getLine
  as <- getInts :: IO [Int]

  let
    xs = scanl (\v (a, b) -> if a <= b then v + 1 else 1) 1 $ zip as $ tail as
    ys = scanr (\(a, b) v -> if a <= b then v + 1 else 1) 1 $ zip as $ tail as

  print $ maximum $ zipWith3 (\a b f -> if f then a + 1 + b else max (a+1) (b+1)) (0:xs) (tail ys ++ [0]) (zipWith (<=) (0:as) (tail as ++ [2*10^9]))

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Array.IO.Safe
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

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

main = do
  getLine
  as <- getInts :: IO [Int]

  let
    xs = scanl (\v (a, b) -> if a <= b then v + 1 else 1) 1 $ zip as $ tail as
    ys = scanr (\(a, b) v -> if a <= b then v + 1 else 1) 1 $ zip as $ tail as

  print $ maximum $ zipWith (\a b -> a + 1 + b) (0:xs) (tail ys ++ [0])

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE ViewPatterns        #-}
{-# LANGUAGE BangPatterns        #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IO
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8       as C
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import           Data.Functor
import           Data.Int
import qualified Data.IntMap                 as M
import           Data.IORef
import           Data.List
import           Data.Maybe
import           Data.Monoid
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as S
import           Data.Word
import           Debug.Trace
import           Text.Printf

-- I/O

readInts :: C.ByteString -> [Int]
readInts = map fst . mapMaybe C.readInt . C.words

getInts :: IO [Int]
getInts = readInts <$> C.getLine

readNums :: Num a => C.ByteString -> [a]
readNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words

getNums :: Num a => IO [a]
getNums = readNums <$> C.getLine

cast :: (Integral a, Integral b) => a -> b
cast = fromIntegral

-----

main :: IO ()
main = do
  _ <- getLine
  ns <- getInts
  let ss = groupBy (<) ns
      ans = foldl' max 0 $ map length ss ++ zipWith f ss (tail ss)
      f xs ys
        | length ys == 1 = length xs + 1
        | length xs == 1 = length ys + 1
        | (ys !! 1) - last xs >= 2 = length xs + length ys
        | otherwise = max (length xs) (length ys) + 1
  print ans

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE ViewPatterns        #-}
{-# LANGUAGE BangPatterns        #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IO
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8       as C
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import           Data.Functor
import           Data.Int
import qualified Data.IntMap                 as M
import           Data.IORef
import           Data.List
import           Data.Maybe
import           Data.Monoid
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as S
import           Data.Word
import           Debug.Trace
import           Text.Printf

-- I/O

readInts :: C.ByteString -> [Int]
readInts = map fst . mapMaybe C.readInt . C.words

getInts :: IO [Int]
getInts = readInts <$> C.getLine

readNums :: Num a => C.ByteString -> [a]
readNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words

getNums :: Num a => IO [a]
getNums = readNums <$> C.getLine

cast :: (Integral a, Integral b) => a -> b
cast = fromIntegral

-----

main :: IO ()
main = do
  _ <- getLine
  ns <- getInts
  let ss = map length $ groupBy (<) ns
      ans = foldl' max 0 $ ss ++ zipWith (+) ss (tail ss)
  print ans

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE ViewPatterns        #-}
{-# LANGUAGE BangPatterns        #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IO
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8       as C
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import           Data.Functor
import           Data.Int
import qualified Data.IntMap                 as M
import           Data.IORef
import           Data.List
import           Data.Maybe
import           Data.Monoid
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as S
import           Data.Word
import           Debug.Trace
import           Text.Printf

-- I/O

readInts :: C.ByteString -> [Int]
readInts = map fst . mapMaybe C.readInt . C.words

getInts :: IO [Int]
getInts = readInts <$> C.getLine

readNums :: Num a => C.ByteString -> [a]
readNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words

getNums :: Num a => IO [a]
getNums = readNums <$> C.getLine

cast :: (Integral a, Integral b) => a -> b
cast = fromIntegral

-----

main :: IO ()
main = do
  _ <- getLine
  ns <- getInts
  let ss = map length $ groupBy (<) ns
      ans = foldl' max 0 $ zipWith (+) ss (tail ss)
  print ans

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE ViewPatterns        #-}
{-# LANGUAGE BangPatterns        #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IO
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8       as C
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import           Data.Functor
import           Data.Int
import qualified Data.IntMap                 as M
import           Data.IORef
import           Data.List
import           Data.Maybe
import           Data.Monoid
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as S
import           Data.Word
import           Debug.Trace
import           Text.Printf

-- I/O

readInts :: C.ByteString -> [Int]
readInts = map fst . mapMaybe C.readInt . C.words

getInts :: IO [Int]
getInts = readInts <$> C.getLine

readNums :: Num a => C.ByteString -> [a]
readNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words

getNums :: Num a => IO [a]
getNums = readNums <$> C.getLine

cast :: (Integral a, Integral b) => a -> b
cast = fromIntegral

-----

main :: IO ()
main = do
  _ <- getLine
  ns <- groupBy (<) <$> getInts

  let ans = foldl' max 0 $ map length ns ++ zipWith f ns (tail ns)

      f [_] ys = length ys + 1
      f xs [_] = length xs + 1
      f xs ys@(_:y2:_)
        | y2 - head xs >= 2 = length xs + length ys
        | otherwise = max (length xs) (length ys) + 1

  print ans

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE ViewPatterns        #-}
{-# LANGUAGE BangPatterns        #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IO
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8       as C
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import           Data.Functor
import           Data.Int
import qualified Data.IntMap                 as M
import           Data.IORef
import           Data.List
import           Data.Maybe
import           Data.Monoid
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as S
import           Data.Word
import           Debug.Trace
import           Text.Printf

-- I/O

readInts :: C.ByteString -> [Int]
readInts = map fst . mapMaybe C.readInt . C.words

getInts :: IO [Int]
getInts = readInts <$> C.getLine

readNums :: Num a => C.ByteString -> [a]
readNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words

getNums :: Num a => IO [a]
getNums = readNums <$> C.getLine

cast :: (Integral a, Integral b) => a -> b
cast = fromIntegral

-----

main :: IO ()
main = do
  _ <- getLine
  ns <- groupBy (<) <$> getInts

  let ans = foldl' max 0 $ map length ns ++ zipWith f ns (tail ns)

      f [_] ys = length ys + 1
      f xs [_] = length xs + 1
      f xs ys@(_:y2:_)
        | y2 - last xs >= 2 = length xs + length ys
        | otherwise = max (length xs) (length ys) + 1

  print ans

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies        #-}
{-# LANGUAGE ViewPatterns        #-}
{-# LANGUAGE BangPatterns        #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IO
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8       as C
import           Data.Char
import qualified Data.Foldable               as F
import           Data.Function
import           Data.Functor
import           Data.Int
import qualified Data.IntMap                 as M
import           Data.IORef
import           Data.List
import           Data.Maybe
import           Data.Monoid
import qualified Data.Sequence               as Seq
import qualified Data.Set                    as S
import           Data.Word
import           Debug.Trace
import           Text.Printf

-- I/O

readInts :: C.ByteString -> [Int]
readInts = map fst . mapMaybe C.readInt . C.words

getInts :: IO [Int]
getInts = readInts <$> C.getLine

readNums :: Num a => C.ByteString -> [a]
readNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words

getNums :: Num a => IO [a]
getNums = readNums <$> C.getLine

cast :: (Integral a, Integral b) => a -> b
cast = fromIntegral

-----

main :: IO ()
main = do
  _ <- getLine
  ns <- groupBy (<) <$> getInts

  let ans = foldl' max 0 $ map length ns ++ zipWith f ns (tail ns)

      f [_] ys = length ys + 1
      f xs [_] = length xs + 1
      f xs ys@(y1:y2:_)
        | y2 - last xs >= 2 = length xs + length ys
        | y1 - last (init xs) >= 2 = length xs + length ys
        | otherwise = max (length xs) (length ys) + 1

  print ans

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Sequence ((<|),(|>),(><),ViewL(..),ViewR(..))
import qualified Data.Sequence as Seq
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
for :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()
for !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)
{-# INLINE for #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  getLine
  xs <- map readInt.B.words <$> B.getLine
  print $ solve xs

solve :: [Int] -> Int
solve xs = go 0 $ splitBy (>=) xs
   where
     go !res (xs:[y]:xss) = go (max res $ length xs + 1) ([y]:xss)
     go !res ([x]:ys:xss) = go (max res $ length ys + 1) (ys:xss)
     go !res (xs:(y:y':ys):xss) = case reverse xs of
        (x:x':xs') | x' + 1 < y || x + 1 < y' -> go (max res $ length xs + length ys + 2) ((y:y':ys):xss)
                   | otherwise -> go (max res $ length xs `max` (length ys + 2 ) + 1) ([y]:xss)
     go !res [xs] = max res $ length xs

splitBy :: (a -> a -> Bool) -> [a] -> [[a]]
splitBy p xs = foldr f [] xs
   where
     f x (yys@(y:_):yss)
       | p x y = [x]:yys:yss
       | otherwise = (x:yys):yss
     f x [] = [[x]]

main=interact$show.f.map read.words
f(p:n:xs)=go [] 1 xs
   where
     go used i (x:xs)
       | h <- mod x p, elem h used = i
       | otherwise = go (mod x p:used) (i+1) xs
     go _ _ _ = -1

readInt x = read x :: Int
main = interact $ show . solve' . map readInt . words

solve' (_:xs) = if length xs < 3 then length xs else solve xs
solve xs =
	maximum $ zipWith f (init $ init ls) (tail $ tail rs)
	where
		ls = incLengths xs
		rs = map (\x -> (-fst x,snd x)) (reverse $ incLengths $ map negate $ reverse xs)
		f a b = if (fst a + 2 <= fst b) then (1 + snd a + snd b) else 2

incLengths (x:xs) = scanl f (x,1) xs
	where f a x = if fst a < x then (x,snd a+1) else (x,1)

readInt x = read x :: Int
main = interact $ show . solve' . map readInt . words

solve' (_:xs) = if length xs < 3 then length xs else solve xs
solve xs =
	maximum $ zipWith f ([(0,0)] ++ init ls) (tail rs ++ [(0,0)])
	where
		ls = incLengths xs
		rs = map (\x -> (-fst x,snd x)) (reverse $ incLengths $ map negate $ reverse xs)
		f a b = if (fst a + 2 <= fst b) then (1 + snd a + snd b) else 2

incLengths (x:xs) = scanl f (x,1) xs
	where f a x = if fst a < x then (x,snd a+1) else (x,1)

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
import Data.Maybe
import Data.Char
import Data.List
import Data.IORef
import Data.Array.IO
import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map              as Map
import qualified Data.Set              as Set
import Text.Printf

getint :: IO Int
getint  = head <$> getints

getints :: IO [Int]
getints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine

getnums :: Num a => IO [a]
getnums = map (fromIntegral . fst) . mapMaybe BS.readInteger . BS.words <$> BS.getLine

getstr = getLine

solveCont :: Int -> [Int] -> Int -> [Int]
solveCont _ [] _ = []
solveCont prev (a:as) pvc
  | prev < a = (pvc + 1) : (solveCont a as (pvc + 1))
  | otherwise = 1 : (solveCont a as 1)

solveCont' :: Int -> [Int] -> Int -> [Int]
solveCont' _ [] _ = []
solveCont' prev (a:as) pvc
  | prev > a = (pvc + 1) : (solveCont' a as (pvc + 1))
  | otherwise = 1 : (solveCont' a as 1)

solve (f1:f2:f3:fs) (b1:b2:b3:bs) (a1:a2:a3:as)
  | a3 - a1 >= 2 = max (f1 + b3 + 1) nxt
  | otherwise = maximum [f1 + 1, f2, b3 + 1, b2, nxt]
  where nxt = solve (f2:f3:fs) (b2:b3:bs) (a2:a3:as)
solve (f1:f2:fs) (b1:b2:bs) (a1:a2:as) =
  maximum [f1 + 1, f2, b2 + 1, b1]

main = do
  n <- getint
  as <- getints
  if n == 1
    then do putStrLn "1"
    else do let fwdLen = solveCont (-1) as 0
                bckLen = reverse $ solveCont' (1000000001) (reverse as) 0
            putStrLn (show (solve fwdLen bckLen as))

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
import Data.Maybe
import Data.Char
import Data.List
import Data.IORef
import Data.Array.IO
import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map              as Map
import qualified Data.Set              as Set
import Text.Printf

getint :: IO Int
getint  = head <$> getints

getints :: IO [Int]
getints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine

getnums :: Num a => IO [a]
getnums = map (fromIntegral . fst) . mapMaybe BS.readInteger . BS.words <$> BS.getLine

getstr = getLine

solveCont :: Int -> [Int] -> Int -> [Int]
solveCont _ [] _ = []
solveCont prev (a:as) pvc
  | prev < a = (pvc + 1) : (solveCont a as (pvc + 1))
  | otherwise = 1 : (solveCont a as 1)

solveCont' :: Int -> [Int] -> Int -> [Int]
solveCont' _ [] _ = []
solveCont' prev (a:as) pvc
  | prev > a = (pvc + 1) : (solveCont' a as (pvc + 1))
  | otherwise = 1 : (solveCont' a as 1)

solve (f1:f2:f3:fs) (b1:b2:b3:bs) (a1:a2:a3:as)
  | a3 - a1 >= 2 = max (f1 + b3 + 1) nxt
  | otherwise = maximum [f1 + 1, f2, b3 + 1, b2, nxt]
  where nxt = solve (f2:f3:fs) (b2:b3:bs) (a2:a3:as)
solve (f1:f2:fs) (b1:b2:bs) (a1:a2:as) =
  maximum [f1 + 1, f2, b2 + 1, b1]

solve2 (f1:f2:fs) (b1:b2:bs) =
  maximum [f1, f2 + 1, b1, b2 + 1]

main = do
  n <- getint
  as <- getints
  if n == 1
    then do putStrLn "1"
    else do let fwdLen = solveCont (-1) as 0
                bckLen = reverse $ solveCont' (1000000001) (reverse as) 0
            putStrLn (show (max (solve fwdLen bckLen as) (solve2 fwdLen bckLen)))

maxTo = scanl (\(c,n) x-> if x > n then (c+1, x) else (1, x)) (0,-1)
maxFrom = reverse . scanl (\(c,n) x-> if x < n then (c+1, x) else (1, x)) (0,10^9+5) . reverse
s(_:l)=maximum$zipWith f mxt (tail mxf) where
  mxt = maxTo l
  mxf = maxFrom l
  f (c1,a) (c2,b) | a < b-1 = c1+c2+1
    | otherwise = 1
main=interact$show.s.map read.words


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -Wno-name-shadowing #-}
{-# OPTIONS_GHC -Wno-type-defaults #-}

module Main where

import Control.Monad
import Data.Bifunctor
import Data.Functor
import Data.List
import Data.Ord
import Debug.Trace

readNumbers :: (Integral b, Read b) => IO [b]
readNumbers = fmap read . words <$> getLine

{-# WARNING todo "'todo' remains in code" #-}
{-# INLINEABLE todo #-}
todo :: a
todo = error "Not implemented"

main :: IO [()]
main = do
  [t] <- readNumbers
  replicateM t $ do
    [m] <- readNumbers
    a1s <- readNumbers
    a2s <- readNumbers
    print $ minimum $ zip (init $ scanl (+) 0 a2s) (tail $ scanr (+) 0 a1s) <&> uncurry max

-- max (sum (take i a2s)) (sum (drop (i + 1) a1s))

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

printResult = do
    m <- readLn :: IO Integer
    a <- readInts
    b <- readInts
    let
        c = scanl (+) 0 $ reverse $ tail a
        d = reverse $ scanl (+) 0 $ init b
        z = zipWith max c d
        r = minimum z
    print r

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

{-# LANGUAGE Strict #-}
{-# LANGUAGE LambdaCase #-}
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)
import Debug.Trace (trace)

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

testCase :: Scanner String
testCase = do
  m <- int
  as <- m >< int
  bs <- m >< int
  return . show $ solve as bs

solve :: [Int] -> [Int] -> Int
solve [_] _ = 0
solve as bs = minimum $ zipWith max (tail $ scanr (+) 0 as) (scanl (+) 0 bs)

-------------------------- 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 (,)

import Control.Monad
import Data.Array

solve :: IO ()
solve = do
    m <- readLn :: IO Int
    a0 <- readMany :: IO [Int]
    a1 <- readMany :: IO [Int]
    let s0 = listArray (0, m) $ scanl (+) 0 a0
        s1 = listArray (0, m) $ scanl (+) 0 a1
        f i = max (s0!m - s0!i) (s1!(i - 1))
    print $ minimum $ map f [1..m]

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

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


import Control.Monad
import Data.List

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

readInts :: IO [Integer]
readInts = readArray

readInt :: IO Integer
readInt = readLn

medlength :: [Integer] -> Integer
medlength l = if length l `mod` 2 == 1 then 1 else
    case drop (length l `div` 2 - 1) ls of
        x:y:xs -> y - x + 1
    where ls = sort l

solve :: ([Integer], [Integer]) -> Integer
solve (a, b) = medlength a * medlength b

readPair :: IO (Integer, Integer)
readPair = do
    x:y:[] <- readInts
    return (x, y)

reassoc :: [(a, b)] -> ([a], [b])
reassoc = foldl (\(xs, ys) (x, y) -> (x:xs, y:ys)) ([], [])

readInput :: IO ([Integer], [Integer])
readInput = fmap reassoc $ readLn >>= flip replicateM readPair

solveCase :: IO Integer
solveCase = fmap solve readInput

main :: IO ()
main = readLn >>= flip replicateM_ (solveCase >>= print)

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

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

import Data.Int

medianCount :: [Int] -> Int
medianCount x = let
  n = length x
  sx = sort x
  [lv, rv] = map (sx !!) [div (n-1) 2, div n 2]
  in  rv - lv + 1

(*!) :: Int -> Int -> Int64
x *! y = fromIntegral x * fromIntegral y

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n] <- readInts
    [x, y] <- transpose <$> replicateM n readInts
    putInt64s [medianCount x *! medianCount y]

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]

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

{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,
    ConstraintKinds, BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Array.IArray
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.Int
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable
import System.IO

------

type Hopper r = State [r]

type HopperT r = StateT [r]

runHopper :: Hopper r a -> [r] -> (a, [r])
runHopper = runState

evalHopper :: Hopper r a -> [r] -> a
evalHopper = evalState

runHopperT :: HopperT r m a -> [r] -> m (a, [r])
runHopperT = runStateT

evalHopperT :: Monad m => HopperT r m a -> [r] -> m a
evalHopperT = evalStateT

type MonadHopper r m = MonadState [r] m

pop :: MonadHopper r m => m (Maybe r)
pop = state f
  where
    f :: [r] -> (Maybe r, [r])
    f [] = (Nothing, [])
    f (q:qs) = (Just q, qs)

popJust :: MonadHopper r m => m r
popJust = fromJust <$> pop

------

popInt :: MonadHopper B.ByteString m => m Int
popInt = fst . fromJust . B.readInt <$> popJust

popInts :: MonadHopper B.ByteString m => m [Int]
popInts = map (fst . fromJust . B.readInt) . B.words <$> popJust

popInteger :: MonadHopper B.ByteString m => m Integer
popInteger = fst . fromJust . B.readInteger <$> popJust

popIntegers :: MonadHopper B.ByteString m => m [Integer]
popIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust

------

dropCR :: B.ByteString -> B.ByteString
dropCR s | not (B.null s) && B.last s == '\r' = B.init s
         | otherwise = s

bshow :: Show a => a -> B.ByteString
bshow = B.pack . show

main = B.interact go
  where
    go :: B.ByteString -> B.ByteString
    go = evalHopper run . map dropCR . B.lines

------

run :: Hopper B.ByteString B.ByteString
run = do
  t <- popInt
  B.unlines <$> replicateM t run1

run1 = do
  n <- popInt
  ps <- map (\[x, y] -> (x, y)) <$> replicateM n popIntegers
  return $ bshow (solve n ps)

map2 f (a, b) = (f a, f b)

solve :: Int -> [(Integer, Integer)] -> Integer
solve n ps =
  let xs = sort $ map fst ps
      ys = sort $ map snd ps in
    case n `rem` 2 of
      0 -> (\(cx, cy) -> cx * cy) $
           map2 ((\[a, b] -> b - a + 1) . take 2 . drop ((n `quot` 2) - 1)) $
           (xs, ys)
      1 -> 1


import Data.List

solve :: [String] -> String
solve [] = "B"
solve (a:xs) = if a == replicate 8 'R' then "R" else solve xs

testCase = do
    n <- getLine
    grid <- repeatDo 8 getLine
    putStrLn $ solve grid

repeatDo 0 m = return []

repeatDo n m = do
  x1 <- m
  x2 <- repeatDo (n - 1) m
  return (x1 : x2)

main = do
    n <- read `fmap` getLine :: IO Int
    repeatDo n testCase

import Control.Monad (forM, forM_)
import Data.List (nub, transpose)

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

main = do
  n <- readLn :: IO Int
  forM_
    [1 .. n]
    ( \_ -> do
        _ <- getLine
        ans <- forM [1 .. 8] (\_ -> do getLine)
        putStrLn $
          if any ((== True) . all (== 'R')) ans
            then "R"
            else "B"
    )

import Control.Monad (forM, forM_)
import Data.List (nub, transpose)

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

main = do
  n <- readLn :: IO Int
  forM_
    [1 .. n]
    ( \_ -> do
        _ <- getLine
        ans <- forM [1 .. 8] (\_ -> do getLine)
        print ans
        putStrLn $
          if any ((== True) . all (== 'R')) ans
            then "R"
            else "B"
    )

import Control.Monad (forM, forM_)
import Data.List (nub, transpose)

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

main = do
  n <- readLn :: IO Int
  forM_
    [1 .. n]
    ( \_ -> do
        ans <- forM [1 .. 8] (\_ -> do getLine)
        putStrLn $
          if any ((== True) . all (== 'R')) ans
            then "R"
            else "B"
    )


import Control.Applicative
import Data.Int
import Data.List (groupBy, sort)
import qualified Data.Map as M
import qualified Data.Set as S

main = do
  _ <- readLn :: IO Int
  xs <- readLs :: IO [Int64]
  let res = solve xs
  print $ length res
  putStrLn $ unwords . map show $ res

solve = map snd . sort . solve' [] . prepare
  where prepare = M.fromList . map (\xs -> let (x:_, ys) = unzip xs in (x, S.fromAscList ys)) .
          groupBy (\x y -> fst x == fst y) . sort . flip zip [0..]
        solve' acc m | M.null m = reverse acc
        solve' acc m = let ((x, is), m') = M.deleteFindMin m
                       in  case S.size is of
                             0 -> solve' acc m'
                             1 -> solve' ((S.findMin is, x) : acc) m'
                             n -> let (i, is') = S.deleteFindMin $ snd $ S.deleteFindMin is
                                  in  solve' acc $ M.insert x is' $
                                        M.insertWith (const $ S.insert i) (2*x) (S.singleton i) m'

readLs = map read . words <$> getLine

{-# LANGUAGE BangPatterns, ViewPatterns #-}
import qualified Data.Set as S
import qualified Data.IntSet as IS
import qualified Data.Map.Strict as M
import Data.Int
import Data.List
import Data.Ord
import Control.Applicative

main = interact exec
exec = (\xs -> show (length xs) ++ "\n" ++ unwords (map show xs)) . (\(n:xs) -> f (read n) (map read xs :: [Int64])) . words
f n = map fst . sortBy (comparing (IS.findMin . snd)) . M.assocs . (g <*> (S.fromAscList . M.keys)) . M.fromListWith IS.union . flip zip (map IS.singleton [n, n - 1..]) . reverse

g (!m) (!xs)
  | Just (x, h (M.delete x m) x (IS.toList $ m M.! x) -> (m', xs')) <- S.minView xs = g m' xs'
  | otherwise = m

h m _ [] xs = (m, xs)
h m x [j] xs = (M.insert x (IS.singleton j) m, xs)
h (!m) x (_:j:is) (!xs) = h (M.alter (Just . maybe (IS.singleton j) (IS.insert j)) (2 * x) m) x is (S.insert (2 * x) xs)

{-# LANGUAGE BangPatterns, ViewPatterns #-}
import qualified Data.IntMap.Strict as M
import qualified Data.IntSet as S
import Data.List
import Data.Ord
import Control.Applicative

main = interact exec
exec = (\xs -> show (length xs) ++ "\n" ++ unwords (map show xs)) . (\(n:xs) -> f (n :: Int) xs) . map read . words
f n = map fst . sortBy (comparing (S.findMin . snd)) . M.assocs . (g <*> (S.fromAscList . M.keys)) . M.fromListWith S.union . flip zip (map S.singleton [n, n - 1..]) . reverse

g (!m) (!xs)
  | Just (x, h (M.delete x m) x (S.toList $ m M.! x) -> (m', xs')) <- S.minView xs = g m' xs'
  | otherwise = m

h m _ [] xs = (m, xs)
h m x [j] xs = (M.insert x (S.singleton j) m, xs)
h (!m) x (_:j:is) (!xs) = h (M.alter (Just . maybe (S.singleton j) (S.insert j)) (2 * x) m) x is (S.insert (2 * x) xs)


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

toint s = (read s) :: Int

m = 200001

doit [] n s = []
doit (x:xs) n s =
  let t = x+s in -- t+k=n
  let w = mod (n-t+m) m in
  if w == 0 then
    doit xs (n-1) s
  else
    (n,w):(doit xs (n-1) (s+w))

printit [] = ""
printit ((a,b):xs) =
  "1 "++show(a)++" "++show(b)++"\n"++(printit xs)

solve::String -> String
solve ss =
  let n:aa = map toint $ words ss in
  let a = reverse $ take n aa in
  let r = doit a n 0 in
  show(length r + 1)++"\n"++(printit r)++"2 "++show(n)++" "++show(m)++"\n"

main = do
  interact $ solve

{-# LANGUAGE BangPatterns #-}

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

showTriple :: (Int,Int,Int) -> String
showTriple (x,y,z)
  = shows x $ (' ' :) $ shows y $ (' ' :) $ show z

printTriple :: (Int,Int,Int) -> IO ()
printTriple = putStrLn . showTriple

main :: IO ()
main = do
  n <- read <$> getLine
  getLine
  print $ n+1
  printTriple (2,n,1)
  printTriple (1,n,2*n)
  mapM_ printTriple $ [(2,j,2*n-j) | j <- [1..n-1]]

{-# LANGUAGE BangPatterns #-}

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

showTriple :: (Int,Int,Int) -> String
showTriple (x,y,z)
  = shows x $ (' ' :) $ shows y $ (' ' :) $ show z

printTriple :: (Int,Int,Int) -> IO ()
printTriple = putStrLn . showTriple

main :: IO ()
main = do
  n <- read <$> getLine
  getLine
  printTriple (2,n,1)
  printTriple (1,n,2*n)
  mapM_ printTriple $ [(1,j,2*n-j) | j <- [1..n-1]]

{-# LANGUAGE BangPatterns #-}

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

showTriple :: (Int,Int,Int) -> String
showTriple (x,y,z)
  = shows x $ (' ' :) $ shows y $ (' ' :) $ show z

printTriple :: (Int,Int,Int) -> IO ()
printTriple = putStrLn . showTriple

main :: IO ()
main = do
  n <- read <$> getLine
  getLine
  print $ n+1
  printTriple (2,n,1)
  printTriple (1,n,2*n)
  mapM_ printTriple $ [(1,j,2*n-j) | j <- [1..n-1]]

{-# LANGUAGE BangPatterns #-}

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

showTriple :: (Int,Int,Int) -> String
showTriple (x,y,z)
  = shows x $ (' ' :) $ shows y $ (' ' :) $ show z

printTriple :: (Int,Int,Int) -> IO ()
printTriple = print . showTriple

main :: IO ()
main = do
  n <- read <$> getLine
  getLine
  printTriple (2,n,1)
  printTriple (1,n,2*n)
  mapM_ printTriple $ [(1,j,2*n-j) | j <- [1..n-1]]


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

main = do
		n<-map length <$> map  (filter (\z->elem z "aeiou") ) <$> replicateM 3 getLine
		putStrLn $ if n==[5,7,5] then "YES" else "NO"

isVowel :: Char -> Bool
isVowel c = c `elem` "aAeEiIoOuU"

vowelsInPhrase :: String -> Int
vowelsInPhrase xs = sum [1 | x <- xs, isVowel x]

isHaiku :: [String] -> Bool
isHaiku phrases = pv == [5, 7, 5]
			where
				pv = [vowelsInPhrase p | p <- phrases]

--haven't written Haskell for sometime, so my
--solution is kinda weird

main :: IO ()
main = do
		line1 <- getLine
		line2 <- getLine
		line3 <- getLine

		if(isHaiku [line1, line2, line3]) then putStrLn "YES" else putStrLn "NO"

import Text.Printf
import List

main = solve

isVowel c = if Nothing == find (==c) "aeiou" then False else True

getVowels = do
  line <- getLine
  return (filter isVowel line)

solve = do
  x <- getVowels
  y <- getVowels
  z <- getVowels
  putStrLn (if ((length x == 5) && (length y == 7) && (length z == 5)) then "YES" else "NO")

main = do cs <- getContents
          putStrLn $ ck $ lines cs

ck :: [String] -> String
ck [x, y, z]
  | length (filter bowel x) /= 5 = "NO"
  | length (filter bowel y) /= 7 = "NO"
  | length (filter bowel z) /= 5 = "NO"
  | otherwise                    = "YES"

ck [x, y, z, xs] = ck [x, y, z]

bowel :: Char -> Bool
bowel x
 | x == 'a' = True
 | x == 'i' = True
 | x == 'u' = True
 | x == 'e' = True
 | x == 'o' = True
 | otherwise = False

import Data.List (intersect)
syllables :: String -> Int
syllables s = length $ s `intersect` "aeuio"
main = do
  l1 <- getLine
  l2 <- getLine
  l3 <- getLine
  putStr $ if map (syllables) [l1,l2,l3] == [5,7,5]
    then "YES"
    else "NO"

vowel = "aeiouAEIOU"

countVowel :: String -> Int
countVowel line = length $ filter (\c -> c `elem` vowel) line

haiku :: [String] -> String
haiku lines = if [5, 7, 5] == (map countVowel lines) then "YES" else "NO"

main = do
    lines <- sequence (map (\n -> getLine) [1..3])
    putStrLn (haiku lines)

main=getContents>>=(putStr.p.lines)
p x|map(length.filter(`elem`"aeoui"))x==[5,7,5]="YES"
p _="NO"

main = interact $ ifte "YES" "NO" . (== [5,7,5]) . map (length . filter (`elem` "aeiou")) . lines
ifte t e c = if c then t else e

main = do
    s1 <- getLine
    s2 <- getLine
    s3 <- getLine
    putStrLn $ if wowels s1 == 5 && wowels s2 == 7 && wowels s3 == 5 then "YES" else "NO"
wowels s = length $ filter wowel s
wowel ch = ch `elem` ['a', 'e', 'i', 'o', 'u']

import Prelude
import List
import Char

main = interact q

q = func.lines

func::[String]->String
func = solve

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve::[String]->String
solve (a:b:c:[]) | a' && b' && c' = "YES"
                 | otherwise      = "NO"
      where
        a' = count a == 5
        b' = count b == 7
        c' = count c == 5

count::String->Int
count [] = 0
count (s:xs) | s `elem` "aeiou" = 1 + count xs
             | otherwise        = count xs

import Data.List

is :: Char -> Bool
is 'a' = True
is 'e' = True
is 'i' = True
is 'o' = True
is 'u' = True
is  x  = False

count :: String -> Int
count xs = sum [ 1 | x <- xs , is x ]

main :: IO()
main = do
        a <- getLine
        b <- getLine
        c <- getLine
        if [ count a, count b , count c] == [5,7,5]
         then putStrLn "YES"
         else putStrLn "NO"

{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, BangPatterns, PatternGuards, ViewPatterns, RecordWildCards, ForeignFunctionInterface, CPP, TypeSynonymInstances, FlexibleInstances, FlexibleContexts, UndecidableInstances, ImplicitParams, ExplicitForAll #-}
{-# OPTIONS_GHC -O2 -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-unused-imports #-}

import Control.Applicative
import Control.Monad

main :: IO ()
main = do
  ss <- replicateM 3 getLine
  let isVowel c | c `elem ` "aeiou" = True
                | otherwise         = False
  case map (length . filter isVowel) ss of
    [5, 7, 5] -> putStrLn "YES"
    _         -> putStrLn "NO"

main = interact $ isVowelHaiku . take 3 . lines

isVowelHaiku :: [String] -> String
isVowelHaiku xs = if vowelLines xs == [5,7,5] then "YES" else "NO"

vowelLines :: [String] -> [Int]
vowelLines = map (length . filter (`elem` "aeiou"))

main = do
    l <- mapM (\_ -> do
        l' <- getLine
        return $ length $ filter(`elem` "aieou") l') [1..3]
    putStrLn (if l == [5, 7, 5] then "YES" else "NO")

import Control.Monad

sy = length . filter (`elem` "aeiou")

main = do
    [a,b,c] <- replicateM 3 getLine
    putStrLn $ if sy a == 5 && sy b == 7 && sy c == 5 then "YES" else "NO"

main = interact $ (\x->if x==[5,7,5] then "YES\n" else "NO\n"). map (length . filter (`elem` "aeiou")) . lines

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Main where
import Control.Applicative
import Data.List
import Text.Printf

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

-- input = lines <$> readFile "input.txt"
input = lines <$> getContents

countVowel text = length xs
    where
      xs = intersect text vowel
vowel = "aeiou"

solve :: [String] -> String
solve xs = if ys == [5,7,5] then "YES" else "NO"
    where ys = map countVowel $ xs

main :: IO ()
main = do { ns <- input
          ; printf "%s" . solve $ ns
          }

import Data.List

count pred = length . (filter pred)

solve x =
    case map (count (flip elem "aeiou")) x of
      (5:7:5:_) -> True
      _ -> False

prepare True = "YES"
prepare False = "NO"

main = do
  stuff <- getContents
  putStrLn . prepare . solve . lines $ stuff

main = do cs <- getContents
          putStrLn $ ck $ lines cs

ck :: [String] -> String
ck [x, y, z]
  | length (filter bowel x) /= 5 = "NO"
  | length (filter bowel y) /= 7 = "NO"
  | length (filter bowel z) /= 5 = "NO"
  | otherwise                    = "TRUE"

ck [x, y, z, xs] = ck [x, y, z]

bowel :: Char -> Bool
bowel x
 | x == 'a' = True
 | x == 'i' = True
 | x == 'u' = True
 | x == 'e' = True
 | x == 'o' = True
 | otherwise = False

import Data.List (intersect)
syllables :: String -> Int
syllables s = length $ s `intersect` "aeuio"
main = do
  l1 <- getLine
  l2 <- getLine
  l3 <- getLine
  print $ if map (syllables) [l1,l2,l3] == [7,5,7]
    then "YES"
    else "NO"

main = do
    l <- mapM (\_ -> do
        l' <- getLine
        return $ length $ filter(`elem` "aieou") l') [1..3]
    print (if l == [5, 7, 5] then "YES" else "NO")

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Main where
import Control.Applicative
import Data.List
import Text.Printf

splitBy :: (a -> Bool) -> [a] -> [[a]]
splitBy p [] = []
splitBy p xs = a : (splitBy p $ dropWhile p $ b)
   where
     (a, b) = break p xs

split :: String -> [String]
split = splitBy (==' ')

-- input = lines <$> readFile "input.txt"
input = lines <$> getContents

countVowel text = length xs
    where
      xs = intersect text vowel
vowel = "aeiou"

solve xs = if ys == [5,7,5] then "YES" else "NO"
    where ys = map countVowel $ xs

main :: IO ()
main = do { ns <- input
          ; print . solve $ ns
          }

import Data.List

count pred = length . (filter pred)

solve x =
    case map (count (flip elem "aeiou")) x of
      (5:7:5:_) -> True
      _ -> False

main = do
  stuff <- getContents
  print . solve . lines $ stuff

isVowel :: Char -> Bool
isVowel c = c `elem` "aAeEiIoOuU"

vowelsInPhrase :: String -> Int
vowelsInPhrase xs = sum [1 | x <- xs, isVowel x]

isHaiku :: String -> Bool
isHaiku s = pv == [5, 7, 5]
			where
				phrases = lines s
				pv = [vowelsInPhrase p | p <- phrases]

--haven't written Haskell for sometime, so my
--solution is kinda weird

main :: IO ()
main = do
		line1 <- getLine
		line2 <- getLine
		line3 <- getLine

		let haiku = line1 ++ line2 ++ line3

		if(isHaiku haiku) then putStrLn "YES" else putStrLn "NO"

isVowel :: Char -> Bool
isVowel c = c `elem` "aAeEiIoOuU"

vowelsInPhrase :: String -> Int
vowelsInPhrase xs = sum [1 | x <- xs, isVowel x]

isHaiku :: String -> Bool
isHaiku s = sum [vowelsInPhrase p | p <- phrases] == 17
			where
				phrases = lines s

--haven't written Haskell for sometime, so my
--solution is kinda weird

main :: IO ()
main = do
		line1 <- getLine
		line2 <- getLine
		line3 <- getLine

		let haiku = line1 ++ line2 ++ line3

		if(isHaiku haiku) then putStrLn "YES" else putStrLn "NO"


import Data.List

readNum :: (Num n, Read n) => IO n
readNum = do
        line <- getLine
        return $ read line

ans :: Int -> [Int] -> Int
ans n x =  succ . length . takeWhile (<n) . scanl1 (+) . reverse . sort $ x

main = do
  n <- readNum
  m <- readNum
  sizes <- sequence $ replicate n readNum
  print $ ans m sizes

import Control.Applicative
import Data.List

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

solve n m []     = 0
solve n m (x:xs) = if (m-x) <= 0 then n - length xs
                   else solve n (m-x) xs

main = do
    n <- readNum
    m <- readNum
    sizes <- sequence $ replicate n readNum
    putStrLn $ show $ solve n m (sortBy (flip compare) sizes)

import Data.List

readNum :: (Num n, Read n) => IO n
readNum = do
        line <- getLine
        return $ read line

solve n m []     = 0
solve n m (x:xs) = if (m-x) <= 0 then n - length xs
                   else solve n (m-x) xs

main = do
    n <- readNum
    m <- readNum
    sizes <- sequence $ replicate n readNum
    putStrLn $ show $ solve n m (sortBy (flip compare) sizes)

import Control.Applicative ((<$>))
import Data.List

readInt :: String -> Int
readInt = read

solve :: [Int] -> Int -> Int -> Int
solve (c:cs) space num =
 if c >= space
   then num
   else solve cs (space - c) (num + 1)
solve _ _ num = num

main = do
  _ <- getLine
  numStr <- readInt <$> getLine
  cards <- map readInt . lines <$> getContents
  print $ solve (sortBy (flip compare) cards) numStr 1

{-# LANGUAGE OverloadedStrings #-}
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Char (intToDigit, digitToInt)
import Control.Monad (replicateM)

import Data.List (sortBy)

parseInt :: ByteString -> Int
parseInt s
  | BS.head s == '-' = negate (go 0 (BS.tail s))
  | otherwise = go 0 s
  where
    go i s
      | BS.null s = i
      | otherwise = go (i*10 + digitToInt (BS.head s)) (BS.tail s)

printInt :: Int -> ByteString
printInt i
  | i < 10 = BS.singleton (intToDigit i)
  | otherwise = BS.snoc (printInt (i `quot` 10)) (intToDigit (i `rem` 10))

darnit :: ByteString -> ByteString
darnit s
  | BS.last s == '\r' = BS.init s
  | otherwise = s

main :: IO ()
main = do
  n <- fmap (parseInt . darnit) BS.getLine
  m <- fmap (parseInt . darnit) BS.getLine
  as <- replicateM n (fmap (parseInt . darnit) BS.getLine)
  let drives = (+1) . length . takeWhile (< m) . scanl1 (+) . sortBy (flip compare) $ as
  BS.putStrLn (printInt drives)

import Control.Applicative
import Data.List

solve :: Int -> [Int] -> Int
solve n vals =
  fst $ head $ filter (\x -> snd x >= n) $ partialSums
  where
    sorted = reverse $ sort $ vals
    partialSums = zip [1..] $ scanl1 (+) sorted

main = do
  getLine
  m <- read <$> getLine
  vals <- map read . lines <$> getContents
  putStrLn $ show $ solve m vals

import Data.List
main = interact $ show . solve . map read . tail . words
solve (m:as) = length $ takeWhile (< m) $ scanl (+) 0 $ reverse $ sort as

import Data.List

main = getContents >>= print . solve . map read . tail . words

solve (m:as) = head [ x | x <- [1..], m <= sum (take x (sortBy (flip compare) as))]

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections     #-}

import           Control.Applicative
import           Control.Monad
import           Control.Monad.ST
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString.Char8       as B
import           Data.Char
import           Data.Function
import           Data.Int
import qualified Data.IntMap                 as IM
import qualified Data.IntSet                 as IS
import           Data.List
import qualified Data.Map                    as M
import           Data.Ord
import qualified Data.Set                    as S
import           Data.STRef
import           Data.Tuple
import qualified Data.Vector                 as V
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as UM
import           Data.Word
import           Debug.Trace

main :: IO ()
main = do
    n <- readLn :: IO Int
    m <- readLn :: IO Int
    xs <- U.unfoldrN n (B.readInt.B.dropWhile isSpace) <$> B.getContents
    print $ solve m xs

solve :: Int -> U.Vector Int -> Int
solve m vec = fst.U.head.U.dropWhile((<m).snd).U.indexed.U.scanl(+)0.U.reverse $ radixSort32 vec

radixSort32 :: U.Vector Int -> U.Vector Int
radixSort32 v = foldl' step v [0, 16]
  where
    mask k x = fromIntegral $ unsafeShiftR x k .&. 0xffff
    step v k = U.create $ do
        pref <- U.unsafeThaw
            . U.prescanl' (+) 0
            . U.unsafeAccumulate (+) (U.replicate 0x10000 0)
            $ U.map ((,1) . mask k) v
        res <- UM.unsafeNew $ U.length v
        U.forM_ v $ \x -> do
            let !masked = mask k x
            i <- UM.unsafeRead pref masked
            UM.unsafeWrite pref masked $ i + 1
            UM.unsafeWrite res i x
        return res

-- @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)
-- }}}

main :: IO ()
main = do
    n <- inputInt
    m <- inputInt
    a <- replicateM n inputInt
    print . length . takeWhile (< m) . scanl (+) 0 . reverse $ sort a

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

onecase = do
		[s,a,b,c]<-map read <$> words <$> getLine ::IO [Integer]
		let x = div s c
		print $ x + (div x a)*b

main = do
		n<-read<$> getLine ::IO Int
		s<-read<$> getLine ::IO Int
		a<-scanl1 (+) <$> reverse <$> sort <$> map read <$>replicateM n getLine ::IO [Int]
		print $ 1+ length (takeWhile (<s) a)

import Data.List (sort)

--process :: Int -> [Int] -> Int
process m = (1+).length.dropWhile (>=m).scanr1 (+).sort

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    m <- fmap readInt getLine
    a <- fmap (map readInt.words) getContents
    print $ process m a

import Data.List
main = do
   c1<- ( getContents )
   let c = lines c1
   let n = head c
   let m = head (tail c)
   let f = drop 2 c
   print ( (calcf (read m) (reverse (sort (map read  f))) 1))

calcf m f i = if (sum (take i f)) >= m then i
              else calcf m f (i+1)

import Data.List (sort)

main = do
  getLine
  [m] <- (map read . words) `fmap` getLine
  as <- (sort . map read . lines) `fmap` getContents

  print . (+1) . length . takeWhile (< m) $ scanl1 (+) (reverse as)

{-# LANGUAGE OverloadedStrings #-}

module Main where

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM)
import qualified Data.Text as T
import qualified Data.List as L

getInt :: IO Int
getInt = (read . T.unpack . T.strip . T.pack) <$> getLine

main :: IO ()
main = do
    (n, m) <- (,) <$> getInt <*> getInt
    items <- L.sort <$> forM [0 .. n - 1] (const getInt)
    let (_, res) = foldr (\x (s, cnt) -> (s + x, if s < m then cnt + 1 else cnt)) (0, 0) items
    putStrLn $ show res

{-# LANGUAGE OverloadedStrings #-}

module Main where

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM)
import qualified Data.Text as T
import qualified Data.List as L

getInt :: IO Int
getInt = (read . T.unpack . T.strip . T.pack) <$> getLine

main :: IO ()
main = do
    (n, m) <- (,) <$> getInt <*> getInt
    items <- L.sort <$> forM [0 .. n - 1] (const getInt)
    putStrLn $ show items
    let (_, cnt) = foldr (\x (s, cnt) -> let s' = s + x in (s', if s' < m then cnt + 1 else cnt)) (0, 0) items
    putStrLn $ show cnt

{-# LANGUAGE OverloadedStrings #-}

module Main where

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM)
import qualified Data.Text as T
import qualified Data.List as L

getInt :: IO Int
getInt = (read . T.unpack . T.strip . T.pack) <$> getLine

main :: IO ()
main = do
    (n, m) <- (,) <$> getInt <*> getInt
    items <- L.sort <$> forM [0 .. n - 1] (const getInt)
    let (_, cnt) = foldr (\x (s, cnt) -> let s' = s + x in (s, if s' < m then cnt + 1 else cnt)) (0, 0) items
    putStrLn $ show cnt

{-# LANGUAGE OverloadedStrings #-}

module Main where

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM)
import qualified Data.Text as T
import qualified Data.List as L

getInt :: IO Int
getInt = (read . T.unpack . T.strip . T.pack) <$> getLine

main :: IO ()
main = do
    (n, m) <- (,) <$> getInt <*> getInt
    items <- L.sort <$> forM [0 .. n - 1] (const getInt)
    let (_, cnt) = foldr (\x (s, cnt) -> let s' = s + x in (s', if s' < m then cnt + 1 else cnt)) (0, 0) items
    putStrLn $ show cnt


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

import qualified Data.ByteString.Char8 as B
readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

second :: [a] -> [a]
second [] = []
second (a:b:c) = b : second c

solve :: String -> Bool
solve = (>=11)
      . length
      . dropWhile (/='8')

yesno :: Bool -> String
yesno b = if b then "YES" else "NO"

main :: IO ()
main = do
    n <- readInt
    s <- replicateM (2 * n) getLine
    mapM_ putStrLn $ map (yesno . solve) $ second s

main = getContents >>= putStr . solve . tail . words

solve [] = []
solve (_:x:xs)
    | (length $ dropWhile (/='8') x) >= 11 = "YES\n" ++ solve xs
    | otherwise = "NO\n" ++ solve xs

import Control.Monad
main = do
  t <- readLn
  replicateM_ t $ do
    n <- readLn
    s <- getLine
    putStrLn $ if n >= 11 && any (== '8') (drop 10 (reverse s))
                  then "YES" else "NO"

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

check c s | c==11 && head s =='8' = True
          | c<11 = False
	  | (length $ take 1 $ filter (=='8') $ take (c-11) s)==1 = True
          | head ( drop (c-11) s)=='8' = True
	  | otherwise = False

onecase = do
		c<- read <$> getLine ::IO Int
		s<- getLine
		putStrLn $ if check c s then "YES" else "NO"

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

--ghc 7.10

isTelephoneNumberable :: String -> Bool
isTelephoneNumberable str
    | n > 0 = elem '8' . take n $ str
    | otherwise = False
    where
        n = length str - 10

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

process :: Int -> IO ()
process 0 = return ()
process t = do
    nStr <- getLine
    phoneNo <- getLine
    putStrLn . showBool . isTelephoneNumberable $ phoneNo
    process (t-1)

main = do
    tStr <- getLine
    let t = read tStr :: Int
    process t

module Main where

import Data.Array
import Control.Monad
import Data.Function
import Data.List

main :: IO ()
main = do
  cases <- read <$> getLine
  replicateM_ cases $ do
    c <- read <$> getLine
    xs <- getLine
    putStrLn $ f c xs

f :: Int -> String -> String
f c xs =
  let
    pos = findIndex (=='8') $ xs
  in case pos of
    Nothing -> "NO"
    Just x -> if (c -x) >= 11 then "YES" else "NO"

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readNInts = readInt >>= flip replicateM readInt

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

main = readInt >>= flip replicateM solve

solve = do
	n <- readInt
	s <- getLine
	let
		rest = dropWhile ( /= '8' ) s
	putStrLn $ if length rest >= 11 then "YES" else "NO"

import Data.Function
solve = (\x -> if x then "YES" else "NO") . (>=11) . length . snd .  break (=='8')
main = interact $  unlines . fix (\f xs -> if null xs then [] else let (x:y:ys) = xs in solve y : f ys) . tail .lines

import Control.Monad
main = do
  t <- readLn
  replicateM_ t $ do
    n <- getLine
    s <- getLine
    putStrLn $ if length n >= 11 && any (== '8') (drop 10 (reverse n))
                  then "YES" else "NO"

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

onecase = do
		c<- read <$> getLine ::IO Int
		s<- getLine
		putStrLn $ if 1==(length $ take 1 $ filter (=='8') $ take (c-11) s) then "YES" else "NO"

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

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

onecase = do
		c<- read <$> getLine ::IO Int
		s<- getLine
		putStrLn $ if (c==11 && head s =='8') then "YES" else if 1==(length $ take 1 $ filter (=='8') $ take (c-11) s) then "YES" else "NO"

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

module Main where

import Data.Array
import Control.Monad
import Data.Function
import Data.List

main :: IO ()
main = do
  cases <- read <$> getLine
  replicateM_ cases $ do
    c <- read <$> getLine
    xs <- getLine
    print $ f c xs

f :: Int -> String -> String
f c xs =
  let
    pos = findIndex (=='8') $ xs
  in case pos of
    Nothing -> "NO"
    Just x -> if (c -x) >= 10 then "YES" else "NO"

module Main where

import Data.Array
import Control.Monad
import Data.Function
import Data.List

main :: IO ()
main = do
  cases <- read <$> getLine
  replicateM_ cases $ do
    c <- read <$> getLine
    xs <- getLine
    print $ f c xs

f :: Int -> String -> String
f c xs =
  let
    pos = findIndex (=='8') $ xs
  in case pos of
    Nothing -> "NO"
    Just x -> if (c -x) >= 11 then "YES" else "NO"


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

main = do
  [n,a,d] <- map read'.B.words <$> B.getLine
  tvs <- map (map read'.B.words).B.lines <$> B.getContents
  C.putStr.C.unlines.map (C.pack.show) $ solve a d tvs

read' s = let Just (n,_) = B.readInteger s in n

solve :: Integer -> Integer -> [[Integer]] -> [Double]
solve a' d' tvs = scanl1 max $ map calc tvs
   where  [a,d] = map fromIntegral [a',d']
          calc [ti',vi']
           | 2*a'*d'<=vi'*vi' = ti + sqrt ((2*d)/a)
           | otherwise        = vi/(2*a) + d/vi + ti
           where [ti,vi] = map fromIntegral [ti',vi']

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

main = do
  [n,a,d] <- map read'.B.words <$> B.getLine
  tvs <- map (map read'.B.words).B.lines <$> B.getContents
  putStr.unlines.map show$solve a d tvs

read' s = let Just (n,_) = B.readInteger s in n

solve :: Integer -> Integer -> [[Integer]] -> [Double]
solve a' d' tvs = scanl1 max $ map calc tvs
   where  [a,d] = map fromIntegral [a',d']
          calc [ti',vi']
           | 2*a'*d'<=vi'*vi' = ti + sqrt ((2*d)/a)
           | otherwise        = vi/(2*a) + d/vi + ti
           where [ti,vi] = map fromIntegral [ti',vi']


{- ok -}
import Control.Applicative ((<$>))

main = do
	getLine
	points <- map ((\[a, b] -> (a, b)) . map read . words) . lines <$> getContents

	let
  		count = length $ filter (<0) $ zipWith mul vects $ tail vects ++ [head vects]
    			where
				vects = zipWith (\(x1, y1) (x2, y2) -> (x2 - x1, y2 - y1)) points $ tail points
				mul (x1, y1) (x2, y2) = x2 * y1 - x1 * y2

	print count

import           Control.Monad
import           Data.List

isCCW (xa,ya) (xb,yb) (xc,yc) =
  let
    v1 = (xb-xa,yb-ya)
    v2 = (xc-xb,yc-yb)
  in fst v1 * snd v2 - snd v1 * fst v2 > 0

unfolder :: [(Int, Int)] -> Maybe (Bool, [(Int, Int)])
unfolder (a:b:c:rest) = Just (isCCW a b c, b:c:rest)
unfolder _ = Nothing

main :: IO ()
main = do
  n <- (read :: String -> Int) <$> getLine
  print =<< sum . map fromEnum . unfoldr unfolder . map ((\[a,b]->(a,b)) . map (read :: String -> Int) . words) <$> replicateM (n + 1) getLine


{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Char (digitToInt)
import Data.Function
import Data.Int
import Data.List
import Data.Maybe
import Debug.Trace (trace)

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines

-- type Input = ()
-- type Output = ()

-- input :: Scanner Input
input = pair int int

-- output :: Output -> C.ByteString
output = C.unwords . map showB

-- solve :: Input -> Output
solve (s, 1) = [s]
solve (s, n) = let p = maximum . filter (<= s - n + 1) $ ps10 in p : solve (s - p, n - 1)

ps10 = map (10 ^) [0 .. 9]

-------------------------- Template ------------------------------------------
-- Lists
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn = groupBy . on (==)

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

adjacents :: [a] -> [(a, a)]
adjacents xs = zip xs (tail xs)

adjacentsWith :: (a -> a -> b) -> [a] -> [b]
adjacentsWith f xs = zipWith f xs (tail xs)

count :: Eq a => a -> [a] -> Int
count = countBy . (==)

countBy :: (a -> Bool) -> [a] -> Int
countBy p = length . filter p

-- Scanner
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

readStr :: Read a => Scanner a
readStr = read <$> str

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show

import Control.Arrow ((>>>))

main :: IO ()
main =
  interact $
    lines
      >>> tail
      >>> map (words >>> map read >>> toPair >>> solve >>> map show >>> unwords)
      >>> unlines
  where
    toPair [a, b] = (a, b)

solve :: (Int, Int) -> [Int]
solve (s, 1) = [s]
solve (s, n) = let p = maximum . filter (<= s - n + 1) $ ps10 in p : solve (s - p, n - 1)

ps10 = map (10 ^) [0 .. 9]

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Char (digitToInt)
import Data.Function
import Data.Int
import Data.List
import Data.Maybe
import Debug.Trace (trace)

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines

-- type Input = ()
-- type Output = ()

-- input :: Scanner Input
input = pair int int

-- output :: Output -> C.ByteString
output = C.unwords . map showB

-- solve :: Input -> Output
solve (s, n)
  | dsum s >= n = let xs = take n $ iterate pickDigit s in zipWith (-) xs (tail xs ++ [0])
  | otherwise = p : solve (s - p, n - 1)
  where
    p = maximum [x | e <- [0..9], let x = 10^e, s - x >= n - 1]

    dsum = sum . map digitToInt . show
    largestP10 = (10 ^) . subtract 1 . length . dropWhile (== '0') . show
    pickDigit n = n - largestP10 n

debug a = trace (show a) a

-------------------------- Template ------------------------------------------
-- Lists
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn = groupBy . on (==)

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

adjacents :: [a] -> [(a, a)]
adjacents xs = zip xs (tail xs)

adjacentsWith :: (a -> a -> b) -> [a] -> [b]
adjacentsWith f xs = zipWith f xs (tail xs)

count :: Eq a => a -> [a] -> Int
count = countBy . (==)

countBy :: (a -> Bool) -> [a] -> Int
countBy p = length . filter p

-- Scanner
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

readStr :: Read a => Scanner a
readStr = read <$> str

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Char (digitToInt)
import Data.Function
import Data.Int
import Data.List
import Data.Maybe
import Debug.Trace (trace)

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines

-- type Input = ()
-- type Output = ()

-- input :: Scanner Input
input = pair int int

-- output :: Output -> C.ByteString
output = C.unwords . map showB

-- solve :: Input -> Output
solve (s, n)
  | dsum >= n = let xs = take n $ iterate pickDigit s in zipWith (-) xs (tail xs ++ [0])
  | s < 10 = replicate n 1
  | s - p >= n - 1 = p : solve (s - p, n - 1)
  | otherwise = let p' = p `div` 10 in p' : solve (s - p', n - 1)
  where
    p = largestP10 s
    dsum = sum . map digitToInt $ show s
    largestP10 = (10 ^) . subtract 1 . length . dropWhile (== '0') . show
    pickDigit n = n - largestP10 n

debug a = trace (show a) a

-------------------------- Template ------------------------------------------
-- Lists
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn = groupBy . on (==)

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

adjacents :: [a] -> [(a, a)]
adjacents xs = zip xs (tail xs)

adjacentsWith :: (a -> a -> b) -> [a] -> [b]
adjacentsWith f xs = zipWith f xs (tail xs)

count :: Eq a => a -> [a] -> Int
count = countBy . (==)

countBy :: (a -> Bool) -> [a] -> Int
countBy p = length . filter p

-- Scanner
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

readStr :: Read a => Scanner a
readStr = read <$> str

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show


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

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

main :: IO ()
main = do
  [caseNum] <- getInts
  forM_ [1..caseNum] $ \_ -> do
    _ <- getInts
    as <- getInts
    let f n x = (length $ filter (==x) as) < n
        g n = fromJust $ find (f n) [0..]
    printf "%d\n" (g 1 + g 2)

{-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import Control.Applicative
import Data.Int
import Data.Maybe
import Data.List
import Data.Functor
import Data.Bool
import Data.Array.Unboxed as UA
import qualified Data.ByteString.Char8 as B8
import Text.Printf

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

readInt64B8 :: B8.ByteString -> Int64
readInt64B8 = fromIntegral . fst . fromJust . B8.readInteger

solve :: Int -> [Int] -> Int
solve n as =
        aValue + bValue
    where
        sortedAs = sort as
        aGroups = map (\as -> (head as, length as)) $ group sortedAs
        aValue = fromMaybe (length aGroups) $ findGroup 1
        bValue = fromMaybe (length aGroups) $ findGroup 2
        findGroup needCnt = fmap fst . find (\(i, (a, cnt)) -> checkGroup i a cnt needCnt) . zip [0..] $ aGroups
        checkGroup i a cnt needCnt
            | (i == a) && (cnt >= needCnt) = False
            | otherwise = True

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    forM_ [1..t] $ \_ -> do
        n <- B8.getLine <&> readIntB8
        as <- B8.getLine <&> B8.words <&> map readIntB8
        let answer = solve n as
        printf "%d\n" $ answer

import Control.Monad
import Data.List

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _nStr <- getLine
    a <- map read . words <$> getLine
    let
      vs :: [[Int]]
      vs = group (sort a)
      q = [length v | (i, v) <- zip [0..] vs, i == head v]
    print . sum . tail $ scanl min 2 q

import Control.Monad
import Data.List

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _nStr <- getLine
    a <- map read . words <$> getLine
    let
      vs = group (sort a)
      q = [length v | (i, v) <- zip [0..] vs, i == head v]
    print . sum $ map (min 2) q


{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables, FlexibleContexts #-}

import qualified Data.ByteString as B (getLine)
import qualified Data.ByteString.Char8 as C (readInt, words)
import qualified Data.Maybe as M (fromJust)
import qualified Data.Int as I (Int64)
import qualified Data.List as L (sort)
import qualified Data.Array.IArray as A (Array, accumArray, (!))
import qualified Data.Array.MArray.Safe as A (newArray, newListArray, readArray, writeArray)
import qualified Data.Array.ST.Safe as ST (STUArray)
import qualified Control.Monad.ST.Safe as ST (runST, ST)
import qualified Data.STRef as ST (newSTRef, modifySTRef, readSTRef)
import qualified Control.Monad as M (forM, forM_)
import qualified Data.Set as S (fromList, toList)

readInt = fst . M.fromJust . C.readInt

-- disjoint set
data DSU s = DSU (ST.STUArray s Int Int) (ST.STUArray s Int Int) (ST.STUArray s Int Int)
create n = do
    rank <- A.newArray (1, n) 0 :: ST.ST s (ST.STUArray s Int Int)
    pare <- A.newListArray (1, n) [1..] :: ST.ST s (ST.STUArray s Int Int)
    size <- A.newArray (1, n) 0 :: ST.ST s (ST.STUArray s Int Int)
    return $ DSU rank pare size
find dsu@(DSU _ pare _) x = do
    r <- A.readArray pare x
    if r /= x then find dsu r >>= A.writeArray pare x else return ()
    A.readArray pare x
union dsu@(DSU rank pare size) x y = do
    x <- find dsu x
    y <- find dsu y
    if x == y then return () else do
        rx <- A.readArray rank x
        ry <- A.readArray rank y
        sx <- A.readArray size x
        sy <- A.readArray size y
        case compare rx ry of
            LT -> A.writeArray pare x y >> A.writeArray size y (sx + sy)
            GT -> A.writeArray pare y x >> A.writeArray size x (sx + sy)
            EQ -> do
                A.writeArray pare y x >> A.writeArray size x (sx + sy)
                A.writeArray rank x (rx + 1)

run n nr ag rs = ST.runST $ do
    xn <- ST.newSTRef (0 :: I.Int64)
    xsum <- ST.newSTRef (0 :: I.Int64)
    xsumsq <- ST.newSTRef (0 :: I.Int64)
    dsu@(DSU _ _ size) <- create n
    (((-1) -) . snd . maximum -> r) <- M.forM [1..nr] $ \i -> do
        M.forM_ (ag A.! i) $ \j -> do
            ST.modifySTRef xn succ
            ST.modifySTRef xsum succ
            ST.modifySTRef xsumsq succ
            A.writeArray size j 1
        M.forM_ (ag A.! i) $ \j -> do
            if j /= 1 then do
                (fromIntegral -> sjp) <- find dsu (j - 1) >>= A.readArray size
                (fromIntegral -> sjq) <- find dsu j >>= A.readArray size
                if sjp /= 0 then do
                    ST.modifySTRef xn pred
                    ST.modifySTRef xsumsq (+ ((sjp + sjq)^2 - sjp^2 - sjq^2))
                    union dsu (j - 1) j
                else return ()
            else return ()
            if j /= n then do
                (fromIntegral -> sjp) <- find dsu j >>= A.readArray size
                (fromIntegral -> sjq) <- find dsu (j + 1) >>= A.readArray size
                if sjq /= 0 then do
                    ST.modifySTRef xn pred
                    ST.modifySTRef xsumsq (+ ((sjp + sjq)^2 - sjp^2 - sjq^2))
                    union dsu j (j + 1)
                else return ()
            else return ()
        xnv <- ST.readSTRef xn
        xsumv <- ST.readSTRef xsum
        xsumsqv <- ST.readSTRef xsumsq
        return (if xsumsqv * xnv - xsumv * xsumv == 0 then xnv else 0, -i)
    return $ rs !! r + 1

main = do
    (readInt -> n) <- B.getLine
    (L.sort . (flip zip) [1..] . map readInt . C.words -> xs) <- B.getLine
    let rs = S.toList . S.fromList . map fst $ xs
        nr = length rs
        gs = (\(_, _, x) -> reverse x) $ foldl (\(i, p, rs) (x, y) -> if p == x then (i, p, (i, y):rs)
            else (i + 1, x, (i + 1, y):rs)) (0, 0, []) $! xs
        ag = A.accumArray (flip (:)) [] (1, nr) gs :: A.Array Int [Int]
    print $ run n nr ag rs

{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables, FlexibleContexts #-}

import qualified Data.ByteString as B (getLine)
import qualified Data.ByteString.Char8 as C (readInt, words)
import qualified Data.Maybe as M (fromJust)
import qualified Data.Int as I (Int64)
import qualified Data.List as L (sort, foldl')
import qualified Data.Array.IArray as A (Array, accumArray, (!))
import qualified Data.Array.MArray.Safe as A (newArray, newListArray, readArray, writeArray)
import qualified Data.Array.ST.Safe as ST (STUArray)
import qualified Control.Monad.ST.Safe as ST (runST, ST)
import qualified Data.STRef as ST (newSTRef, modifySTRef, readSTRef)
import qualified Control.Monad as M (forM, forM_)
import qualified Data.Set as S (fromList, toList)

readInt = fst . M.fromJust . C.readInt

-- disjoint set
data DSU s = DSU (ST.STUArray s Int Int) (ST.STUArray s Int Int) (ST.STUArray s Int Int)
create n = do
    rank <- A.newArray (1, n) 0 :: ST.ST s (ST.STUArray s Int Int)
    pare <- A.newListArray (1, n) [1..] :: ST.ST s (ST.STUArray s Int Int)
    size <- A.newArray (1, n) 0 :: ST.ST s (ST.STUArray s Int Int)
    return $ DSU rank pare size
find dsu@(DSU _ pare _) x = do
    r <- A.readArray pare x
    if r /= x then find dsu r >>= A.writeArray pare x else return ()
    A.readArray pare x
union dsu@(DSU rank pare size) x y = do
    x <- find dsu x
    y <- find dsu y
    if x == y then return () else do
        rx <- A.readArray rank x
        ry <- A.readArray rank y
        sx <- A.readArray size x
        sy <- A.readArray size y
        case compare rx ry of
            LT -> A.writeArray pare x y >> A.writeArray size y (sx + sy)
            GT -> A.writeArray pare y x >> A.writeArray size x (sx + sy)
            EQ -> do
                A.writeArray pare y x >> A.writeArray size x (sx + sy)
                A.writeArray rank x (rx + 1)

run n nr ag rs = ST.runST $ do
    xn <- ST.newSTRef (0 :: I.Int64)
    xsum <- ST.newSTRef (0 :: I.Int64)
    xsumsq <- ST.newSTRef (0 :: I.Int64)
    dsu@(DSU _ _ size) <- create n
    (((-1) -) . snd . maximum -> r) <- M.forM [1..nr] $ \i -> do
        M.forM_ (ag A.! i) $ \j -> do
            ST.modifySTRef xn succ
            ST.modifySTRef xsum succ
            ST.modifySTRef xsumsq succ
            A.writeArray size j 1
        M.forM_ (ag A.! i) $ \j -> do
            if j /= 1 then do
                (fromIntegral -> sjp) <- find dsu (j - 1) >>= A.readArray size
                (fromIntegral -> sjq) <- find dsu j >>= A.readArray size
                if sjp /= 0 then do
                    ST.modifySTRef xn pred
                    ST.modifySTRef xsumsq (+ ((sjp + sjq)^2 - sjp^2 - sjq^2))
                    union dsu (j - 1) j
                else return ()
            else return ()
            if j /= n then do
                (fromIntegral -> sjp) <- find dsu j >>= A.readArray size
                (fromIntegral -> sjq) <- find dsu (j + 1) >>= A.readArray size
                if sjq /= 0 then do
                    ST.modifySTRef xn pred
                    ST.modifySTRef xsumsq (+ ((sjp + sjq)^2 - sjp^2 - sjq^2))
                    union dsu j (j + 1)
                else return ()
            else return ()
        xnv <- ST.readSTRef xn
        xsumv <- ST.readSTRef xsum
        xsumsqv <- ST.readSTRef xsumsq
        return (if xsumsqv * xnv - xsumv * xsumv == 0 then xnv else 0, -i)
    return $ rs !! r + 1

main = do
    (readInt -> n) <- B.getLine
    (L.sort . (flip zip) [1..] . map readInt . C.words -> xs) <- B.getLine
    let rs = S.toList . S.fromList . map fst $ xs
        nr = length rs
        gs = (\(_, _, x) -> reverse x) $ L.foldl' (\(i, p, rs) (x, y) -> if p == x then (i, p, (i, y):rs)
            else (i + 1, x, (i + 1, y):rs)) (0, 0, []) xs
        ag = A.accumArray (flip (:)) [] (1, nr) gs :: A.Array Int [Int]
    print $ run n nr ag rs