You have an array $$$a_1, a_2, \dots, a_n$$$. All $$$a_i$$$ are positive integers.In one step you can choose three distinct indices $$$i$$$, $$$j$$$, and $$$k$$$ ($$$i \neq j$$$; $$$i \neq k$$$; $$$j \neq k$$$) and assign the sum of $$$a_j$$$ and $$$a_k$$$ to $$$a_i$$$, i. e. make $$$a_i = a_j + a_k$$$.Can you make all $$$a_i$$$ lower or equal to $$$d$$$ using the operation above any number of times (possibly, zero)?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$d$$$ ($$$3 \le n \le 100$$$; $$$1 \le d \le 100$$$) — the number of elements in the array $$$a$$$ and the value $$$d$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$) — the array $$$a$$$.

For each test case, print YES, if it's possible to make all elements $$$a_i$$$ less or equal than $$$d$$$ using the operation above. Otherwise, print NO. You may print each letter in any case (for example, YES, Yes, yes, yEs will all be recognized as positive answer).

NoteIn the first test case, we can prove that we can't make all $$$a_i \le 3$$$.In the second test case, all $$$a_i$$$ are already less or equal than $$$d = 4$$$.In the third test case, we can, for example, choose $$$i = 5$$$, $$$j = 1$$$, $$$k = 2$$$ and make $$$a_5 = a_1 + a_2 = 2 + 1 = 3$$$. Array $$$a$$$ will become $$$[2, 1, 5, 3, 3]$$$.After that we can make $$$a_3 = a_5 + a_2 = 3 + 1 = 4$$$. Array will become $$$[2, 1, 4, 3, 3]$$$ and all elements are less or equal than $$$d = 4$$$.

findAllChar :: (Char, [Char]) -> [Int]
findAllChar (element, list) = ([ind | ind<-[0..((length list)-1)], (list!!ind)==element]++[length list])

findAllInt :: (Int, [Int]) -> [Int]
findAllInt (element, list) = ([ind | ind<-[0..((length list)-1)], (list!!ind)==element]++[length list])

findFirstChar :: (Char, [Char]) -> Int
findFirstChar (element, list) = (findAllChar(element, list)!!0)

findFirstInt :: (Int, [Int]) -> Int
findFirstInt (element, list) = (findAllInt(element, list)!!0)

takeLast :: (Int, [Char]) -> [Char]
takeLast (cnt, list) = reverse ( take cnt (reverse list) )

split :: (Char, [Char]) -> [[Char]]

split (element, []) = []
split (element, list) = [[ (list!!(ind-1)) | ind <- take (findFirstChar(element, list))  [1..] ]]
                        ++split(element, takeLast((length list)-findFirstChar(element, list)-1, list))

excludeFirst :: (Int, [Int]) -> [Int]
excludeFirst(val, list) = [list!!(ind-1) | ind<-[1..(length list)],
                           ((ind-1)/=(findFirstInt(val, list)))]

readIntLsit :: IO[Int]
readIntLsit  = do
    input <- getLine
    let l = split(' ', input)

    return [(read str :: Int) | str <- l]

minim :: [Int] -> Int
minim []       = 0
minim [x]      = x
minim (x:xs)   = min x (minim xs)

maxim :: [Int] -> Int
maxim []       = 0
maxim [x]      = x
maxim (x:xs)   = max x (maxim xs)

solveTestcase :: () -> (IO [Char])
solveTestcase () = do
    help1 <- readIntLsit
    let help2 = [1, 2, 3]

    let n = help1!!0
    let d = help1!!1
    a <- readIntLsit

    let minVal1 = minim a
    let minVal2 = minim (excludeFirst(minVal1, a))

    let maxVal = maxim a

    if( (minVal1+minVal2) > d && maxVal>d)
        then
            return "NO"
    else
        return "YES"

    --let m = (help!!1)

    --print help

    --print ""

--loop :: Int -> IO()
--loop 0 = print ""
--loop t = do
--    solveTestcase
--    return (loop (t - 1))

--getRes :: (Int) -> ()
--getRes 0 = IO[Char]::Empty
getRes :: Int -> (IO[Char])
getRes 0 = return ""
getRes (t) = do
    x <- solveTestcase()
    y <- getRes(t-1)

    return (x++"\n"++y)

main = do
    help <- readIntLsit
    let t = help!!0

    res <- getRes(t)
    putStr res

import           Control.Monad
import qualified Data.List             as L
import qualified Data.Map.Strict       as M
import qualified Data.Set              as S

--
-- UTILITIES
--
import qualified Data.ByteString.Char8 as C8
import           Data.Maybe            (fromJust)

getInt :: IO Int
getInt = read <$> getLine

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

getInteger :: IO Integer
getInteger = read <$> getLine

getIntegers :: IO [Integer]
getIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine

--
-- MAIN
--

main :: IO ()
main = do
  t <- getInt
  replicateM_ t $ do
      [n, d] <- getInts
      a@(a1:a2:_) <- L.sort <$> getInts
      if all (<= d) a || (a1 + a2 <= d) then putStrLn "YES" else putStrLn "NO"

import Prelude
import Data.Int
import Control.Arrow

parseIntList :: String -> [Int64]
parseIntList = words >>> map read

makePair :: a -> [a] -> [(a,a)]
makePair val list = map (\x -> (val,x)) list

pairs :: [Int64] -> [(Int64,Int64)]
pairs [] = []
pairs (x:xs) = (makePair x xs) ++ (pairs xs)

problem :: [[Int64]] -> String
problem [] = ""
problem (x:y:z) = (if((foldr (\(a,b) c -> c || (a + b <= d)) False (pairs y)) || (foldr (\a b -> b && a <= d)) True y) then "YES" else "NO")++"\n"++(problem z) where d = x !! 1
problem (_:_) = ""

solve :: String -> String
solve str = problem $ map parseIntList $ tail $ lines str

main :: IO ()
main = interact $ solve

import Data.Char
import Data.List
import qualified Data.ByteString.Char8 as B

main = B.interact $ B.unlines .  solves . tail . toInt
  where toInt = unfoldr (B.readInt . B.dropWhile isSpace)

solves [] = []
solves (m:n:ss) = (B.pack . solve n $ sort xs) : solves ys
  where (xs, ys) = splitAt m ss

solve n (x:y:xs)
    | min (x + y) (last xs) <= n = "YES"
    | otherwise = "NO"

module Main where
import Data.Foldable (traverse_)
import Data.List (sort)

getTestCases :: Int -> IO [((Int,Int), [Int])]
getTestCases n = go n []
  where
    go 0 ret = return ret
    go n ret = do
      line <- getLine
      let [a,b] = read <$> words line :: [Int]
      line2 <- getLine
      let l1 = read <$> words line2 :: [Int]
      let tcase = ((a,b), l1)
      -- print tcase
      -- print n
      go (n-1) (ret ++ [tcase])

solve :: ((Int, Int), [Int]) -> String
solve ((_,_), []) = "NO"
solve ((n, d), (x:xs)) =
  let
    srtd = sort (x:xs)
    srtdzip = zip [0..] srtd
    lst = [(a,b) | (i,a) <- srtdzip, (j,b) <- srtdzip, i /= j, a+b <= d]
    isOks = all (<=d) srtd
  in
    if not (null lst) || isOks
    then "YES"
    else "NO"

main :: IO ()
main = do
  ts <- getLine
  let t = read ts :: Int
  testCases <- getTestCases t
  traverse_ (putStrLn . solve) testCases

{-# LANGUAGE Safe #-}
{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             guard, join, replicateM_)
import qualified Control.Monad.ST.Strict    as ST
import qualified Control.Monad.State.Strict as S
import qualified Data.Array                 as A
import qualified Data.Array.MArray.Safe     as MA
import qualified Data.Array.ST.Safe         as STA
import qualified Data.Array.Unboxed         as UA
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             intersect, isPrefixOf, nub, sort,
                                             sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           GHC.IO.Handle              (hDuplicateTo)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             openFile, stdin, stdout)
import           Text.Printf                (printf)

-- import Debug.Trace (trace)
-- debug = flip trace

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

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

solve :: Int -> Int -> [Int] -> Bool
solve n d as = min (maximum as) minS <= d
    where
        minS = sum . take 2 . sort $ as

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, d] <- B8.getLine <&> map readIntB8 . B8.words
        as <- B8.getLine <&> map readIntB8 . B8.words
        let answer = solve n d as
        putStrLn ((if answer then "YES" else "NO") :: String)

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

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

printList [a] = print a
printList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as

main = readInt >>= flip replicateM solve

solve = do
	[ _, d ] <- readInts
	as@( a1 : a2 : _ ) <- sort <$> readInts
	putStrLn $ which "YES" "NO" $ all ( <= d ) as || a1 + a2 <= d

findAllChar :: (Char, [Char]) -> [Int]
findAllChar (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])

findAllInt :: (Int, [Int]) -> [Int]
findAllInt (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])

findFirstChar :: (Char, [Char]) -> Int
findFirstChar (element, list) = (findAllChar(element, list)!!0)

findFirstInt :: (Int, [Int]) -> Int
findFirstInt (element, list) = (findAllInt(element, list)!!0)

takeLast :: (Int, [Char]) -> [Char]
takeLast (cnt, list) = reverse ( take cnt (reverse list) )

split :: (Char, [Char]) -> [[Char]]

split (element, []) = []
split (element, list) = [[ (list!!(ind-1)) | ind <- take (findFirstChar(element, list))  [1..] ]]
                        ++split(element, takeLast((length list)-findFirstChar(element, list)-1, list))

excludeFirst :: (Int, [Int]) -> [Int]
excludeFirst(val, list) = [list!!(ind-1) | ind<-[1..(length list)],
                           ((ind-1)/=(findFirstInt(val, list)))]

readIntLsit :: IO[Int]
readIntLsit  = do
    input <- getLine
    let l = split(' ', input)

    return [(read str :: Int) | str <- l]

minim :: [Int] -> Int
minim []       = 0
minim [x]      = x
minim (x:xs)   = min x (minim xs)

maxim :: [Int] -> Int
maxim []       = 0
maxim [x]      = x
maxim (x:xs)   = max x (maxim xs)

solveTestcase :: () -> (IO [Char])
solveTestcase () = do
    help1 <- readIntLsit
    let help2 = [1, 2, 3]

    let n = help1!!0
    let d = help1!!1
    a <- readIntLsit

    let minVal1 = minim a
    let minVal2 = minim (excludeFirst(minVal1, a))

    let maxVal = maxim a

    if( (minVal1+minVal2) > d && maxVal>d )
        then
            return "NO"
    else
        return "YES"

    --let m = (help!!1)

    --print help

    --print ""

--loop :: Int -> IO()
--loop 0 = print ""
--loop t = do
--    solveTestcase
--    return (loop (t - 1))

--getRes :: (Int) -> ()
--getRes 0 = IO[Char]::Empty
getRes :: Int -> (IO[Char])
getRes 0 = return ""
getRes (t) = do
    x <- solveTestcase()
    y <- getRes(t-1)

    return (x++"\n"++y)

main = do
    help <- readIntLsit
    let t = help!!0

    res <- getRes(t)
    putStr res

findAllChar :: (Char, [Char]) -> [Int]
findAllChar (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])

findAllInt :: (Int, [Int]) -> [Int]
findAllInt (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])

findFirstChar :: (Char, [Char]) -> Int
findFirstChar (element, list) = (findAllChar(element, list)!!0)

findFirstInt :: (Int, [Int]) -> Int
findFirstInt (element, list) = (findAllInt(element, list)!!0)

takeLast :: (Int, [Char]) -> [Char]
takeLast (cnt, list) = reverse ( take cnt (reverse list) )

split :: (Char, [Char]) -> [[Char]]

split (element, []) = []
split (element, list) = [[ (list!!(ind-1)) | ind <- take (findFirstChar(element, list))  [1..] ]]
                        ++split(element, takeLast((length list)-findFirstChar(element, list)-1, list))

excludeFirst :: (Int, [Int]) -> [Int]
excludeFirst(val, list) = [list!!(ind-1) | ind<-[1..(length list)],
                           ((ind-1)/=(findFirstInt(val, list)))]

readIntLsit :: IO[Int]
readIntLsit  = do
    input <- getLine
    let l = split(' ', input)

    return [(read str :: Int) | str <- l]

minim :: [Int] -> Int
minim []       = 0
minim [x]      = x
minim (x:xs)   = min x (minim xs)

maxim :: [Int] -> Int
maxim []       = 0
maxim [x]      = x
maxim (x:xs)   = max x (minim xs)

solveTestcase :: () -> (IO [Char])
solveTestcase () = do
    help1 <- readIntLsit
    let help2 = [1, 2, 3]

    let n = help1!!0
    let d = help1!!1
    a <- readIntLsit

    let minVal1 = minim a
    let minVal2 = minim (excludeFirst(minVal1, a))

    let maxVal = maxim a

    if( (minVal1+minVal2) > d && maxVal>d )
        then
            return "NO"
    else
        return "YES"

    --let m = (help!!1)

    --print help

    --print ""

--loop :: Int -> IO()
--loop 0 = print ""
--loop t = do
--    solveTestcase
--    return (loop (t - 1))

--getRes :: (Int) -> ()
--getRes 0 = IO[Char]::Empty
getRes :: Int -> (IO[Char])
getRes 0 = return ""
getRes (t) = do
    x <- solveTestcase()
    y <- getRes(t-1)

    return (x++"\n"++y)

main = do
    help <- readIntLsit
    let t = help!!0

    res <- getRes(t)
    putStr res

findAllChar :: (Char, [Char]) -> [Int]
findAllChar (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])

findAllInt :: (Int, [Int]) -> [Int]
findAllInt (element, list) = ([ind | ind<-[1..((length list)-1)], (list!!ind)==element]++[length list])

findFirstChar :: (Char, [Char]) -> Int
findFirstChar (element, list) = (findAllChar(element, list)!!0)

findFirstInt :: (Int, [Int]) -> Int
findFirstInt (element, list) = (findAllInt(element, list)!!0)

takeLast :: (Int, [Char]) -> [Char]
takeLast (cnt, list) = reverse ( take cnt (reverse list) )

split :: (Char, [Char]) -> [[Char]]

split (element, []) = []
split (element, list) = [[ (list!!(ind-1)) | ind <- take (findFirstChar(element, list))  [1..] ]]
                        ++split(element, takeLast((length list)-findFirstChar(element, list)-1, list))

excludeFirst :: (Int, [Int]) -> [Int]
excludeFirst(val, list) = [list!!(ind-1) | ind<-[1..(length list)],
                           ((ind-1)/=(findFirstInt(val, list)))]

readIntLsit :: IO[Int]
readIntLsit  = do
    input <- getLine
    let l = split(' ', input)

    return [(read str :: Int) | str <- l]

minim :: [Int] -> Int
minim []       = 0
minim [x]      = x
minim (x:xs)   = min x (minim xs)

solveTestcase :: () -> (IO [Char])
solveTestcase () = do
    help1 <- readIntLsit
    let help2 = [1, 2, 3]

    let n = help1!!0
    let d = help1!!1
    a <- readIntLsit

    let minVal1 = minim a
    let minVal2 = minim (excludeFirst(minVal1, a))

    if( (minVal1+minVal2) > d )
        then
            return "NO"
    else
        return "YES"

    --let m = (help!!1)

    --print help

    --print ""

--loop :: Int -> IO()
--loop 0 = print ""
--loop t = do
--    solveTestcase
--    return (loop (t - 1))

--getRes :: (Int) -> ()
--getRes 0 = IO[Char]::Empty
getRes :: Int -> (IO[Char])
getRes 0 = return ""
getRes (t) = do
    x <- solveTestcase()
    y <- getRes(t-1)

    return (x++"\n"++y)

main = do
    help <- readIntLsit
    let t = help!!0

    res <- getRes(t)
    putStr res

import           Control.Monad
import qualified Data.List             as L
import qualified Data.Map.Strict       as M
import qualified Data.Set              as S

--
-- UTILITIES
--
import qualified Data.ByteString.Char8 as C8
import           Data.Maybe            (fromJust)

getInt :: IO Int
getInt = read <$> getLine

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

getInteger :: IO Integer
getInteger = read <$> getLine

getIntegers :: IO [Integer]
getIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine

--
-- MAIN
--

main :: IO ()
main = do
  t <- getInt
  replicateM_ t $ do
      [n, d] <- getInts
      a@(a1:a2:_) <- L.sort <$> getInts
      if all (<= d) a || (a1 + a2 < 0) then putStrLn "YES" else putStrLn "NO"

import Prelude
import Data.List
import Data.Int
import Control.Arrow

parseIntList :: String -> [Int64]
parseIntList = words >>> map read

makePair :: a -> [a] -> [(a,a)]
makePair val list = map (\x -> (val,x)) list

pairs :: [Int64] -> [(Int64,Int64)]
pairs list = foldr (++) [] (map (\x -> makePair x (tail list)) list)

problem :: [[Int64]] -> String
problem [] = ""
problem (x:y:z) = (if((foldr (\(a,b) c -> c || (a + b <= d)) False (pairs y)) || (foldr (\a b -> b && a <= d)) True y) then "YES" else "NO")++"\n"++(problem z) where d = x !! 1
problem (_:_) = ""

solve :: String -> String
solve str = problem $ map parseIntList $ tail $ lines str

main :: IO ()
main = interact $ solve


Vasya has got $$$n$$$ books, numbered from $$$1$$$ to $$$n$$$, arranged in a stack. The topmost book has number $$$a_1$$$, the next one — $$$a_2$$$, and so on. The book at the bottom of the stack has number $$$a_n$$$. All numbers are distinct.Vasya wants to move all the books to his backpack in $$$n$$$ steps. During $$$i$$$-th step he wants to move the book number $$$b_i$$$ into his backpack. If the book with number $$$b_i$$$ is in the stack, he takes this book and all the books above the book $$$b_i$$$, and puts them into the backpack; otherwise he does nothing and begins the next step. For example, if books are arranged in the order $$$[1, 2, 3]$$$ (book $$$1$$$ is the topmost), and Vasya moves the books in the order $$$[2, 1, 3]$$$, then during the first step he will move two books ($$$1$$$ and $$$2$$$), during the second step he will do nothing (since book $$$1$$$ is already in the backpack), and during the third step — one book (the book number $$$3$$$). Note that $$$b_1, b_2, \dots, b_n$$$ are distinct.Help Vasya! Tell him the number of books he will put into his backpack during each step.

The first line contains one integer $$$n~(1 \le n \le 2 \cdot 10^5)$$$ — the number of books in the stack. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n~(1 \le a_i \le n)$$$ denoting the stack of books. The third line contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n~(1 \le b_i \le n)$$$ denoting the steps Vasya is going to perform. All numbers $$$a_1 \dots a_n$$$ are distinct, the same goes for $$$b_1 \dots b_n$$$.

Print $$$n$$$ integers. The $$$i$$$-th of them should be equal to the number of books Vasya moves to his backpack during the $$$i$$$-th step.

NoteThe first example is described in the statement.In the second example, during the first step Vasya will move the books $$$[3, 1, 4]$$$. After that only books $$$2$$$ and $$$5$$$ remain in the stack ($$$2$$$ is above $$$5$$$). During the second step Vasya will take the books $$$2$$$ and $$$5$$$. After that the stack becomes empty, so during next steps Vasya won't move any books.

{-# LANGUAGE BangPatterns #-}
import Data.List(foldl')
import qualified Data.HashMap.Strict as Map
import qualified Data.Text.IO as TIO
import qualified Data.Text.Read as TR
import qualified Data.Text as T

getMap :: [Int] -> Map.HashMap Int Int
getMap !xs = Map.fromList $ zip xs [1..]

getIndeces :: Map.HashMap Int Int -> [Int] -> [Int]
getIndeces !m !xs = map (m Map.!) xs

putBooks :: Map.HashMap Int Int -> [Int] -> [Int]
putBooks !stack !books = reverse . fst $ foldl' putBook ([], 0) indeces
    where indeces = getIndeces stack books
          putBook :: ([Int], Int) -> Int -> ([Int], Int)
          putBook (!steps, !last) book = if book < last
              then (0 : steps, last)
              else ((book - last) : steps, book)

right :: Either a b -> b
right (Right b) = b

readIntList :: T.Text -> [Int]
readIntList = (map (fst . right . TR.decimal)) . T.words

main :: IO ()
main = do
  n <- TIO.getLine
  stack <- fmap (getMap . readIntList) TIO.getLine
  books <- fmap readIntList TIO.getLine
  putStrLn $ unwords $ map show $ putBooks stack books


You are given a problemset consisting of $$$n$$$ problems. The difficulty of the $$$i$$$-th problem is $$$a_i$$$. It is guaranteed that all difficulties are distinct and are given in the increasing order.You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to assemble should be a subset of problems (not necessary consecutive) of the given problemset. There is only one condition that should be satisfied: for each problem but the hardest one (the problem with the maximum difficulty) there should be a problem with the difficulty greater than the difficulty of this problem but not greater than twice the difficulty of this problem. In other words, let $$$a_{i_1}, a_{i_2}, \dots, a_{i_p}$$$ be the difficulties of the selected problems in increasing order. Then for each $$$j$$$ from $$$1$$$ to $$$p-1$$$ $$$a_{i_{j + 1}} \le a_{i_j} \cdot 2$$$ should hold. It means that the contest consisting of only one problem is always valid.Among all contests satisfying the condition above you have to assemble one with the maximum number of problems. Your task is to find this number of problems.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of problems in the problemset. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — difficulties of the problems. It is guaranteed that difficulties of the problems are distinct and are given in the increasing order.

Print a single integer — maximum number of problems in the contest satisfying the condition in the problem statement.

NoteDescription of the first example: there are $$$10$$$ valid contests consisting of $$$1$$$ problem, $$$10$$$ valid contests consisting of $$$2$$$ problems ($$$[1, 2], [5, 6], [5, 7], [5, 10], [6, 7], [6, 10], [7, 10], [21, 23], [21, 24], [23, 24]$$$), $$$5$$$ valid contests consisting of $$$3$$$ problems ($$$[5, 6, 7], [5, 6, 10], [5, 7, 10], [6, 7, 10], [21, 23, 24]$$$) and a single valid contest consisting of $$$4$$$ problems ($$$[5, 6, 7, 10]$$$).In the second example all the valid contests consist of $$$1$$$ problem.In the third example are two contests consisting of $$$3$$$ problems: $$$[4, 7, 12]$$$ and $$$[100, 150, 199]$$$.

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

main = sol <$> (C.getLine *> get) >>= print

get = fmap fst . mapMaybe C.readInt . C.words <$> C.getLine

sol (a:as) = (\(_,_,m) -> m) $ foldl' f (a,1,1) as

f (a,n,m) a' = (a', n', max n' m)
    where
    n' = if a*2 >= a' then n+1 else 1


Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an n by n square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. In other words, for every x, y such that 1 ≤ x, y ≤ n and ax, y ≠ 1, there should exist two indices s and t so that ax, y = ax, s + at, y, where ai, j denotes the integer in i-th row and j-th column.Help Okabe determine whether a given lab is good!

The first line of input contains the integer n (1 ≤ n ≤ 50) — the size of the lab.  The next n lines contain n space-separated integers denoting a row of the grid. The j-th integer in the i-th row is ai, j (1 ≤ ai, j ≤ 105).

Print "Yes" if the given lab is good and "No" otherwise. You can output each letter in upper or lower case.

NoteIn the first sample test, the 6 in the bottom left corner is valid because it is the sum of the 2 above it and the 4 on the right. The same holds for every number not equal to 1 in this table, so the answer is "Yes".In the second sample test, the 5 cannot be formed as the sum of an integer in the same row and an integer in the same column. Thus the answer is "No".

import Control.Monad
import Control.Applicative

-- f :: [[Int]] -> [[Int]] -> [Int] -> [Int] -> Bool
f n ns ns' is xs = and $ zipWith (\i x -> if x == 1
                                            then True
                                            else let (q,r) = i `quotRem` n
                                                     ar = (+) <$>  ns!!q <*> ns' !! r
                                                 in x `elem` ar
                               ) is xs

main = do
   n <- readLn :: IO Int
   ns <- replicateM n (getLine >>= return . map (read :: String -> Int) . words)
   let ns' =  map (\i -> map (!!i) ns) [0..n-1]
   let a = f n ns ns' [0..n*n-1] $ concat ns
   putStrLn $ if a then "Yes" else "No"

f::Int->Int->Int->[[Int]]->String
f (-1) _ _ _="Yes"
f y (-1) c ms=f (y-1) c c ms
f y x c ms=let t=[1|y1<-[0..c],x1<-[0..c],y1/=y,x1/=x,(ms!!y1!!x)+(ms!!y!!x1)==(ms!!y!!x)]
           in if t==[] && (ms!!y!!x)>1 then "No" else f y (x-1) c ms

f2::[String]->[[Int]]
f2 []=[]
f2 (s:str)=let xs=map read (words s)::[Int]
           in xs:f2 str

main =do
      e<-getLine
      es<-getContents
      let xs=lines es
          ys=f2 xs
          n=read e::Int
      putStrLn $ f (n-1) (n-1) (n-1) ys

import Control.Applicative
import Control.Monad
import Data.Array
import Data.Bool

main = sol <$> get >>= put

get :: IO [[Int]]
get = fmap (fmap read . words) . tail . lines <$> getContents

put = putStrLn . bool "No" "Yes"

sol ass = all gd [(x,y) | x <- [1..n], y <- [1..n], ar!(x,y) /= 1]
    where
    n = length ass
    ar = listArray ((1,1),(n,n)) $ concat ass
    gd (x,y) = ar!(x,y) `elem` [ar!(x,j) + ar!(i,y) | i <- [1..n], j <- [1..n]]

{-
ass = [
    [1, 1, 2],
    [2, 3, 1],
    [6, 4, 1]]
n = length ass
ar = listArray ((1,1),(n,n)) $ concat ass
gd (x,y) = ar!(x,y) `elem` [ar!(x,j) + ar!(i,y) | i <- [1..n], j <- [1..n]]
aa = [gd (x,y) | x <- [1..n], y <- [1..n], ar!(x,y) /= 1]
-}

import Control.Applicative( (<$>))
import Data.Array.IArray( listArray, (!))
import Data.Array.Unboxed( UArray)
import Control.Monad( replicateM)

main = do
    n_ <- readLn
    let
	row = map (read::String->Int) . words <$> getLine

    rows_ <- replicateM n_ row
    let
	dataArray::UArray (Int,Int) Int
	dataArray = listArray ((1,1),(n_,n_)) $ concat rows_

	candidate (x,y) = let
	    row = (\s->dataArray!(x,s)) <$> ([1..y-1] ++ [y+1..n_])
	    col = (\t->dataArray!(t,y)) <$> ([1..x-1] ++ [x+1..n_])
	  in
	    (row,col)

	check (x,y) = let
		    (r,c) = candidate (x,y)
		    v = dataArray!(x,y)
		in
		    or $ (\i-> (v-i) `elem` c) <$> r

	allIx = [(x,y) | x<-[1..n_], y<-[1..n_]]

	verify (i,j) = if dataArray!(i,j) == 1
			then True
			else check (i,j)

    putStr $ if and $ verify <$> allIx
		then "Yes"
		else "No"

import Data.List (transpose)
import Data.Bool (bool)

sol :: [[Int]] -> [[Bool]]
sol rs = map rf rs where
    rf r = zipWith (cf r) cs r
    cf r c x | x == 1    = True
             | otherwise = or $ flip map c $ flip elem r . (x -)
    cs = transpose rs

main = interact $
    (bool "No" "Yes") . (and . concat)
  . sol
  . map (map read . words) . tail . lines

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

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

solve g = all (\r -> all (\(x, c) -> x == 1 || any (`elem` c) [x - x' | x' <- r]) $ zip r g') g
  where
    g' = transpose g

main = do
  n <- fmap readInt B.getLine
  g <- replicateM n (fmap readInts B.getLine)
  putStr $ if solve g then "Yes" else "No"

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

check a b n x y | x==n = "Yes"
		| ((a!!x)!!y) ==1 = if y==n-1 then check a b n (x+1) 0 else check a b n x (y+1)
		| elem ((a!!x)!!y) [i+j|i<-a!!x, j<-b!!y] =  if y==n-1 then check a b n (x+1) 0 else check a b n x (y+1)
		|otherwise = "No"
main=do
  n<- read <$> getLine::IO Int
  a<- map(map read) <$> map words <$> replicateM n getLine ::IO [[Int]]
  let b= transpose a
  putStrLn $ check a b n 0 0


Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array a consisting of n distinct integers.Unfortunately, the size of a is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question correctly: is it possible to sort the array a (in increasing order) by reversing exactly one segment of a? See definitions of segment and reversing in the notes.

The first line of the input contains an integer n (1 ≤ n ≤ 105) — the size of array a. The second line contains n distinct space-separated integers: a[1], a[2], ..., a[n] (1 ≤ a[i] ≤ 109).

Print "yes" or "no" (without quotes), depending on the answer. If your answer is "yes", then also print two space-separated integers denoting start and end (start must not be greater than end) indices of the segment to be reversed. If there are multiple ways of selecting these indices, print any of them.

NoteSample 1. You can reverse the entire array to get [1, 2, 3], which is sorted.Sample 3. No segment can be reversed such that the array will be sorted.DefinitionsA segment [l, r] of array a is the sequence a[l], a[l + 1], ..., a[r].If you have an array a of size n and you reverse its segment [l, r], the array will become:a[1], a[2], ..., a[l - 2], a[l - 1], a[r], a[r - 1], ..., a[l + 1], a[l], a[r + 1], a[r + 2], ..., a[n - 1], a[n].

import Data.List

main = interact $ ans.parse.tail.words
parse x = (map read x :: [Integer])
ans lst = f (reverse (g (zip lst [1..(length lst)]) [] 1)) lst

g (x:y:xs) lst orientation
  | orientation == 1 = if (fst x) < (fst y)
                       then g (y:xs) lst 1
                       else g (y:xs) ((snd x):lst) (-1)
  | orientation == (-1) = if (fst x) < (fst y)
                          then g (y:xs) ((snd x):lst) 1
                          else g (y:xs) lst (-1)

g (x:[]) lst orientation = lst

f [] orig = "yes\n1 1"

f (x:[]) orig
  | (take (x-1) orig) ++ (reverse (drop (x-1) orig)) == (sort orig) = "yes\n" ++ (show x) ++ " " ++ (show (length orig))
  | otherwise = "no"

f (x:y:[]) orig
  | (take (x-1) orig)
    ++ (reverse (drop (x-1) (take y orig))) ++
    (drop y orig) == (sort orig) = "yes\n" ++ (show x) ++ " " ++ (show y)
  | otherwise = "no"

f (x:y:xs) orig = "no"

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

import Control.Applicative
import Control.Monad hiding ((<$!>))
import Control.Monad.ST.Safe
import Control.Monad.State hiding ((<$!>))
-- import Data.Array
import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

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

main = do
  getLine
  xs <- getInts

  let
    check l r = and $ zipWith (<) ys $ tail ys
      where
        ys = take (l-1) xs ++ (reverse $ take (r-l+1) $ drop (l-1) xs) ++ (drop r xs)

    r =
      case map (+1) $ True `elemIndices` (zipWith (>) xs $ tail xs) of
        [] -> Just (1, 1)
        [i] -> if check i (i+1) then Just (i, i+1) else Nothing
        r -> let (i, j) = (head r, last r) in if check i (j+1) then Just (i, j+1) else Nothing

  -- print $ True `elemIndices` (zipWith (>) xs $ tail xs)

  case r of
    Just (l, r) -> do
      putStrLn "yes"
      putStrLn $ show l ++ " " ++ show r
    Nothing ->
      putStrLn "no"

{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE MultiWayIf           #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Trans.State
import qualified Data.ByteString.Lazy.Char8 as B
import           Data.Function
import           Data.List
import           Data.Maybe
import           System.Environment
import           System.IO

type BString = B.ByteString

type Result = (String, [Int])

solve :: [Int] -> Result
solve xs = decide_on $ merge_singles parts
  where
    decide_on [one]
        | one == sorted = ("yes", [1, 1])
        | reverse one == sorted = ("yes", [1, length one])
        | otherwise = ("no", [])
    decide_on [one, two]
        | reverse one ++ two == sorted = ("yes", [1, length one])
        | one ++ reverse two == sorted = ("yes", [length one + 1, length xs])
        | otherwise = ("no", [])
    decide_on [one, two, three]
        | one ++ reverse two ++ three == sorted = ("yes", [length one + 1, length one + length two])
        | otherwise = ("no", [])
    decide_on _ = ("no", [])
    merge_singles (a:b:c:rest)
        | descending (a ++ b ++ c) = (a ++ b ++ c) : merge_singles rest
        | otherwise = a : merge_singles (b : c : rest)
    merge_singles other = other

    parts = map fst <$> groupBy ((==) `on` equal) (zip xs sorted)
    sorted = sort xs
    equal = uncurry (==)
    descending = snd . foldr (\x (prev, acc) -> (x, acc && x >= prev)) (0, True)

process :: State Reader Result
process = do
    parse :: State Reader BString
    as <- parse :: State Reader [Int]
    let (answer, range) = solve as
    return (answer, range)

main :: IO ()
main = do
    input <- B.lines <$> B.getContents
    let (answer, range) = evalState process input
    say answer
    say range

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True  = 1

type Reader = [BString]

class Display a =>
      EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString

class (Read a, Show a) =>
      Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Integer

instance Display Double

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Function
import Data.Ord
import Data.Bits
import Data.Monoid
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main= someFunc
rIn x= fst $ fromJust  $ C.readInteger x
someFunc::IO()
someFunc = solve.tail.concat=<<forM [1..2] (\i->map rIn.C.words<$>C.getLine)
solve xs = let zs= groupBy ((>=) `on` snd) $ zip [1..] xs; fs =filter (\a->length a>1) zs; fs1 = concat fs; xs1=map snd $ concat $ map reverse zs  in if length fs > 1 then putStr "no" else if length fs==0 then  putStrLn "yes" >> putStr "1 1"  else if sort xs /= xs1 then putStr "no" else  putStrLn "yes" >> putStr (show (fst $ head fs1)++" "++show (fst $ last fs1))

-- Codeforces 451B

import Data.List

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

solve :: [Int] -> String
solve (n:xs)
    | xs == (sort xs) = "yes\n1 1"
    | otherwise = case (reverse $ map fst k) == (map snd k)
    of {
        True -> "yes\n" ++ (intercalate " " $ map show [len+1, len+(length k)]);
        False -> "no";
    } where
        all = zip xs (sort xs)
        len = length $ takeWhile (\x -> (fst x) == (snd x)) all
        k = dropWhile (\x -> (fst x) == (snd x)) $ dropWhileEnd (\x -> (fst x) == (snd x)) all

-- judge if a list is sorted in non-decreasing ordering.
sorted :: [Int] -> Bool
sorted xs = and $ zipWith (<=) xs (tail xs)

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.List (sort)
import Data.Maybe (mapMaybe)
import Text.Printf

main = do
  _ <- getLine
  xs <- map fst . mapMaybe B.readInt . B.words <$> B.getLine
  let
    sorted_xs = sort xs
    not_matched [] _ _ = []
    not_matched (x:xs) (y:ys) index
      | x == y = not_matched xs ys (index+1)
      | otherwise = index : not_matched xs ys (index+1)
    not_sorted_segment = not_matched xs sorted_xs 0
    begin = head not_sorted_segment
    end = last not_sorted_segment + 1
    a = take begin xs
    b = reverse . take (end-begin) $ drop begin xs
    c = drop end xs
   in if xs == sorted_xs
      then putStrLn "yes\n1 1"
      else if a ++ b ++ c == sorted_xs
           then putStrLn "yes" >> printf "%d %d\n" (begin+1) end
           else putStrLn "no"

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.List (sort)
import Data.Maybe (fromJust)

extract :: Int -> Int -> [a] -> [a]
extract first last xs = take (last-first+1) ys
  where
    (_,ys) = splitAt first xs

main = do
  n <- readLn
  xs <- map (fst.fromJust.B.readInt) . B.words <$> B.getLine
  let
    sorted_xs = sort xs
    nochange = xs == sorted_xs
    first = length . takeWhile (uncurry (==)) $ zip xs sorted_xs
    last = n - (length . takeWhile (uncurry (==)) $ zip (reverse xs) (reverse sorted_xs)) - 1
    xs' = take first xs ++ (reverse $ extract first last xs) ++ drop (last+1) xs
    change = xs' == sorted_xs
    in putStrLn $ if nochange then "yes\n1 1" else if change then "yes\n" ++ (unwords $ map show [first+1, last+1]) else "no"

import Data.List (sort)

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

solve :: [Int] -> String
solve as | null is = unlines [ "yes", "1 1" ]
         | reverseSegment as imin imax == sort as = unlines [ "yes", unwords (map show [ imin, imax ]) ]
         | otherwise = "no"
  where is = [ i | (i, a, a') <- zip3 [1..] as (sort as), a /= a' ]
        imin = head is; imax = last is

reverseSegment :: [a] -> Int -> Int -> [a]
reverseSegment as i j = take (i - 1) as ++ reverse (drop (i - 1) (take j as)) ++ drop j as

import Data.List (sort)

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

solve :: [Int] -> String
solve as | null is = unlines [ "yes", "1 1" ]
         | take (imin - 1) as ++ reverse (drop (imin - 1) (take imax as)) ++ drop imax as == sort as = unlines [ "yes", unwords (map show [ imin, imax ]) ]
         | otherwise = "no"
  where is = [ i | ((i, a), a') <- zip (zip [1..] as) (sort as), a /= a' ]
        imin = head is; imax = last is

import Data.List
import Data.Function
import Control.Monad
main = interact $ format . solve . map read . words
format Nothing = "no"
format (Just (a,b)) = unlines [ "yes", show (a+1) ++ " " ++ show (b+1) ]
solve (n : xs)
  | null drs = Just (0,0)
  | [(a,b)] <- drs = guard (a == 0 || xs!!(a-1) < xs!!b) *>
                     guard (b == n-1 || xs!!a < xs!!(b+1)) *>
                     Just (a,b)
  | otherwise = Nothing
  where
    drs = go 0 $ groupBy ((==) `on` signum) $ zipWith (-) (tail xs) xs
    go i (ds@(d:_):dss) | d > 0 = go (i + length ds) dss
                        | otherwise = (i,i+length ds) : go (i + length ds) dss
    go _ _ = []

{-# 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.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
  n <- readLn
  xs <- map readInt.B.words <$> B.getLine
  case solve n xs of
    Just (l,r) -> putStrLn "yes" >> putStr (shows l " " ++ shows r "\n")
    Nothing -> putStrLn "no"

solve :: Int -> [Int] -> Maybe (Int, Int)
solve n xs
  | xs == sorted = Just (1,1)
  | otherwise = case divide xs of
                  [xs]
                    | reverse xs == sorted -> Just (1,n)
                  [xs,ys]
                    | reverse xs ++ ys == sorted -> Just (1, length xs)
                    | xs ++ reverse ys == sorted -> Just (length xs+1, n)
                  [xs,ys,zs]
                    | xs ++ reverse ys ++ zs == sorted -> Just (length xs+1, length (xs++ys))
                  _ -> Nothing
 where
   !sorted = sort xs

divide [] = []
divide [x] = [[x]]
divide (x:y:xs)
  | x < y = asc [y,x] xs
  | otherwise = des [y,x] xs

asc (top:stack) (x:xs)
  | top < x = asc (x:top:stack) xs
  | otherwise = reverse stack : des [x,top] xs
asc stack [] = [reverse stack]

des (top:stack) (x:xs)
  | top > x = des (x:top:stack) xs
  | otherwise = (reverse $ top:stack) : asc [x] xs
des stack [] = [reverse stack]

sorted :: Ord a => [a] -> Bool
sorted [] = True
sorted [x] = True
sorted (x:y:xs) = x <= y && sorted (y:xs)

f :: [Int] -> Maybe (Int, Int)
f [] = undefined
f [x] = Just (1, 1)
f [x,y] = if x > y then Just (1,2) else Just (1,1)
f (x:y:z:xs) = if x > y then g (-2000000000) x (x:y:z:xs) >>= \r->Just(1,r) else
               if y > z then g x y (y:z:xs) >>= \r->Just (2, r + 1)
               else f (y:z:xs) >>= \(x,y)->Just (x + 1, y + 1)

g :: Int -> Int -> [Int] -> Maybe Int
g _ _ [] = undefined
g xx yy [p] = if xx < p && p < yy then Just 1 else Nothing
g xx yy (p:q:pp) = if p > q then g xx yy (q:pp) >>= Just . (1+)
                   else if xx < p && yy < q && sorted (q:pp) then Just 1 else Nothing
par :: String -> [Int]
par = (map read) . words

good x y= do
  putStrLn "yes"
  putStrLn $ show x ++ " " ++ show y
main = do
  l <- getLine
  l1 <- getLine
  let a = par l1
  case f a of
    Just (x, y) -> good x y
    Nothing -> putStrLn "no"

import Data.List
import Text.Printf

isSorted [x] = 1
isSorted [] = 1
isSorted (a:b:xs) = if (a < b) then isSorted (b:xs) else 0

getInts s = map read $ words s

get :: [Int] -> [Int] -> ([Int], [Int])
get f [x] = (f, [])
get f (a:b:xs) = if (a < b) then get (a:f) (b:xs) else (f, a:b:xs)

got :: [Int] -> [Int] -> ([Int], [Int])
got f [x] = ([x], [])
got f [] = ([], [])
got f (a:b:xs) = if (a > b) then got (a:f) (b:xs) else (a:f, b:xs)

main = do
    s <- getLine
    s <- getLine
    let t = getInts s
        y = get [] t
        u = got [] (snd y)
--    print(t);
--    print(y);
--    print(u);
    if (isSorted ((reverse $ fst y) ++ (fst u) ++ (snd u)) == 1)
        then printf "yes\n%d %d\n" (length (fst y) + 1) (length t - (length (snd u)))
        else printf "no\n"

{-# OPTIONS_GHC -O2 #-}
import Data.Maybe
import Data.Char
import Data.List
import Data.Int
import Data.Bits
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

extract [] [] _ = []
extract (a:as) (b:bs) n
  | a == b    = extract as bs (n + 1)
  | otherwise = n: extract as bs (n + 1)

main = do
  n <- head . map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine
  as <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine
  let sortAs = sort as
      inds = extract as sortAs 0
  if inds == []
    then putStrLn "yes\n1 1"
    else do let mn = minimum inds
                mx = 1 + maximum inds
                aas = reverse. drop mn . take mx $ as
                prefix = take mn as
                suffix = drop mx as
                bs = prefix ++ aas ++ suffix
            if bs == sortAs
              then putStrLn "yes" >> printf "%d %d\n" (mn + 1) mx
              else putStrLn "no"

import Data.List

cal ls = if allSame
         then "yes\n1 1"
         else if result then "yes\n" ++ show startIdx ++ " " ++ show endIdx else "no"
  where arr = map (+0) $ map read $ words $ head $ tail $ lines ls
        zips = zip arr $ sort arr
        allSame = all (\p -> (fst p) == (snd p) ) zips
        sameFront = length $ takeWhile (\p -> (fst p) == (snd p)) zips
        startIdx = sameFront + 1
        sameEnd = length $ takeWhile (\p -> (fst p) == (snd p)) $ reverse zips
        endIdx  = (length zips) - sameEnd
        remains = reverse $ drop sameEnd $ reverse $ drop sameFront zips
        (ori,rev) = unzip remains
        newZip = zip ori $ reverse rev
        result = all (\p -> (fst p) == (snd p)) newZip

main = interact cal

import Data.List

main = interact $ ans.parse.tail.words
parse x = (map read x :: [Integer])
ans lst = f (g (zip lst [1..(length lst)]) [] 1) lst

g (x:y:xs) lst orientation
  | orientation == 1 = if (fst x) < (fst y)
                       then g (y:xs) lst 1
                       else g (y:xs) ((snd x):lst) (-1)
  | orientation == (-1) = if (fst x) < (fst y)
                          then g (y:xs) ((snd x):lst) 1
                          else g (y:xs) lst (-1)

g (x:[]) lst orientation = lst

f [] orig = "Yes\n1 1"

f (x:[]) orig
  | (take (x-1) orig) ++ (reverse (drop (x-1) orig)) == (sort orig) = "Yes\n" ++ (show x) ++ " " ++ (show (length orig))
  | otherwise = "No"

f (x:y:[]) orig
  | (take (x-1) orig)
    ++ (reverse (drop (x-1) (take (y-1) orig))) ++
    (drop (y-1) orig) == (sort orig) = "Yes\n" ++ (show x) ++ (show y)
  | otherwise = "No"

f (x:y:xs) orig = "No"

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

import Control.Applicative
import Control.Monad hiding ((<$!>))
import Control.Monad.ST.Safe
import Control.Monad.State hiding ((<$!>))
-- import Data.Array
import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

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

main = do
  getLine
  xs <- getInts

  let
    check l r = and $ zipWith (<) ys $ tail ys
      where
        ys = take (l-1) xs ++ (reverse $ take (r-l+1) $ drop (l-1) xs) ++ (drop r xs)

    r =
      case map (+1) $ True `elemIndices` (zipWith (>) xs $ tail xs) of
        [] -> Just (1, 1)
        [i] -> if check i (i+1) then Just (i, i+1) else Nothing
        [i, j] -> if check i (j+1) then Just (i, j+1) else Nothing
        otherwise -> Nothing

  case r of
    Just (l, r) -> do
      putStrLn "yes"
      putStrLn $ show l ++ " " ++ show r
    Nothing ->
      putStrLn "no"

{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import Control.Applicative
import Control.Monad
import Control.Monad.Trans.State
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Function
import Data.List
import Data.Maybe
import System.Environment
import System.IO

type BString = B.ByteString

type Result = (String, [Int])

solve :: Int -> [Int] -> Result
solve x xs = decide_on parts
  where
    decide_on [one]
        | one == sorted = ("yes", [1, 1])
        | reverse one == sorted = ("yes", [1, length one])
        | otherwise = ("no", [])
    decide_on [one, two]
        | reverse one ++ two == sorted = ("yes", [1, length one])
        | one ++ reverse two == sorted = ("yes", [length one + 1, length one + length two])
        | otherwise = ("no", [])
    decide_on [one, two, three]
        | one ++ reverse two ++ three == sorted = ("yes", [length one + 1, length one + length two])
        | otherwise = ("no", [])
    decide_on _ = ("no", [])

    parts = eliminate_singles $ map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted
    sorted = sort xs
    descending range = range == sortBy (flip compare) range
    equal (a, b) = a == b
    eliminate_singles (a:b:c:rest)
        | length b == 1 || length a == 1 && length c == 1 = (a ++ b ++ c) : eliminate_singles rest
        | length a == 1 = (a ++ b) : eliminate_singles (c : rest)
        | length c == 1 = a : (b ++ c) : eliminate_singles rest
        | otherwise = a : b : eliminate_singles (c : rest)
    eliminate_singles other = other

process :: State Reader Result
process = do
    n <- parse
    as <- parse
    return $ solve n as

main :: IO ()
main = do
    input <- B.lines <$> B.getContents
    let (answer, range) = evalState process input
    say answer
    say range

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True = 1

type Reader = [BString]

class Display a =>
      EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString

class (Read a, Show a) =>
      Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Integer

instance Display Double

{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE MultiWayIf           #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Trans.State
import qualified Data.ByteString.Lazy.Char8 as B
import           Data.Function
import           Data.List
import           Data.Maybe
import           System.Environment
import           System.IO

type BString = B.ByteString
type Result = (String, [Int])

solve :: Int -> [Int] -> Result
solve x xs = decide_on parts
  where
    decide_on [one]
        | one == sorted = ("yes", [1, 1])
        | reverse one == sorted = ("yes", [1, length one])
        | otherwise = ("no", [])
    decide_on [one, two]
        | reverse one ++ two == sorted = ("yes", [1, length one])
        | one ++ reverse two == sorted = ("yes", [length one + 1, length one + length two])
        | otherwise = ("no", [])
    decide_on [one, two, three]
        | one ++ reverse two ++ three == sorted = ("yes", [length one + 1, length one + length two])
        | otherwise = ("no", [])
    decide_on _ = ("no", [])

    parts = eliminate_singles $ map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted
    sorted = sort xs
    descending range = range == sortBy (flip compare) range
    equal (a, b) = a == b

    eliminate_singles (a:b:c:rest)
        | length a == 1 = (a++b) : eliminate_singles rest
        | length b == 1 = (a++b++c) : eliminate_singles rest
        | length c == 1 = a : (b++c) : eliminate_singles rest
        | otherwise = a : b : eliminate_singles (c:rest)
    eliminate_singles other = other

process :: State Reader Result
process = do
    n <- parse
    as <- parse
    return $ solve n as

main :: IO ()
main = do
    input <- B.lines <$> B.getContents
    let (answer, range) = evalState process input
    say answer
    say range

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True  = 1

type Reader = [BString]

class Display a => EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int where

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString where

class (Read a, Show a) => Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Integer
instance Display Double

{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE MultiWayIf           #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Trans.State
import qualified Data.ByteString.Lazy.Char8 as B
import           Data.Function
import           Data.List
import           Data.Maybe
import           System.Environment
import           System.IO

type BString = B.ByteString

type Result = (String, [Int])

solve :: [Int] -> Result
solve xs = decide_on parts
  where
    decide_on [one]
        | one == sorted = ("yes", [1, 1])
        | reverse one == sorted = ("yes", [1, length one])
        | otherwise = ("no", [])
    decide_on [one, two]
        | reverse one ++ two == sorted = ("yes", [1, length one])
        | one ++ reverse two == sorted = ("yes", [length one + 1, length xs])
        | otherwise = ("no", [])
    decide_on [one, two, three]
        | reverse (one ++ two ++ three) == sorted = ("yes", [1, length xs])
        | one ++ reverse two ++ three == sorted = ("yes", [length one + 1, length one + length two])
        | otherwise = ("no", [])
    decide_on [one, two, three, four]
        | reverse (one ++ two ++ three) ++ four == sorted = ("yes", [1, length xs - length four])
        | one ++ reverse (two ++three ++ four) == sorted = ("yes", [length one + 1, length xs])
        | otherwise = ("no", [])
    decide_on _ = ("no", [])
    parts = map fst <$> groupBy ((==) `on` equal) (zip xs sorted)
    sorted = sort xs
    equal = uncurry (==)

process :: State Reader Result
process = do
    parse :: State Reader BString
    as <- parse :: State Reader [Int]
    let (answer, range) = solve as
    return (answer, range)

main :: IO ()
main = do
    input <- B.lines <$> B.getContents
    let (answer, range) = evalState process input
    say answer
    say range

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True  = 1

type Reader = [BString]

class Display a =>
      EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString

class (Read a, Show a) =>
      Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Integer

instance Display Double

{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE MultiWayIf           #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Trans.State
import qualified Data.ByteString.Lazy.Char8 as B
import           Data.Function
import           Data.List
import           Data.Maybe
import           System.Environment
import           System.IO

type BString = B.ByteString
type Result = (String, [Int])

solve :: Int -> [Int] -> Result
solve x xs = decide_on parts
  where
    decide_on [one]
        | one == sorted = ("yes", [1, 1])
        | reverse one == sorted = ("yes", [1, length one])
        | otherwise = ("no", [])
    decide_on [one, two]
        | reverse one ++ two == sorted = ("yes", [1, length one])
        | one ++ reverse two == sorted = ("yes", [length one + 1, length one + length two])
        | otherwise = ("no", [])
    decide_on [one, two, three]
        | one ++ reverse two ++ three == sorted = ("yes", [length one + 1, length one + length two])
        | otherwise = ("no", [])
    decide_on _ = ("no", [])

    parts = eliminate_singles $ map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted
    sorted = sort xs
    descending range = range == sortBy (flip compare) range
    equal (a, b) = a == b

    eliminate_singles (a:b:c:rest)
        | length b == 1 = (a++b++c) : eliminate_singles rest
        | length a == 1 = (a++b) : eliminate_singles rest
        | length c == 1 = a : (b++c) : eliminate_singles rest
        | otherwise = a : b : eliminate_singles (c:rest)
    eliminate_singles other = other

process :: State Reader Result
process = do
    n <- parse
    as <- parse
    return $ solve n as

main :: IO ()
main = do
    input <- B.lines <$> B.getContents
    let (answer, range) = evalState process input
    say answer
    say range

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True  = 1

type Reader = [BString]

class Display a => EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int where

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString where

class (Read a, Show a) => Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Integer
instance Display Double

{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE MultiWayIf #-}

module Main where

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Trans.State
import qualified Data.ByteString.Lazy.Char8 as B
import           Data.Function
import           Data.List
import           Data.Maybe
import           System.Environment
import           System.IO

type BString = B.ByteString
type Result = (String, [Int])

solve :: Int -> [Int] -> Result
solve x xs = decide_on parts
    where decide_on [one]
            | one == sorted = ("yes", [1, 1])
            | reverse one == sorted = ("yes", [1, length one])
            | otherwise = ("no", [])

          decide_on [one, two]
            | reverse one ++ two == sorted = ("yes", [1, length one])
            | one ++ reverse two == sorted = ("yes", [length one + 1, length one + length two])
            | otherwise = ("no", [])

          decide_on [one, two, three]
            | one ++ reverse two ++ three == sorted = ("yes", [length one + 1, length one + length two])
            | otherwise = ("no", [])

          decide_on _ = ("no", [])

          parts
            | reverse xs == sorted = [xs]
            | otherwise = map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted

          sorted = sort xs
          descending range = range == sortBy (flip compare) range
          equal (a, b) = a == b

process :: State Reader Result
process = do
    n <- parse
    as <- parse
    return $ solve n as

main :: IO ()
main = do
    args <- getArgs
    input <- if not (null args) && head args == "MINE"
              then B.lines <$> (openFile "input.txt" ReadMode >>= B.hGetContents)
              else B.lines <$> B.getContents
    let (answer, range) = evalState process input
    say answer
    say range

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True  = 1

type Reader = [BString]

class Display a => EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int where

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString where

class (Read a, Show a) => Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Integer
instance Display Double

{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import Control.Applicative
import Control.Monad
import Control.Monad.Trans.State
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Function
import Data.List
import Data.Maybe
import System.Environment
import System.IO

type BString = B.ByteString

type Result = (String, [Int])

solve :: Int -> [Int] -> Result
solve x xs = decide_on parts
  where
    decide_on [one]
        | one == sorted = ("yes", [1, 1])
        | reverse one == sorted = ("yes", [1, length one])
        | otherwise = ("no", [])
    decide_on [one, two]
        | reverse one ++ two == sorted = ("yes", [1, length one])
        | one ++ reverse two == sorted = ("yes", [length one + 1, length one + length two])
        | otherwise = ("no", [])
    decide_on [one, two, three]
        | one ++ reverse two ++ three == sorted = ("yes", [length one + 1, length one + length two])
        | otherwise = ("no", [])
    decide_on _ = ("no", [])

    parts = eliminate_singles $ map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted
    sorted = sort xs
    descending range = range == sortBy (flip compare) range
    equal (a, b) = a == b
    eliminate_singles (a:b:c:rest)
        | length b == 1 = (a ++ b ++ c) : eliminate_singles rest
        | length a == 1 = (a ++ b) : eliminate_singles (c : rest)
        | length c == 1 = a : (b ++ c) : eliminate_singles rest
        | otherwise = a : b : eliminate_singles (c : rest)
    eliminate_singles other = other

process :: State Reader Result
process = do
    n <- parse
    as <- parse
    return $ solve n as

main :: IO ()
main = do
    input <- B.lines <$> B.getContents
    let (answer, range) = evalState process input
    say answer
    say range

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True = 1

type Reader = [BString]

class Display a =>
      EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString

class (Read a, Show a) =>
      Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Integer

instance Display Double

{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE MultiWayIf           #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Trans.State
import qualified Data.ByteString.Lazy.Char8 as B
import           Data.Function
import           Data.List
import           Data.Maybe
import           System.Environment
import           System.IO

type BString = B.ByteString

type Result = (String, [Int])

solve :: [Int] -> Result
solve xs
    | concat [l, reverse m1, m2, r] == sorted = ("yes", (length l +) <$> bounds m1)
    | concat [l, reverse (m1 ++ m2), r] == sorted = ("yes", (length l +) <$> bounds (m1 ++ m2))
    | reverse (concat [l, m1, m2, r]) == sorted = ("yes", bounds xs)
    | otherwise = ("no", [])
  where
    [l, m1, m2, r] = map fst <$> [left, middle1, middle2, right]
    sorted = sort xs
    (left, rest) = break (uncurry (/=)) $ zip xs sorted
    (middle1, rest') = break (uncurry (==)) rest
    (middle2, right) = break (uncurry (/=)) rest'
    bounds range = if null range then [0, 0] else [1, length range]

process = do
    parse :: State Reader BString
    as <- parse
    return $ solve as

main :: IO ()
main = do
    input <- B.lines <$> B.getContents
    let (answer, range) = evalState process input
    say answer
    say range
--    say $ evalState process input

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True  = 1

type Reader = [BString]

class Display a => EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString

class (Read a, Show a) => Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Integer

instance Display Double

{-# LANGUAGE FlexibleContexts     #-}
{-# LANGUAGE FlexibleInstances    #-}
{-# LANGUAGE MultiWayIf           #-}
{-# LANGUAGE OverlappingInstances #-}

module Main where

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Trans.State
import qualified Data.ByteString.Lazy.Char8 as B
import           Data.Function
import           Data.List
import           Data.Maybe
import           System.Environment
import           System.IO

type BString = B.ByteString
type Result = (String, [Int])

solve :: Int -> [Int] -> Result
solve x xs = decide_on parts
  where
    decide_on [one]
        | one == sorted = ("yes", [1, 1])
        | reverse one == sorted = ("yes", [1, length one])
        | otherwise = ("no", [])
    decide_on [one, two]
        | reverse one ++ two == sorted = ("yes", [1, length one])
        | one ++ reverse two == sorted = ("yes", [length one + 1, length one + length two])
        | otherwise = ("no", [])
    decide_on ps@[one, two, three]
        | one ++ reverse two ++ three == sorted = ("yes", [length one + 1, length one + length two])
        | reverse (concat ps) == sorted = ("yes", [1, length (concat ps)])
        | otherwise = ("no", [])
    decide_on _ = ("no", [])

    parts = map (map fst) $ groupBy ((==) `on` equal) $ zip xs sorted
    sorted = sort xs
    descending range = range == sortBy (flip compare) range
    equal (a, b) = a == b

process :: State Reader Result
process = do
    n <- parse
    as <- parse
    return $ solve n as

main :: IO ()
main = do
    input <- B.lines <$> B.getContents
    let (answer, range) = evalState process input
    say answer
    say range

say :: Display a => a -> IO ()
say = putStrLn . display

toNum :: Num a => Bool -> a
toNum False = 0
toNum True  = 1

type Reader = [BString]

class Display a => EIO a where
    parse :: State Reader a
    parse = state $ \(line:rest) -> (scan line, rest)

instance EIO Int where

instance EIO [Int] where
    parse = state $ \(line:rest) -> (map scan . B.words $ line, rest)

instance EIO BString where

class (Read a, Show a) => Display a where
    display :: a -> String
    scan :: BString -> a
    display = show
    scan = read . B.unpack

instance Display String where
    display = id

instance Display BString where
    display = B.unpack
    scan = id

instance Display [a] => Display [[a]] where
    display = unlines . map display

instance Display a => Display [a] where
    display = unwords . map display

instance Display Int where
    scan = fst . fromJust . B.readInt

instance Display Integer
instance Display Double

import Data.List (sort)

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

solve :: [Int] -> String
solve as | length is < 2 = "no"
         | take (imin - 1) as ++ reverse (drop (imin - 1) (take imax as)) ++ drop imax as == sort as = unlines [ "yes", unwords (map show [ imin, imax ]) ]
         | otherwise = "no"
  where is = [ i | (i, a) <- zip [1..] as, a /= i ]
        imin = head is; imax = last is

import Data.List (sort)

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

solve :: [Int] -> String
solve as | null is = unlines [ "yes", "1 1" ]
         | take (imin - 1) as ++ reverse (drop (imin - 1) (take imax as)) ++ drop imax as == sort as = unlines [ "yes", unwords (map show [ imin, imax ]) ]
         | otherwise = "no"
  where is = [ i | (i, a) <- zip [1..] as, a /= i ]
        imin = head is; imax = last is

import Data.List (sort)

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

solve :: [Int] -> String
solve as | null is = "no"
         | take (imin - 1) as ++ reverse (drop (imin - 1) (take imax as)) ++ drop imax as == sort as = unlines [ "yes", unwords (map show [ imin, imax ]) ]
         | otherwise = "no"
  where is = [ i | (i, a) <- zip [1..] as, a /= i ]
        imin = head is; imax = last is


A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≤ k1 < k2 < ... < k|x| ≤ |s|).You've got two strings — s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at least one of these subsequences? In other words, is it true that for all i (1 ≤ i ≤ |s|), there is such subsequence x = sk1sk2... sk|x| of string s, that x = t and for some j (1 ≤ j ≤ |x|) kj = i.

The first line contains string s, the second line contains string t. Each line consists only of lowercase English letters. The given strings are non-empty, the length of each string does not exceed 2·105.

Print "Yes" (without the quotes), if each character of the string s occurs in at least one of the described subsequences, or "No" (without the quotes) otherwise.

NoteIn the first sample string t can occur in the string s as a subsequence in three ways: abab, abab and abab. In these occurrences each character of string s occurs at least once.In the second sample the 4-th character of the string s doesn't occur in any occurrence of string t.In the third sample there is no occurrence of string t in string s.

import Data.Map as Map
import Debug.Trace
match [] y i = []
match x [] i = []
match (x:sx) (y:sy) i
    | x == y = i:match sx sy (i+1)
    | otherwise = match sx (y:sy) (i+1)
check2 :: String -> String -> Int -> Int -> Map Char Int -> Map Int Int -> Bool
-- check2 a b c d e f | trace (show a++" "++show b++" "++show c++" "++show d++" "++show e++" "++show f) False = undefined
check2 [] y i j pos m = True
check2 (x:sx) y i j pos m
    | Prelude.null y || x /= head y = check1 && check2 sx y i (j-1) pos m
    | otherwise = check2 sx (tail y) (i-1) (j-1) (insert x i pos) m
    where check1 = x `member` pos && (findWithDefault 0 (findWithDefault 0 x pos :: Int) m) <= j
solve s1 s2
    | length m < length s2 = "No"
    | otherwise = if check2 (reverse s1) (reverse s2) (length s2 - 1) (length s1 - 1) empty (fromList (zip [0,1..] m))
                    then "Yes"
                    else "No"
    where m = match s1 s2 0
main = do
    str1 <- getLine
    str2 <- getLine
    putStrLn (solve str1 str2)


Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to ai inclusive. No tickets are sold at the last station.Let ρi, j be the minimum number of tickets one needs to buy in order to get from stations i to station j. As Vasya is fond of different useless statistic he asks you to compute the sum of all values ρi, j among all pairs 1 ≤ i < j ≤ n.

The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the number of stations. The second line contains n - 1 integer ai (i + 1 ≤ ai ≤ n), the i-th of them means that at the i-th station one may buy tickets to each station from i + 1 to ai inclusive.

Print the sum of ρi, j among all pairs of 1 ≤ i < j ≤ n.

NoteIn the first sample it's possible to get from any station to any other (with greater index) using only one ticket. The total number of pairs is 6, so the answer is also 6.Consider the second sample:   ρ1, 2 = 1  ρ1, 3 = 2  ρ1, 4 = 3  ρ1, 5 = 3  ρ2, 3 = 1  ρ2, 4 = 2  ρ2, 5 = 2  ρ3, 4 = 1  ρ3, 5 = 1  ρ4, 5 = 1 Thus the answer equals 1 + 2 + 3 + 3 + 1 + 2 + 2 + 1 + 1 + 1 = 17.

import Data.List

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

data SegmentTree = Empty
                 | Node { lchild :: SegmentTree, rchild :: SegmentTree,
                          left :: Int, right :: Int,
                          maxVal :: (Int, Integer, Int) }

build :: Int -> SegmentTree
build = build' 1
    where build' :: Int -> Int -> SegmentTree
          build' l r | l == r = Node Empty Empty l r (-1, 0, 0)
                     | otherwise = let mid = div (l + r) 2
                                       lc = build' l mid
                                       rc = build' (mid + 1) r
                                   in Node lc rc l r (-1, 0, 0)

update :: Int -> (Int, Integer, Int) -> SegmentTree -> SegmentTree
update pos val = update'
    where update' :: SegmentTree -> SegmentTree
          update' (Node lc rc l r v) | l == r = Node lc rc l r (max v val)
                                     | pos <= div (l + r) 2 = Node (update' lc) rc l r (max v val)
                                     | otherwise = Node lc (update' rc) l r (max v val)

query :: Int -> Int -> SegmentTree -> (Int, Integer, Int)
query ql qr (Node lc rc l r v) | ql == l && qr == r = v
                               | qr <= div (l + r) 2 = query ql qr lc
                               | div (l + r) 2 < ql = query ql qr rc
                               | otherwise = let mid = div (l + r) 2
                                             in max (query ql mid lc) (query (mid + 1) qr rc)

solve :: [Int] -> Integer
solve (n:a) = solve' (n - 1) (reverse a) 0 (update n (n, 0, n) (build n))
    where solve' :: Int -> [Int] -> Integer -> SegmentTree -> Integer
          solve' _ [] s _ = s
          solve' i (a:ax) s t = let (_, d, m) = query (i + 1) a t
                                    val = d - (fromIntegral ((a - m) - n + i))
                                    nt = update i (a, val, i) t
                                    ns = s + val
                                in solve' (i - 1) ax ns nt

import Data.List

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

data SegmentTree = Empty
                 | Node { lchild :: SegmentTree, rchild :: SegmentTree,
                          left :: Int, right :: Int,
                          maxVal :: (Int, Int, Int) }

build :: Int -> SegmentTree
build = build' 1
    where build' :: Int -> Int -> SegmentTree
          build' l r | l == r = Node Empty Empty l r (-1, 0, 0)
                     | otherwise = let mid = div (l + r) 2
                                       lc = build' l mid
                                       rc = build' (mid + 1) r
                                   in Node lc rc l r (-1, 0, 0)

update :: Int -> (Int, Int, Int) -> SegmentTree -> SegmentTree
update pos val = update'
    where update' :: SegmentTree -> SegmentTree
          update' (Node lc rc l r v) | l == r = Node lc rc l r (max v val)
                                     | pos <= div (l + r) 2 = Node (update' lc) rc l r (max v val)
                                     | otherwise = Node lc (update' rc) l r (max v val)

query :: Int -> Int -> SegmentTree -> (Int, Int, Int)
query ql qr (Node lc rc l r v) | ql == l && qr == r = v
                               | qr <= div (l + r) 2 = query ql qr lc
                               | div (l + r) 2 < ql = query ql qr rc
                               | otherwise = let mid = div (l + r) 2
                                             in max (query ql mid lc) (query (mid + 1) qr rc)

solve :: [Int] -> Integer
solve (n:a) = solve' (n - 1) (reverse a) 0 (update n (n, 0, n) (build n))
    where solve' :: Int -> [Int] -> Integer -> SegmentTree -> Integer
          solve' _ [] s _ = s
          solve' i (a:ax) s t = let (_, d, m) = query (i + 1) a t
                                    val = d - (a - m) + n - i
                                    nt = update i (a, val, i) t
                                    ns = s + fromIntegral val
                                in solve' (i - 1) ax ns nt


Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?Jeff must make the number without leading zero. At that, we assume that number 0 doesn't contain any leading zeroes. Jeff doesn't have to use all the cards.

The first line contains integer n (1 ≤ n ≤ 103). The next line contains n integers a1, a2, ..., an (ai = 0 or ai = 5). Number ai represents the digit that is written on the i-th card.

In a single line print the answer to the problem — the maximum number, divisible by 90. If you can't make any divisible by 90 number from the cards, print -1.

NoteIn the first test you can make only one number that is a multiple of 90 — 0.In the second test you can make number 5555555550, it is a multiple of 90.

papa nine zero
  | zero == 0 = [-1]
  | nine == 0 = [0]
  | otherwise = replicate nine 5 ++ replicate zero 0

solve x =
  papa nine_cnt zero
  where nine = length $ filter (=="5") x
        zero = length $ filter (=="0") x
        nine_cnt = 9 * (nine `div` 9)

main = do
  getLine
  xs <- getLine
  mapM_ (putStr.show) $ solve $ words xs

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

papa nine zero
  | zero == 0 = [-1]
  | nine == 0 = [0]
  | otherwise = replicate nine 5 ++ replicate zero 0

solve x =
  papa nine_cnt zero
  where nine = length $ filter (==5) x
        zero = length $ filter (==0) x
        nine_cnt = 9 * (nine `div` 9)

main = do
  getLine
  xs <- map (fromJust . fmap fst . B.readInt) . B.words <$> B.getLine
  mapM_ (putStr.show) $ solve xs

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

main = do
     n <- read <$> getLine :: IO Int
     cards <- sort <$> (words <$> getLine) :: IO [String]
     putStrLn (solve n cards)
     return ()

solve n cards = if n0 == 0 then "-1"
                           else (replicate n5 '5') ++ (replicate n0 '0')
      where n5 = (length (filter (\s -> s=="5") cards))`div`9*9
            n0 = if n5==0 then min 1 (length (filter (\s -> s=="0") cards))
                          else length (filter (\s -> s=="0") cards)

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

solve :: [Int] -> String
solve a =
    let num5 = length $ filter (== 5) a
        num0 = length $ filter (== 0) a
        rnum5 = num5 - (mod num5 9)
    in  if num0 == 0 then "-1" else (if rnum5 == 0 then "0" else (construct rnum5 num0))

construct :: Int -> Int -> String
construct 0    0    = ""
construct 0    num0 = '0' : (construct 0 (num0 - 1))
construct num5 num0 = '5' : (construct (num5 - 1) num0)

import Control.Monad
import Control.Applicative

import Data.List
import Data.Char
main = do
    n <- readLn
    l <- take n . map read . words <$> getLine
    let (zeros,fives) = partition (==0) l
    let k = length fives `div` 9 * 9
    let ans = take k fives ++ zeros
    if null zeros then
        print (-1)
    else if k == 0 then
        print 0
    else
        putStrLn $ map intToDigit ans

import Control.Monad (liftM)
import Prelude hiding (reads)

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

solve :: [Int] -> String
solve as
  | zero == 0  =  "-1"
  | five < 9  =  "0"
  | otherwise  =  replicate (five - five `mod` 9) '5' ++ replicate zero '0'
  where
    five  =  length $ filter (== 5) as
    zero  =  length $ filter (== 0) as

main :: IO ()
main  =  do
    getLine
    as  <-  reads
    putStrLn $ solve as

module Main where
import Control.Applicative
main :: IO ()
main = do
  _ <- getLine
  nums <- map read . words <$> getLine :: IO [Int]
  let (zeros,fives) = foldl (\(z,f) x -> case x of
                                           0 -> (z+1,f)
                                           5 -> (z,f+1))
                            (0,0)
                            nums
      possNumFives = filter (isDiv9 . (5*)) [fives,fives-1..0]
      numba:_ = map (getNumber 0) possNumFives
  if zeros == 0
    then print (-1)
    else print $ numba * 10^zeros

getNumber acc 0 = acc
getNumber acc n = getNumber (10*acc+5) (n-1)

sumd2 0 acc = acc
sumd2 x acc = sumd2 (x `div` 10) (acc + (x `mod` 10))

isDiv9 :: Integral a => a -> Bool
isDiv9 x
  | x <= 9 = x `elem` [0,9]
  | otherwise = isDiv9 $ sumd2 x 0

import Data.List
import Data.Maybe

solve :: [Int] -> String
solve xs =
  if isJust $ find (==0) xs
  then
    case result of
      []  -> "-1"
      0:_ -> "0"
      _   -> concatMap show result
  else
    "-1"
  where ys = reverse $ sort xs
        s = sum xs
        n = length $ takeWhile (\x -> x `mod` 9 /= 0) $ scanl (-) s ys
        (_, result) = splitAt n ys

f = solve . map read . tail . words
main = interact f

main=getContents>>=putStrLn.s.map read.words
s(_:a)|z<1="-1"|f<9="0"|1>0=replicate(f-f`mod`9)'5'++replicate z '0' where f=length(filter(==5)a);z=length(filter(==0)a)

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

solve :: [Int] -> String
solve as | zero < 1 = "-1"
         | five < 9 = "0"
         | otherwise = replicate (five - five `mod` 9) '5' ++ replicate zero '0'
  where five = length (filter (==5) as)
        zero = length (filter (==0) as)

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

solve :: [Int] -> String
solve (_:as) | zero < 1 = "-1"
             | five < 9 = "0"
             | otherwise = replicate (9 * (five `div` 9)) '5' ++ replicate zero '0'
  where five = length (filter (==5) as)
        zero = length (filter (==0) as)
solve _ = undefined

import Data.List
main = interact $ solve . map head . tail . words
solve as | null res = "-1"
         | all (== '0') res = "0"
         | null zs = "-1"
         | otherwise = res where
  (fs,zs) = partition (== '5') as
  nf = length fs
  res = replicate (nf `div` 9 * 9) '5' ++ zs

import Data.List
main = getContents >>= putStrLn . solve . group . sort . map head . tail . words

solve [as] = if head as == '0' then "0" else "-1"
solve [zeros, fives] = replicate (9 * (length fives `div` 9)) '5' ++
                       if 9 <= length fives then zeros else "0"

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

solve :: [Int] -> String
solve xs
	| zeroes == 0 = "-1"
	| fives < 9 = "0"
	| otherwise = replicate (9 * countFives) '5' ++ replicate zeroes '0'
	where fives = length $ filter (== 5) xs
	      zeroes = length xs - fives;
	      countFives = fives `div` 9;

main :: IO ()
main = do
	B.getLine
	xs <- getIntList
	putStrLn $ solve xs

getInt :: IO Int
getInt = readInt `fmap` B.getLine

getIntList :: IO [Int]
getIntList = readIntList `fmap` B.getLine

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

readIntList :: C.ByteString -> [Int]
readIntList = map readInt . C.words

import Control.Applicative
import Data.List

main= do
	getLine
	s<-  getLine
	let c5 = length $ filter (=='5') s
	let c0 = length $ filter (=='0') s
        putStrLn $ if c0==0 then "-1" else if c5<9 then "0" else (replicate (c5-(mod c5 9)) '5' )++ (replicate c0 '0')

solve xs
    |nFives < 9 = if (foldl (\x y -> if x == True then x else y == "0") False xs) == True then "0" else "-1"
    |nZeros == 0 = "-1"
    |otherwise = (replicate remain '5') ++ ( ['0'|x<-xs,x=="0"])
    where nFives = length $ filter (=="5") xs
          nZeros = length xs - nFives
          remain = (nFives `div`9) * 9

main = interact $ solve . tail . words

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

main = do
     n <- read <$> getLine :: IO Int
     cards <- sort <$> (words <$> getLine) :: IO [String]
     putStrLn (solve n cards)
     return ()

solve n cards = if n0 == 0 then "-1"
                           else (replicate n5 '5') ++ (replicate n0 '0')
      where n5 = (length (filter (\s -> s=="5") cards))`div`9*9
            n0 = if n5==0 then 1 else length (filter (\s -> s=="0") cards)

import Control.Monad
import Control.Applicative

import Data.List
import Data.Char
main = do
    n <- readLn
    l <- take n . map read . words <$> getLine
    let (zeros,fives) = partition (==0) l
    let k = length fives `div` 9 * 9
    let ans = take k fives ++ zeros
    if k == 0 && null zeros then
        print (-1)
    else if k == 0 then
        print 0
    else
        putStrLn $ map intToDigit ans

import Control.Monad
import Control.Applicative

import Data.List
import Data.Char
main = do
    n <- readLn
    l <- take n . map read . words <$> getLine
    let (zeros,fives) = partition (==0) l
    let k = length fives `div` 9 * 9
    let ans = if k == 0 then [0] else take k fives ++ zeros
    putStrLn $ map intToDigit ans

module Main where
import Control.Applicative
main :: IO ()
main = do
  _ <- getLine
  nums <- map read . words <$> getLine :: IO [Int]
  let (zeros,fives) = foldl (\(z,f) x -> case x of
                                           0 -> (z+1,f)
                                           5 -> (z,f+1))
                            (0,0)
                            nums
      possNumFives = filter (isDiv9 . (5*)) [fives,fives-1..0]
      numba:_ = map (getNumber 0) possNumFives
  print $ numba * 10^zeros

getNumber acc 0 = acc
getNumber acc n = getNumber (10*acc+5) (n-1)

sumd2 0 acc = acc
sumd2 x acc = sumd2 (x `div` 10) (acc + (x `mod` 10))

isDiv9 :: Integral a => a -> Bool
isDiv9 x
  | x <= 9 = x `elem` [0,9]
  | otherwise = isDiv9 $ sumd2 x 0

import Data.List
main = interact $ solve . map head . tail . words
solve as | (null zs || null (tail zs)) && fives == 0 = "-1"
         | fives == 0 = "0"
         | otherwise = replicate fives '5' ++ zs where
  (fs,zs) = partition (== '5') as
  nf = length fs
  fives = nf `div` 9 * 9

import Data.List
main = interact $ solve . map head . tail . words
solve as | null zs && fives == 0 = "-1"
         | fives == 0 = "0"
         | otherwise = replicate fives '5' ++ zs where
  (fs,zs) = partition (== '5') as
  nf = length fs
  fives = nf `div` 9 * 9

import Data.List
main = interact $ solve . map head . tail . words
solve as | null (drop 1 zs) && fives == 0 && not (null zs) = "-1"
         | fives == 0 = "0"
         | otherwise = replicate fives '5' ++ zs where
  (fs,zs) = partition (== '5') as
  nf = length fs
  fives = nf `div` 9 * 9

import Data.List
main = interact $ solve . map head . tail . words
solve as = replicate fives '5' ++ zs where
  (fs,zs) = partition (== '5') as
  nf = length fs
  fives = nf `div` 9

import Data.List
main = interact $ solve . map head . tail . words
solve as | fives == 0 = "0"
         | otherwise = replicate fives '5' ++ zs where
  (fs,zs) = partition (== '5') as
  nf = length fs
  fives = nf `div` 9 * 9

import Data.List
main = interact $ solve . map head . tail . words
solve as | null (drop 1 zs) && fives == 0 = "-1"
         | fives == 0 = "0"
         | otherwise = replicate fives '5' ++ zs where
  (fs,zs) = partition (== '5') as
  nf = length fs
  fives = nf `div` 9 * 9

import Data.List
main = getContents >>= putStrLn . solve . group . sort . map head . tail . words

solve [zeros] = "0"
solve [zeros, fives] = replicate (9 * (length fives `div` 9)) '5' ++
                       if 9 <= length fives then zeros else "0"

import Data.List
main = getContents >>= putStrLn . solve . group . sort . map head . tail . words

solve [as] = if head as == '0' then "0"
             else if 9 <= length as then replicate (9 * (length as `div` 9)) '5'
                  else "-1"
solve [zeros, fives] = replicate (9 * (length fives `div` 9)) '5' ++
                       if 9 <= length fives then zeros else "0"

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

solve :: [Int] -> String
solve xs
	| zeroes == 0 = "-1"
	| fives < 9 = "0"
	| otherwise = replicate (9 * fives `div` 9) '5' ++ replicate zeroes '0'
	where fives = length $ filter (== 5) xs
	      zeroes = length xs - fives;

main :: IO ()
main = do
	B.getLine
	xs <- getIntList
	putStrLn $ solve xs

getInt :: IO Int
getInt = readInt `fmap` B.getLine

getIntList :: IO [Int]
getIntList = readIntList `fmap` B.getLine

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

readIntList :: C.ByteString -> [Int]
readIntList = map readInt . C.words

solve xs
    |nFives < 9 = if (foldl (\x y -> if x == True then x else y == "0") False xs) == True then "0" else "-1"
    |otherwise = (replicate remain '5') ++ ( ['0'|x<-xs,x=="0"])
    where nFives = length $ filter (=="5") xs
          remain = (nFives `div`9) * 9

main = interact $ solve . tail . words

solve xs
    |nFives < 9 = if (foldl (\x y -> if x == True then x else y == "0") False xs) == True then "0" else "-1"
    |otherwise = (replicate remain '5') ++ (unlines [x|x<-xs,x=="0"])
    where nFives = length $ filter (=="5") xs
          remain = (nFives `div`9) * 9

main = interact $ solve . tail . words