You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1 to |s| / p (inclusive) the following condition was fulfilled sp = sp × i. If the answer is positive, find one way to rearrange the characters.

The only line contains the initial string s, consisting of small Latin letters (1 ≤ |s| ≤ 1000).

If it is possible to rearrange the characters in the string so that the above-mentioned conditions were fulfilled, then print in the first line "YES" (without the quotes) and print on the second line one of the possible resulting strings. If such permutation is impossible to perform, then print the single string "NO".

NoteIn the first sample any of the six possible strings will do: "abc", "acb", "bac", "bca", "cab" or "cba".In the second sample no letter permutation will satisfy the condition at p = 2 (s2 = s4).In the third test any string where character "y" doesn't occupy positions 2, 3, 4, 6 will be valid.

import Data.List
import Debug.Trace

rsort = sortBy (flip compare)

counts :: String -> [(Int,Char)]
counts s = map (\g -> (length g, head g)) $ group $ sort s

-- number of primes s.t. p <= n < 2*p

isPrime 2 = True
isPrime n =  all (\a -> n `mod` a /= 0)  (takeWhile ltsqrt [2..])
  where ltsqrt x = x*x <= n

largePrimes n = [ p | p <- [1 + div n 2..n], isPrime p ]

solve :: String -> Maybe String
solve str =
  let n = length str
      cnts = rsort $ counts str
      most = fst $ head cnts
      largeps = largePrimes n
  in if most >= n - length largeps -1
       then Just $ solve' cnts largeps n
       else Nothing

solve' :: [(Int,Char)] -> [Int] -> Int -> String
solve' ((_,ch):cnts) primes n = go rest (1:primes) 1
  where
    rest = concatMap (\(k,c) -> replicate k c) cnts
    go _ _ i | i > n = []
    go xs ps i
      | null ps || i /= head ps = ch : go xs ps (i+1)
      | null xs                 = ch : go [] ps (i+1)
      | otherwise               = (head xs) : go (tail xs) (tail ps) (i+1)

main = do
  str <- getLine
  case solve str of
    Nothing  -> putStrLn "NO"
    Just ans -> do putStrLn "YES"; putStrLn ans


Vasya decided to go to the grocery store. He found in his wallet $$$a$$$ coins of $$$1$$$ burle and $$$b$$$ coins of $$$2$$$ burles. He does not yet know the total cost of all goods, so help him find out $$$s$$$ ($$$s > 0$$$): the minimum positive integer amount of money he cannot pay without change or pay at all using only his coins.For example, if $$$a=1$$$ and $$$b=1$$$ (he has one $$$1$$$-burle coin and one $$$2$$$-burle coin), then:  he can pay $$$1$$$ burle without change, paying with one $$$1$$$-burle coin,  he can pay $$$2$$$ burle without change, paying with one $$$2$$$-burle coin,  he can pay $$$3$$$ burle without change by paying with one $$$1$$$-burle coin and one $$$2$$$-burle coin,  he cannot pay $$$4$$$ burle without change (moreover, he cannot pay this amount at all). So for $$$a=1$$$ and $$$b=1$$$ the answer is $$$s=4$$$.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases in the test. The description of each test case consists of one line containing two integers $$$a_i$$$ and $$$b_i$$$ ($$$0 \le a_i, b_i \le 10^8$$$) — the number of $$$1$$$-burle coins and $$$2$$$-burles coins Vasya has respectively.

For each test case, on a separate line print one integer $$$s$$$ ($$$s > 0$$$): the minimum positive integer amount of money that Vasya cannot pay without change or pay at all.

Note  The first test case of the example is clarified into the main part of the statement.  In the second test case, Vasya has only $$$1$$$ burle coins, and he can collect either any amount from $$$1$$$ to $$$4$$$, but $$$5$$$ can't.  In the second test case, Vasya has only $$$2$$$ burle coins, and he cannot pay $$$1$$$ burle without change.  In the fourth test case you don't have any coins, and he can't even pay $$$1$$$ burle.

module Main where

import           Control.Monad

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

solvet :: IO ()
solvet = do
  input <- getLine
  let [n, m] = map read (words input)
  let res = if n == 0 then 0 else m * 2 + n
  print (res + 1)

import Control.Arrow ((>>>))
import Control.Monad (replicateM_)

main =
    interact $
        lines
            >>> drop 1
            >>> map words
            >>> map (map read)
            >>> map (\[a, b] -> if a == 0 then 1 else b * 2 + a + 1)
            >>> map show
            >>> unlines

module Main where

import           Control.Monad

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

solvet :: IO ()
solvet = do
  input <- getLine
  let [n, m] = map read (words input)
  let res = if n == 0 then m * 2 - 1 else m * 2 + n
  print res


Alice and Bob are playing a game. They start with a positive integer $$$n$$$ and take alternating turns doing operations on it. Each turn a player can subtract from $$$n$$$ one of its divisors that isn't $$$1$$$ or $$$n$$$. The player who cannot make a move on his/her turn loses. Alice always moves first.Note that they subtract a divisor of the current number in each turn.You are asked to find out who will win the game if both players play optimally.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^9$$$) — the initial number.

For each test case output "Alice" if Alice will win the game or "Bob" if Bob will win, if both players play optimally.

NoteIn the first test case, the game ends immediately because Alice cannot make a move.In the second test case, Alice can subtract $$$2$$$ making $$$n = 2$$$, then Bob cannot make a move so Alice wins.In the third test case, Alice can subtract $$$3$$$ so that $$$n = 9$$$. Bob's only move is to subtract $$$3$$$ and make $$$n = 6$$$. Now, Alice can subtract $$$3$$$ again and $$$n = 3$$$. Then Bob cannot make a move, so Alice wins.

import Control.Monad
import Data.Bits
import Data.Maybe
import Data.Array
import qualified Data.ByteString.Char8 as C
import qualified Data.IntSet as IS
import Data.ByteString.Builder
import System.IO

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

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

kMaxN :: Int
kMaxN = 200

sg :: Array Int Int
sg = listArray (1, kMaxN) [f i | i <- [1..kMaxN]]
  where f n = head $ filter (flip IS.notMember st) [0..]
          where st = IS.fromList [sg ! (n - i) | i <- [2..n-1], n `mod` i == 0]

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    let
      result
        | popCount n == 1 && odd (countTrailingZeros n) = False
        | odd n = False
        | otherwise = True
    return $ string7 (if result then "Alice" else "Bob") `mappend` charUtf8 '\n'
  hPutBuilder stdout output

{-# LANGUAGE FlexibleContexts #-}
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.IO
import Data.Array.Unboxed
import Data.Bits
import Data.Bool
import Data.Char
import Data.Int
import Data.List
import Data.Maybe
import Data.Ord
import Data.Ratio
import qualified Data.Set as Set
import qualified Data.Sequence as Seq
import System.IO
import System.IO.Unsafe

(><) a b = a Seq.>< b

deb s e = unsafePerformIO $ do
    hPutStrLn stderr s
    return e

parseInt = fst . fromJust . BS.readInt
parseInteger = fst . fromJust . BS.readInteger

main = do
    let pingo = Set.fromList ([2 ^ j | j <- [1..30], odd j]::[Int])
    tn <- parseInt <$> BS.getLine
    replicateM_ tn $ do
        n <- parseInt <$> BS.getLine
        let r = odd n || n `Set.member` pingo
        putStrLn $ if r then "Bob" else "Alice"


You've got a undirected graph G, consisting of n nodes. We will consider the nodes of the graph indexed by integers from 1 to n. We know that each node of graph G is connected by edges with at least k other nodes of this graph. Your task is to find in the given graph a simple cycle of length of at least k + 1.A simple cycle of length d (d > 1) in graph G is a sequence of distinct graph nodes v1, v2, ..., vd such, that nodes v1 and vd are connected by an edge of the graph, also for any integer i (1 ≤ i < d) nodes vi and vi + 1 are connected by an edge of the graph.

The first line contains three integers n, m, k (3 ≤ n, m ≤ 105; 2 ≤ k ≤ n - 1) — the number of the nodes of the graph, the number of the graph's edges and the lower limit on the degree of the graph node. Next m lines contain pairs of integers. The i-th line contains integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — the indexes of the graph nodes that are connected by the i-th edge.  It is guaranteed that the given graph doesn't contain any multiple edges or self-loops. It is guaranteed that each node of the graph is connected by the edges with at least k other nodes of the graph.

In the first line print integer r (r ≥ k + 1) — the length of the found cycle. In the next line print r distinct integers v1, v2, ..., vr (1 ≤ vi ≤ n) — the found simple cycle. It is guaranteed that the answer exists. If there are multiple correct answers, you are allowed to print any of them.

import Data.Array
import Data.List
import Data.Maybe
import Data.Ord
import qualified Data.IntMap as M
import qualified Data.ByteString.Char8 as C

pairs :: [a] -> [(a, a)]
pairs (x:y:z) = (x, y): (y, x): pairs z
pairs _ = []

main :: IO ()
main = do
  (n:_:_:el) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents
  let e = accumArray (flip (:)) [] (1, n) $ pairs el
      gao v d p =
        case filter (`M.notMember` d) $ e!v of
          (w:_) -> gao w (M.insert w (M.size d) d) (w:p)
          _     -> let w = minimumBy (comparing (d M.!)) $ e!v in w: takeWhile (/=w) p
      ans = gao 1 (M.singleton 1 0) [1]
  print $ length ans
  putStrLn $ unwords $ map show ans

{-# OPTIONS_GHC -O2 -optc-Ofast -ignore-asserts #-}
import Data.Maybe
import Data.Array
import Control.Monad
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.List as L
import qualified Data.ByteString.Char8 as B

-- link edges
type Vertex = Int
pairs :: [Int] -> [(Int, Vertex)]
pairs (x : y : xs) = (x , y) : (y , x) : pairs xs
pairs _ = []

edges :: Int -> [Int] -> Array Int [Vertex]
edges n = accumArray (flip (:)) [] (1, n) . pairs   -- from 1 to n, may be different
-- end here

findPath :: Vertex -> (Array Int [Vertex]) -> (M.Map Vertex Int) -> [Vertex]
findPath u e m
    | null adj  =
        let     path = map snd . L.sort . map (\(a,b) -> (b, a)) . M.assocs $ m
                s    = S.fromList (e ! u)
        in      dropWhile (\v -> S.notMember v s) $ path

    | otherwise =
        let     v = head adj
        in      findPath v e (M.insert v (M.size m) m)
    where
        adj = filter (\v -> M.notMember v m) $ (e ! u)

main = do
    (n : _ : _ : e') <- liftM (map (fst . fromJust . B.readInt) . B.words) $ B.getContents
    let
        e = edges n e'
        ans = findPath 1 e (M.singleton 1 0)
    putStrLn . show . length $ ans
    putStrLn . L.intercalate " " . map show $ ans


Ayoub thinks that he is a very smart person, so he created a function $$$f(s)$$$, where $$$s$$$ is a binary string (a string which contains only symbols "0" and "1"). The function $$$f(s)$$$ is equal to the number of substrings in the string $$$s$$$ that contains at least one symbol, that is equal to "1".More formally, $$$f(s)$$$ is equal to the number of pairs of integers $$$(l, r)$$$, such that $$$1 \leq l \leq r \leq |s|$$$ (where $$$|s|$$$ is equal to the length of string $$$s$$$), such that at least one of the symbols $$$s_l, s_{l+1}, \ldots, s_r$$$ is equal to "1". For example, if $$$s = $$$"01010" then $$$f(s) = 12$$$, because there are $$$12$$$ such pairs $$$(l, r)$$$: $$$(1, 2), (1, 3), (1, 4), (1, 5), (2, 2), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 4), (4, 5)$$$.Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers $$$n$$$ and $$$m$$$ and asked him this problem. For all binary strings $$$s$$$ of length $$$n$$$ which contains exactly $$$m$$$ symbols equal to "1", find the maximum value of $$$f(s)$$$.Mahmoud couldn't solve the problem so he asked you for help. Can you help him?

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^5$$$)  — the number of test cases. The description of the test cases follows. The only line for each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n \leq 10^{9}$$$, $$$0 \leq m \leq n$$$) — the length of the string and the number of symbols equal to "1" in it.

For every test case print one integer number — the maximum value of $$$f(s)$$$ over all strings $$$s$$$ of length $$$n$$$, which has exactly $$$m$$$ symbols, equal to "1".

NoteIn the first test case, there exists only $$$3$$$ strings of length $$$3$$$, which has exactly $$$1$$$ symbol, equal to "1". These strings are: $$$s_1 = $$$"100", $$$s_2 = $$$"010", $$$s_3 = $$$"001". The values of $$$f$$$ for them are: $$$f(s_1) = 3, f(s_2) = 4, f(s_3) = 3$$$, so the maximum value is $$$4$$$ and the answer is $$$4$$$.In the second test case, the string $$$s$$$ with the maximum value is "101".In the third test case, the string $$$s$$$ with the maximum value is "111".In the fourth test case, the only string $$$s$$$ of length $$$4$$$, which has exactly $$$0$$$ symbols, equal to "1" is "0000" and the value of $$$f$$$ for that string is $$$0$$$, so the answer is $$$0$$$.In the fifth test case, the string $$$s$$$ with the maximum value is "01010" and it is described as an example in the problem statement.

import Control.Monad
import Prelude

main = do
    testCases <- getLine
    strNums <- replicateM (read testCases) testCase
    return ()

testCase = do
    line <- getLine
    print $ solution (map read (words line))

solution :: [Integer] -> Integer
solution [len, ones] = result where
    zeros = len - ones
    countSequences n = div (n * (n+1)) 2
    bags = ones + 1
    smallBagSize = div zeros bags
    bigBagSize = smallBagSize + 1
    bigBagsCount = zeros - (bags * smallBagSize)
    smallBagsCount = bags - bigBagsCount
    r1 = bigBagsCount * (countSequences bigBagSize)
    r2 = smallBagsCount * (countSequences smallBagSize)
    result = countSequences (ones + zeros) - (r1 + r2)

subStringCount :: Integer -> Integer
subStringCount l = div (l*(l+1)) 2

solve :: Integer -> Integer -> Integer
solve n m = allSubstrings - groups*(subStringCount lengthOfEach) - (mod numberOfZeros groups)*(lengthOfEach+1)
  where allSubstrings = div (n*(n+1)) 2
        numberOfZeros = n-m
        groups = m+1
        lengthOfEach = div numberOfZeros groups

parse :: String -> String
parse line = show $ solve n m
  where [n, m] = map (\x -> read x :: Integer) $ words line

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

import Control.Monad
import Prelude

main = do
    testCases <- getLine
    strNums <- replicateM (read testCases) testCase
    return ()

testCase = do
    line <- getLine
    print $ solution (map read (words line))

solution :: [Int] -> Int
solution [len, ones] = result where
    zeros = len - ones
    countSequences n = div (n * (n+1)) 2
    bags = ones + 1
    smallBagSize = div zeros bags
    bigBagSize = smallBagSize + 1
    bigBagsCount = mod zeros bags
    smallBagsCount = bags - bigBagsCount
    r1 = bigBagsCount * (countSequences bigBagSize)
    r2 = smallBagsCount * (countSequences smallBagSize)
    result = countSequences (ones + zeros) - (r1 + r2)

import Control.Monad
import Prelude

main = do
    testCases <- getLine
    strNums <- replicateM (read testCases) testCase
    return ()

testCase = do
    line <- getLine
    print $ solution (map read (words line))

solution :: [Int] -> Int
solution [len, ones] = result where
    zeros = len - ones
    countSequences n = div (n * (n+1)) 2
    bags = ones + 1
    smallBagSize = div zeros bags
    bigBagSize = smallBagSize + 1
    bigBagsCount = zeros - (bags * smallBagSize)
    smallBagsCount = bags - bigBagsCount
    r1 = bigBagsCount * (countSequences bigBagSize)
    r2 = smallBagsCount * (countSequences smallBagSize)
    result = countSequences (ones + zeros) - (r1 + r2)

subStringCount :: Integer -> Integer
subStringCount l = div (l*(l+1)) 2

solve :: Integer -> Integer -> Integer
solve n m
  | remaining == 0 = allSubstrings - (subStringCount lenZero)*(m+1)
  | otherwise = allSubstrings - (subStringCount lenZero)*m - (subStringCount remaining)
  where allSubstrings = div (n*(n+1)) 2
        lenZero = div (n-m) (m+1)
        remaining = mod (n-m) (m+1)

parse :: String -> String
parse line = show $ solve n m
  where [n, m] = map (\x -> read x :: Integer) $ words line

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


The tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. n best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. n·(n - 1) / 2 games were played during the tournament, and each participant had a match with each other participant. The rules of the game are quite simple — the participant who falls asleep first wins. The secretary made a record of each game in the form «xi yi», where xi and yi are the numbers of participants. The first number in each pair is a winner (i.e. xi is a winner and yi is a loser). There is no draws.Recently researches form the «Institute Of Sleep» have found that every person is characterized by a value pj — the speed of falling asleep. The person who has lower speed wins. Every person has its own value pj, constant during the life. It is known that all participants of the tournament have distinct speeds of falling asleep. Also it was found that the secretary made records about all the games except one. You are to find the result of the missing game.

The first line contains one integer n (3 ≤ n ≤ 50) — the number of participants. The following n·(n - 1) / 2 - 1 lines contain the results of the games. Each game is described in a single line by two integers xi, yi (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi и yi are the numbers of the opponents in this game. It is known that during the tournament each of the n participants played n - 1 games, one game with each other participant.

Output two integers x and y — the missing record. If there are several solutions, output any of them.

import Control.Monad
import Data.Array

main = do
	[n] <- getA
	a <- replicateM (n * (n - 1) `div` 2 - 1) getA
	putStr $ unwords $ map show $ gao n a where
		getA = fmap (map read . words) getLine

gao n a = if w!x > w!y then [x, y] else [y, x] where
	[w, l] = [accumArray (+) 0 (1, n) $ zip (map f a) $ repeat 1 | f <- [head, last]]
	[x, y] = filter (\i -> w!i + l!i < n - 1) [1 .. n]

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

main :: IO ()
main = do
  n  <- readLn
  let m = n * (n - 1) `quot` 2 - 1
  xs <- replicateM m (map read . words <$> getLine) :: IO [[Int]]
  matches <- newArray ((1, 1), (n, n)) False :: IO (IOArray (Int, Int) Bool)
  ranks <- newArray (1, n) 0 :: IO (IOArray Int Int)
  forM [1 .. n] $ \i -> do
    writeArray matches (i, i) True
  forM xs $ \(i : j : _) -> do
    writeArray matches (i, j) True
    writeArray matches (j, i) True
    v <- readArray ranks i
    writeArray ranks i (v + 1)
  Just ((i , j), _) <- find (not . snd) <$> getAssocs matches
  ri <- readArray ranks i
  rj <- readArray ranks j
  if ri >= rj
    then printf "%d %d\n" i j
    else printf "%d %d\n" j i

import Array
import Data.List

bfs :: (Eq a) => (a -> [a]) -> a -> [a]
bfs f s = (foldl' union []) $ takeWhile (not . null) $ iterate (nub . (>>= f)) [s]

graph :: String -> (Int -> [Int], Int -> Int, Int)
graph s =
  ((!) (accumArray (\ e a -> a : e) [] (1, n) assocList),
   (!) (foldl' (\ a (b, c) -> a // [(b, a ! b + 1), (c, a ! c + 1)])
               (array (1, n) [(i, 0) | i <- [1..n]])
               assocList),
   n)
  where
  assocList = map ((\ [a, b] -> (read a, read b)) . words) (tail ls)
  n = read $ head $ ls
  ls = lines s

solve s =
  (show a') ++ " " ++ (show b')
  where
  [a, b] = filter ((< n - 1) . degree) [1..n]
  (a', b') = if b `elem` bfs g a then (a, b) else (b, a)
  (g, degree, n) = graph s

main = interact solve

import Array
import List

bfs :: (Eq a) => (a -> [a]) -> a -> [a]
bfs f s = (foldr union []) $ takeWhile (not . null) $ iterate (nub . (>>= f)) [s]

graph :: String -> (Int -> [Int], Int -> Int, Int)
graph s =
  ((!) (accumArray (\ e a -> a : e) [] (1, n) assocList),
   (!) (foldr (\ (a, b) ar -> ar // [(a, ar ! a + 1), (b, ar ! b + 1)])
              (array (1, n) [(i, 0) | i <- [1..n]])
              assocList),
   n)
  where
  assocList = map ((\ [a, b] -> (read a, read b)) . words) (tail ls)
  n = read $ head $ ls
  ls = lines s

solve s =
  (show a') ++ " " ++ (show b')
  where
  [a, b] = filter ((< n - 1) . degree) [1..n]
  (a', b') = if b `elem` bfs g a then (a, b) else (b, a)
  (g, degree, n) = graph s

main = interact solve

import Data.List
main = do
  ([n]:pairs) <- fmap (map (map read . words) . lines) getContents
  let sortedPairs = map sort pairs
      [[x,y]] = [[i,j] | i <- [1..n], j <- [i+1..n]] \\ sortedPairs
      f ([a,z], [w,b]) | z == w && a == x && b == y  = True
      f _ = False
      ans = if any f [(a,b) | a <- pairs, b <- pairs]
              then [x,y]
              else [y,x]
  putStrLn . unwords . map show $ ans

import Control.Monad
import Data.List

main = do
	n <- fmap read getLine
	a <- replicateM (n * (n - 1) `div` 2 - 1) $ fmap (map read . words) getLine
--	a <- fmap (map (map read . words) . lines) getContents
	putStr $ unwords $ map show $ head $ [[i, j] | i <- [1 .. n], j <- [i + 1 .. n]] \\ map sort a
{-

-}

import Control.Monad
import Data.List

main = do
	n <- fmap read getLine
	a <- fmap (map (map read . words) . lines) getContents
	putStr $ unwords $ map show $ head $ [[i, j] | i <- [1 .. n], j <- [i + 1 .. n]] \\ map sort a

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

main :: IO ()
main = do
  n  <- readLn
  let m = n * (n - 1) `quot` 2 - 1
  xs <- replicateM m (map read . words <$> getLine) :: IO [[Int]]
  let pairs = do
        x : y : _ <- xs
        [(x, y), (y, x)]
  let b = ((1, 1), (n, n))
  arr <- newArray b False :: IO (IOArray (Int, Int) Bool)
  forM [1 .. n] $ \i -> do
    writeArray arr (i, i) True
  forM pairs $ \idx -> do
    writeArray arr idx True
  Just (idx, _) <- find (not . snd) <$> getAssocs arr
  uncurry (printf "%d %d\n") idx

import Data.List
main = do
  ([n]:pairs) <- fmap (map (map read . words) . lines) getContents
  let sortedPairs = map sort pairs
      [[x,y]] = [[i,j] | i <- [1..n], j <- [i+1..n]] \\ sortedPairs
      f ([x,z], [w,y]) | z == w  = True
      f _ = False
  if any f [(a,b) | a <- pairs, b <- pairs]
     then putStrLn . unwords . map show $ [y,x]
     else putStrLn . unwords . map show $ [x,y]


Someone gave Alyona an array containing n positive integers a1, a2, ..., an. In one operation, Alyona can choose any element of the array and decrease it, i.e. replace with any positive integer that is smaller than the current one. Alyona can repeat this operation as many times as she wants. In particular, she may not apply any operation to the array at all.Formally, after applying some operations Alyona will get an array of n positive integers b1, b2, ..., bn such that 1 ≤ bi ≤ ai for every 1 ≤ i ≤ n. Your task is to determine the maximum possible value of mex of this array.Mex of an array in this problem is the minimum positive integer that doesn't appear in this array. For example, mex of the array containing 1, 3 and 4 is equal to 2, while mex of the array containing 2, 3 and 2 is equal to 1.

The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — the number of elements in the Alyona's array. The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the elements of the array.

Print one positive integer — the maximum possible value of mex of the array after Alyona applies some (possibly none) operations.

NoteIn the first sample case if one will decrease the second element value to 2 and the fifth element value to 4 then the mex value of resulting array 1 2 3 3 4 will be equal to 5.To reach the answer to the second sample case one must not decrease any of the array elements.

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

main = do
  _ <- getLine
  as <- sort . map read . words <$> getLine
  print $ solve as 1

solve :: [Int] -> Int -> Int
solve [] x = x
solve (a:as) x = solve as (if x <= a then x + 1 else x)

import Data.List( sort)
main = do
    n <- getLine
    nums <- return . (map read) . words =<< getLine
    let snums = sort  nums
	process p [] = p
	process p (x:xs) = if p<=x then process (p+1) xs else process p xs
    print $ process 1 snums

module Main where

import System.IO
import Data.Array
import Data.Int
import Data.List

main :: IO ()
main = do
		n <- readAllArr
		l <- readAllArr
		let ws = words l
		putStrLn $ show $ foldl (\x y -> if x <= y then x+1 else x) 1 $ sort (map read $ ws)

readAllArr :: IO String
readAllArr = getLine

startsWith :: Eq a => [a] -> [a] -> Bool
startsWith [] _ = True
startsWith _ [] = False
startsWith (x:xs) (y:ys)= x == y && startsWith xs ys

orF :: (a->Bool) -> (a->Bool) -> a -> Bool
orF f g a = (f a) || (g a)

pairs :: [a] -> [(a, a)]
pairs l = [(x,y) | (x:ys) <- tails l, y <- ys]

replace' :: Eq b => b -> b -> [b] -> [b]
replace' a b = map (\x -> if (a == x) then b else x)

import Data.List
import qualified Data.ByteString.Char8 as C

mex :: [Int] -> Int
mex = mexRec 1 . sort
        where mexRec index []   = index
              mexRec index (x:xs)
                    | x >= index   = mexRec (index + 1) xs
                    | otherwise    = mexRec index xs

readInt s = let Just (i, _) = C.readInt s in i

main = do
    getLine
    ar <- fmap (map readInt . C.words) C.getLine
    print $ mex ar

import Control.Monad
import Control.Monad.Trans.State.Strict
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.List

main = do
    s <- B.getContents
    let a = flip evalState s $ do
                n <- readInt
                replicateM n readInt
    print $ solve a

solve a = foldl' (\r b -> if b >= r then r+1 else r) 1 bs
  where bs = sort a

readInt :: State B.ByteString Int
readInt = do
    Just (n, rest) <- gets (B.readInt . B.dropWhile isSpace)
    put rest
    return n

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

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

import qualified Data.ByteString.Char8 as B

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

getList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

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

main = getLine >> getList >>= print . succ . f 1 . sort

f k [] = 0
f k (a:as)
	| k <= a = 1 + f ( k + 1 ) as
	| otherwise = f k as

import Data.List

main :: IO ()
main = do
    let parseInt = read :: String -> Int
    nLine <- getLine
    aLine <- getLine
    let n = parseInt $ nLine
        a = map parseInt . words $ aLine
    putStrLn $ show $ maxMex a

maxMex :: [Int] -> Int
maxMex = foldl findMaxMex 1 . sort
    where findMaxMex ans x = if x >= ans then ans + 1 else ans

import Data.List

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

solve :: Int -> [Int] -> Int
solve i [] = i
solve i (a:s) | i <= a = solve (i + 1) s
              | otherwise = solve i s

import Data.List

main = do
  _ <- getLine
  xs <- fmap (map read . words) getLine :: IO [Int]
  print (solve xs)

solve :: [Int] -> Int
solve xs = g 1 . sort $ xs
    where
      g x [] = x
      g x (a:as) | x <= a = g (x+1) as
                 | otherwise = g x as

{-# LANGUAGE TupleSections, MultiParamTypeClasses, ExistentialQuantification,
             RankNTypes, FlexibleContexts, DeriveFunctor #-}

import Control.Monad
import Control.Applicative
--import Control.Lens
--import Control.Zipper
import Control.Arrow
import qualified Data.Map as M
--import qualified Data.Vector as V
import qualified Data.Set as S
import Data.List
--import Debug.Trace
--import Control.Comonad
import Data.Monoid
--import Data.Functor.Foldable
--import Test.QuickCheck
import Data.Tree
--import Data.Machine
--import Data.Traversable
--import Data.Distributive
--import Linear
import Control.Monad.Cont

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

solve :: [Int] -> Int
solve = foldl f 1 . sort
    where
      f mex x | mex <= x = mex + 1
              | otherwise = mex

import Data.List

main = interact $ show . (+ 1) . foldl (\a x -> min (a + 1) x) 0 . sort . map read . tail . words

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

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

import qualified Data.ByteString.Char8 as B

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

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

main = getLine >> B.getLine >>= print . succ . f 1 . sort . map ( fst . fromJust . B.readInt ) . B.words

f k [] = 0
f k (a:as)
	| k <= a = 1 + f ( k + 1 ) as
	| otherwise = f ( k + 1 ) as

import Data.List

main :: IO ()
main = do
    let parseInt = read :: String -> Int
    nLine <- getLine
    aLine <- getLine
    let n = parseInt $ nLine
        a = map parseInt . words $ aLine
    putStrLn $ show $ maxMex a

maxMex :: [Int] -> Int
maxMex = foldl findMaxMex 1 . zip [1..] . sort
    where findMaxMex ans (i, x) = if x >= i then ans + 1 else ans

import Data.List

main = do
  _ <- getLine
  xs <- fmap (map read . words) getLine :: IO [Int]
  print (solve xs)

solve :: [Int] -> Int
solve xs = g . takeWhile (uncurry (<)) . zip [1..] . sort $ xs
    where
      g [] = length xs
      g ((a, _):_) = a


Real stupidity beats artificial intelligence every time.— Terry Pratchett, Hogfather, DiscworldYou are given a string $$$s$$$ of length $$$n$$$ and a number $$$k$$$. Let's denote by $$$rev(s)$$$ the reversed string $$$s$$$ (i.e. $$$rev(s) = s_n s_{n-1} ... s_1$$$). You can apply one of the two kinds of operations to the string: replace the string $$$s$$$ with $$$s + rev(s)$$$ replace the string $$$s$$$ with $$$rev(s) + s$$$How many different strings can you get as a result of performing exactly $$$k$$$ operations (possibly of different kinds) on the original string $$$s$$$?In this statement we denoted the concatenation of strings $$$s$$$ and $$$t$$$ as $$$s + t$$$. In other words, $$$s + t = s_1 s_2 ... s_n t_1 t_2 ... t_m$$$, where $$$n$$$ and $$$m$$$ are the lengths of strings $$$s$$$ and $$$t$$$ respectively.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — number of test cases. Next $$$2 \cdot t$$$ lines contain $$$t$$$ test cases: The first line of a test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$0 \le k \le 1000$$$) — the length of the string and the number of operations respectively. The second string of a test case contains one string $$$s$$$ of length $$$n$$$ consisting of lowercase Latin letters.

For each test case, print the answer (that is, the number of different strings that you can get after exactly $$$k$$$ operations) on a separate line. It can be shown that the answer does not exceed $$$10^9$$$ under the given constraints.

4

3 2

aab

3 3

aab

7 1

abacaba

2 0

ab

NoteIn the first test case of the example:After the first operation the string $$$s$$$ can become either aabbaa or baaaab. After the second operation there are 2 possibilities for $$$s$$$: aabbaaaabbaa and baaaabbaaaab.

import qualified Data.ByteString.Lazy.Char8 as P
import Control.Monad.ST
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Control.Monad.Trans
import Data.Maybe
import Data.Bits
import Prelude hiding (reverse)
import Data.ByteString.Lazy.Char8
import Debug.Trace

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

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

str = string7

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

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

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

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

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

tloop :: SP Builder
tloop = do
  t <- getInt
  -- let t = 1
  fmap mconcat $ replicateM t $ solve

solve :: SP Builder
solve = do
  n <- getInt
  k <- getInt
  s <- getNext
  let
    rs = reverse s
    one = (||) (k == 0) (s == rs)
  pure $ putInts $ if one then [1] else [2]

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe
import Data.Bits
import Prelude hiding (reverse)
import Data.ByteString.Lazy.Char8
import Debug.Trace

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

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

str = string7

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

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

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

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

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

tloop :: SP Builder
tloop = do
  t <- getInt
  -- let t = 1
  fmap mconcat $ replicateM t $ solve

solve :: SP Builder
solve = do
  n <- getInt
  k <- getInt
  s <- getNext
  let
    rs = reverse s
    one = (||) ((==) k 0) ((==) s rs)
  pure $ putInts $ if one then [1] else [2]

import qualified Data.ByteString as BS
import Control.Monad
solve :: BS.ByteString -> Int -> Int
solve x k
  | k == 0 = 1
  | x == BS.reverse x = 1
  | otherwise = 2

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, k] <- map read . words <$> getLine
    x <- BS.getLine
    print $ solve (BS.take n x) k

import Control.Monad

main :: IO ()
main = do
    t <- readLn
    replicateM t $ do
        line <- getLine
        let [n, k] = map read $ words line :: [Int]
        str <- getLine
        putStrLn $ show $ solve n k str
    return ()

solve :: Int -> Int -> [Char] -> Int
solve n k str
  | k == 0                  = 1
  | (reverse str) == str    = 1
  | otherwise               = 2

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

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

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    k <- getInt
    s <- getNext
    let  ans = if  s == P.reverse s || k == 0
           then  1
           else  2
    pure $ putInts [ans]

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

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

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

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

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

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

import qualified Data.ByteString as BS
import Control.Monad
solve :: BS.ByteString -> Int -> Int
solve x k
  | k == 0 = 1
  | x == BS.reverse x = 1
  | otherwise = 2

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [_n, k] <- map read . words <$> getLine
    x <- BS.getLine
    print $ solve x k


It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be transferred from one accumulator to the other. Every time x units of energy are transferred (x is not necessarily an integer) k percent of it is lost. That is, if x units were transferred from one accumulator to the other, amount of energy in the first one decreased by x units and in other increased by  units.Your task is to help Petya find what maximum equal amount of energy can be stored in each accumulator after the transfers.

First line of the input contains two integers n and k (1 ≤ n ≤ 10000, 0 ≤ k ≤ 99) — number of accumulators and the percent of energy that is lost during transfers. Next line contains n integers a1, a2, ... , an — amounts of energy in the first, second, .., n-th accumulator respectively (0 ≤ ai ≤ 1000, 1 ≤ i ≤ n).

Output maximum possible amount of energy that can remain in each of accumulators after the transfers of energy. The absolute or relative error in the answer should not exceed 10 - 6.

module Main where

check :: Double -> [Double] -> Double -> Bool
check k a value = rem*(1 - k/100.0) > nec where
    rem = sum $ map (\x -> max 0.0 (x - value)) a
    nec = sum $ map (\x -> max 0.0 (value - x)) a

eps :: Double
eps = 1e-7

binS :: Double -> [Double] -> Double -> Double -> Double
binS k a left right =
    let binSearch = binS k a
        s = (left + right)/2 in
            if right - left < eps then s
                else if check k a s
                    then binSearch s right
                    else binSearch left s

solve :: String -> String -> Double
solve nk a = binS k al 0.0 (maximum al) where
    nkl = map read (words nk)
    k = head $ tail nkl
    al = map read (words a)

main = do
    nk <- getLine
    a <- getLine
--    print $ map (\x -> max 0.0 (x - 2.0)) a
    print $ solve nk a

import Monad (liftM)

eps  =  1e-06

binFind :: (Double -> Double) -> (Double, Double) -> Double
binFind f (l, r)
  | l + eps > r  =  m
  | f l * f r > eps  =  error "fl * fr > 0"
  | f m * f r > 0  =  binFind f (l, m)
  | otherwise  =  binFind f (m, r)
  where
    m  =  0.5 * (l+r)

solve :: Double -> [Double] -> Double
solve k as  =  binFind f (0, 1000)
  where
    k'  =  1 - k / 100
    f x  =  sum $ map (\a -> if a > x then k' * (a-x) else (a-x)) as

main :: IO ()
main  =  do
    [_, k]  <-  liftM (map read . words) getLine
    as  <-  liftM (map read . words) getLine
    print $ solve k as

import IO
import Text.Printf

half :: [Int] -> Double -> Double
half [] _ = 0 :: Double
half (a:as) m = half as m + if (realToFrac a) > m
                            then ((realToFrac a)-m)
                            else 0

half2 [] _ = 0 :: Double
half2 (a:as) m = half2 as m + if (realToFrac a) < m
                            then (m - (realToFrac a))
                            else 0

binSearch :: (Double -> (Int, a)) -> Double -> Double -> (Double, a)
binSearch f min max =
        --putStrLn (show (min, max, (max+min)/2))
        case (f ((max+min)/2)) of
             (-1, _) -> binSearch f min ((max + min)/2)
             (0, cx) -> ((max + min)/2, cx)
             (1, _) -> binSearch f ((max + min)/2) max

solve :: Int -> Int -> [Int] -> Double
solve n k as = let max = realToFrac $ maximum as
                   min = realToFrac $ minimum as
                   q = 1 - ((realToFrac k)/100)
                   f t = let h1 = half as t
                             h2 = half2 as t
                             r = (h1*q) - h2
                         in if (abs r) < (0.1^6)
                            then (0, t)
                            else if r > 0
                                 then (1, t)
                                 else (-1, t)
                   (_, x) = binSearch f min max
               in x

main = do
        line <- getLine
        line2 <- getLine
        let (n:k:[]) = map read (words line) :: [Int]
            as = map read (words line2) :: [Int]
        printf "%.6f" $ solve n k as
        return ()

import Data.List
import Text.Printf
main = do
    [n, k] <- (map read . words) `fmap` getLine
    a <- (map (fromInteger . read) . words) `fmap` getLine
    let averge = sum a / fromInteger n
        k' = fromInteger k / 100.0
        f x = let (p, m) = foldl' (\(a, b) xi -> if xi > x then (a + xi - x, b)
                    else (a, b + x - xi)) (0, 0) a in p * (1.0 - fromInteger k/100.0) - m
        sol a fa b fb | a - b < min ((a + b)*1e-7) 1e-7 = (a + b)/2
                      | otherwise = let c = (a + b)/2
                                        fc = f c in
                        if fc < 0 then sol c fc b fb else sol a fa c fc
        x = sol averge (f averge) 0 (f 0) :: Double
    printf "%.6f" x


Let's call an array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$ a $$$k$$$-extension for some non-negative integer $$$k$$$ if for all possible pairs of indices $$$1 \leq i, j \leq n$$$ the inequality $$$k \cdot |i - j| \leq min(a_i, a_j)$$$ is satisfied. The expansion coefficient of the array $$$a$$$ is the maximal integer $$$k$$$ such that the array $$$a$$$ is a $$$k$$$-extension. Any array is a 0-expansion, so the expansion coefficient always exists.You are given an array of non-negative integers $$$a_1, a_2, \ldots, a_n$$$. Find its expansion coefficient.

The first line contains one positive integer $$$n$$$ — the number of elements in the array $$$a$$$ ($$$2 \leq n \leq 300\,000$$$). The next line contains $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$, separated by spaces ($$$0 \leq a_i \leq 10^9$$$).

Print one non-negative integer — expansion coefficient of the array $$$a_1, a_2, \ldots, a_n$$$.

NoteIn the first test, the expansion coefficient of the array $$$[6, 4, 5, 5]$$$ is equal to $$$1$$$ because $$$|i-j| \leq min(a_i, a_j)$$$, because all elements of the array satisfy $$$a_i \geq 3$$$. On the other hand, this array isn't a $$$2$$$-extension, because $$$6 = 2 \cdot |1 - 4| \leq min(a_1, a_4) = 5$$$ is false.In the second test, the expansion coefficient of the array $$$[0, 1, 2]$$$ is equal to $$$0$$$ because this array is not a $$$1$$$-extension, but it is $$$0$$$-extension.

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

main = do
	n <- readInt
	as <- readInts
	print $ minimum $ do
		( a, i ) <- zip as [ 0 .. ]
		j <- [ 0, n - 1 ]
		guard $ i /= j
		return $ a `div` ( abs $ i - j )

main::IO()
main=do
    n<-readLn::IO Int
    s<-getLine
    let t=(map read $ words s)::[Int]
    print $ foldl1 min $ zipWith (\x i->x `div` (max i (n-i-1))) t [0..]

f::Int->Int->Int->Int
f n x i=x `div` if i==0 then n-1
                else if i==n-1 then n-1
                else min i (n-i-1)

main::IO()
main=do
    n<-readLn::IO Int
    s<-getLine
    let t=(map read $ words s)::[Int]
    print $ foldl1 min $ zipWith (f n) t [0..]


You are given an array $$$a$$$ of $$$n$$$ integers, where $$$n$$$ is odd. You can make the following operation with it:  Choose one of the elements of the array (for example $$$a_i$$$) and increase it by $$$1$$$ (that is, replace it with $$$a_i + 1$$$). You want to make the median of the array the largest possible using at most $$$k$$$ operations.The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array $$$[1, 5, 2, 3, 5]$$$ is $$$3$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$n$$$ is odd, $$$1 \le k \le 10^9$$$) — the number of elements in the array and the largest number of operations you can make. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$).

Print a single integer — the maximum possible median after the operations.

NoteIn the first example, you can increase the second element twice. Than array will be $$$[1, 5, 5]$$$ and it's median is $$$5$$$.In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is $$$3$$$.In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be $$$[5, 1, 2, 5, 3, 5, 5]$$$ and the median will be $$$5$$$.

import Control.Monad
import Data.String
import Data.List
parseLineToInt :: String -> [Int]
parseLineToInt data_s = do
  (read::String->Int) <$> (words data_s)

findMaxRec :: [Int] -> Int -> Int -> Int -> Int
findMaxRec array_ index_ lastMax rest_ =
  if null array_
     then lastMax + (div rest_ index_)
     else
       let value_ = array_!!0 in
       let needed = (toInteger index_) * (toInteger (value_ - lastMax)) in
       if (toInteger rest_) < needed
         then lastMax + (div rest_ index_)
         else findMaxRec (drop 1 array_) (index_ + 1) value_ (rest_ - (fromInteger needed))

main = do
  twoInts <-getLine
  let mS = parseLineToInt twoInts
  dataInts <- getLine
  let array_ = sort (parseLineToInt dataInts)
  let half = div (length array_) 2
  let upperHalf = drop half array_
  let k = mS!!1
  print (findMaxRec upperHalf 0 0 k)

import Control.Monad
import Data.String
import Data.List
parseLineToInt :: String -> [Int]
parseLineToInt data_s = do
  (read::String->Int) <$> (words data_s)

findMaxRec :: [Int] -> Int -> Int -> Int -> Int
findMaxRec array_ index_ lastMax rest_ =
  if null array_
     then lastMax + (div rest_ index_)
     else
       let value_ = array_!!0 in
       let needed = index_ * (value_ - lastMax) in
       if (rest_ < (needed))
         then lastMax + (div rest_ index_)
         else findMaxRec (drop 1 array_) (index_ + 1) value_ (rest_ - needed)

main = do
  twoInts <-getLine
  let mS = parseLineToInt twoInts
  dataInts <- getLine
  let array_ = sort (parseLineToInt dataInts)
  let half = div (length array_) 2
  let upperHalf = drop half array_
  let k = mS!!1
  print (findMaxRec upperHalf 0 0 k)


International Women's Day is coming soon! Polycarp is preparing for the holiday.There are $$$n$$$ candy boxes in the shop for sale. The $$$i$$$-th box contains $$$d_i$$$ candies.Polycarp wants to prepare the maximum number of gifts for $$$k$$$ girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift equally, so the total amount of candies in a gift (in a pair of boxes) should be divisible by $$$k$$$. In other words, two boxes $$$i$$$ and $$$j$$$ ($$$i \ne j$$$) can be combined as a gift if $$$d_i + d_j$$$ is divisible by $$$k$$$.How many boxes will Polycarp be able to give? Of course, each box can be a part of no more than one gift. Polycarp cannot use boxes "partially" or redistribute candies between them.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2 \cdot 10^5, 1 \le k \le 100$$$) — the number the boxes and the number the girls. The second line of the input contains $$$n$$$ integers $$$d_1, d_2, \dots, d_n$$$ ($$$1 \le d_i \le 10^9$$$), where $$$d_i$$$ is the number of candies in the $$$i$$$-th box.

Print one integer — the maximum number of the boxes Polycarp can give as gifts.

NoteIn the first example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(2, 3)$$$;  $$$(5, 6)$$$;  $$$(1, 4)$$$. So the answer is $$$6$$$.In the second example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(6, 8)$$$;  $$$(2, 3)$$$;  $$$(1, 4)$$$;  $$$(5, 7)$$$. So the answer is $$$8$$$.In the third example Polycarp can give the following pairs of boxes (pairs are presented by indices of corresponding boxes):   $$$(1, 2)$$$;  $$$(6, 7)$$$. So the answer is $$$4$$$.

{-# LANGUAGE Safe #-}
{-# Options_GHC -O3 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Char
import Data.Int
import Data.Array.Unboxed

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

test :: Int -> Int -> [Int] -> Int
test n k a = (* 2) $ sum l
  where
    c = accumArray (+) 0 (0, k - 1) $ [ (mod j k, 1) | (i, j) <- zip [0 .. ] a] :: UArray Int Int
    l = [ if i < j then min (c ! i) (c ! j) else div (c ! i) 2 | i <- [ 0 .. pred k], let j = mod (2 * k - i) k, i <= j]

main = do
  s <- C.getContents
  let (n:k:a) = map ru $ C.words s
  print $ test n k $ take n a

{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import Data.Ord
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet

getWords  = words <$> getLine :: IO [String]
getInts   = map read <$> getWords :: IO [Int]
getDoubles = map read <$> getWords :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()

---- Answer Code Section ----

counter :: [Int] -> Int -> Array Int Int
counter l maxVal = accumArray (+) 0 (0, maxVal) $ map (\x -> (x, 1)) l

process :: [Int] -> Int -> Int
process boxes k = pairCnt where
    mods = map (`mod` k) boxes
    counts = counter mods (k-1)
    (lBound, hBound) = bounds counts
    pair s i = s + if i == 0 || 2*i == k then 2 * ((counts ! i) `div` 2) else min (counts ! i) (counts ! (k-i))
    pairCnt = foldl pair 0 [lBound..hBound]

main = do
    n:k:[] <- getInts
    boxes <- getInts
    print $ process boxes k


Vasya has recently developed a new algorithm to optimize the reception of customer flow and he considered the following problem.Let the queue to the cashier contain n people, at that each of them is characterized by a positive integer ai — that is the time needed to work with this customer. What is special about this very cashier is that it can serve two customers simultaneously. However, if two customers need ai and aj of time to be served, the time needed to work with both of them customers is equal to max(ai, aj). Please note that working with customers is an uninterruptable process, and therefore, if two people simultaneously come to the cashier, it means that they begin to be served simultaneously, and will both finish simultaneously (it is possible that one of them will have to wait).Vasya used in his algorithm an ingenious heuristic — as long as the queue has more than one person waiting, then some two people of the first three standing in front of the queue are sent simultaneously. If the queue has only one customer number i, then he goes to the cashier, and is served within ai of time. Note that the total number of phases of serving a customer will always be equal to ⌈n / 2⌉.Vasya thinks that this method will help to cope with the queues we all hate. That's why he asked you to work out a program that will determine the minimum time during which the whole queue will be served using this algorithm.

The first line of the input file contains a single number n (1 ≤ n ≤ 1000), which is the number of people in the sequence. The second line contains space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). The people are numbered starting from the cashier to the end of the queue.

Print on the first line a single number — the minimum time needed to process all n people. Then on ⌈n / 2⌉ lines print the order in which customers will be served. Each line (probably, except for the last one) must contain two numbers separated by a space — the numbers of customers who will be served at the current stage of processing. If n is odd, then the last line must contain a single number — the number of the last served customer in the queue. The customers are numbered starting from 1.

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

import Data.List
import Data.Maybe
import Data.Char
import Data.Array
import Data.Int
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as BS

solve n a =
    (answer, go2 (1,1))
  where
    (a', n') = if even n then (a, n) else (a ++ [0], n + 1)

    arr = listArray (1, n') a' :: Array Int Int
    bnds = ((1,1), (n', n'))
    cache = listArray bnds [go idx | idx <- range bnds] :: Array (Int,Int) Int

    answer = go (1, 1)

    go (x, e)
        | even x || x < 1 || x > n' = 0
        | x + 1 == n'               = max val1 val2
        | otherwise                 = ans1 `min` ans2 `min` ans3
      where
        go' idx = cache ! idx
        val1 = arr ! e
        val2 = arr ! (x + 1)
        val3 = arr ! (x + 2)
        ans1 = max val2 val3 + go' (x + 2, e)
        ans2 = max val1 val3 + go' (x + 2, x + 1)
        ans3 = max val1 val2 + go' (x + 2, x + 2)

    go2 (x, e)
        | even x || x < 1 || x > n' = error "impossible"
        | x + 1 == n'               = [(e, x + 1)]
        | ans1 == ans               = (x + 1, x + 2) : go2 (x + 2, e)
        | ans2 == ans               = (e, x + 2) : go2 (x + 2, x + 1)
        | ans3 == ans               = (e, x + 1) : go2 (x + 2, x + 2)
        | otherwise                 = error "impossible"
      where
        ans = go (x, e)
        val1 = arr ! e
        val2 = arr ! (x + 1)
        val3 = arr ! (x + 2)
        go' idx = cache ! idx
        ans1 = max val2 val3 + go' (x + 2, e)
        ans2 = max val1 val3 + go' (x + 2, x + 1)
        ans3 = max val1 val2 + go' (x + 2, x + 2)

parseInput = do
    n <- readInt
    a <- replicateM n readInt
    return (n, a)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace

main = do
    (n, a) <- evalState parseInput <$> BS.getContents
    let (ans, pairs) = solve n a
    print ans
    forM_ pairs $ \(x, y) -> if x <= n && y <= n then putStrLn (show x ++ " " ++ show y) else print (min x y)

--{{{ Start of a minimal State Monad
class (Monad m) => MonadState s m | m -> s where
	get :: m s
	put :: s -> m ()

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

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

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

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

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

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

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

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

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

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

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

state = State
--}}} end of a minimal State Monad


After rejecting $$$10^{100}$$$ data structure problems, Errorgorn is very angry at Anton and decided to kill him.Anton's DNA can be represented as a string $$$a$$$ which only contains the characters "ANTON" (there are only $$$4$$$ distinct characters). Errorgorn can change Anton's DNA into string $$$b$$$ which must be a permutation of $$$a$$$. However, Anton's body can defend against this attack. In $$$1$$$ second, his body can swap $$$2$$$ adjacent characters of his DNA to transform it back to $$$a$$$. Anton's body is smart and will use the minimum number of moves.To maximize the chance of Anton dying, Errorgorn wants to change Anton's DNA the string that maximizes the time for Anton's body to revert his DNA. But since Errorgorn is busy making more data structure problems, he needs your help to find the best string $$$B$$$. Can you help him?

The first line of input contains a single integer $$$t$$$ $$$(1 \leq t \leq 100000)$$$ — the number of testcases. The first and only line of each testcase contains $$$1$$$ string $$$a$$$ ($$$1 \leq |a| \leq 100000$$$). $$$a$$$ consists of only the characters "A", "N", "O" and "T". It is guaranteed that the sum of $$$|a|$$$ over all testcases does not exceed $$$100000$$$.

For each testcase, print a single string, $$$b$$$. If there are multiple answers, you can output any one of them. $$$b$$$ must be a permutation of the string $$$a$$$.

NoteFor the first testcase, it takes $$$7$$$ seconds for Anton's body to transform NNOTA to ANTON: NNOTA $$$\to$$$ NNOAT $$$\to$$$ NNAOT $$$\to$$$ NANOT $$$\to$$$ NANTO $$$\to$$$ ANNTO $$$\to$$$ ANTNO $$$\to$$$ ANTON. Note that you cannot output strings such as AANTON, ANTONTRYGUB, AAAAA and anton as it is not a permutation of ANTON.For the second testcase, it takes $$$2$$$ seconds for Anton's body to transform AANN to NAAN. Note that other strings such as NNAA and ANNA will also be accepted.

import Control.Monad
import Data.Maybe
import Data.Int
import Data.List
import qualified Data.ByteString.Char8 as C
import qualified Data.Map.Strict as M
import Data.ByteString.Builder
import System.IO

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

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

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    str <- C.getLine
    let add d val = case val of
          Nothing -> Just d
          Just x -> Just (x + d)
        sub d val = case val of
          Nothing -> Nothing
          Just x -> if x <= d then Nothing else Just (x - d)
        allCounts = C.foldl' (\mp ch -> M.alter (add 1) ch mp) M.empty str
        (_, dirCounts) = C.foldl' acc (allCounts, M.empty) str
          where acc (rs, mp) ch = (rs', mp')
                  where rs' = M.alter (sub 1) ch rs
                        mp' = M.foldlWithKey' (\m char cnt -> M.alter (add (fromIntegral cnt :: Int64)) (char, ch) m) mp rs'
        calc perm = sum $ map (\e -> M.findWithDefault 0 e dirCounts) $ concat $ zipWith (\x xs -> zip (repeat x) xs) perm $ tail $ tails perm
        (_, res) = maximum [(calc perm, perm) | perm <- permutations "ANTO"]
        result = concatMap (\ch -> replicate (M.findWithDefault 0 ch allCounts) ch) res
    return $ string8 result `mappend` charUtf8 '\n'
  hPutBuilder stdout output

import Control.Monad
import Data.Maybe
import Data.Int
import Data.List
import qualified Data.ByteString.Char8 as C
import qualified Data.Map.Strict as M
import Data.ByteString.Builder
import System.IO

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

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

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    str <- C.getLine
    let add d val = case val of
          Nothing -> Just d
          Just x -> Just (x + d)
        sub d val = case val of
          Nothing -> Nothing
          Just x -> if x <= d then Nothing else Just (x - d)
        allCounts = C.foldl' (\mp ch -> M.alter (add 1) ch mp) M.empty str
        (_, dirCounts) = C.foldl' acc (allCounts, M.empty) str
          where acc (rs, mp) ch = (rs', mp')
                  where rs' = M.alter (sub 1) ch rs
                        mp' = M.foldlWithKey' (\m char cnt -> M.alter (add cnt) (char, ch) m) mp rs'
        calc :: String -> Int64
        calc perm = sum $ map (\e -> fromIntegral $ M.findWithDefault 0 e dirCounts) $ concat $ zipWith (\x xs -> zip (repeat x) xs) perm $ tail $ tails perm
        (_, res) = maximum [(calc perm, perm) | perm <- permutations "ANTO"]
        result = concatMap (\ch -> replicate (M.findWithDefault 0 ch allCounts) ch) res
    return $ string8 result `mappend` charUtf8 '\n'
  hPutBuilder stdout output

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    str <- C.unpack <$> C.getLine
    let (_, positions) = foldl' acc (0 :: Int64, []) $ zip [1..] str
        acc (total, []) (index, char) = (total + index - 1, [(char, 1)])
        acc (total, (ch, i) : ps) (index, char)
          | ch == char = (total + index - i - 1, (ch, i + 1) : ps)
          | otherwise = let (total', ps') = acc (total, ps) (index, char) in (total', (ch, i + 1) : ps')
        calc [(c, i)] = replicate i c
        calc ((c, i) : (d, j) : rest) = replicate (i - j) c ++ calc ((d, j) : rest)
    return $ string8 (reverse $ calc $ map (\(c, i) -> (c, fromIntegral i)) positions) `mappend` charUtf8 '\n'
  hPutBuilder stdout output

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    str <- C.unpack <$> C.getLine
    let (_, positions) = foldl' acc (0 :: Int64, []) $ zip [1..] str
        acc (total, []) (index, char) = (total + index - 1, [(char, 1)])
        acc (total, (ch, i) : ps) (index, char)
          | ch == char = (total + index - i - 1, (ch, i + 1) : ps)
          | otherwise = let (total', ps') = acc (total, ps) (index, char) in (total', (ch, i + 1) : ps')
        calc [(c, i)] = replicate i c
        calc ((c, i) : (d, j) : rest) = replicate (i - j) c ++ calc ((d, j) : rest)
    return $ string8 (calc $ map (\(c, i) -> (c, fromIntegral i)) positions) `mappend` charUtf8 '\n'
  hPutBuilder stdout output

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    let cmp (a, _) (b, _) = a == b
    as <- map (\ps -> (fst (head ps), map snd ps, length ps)) . groupBy cmp . sort . (flip zip) [1..] . C.unpack <$> C.getLine
    let calc pairs = fst $ foldl' acc (0 :: Int64, 0) pairs
          where acc (cost, num) (_, ps, len) = (cost + fromIntegral (sum (zipWith (\i j -> abs (i - j)) [num+1..] ps)), num + len)
        result = foldl' acc (-1 :: Int64, []) $ permutations as
          where acc (cost, perm) pairs
                  | c > cost = (c, pairs)
                  | otherwise = (cost, perm)
                  where c = calc pairs
        output = concatMap (\(c, _, len) -> replicate len c) $ snd result
    return $ string8 output `mappend` charUtf8 '\n'
  hPutBuilder stdout output


An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme. Three distinct states i, j and k are selected, where i < j < k. After that the following process happens:   initially the atom is in the state i, we spend Ek - Ei energy to put the atom in the state k, the atom emits a photon with useful energy Ek - Ej and changes its state to the state j, the atom spontaneously changes its state to the state i, losing energy Ej - Ei, the process repeats from step 1. Let's define the energy conversion efficiency as , i. e. the ration between the useful energy of the photon and spent energy.Due to some limitations, Arkady can only choose such three states that Ek - Ei ≤ U.Help Arkady to find such the maximum possible energy conversion efficiency within the above constraints.

The first line contains two integers n and U (3 ≤ n ≤ 105, 1 ≤ U ≤ 109) — the number of states and the maximum possible difference between Ek and Ei. The second line contains a sequence of integers E1, E2, ..., En (1 ≤ E1 < E2... < En ≤ 109). It is guaranteed that all Ei are given in increasing order.

If it is not possible to choose three states that satisfy all constraints, print -1. Otherwise, print one real number η — the maximum possible energy conversion efficiency. Your answer is considered correct its absolute or relative error does not exceed 10 - 9. Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if .

NoteIn the first example choose states 1, 2 and 3, so that the energy conversion efficiency becomes equal to .In the second example choose states 4, 5 and 9, so that the energy conversion efficiency becomes equal to .

{-# LANGUAGE ViewPatterns #-}
import qualified Data.IntSet as S
import Data.List
import Data.Maybe

main = interact exec
exec = maybe "-1" show . (\(n:u:xs) -> fn n u xs) . map read . words
fn n u (S.fromAscList -> xs) = maximumMay $ mapMaybe (\(x, y, mz) -> fmap (\z -> fromIntegral (z - y) / fromIntegral (z - x) :: Double) mz) $ take (n - 2) $ unfoldr (\(x, s) -> let (y, s') = S.deleteFindMin s in Just ((x, y, S.lookupLE (x + u) s'), (y, s')))  (let (x, s) = S.deleteFindMin xs in (x, s))

maximumMay [] = Nothing
maximumMay xs = Just $ maximum xs

import           Data.Array.Unboxed    (Array, bounds, listArray, (!))
import qualified Data.ByteString.Char8 as B
import           Data.Maybe            (fromJust)

findIndexFrom :: Array Int Int -> Int -> Int -> Int
findIndexFrom v i x = let (_, n) = bounds v in go i n
  where go lo hi | lo >= hi = hi
        go lo hi = let m = lo + (hi - lo + 1) `quot` 2
                   in if v ! m > x
                      then go lo (m - 1)
                      else go m  hi

bestEta :: Array Int Int -> Int -> Maybe Double
bestEta v u = maximum $ map findTriple [1..(n-2)]
  where (_, n) = bounds v
        findTriple i = let k = findIndexFrom v i (u + v ! i)
                       in if (i + 1 < k)
                          then Just (toEta i (i + 1) k)
                          else Nothing
        toEta i j k = fromIntegral (v ! k - v ! j) / fromIntegral (v ! k - v ! i)

main = do
  let toInt = fst . fromJust . B.readInt
  let readInts = fmap (map toInt . B.words) B.getLine

  [n, u] <- readInts
  v <- fmap (listArray (1, n)) readInts

  case bestEta v u of
    Just v  -> putStrLn (show v)
    Nothing -> putStrLn "-1"

{-# LANGUAGE ViewPatterns #-}
import qualified Data.IntSet as S
import Data.List
import Data.Maybe

main = interact exec
exec = maybe "No" (("Yes\n" ++) . show) . (\(n:u:xs) -> fn n u xs) . map read . words
fn n u (S.fromAscList -> xs) = maximumMay $ mapMaybe (\(x, y, mz) -> fmap (\z -> fromIntegral (z - y) / fromIntegral (z - x)) mz) $ take (n - 2) $ unfoldr (\(x, s) -> let (y, s') = S.deleteFindMin s in Just ((x, y, S.lookupLE (x + u) s'), (y, s')))  (let (x, s) = S.deleteFindMin xs in (x, s))

maximumMay [] = Nothing
maximumMay xs = Just $ maximum xs

{-# LANGUAGE ViewPatterns #-}
import qualified Data.IntSet as S
import Data.List
import Data.Maybe

main = interact exec
exec = maybe "No" show . (\(n:u:xs) -> fn n u xs) . map read . words
fn n u (S.fromAscList -> xs) = maximumMay $ mapMaybe (\(x, y, mz) -> fmap (\z -> fromIntegral (z - y) / fromIntegral (z - x) :: Double) mz) $ take (n - 2) $ unfoldr (\(x, s) -> let (y, s') = S.deleteFindMin s in Just ((x, y, S.lookupLE (x + u) s'), (y, s')))  (let (x, s) = S.deleteFindMin xs in (x, s))

maximumMay [] = Nothing
maximumMay xs = Just $ maximum xs


One very well-known internet resource site (let's call it X) has come up with a New Year adventure. Specifically, they decided to give ratings to all visitors.There are n users on the site, for each user we know the rating value he wants to get as a New Year Present. We know that user i wants to get at least ai rating units as a present.The X site is administered by very creative and thrifty people. On the one hand, they want to give distinct ratings and on the other hand, the total sum of the ratings in the present must be as small as possible.Help site X cope with the challenging task of rating distribution. Find the optimal distribution.

The first line contains integer n (1 ≤ n ≤ 3·105) — the number of users on the site. The next line contains integer sequence a1, a2, ..., an (1 ≤ ai ≤ 109).

Print a sequence of integers b1, b2, ..., bn. Number bi means that user i gets bi of rating as a present. The printed sequence must meet the problem conditions.  If there are multiple optimal solutions, print any of them.

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

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

import qualified Data.ByteString.Lazy.Builder as BB

import Data.Monoid
import System.IO

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

main = do
  n <- readLn
  as <- getInts

  let
    as' = sort $ zip as [1..]
    b = zipWith (\(a, i) p -> (max a (p+1), i)) as' $ (-100):(map fst b)

  putStrLn $ unwords $ map show $ elems (array (1, n) $ map swap b :: UArray Int Int)

import Control.Monad
import Data.Array.IO
import Data.List

import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Data.Char

readInt :: IO Int
readInt = do line <- BS.getLine
             let Just (n,_) = BS.readInt line
             return n

parseInts :: Int -> ByteString -> [Int]
parseInts k bs | k <= 0 = []
parseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of
                   Nothing -> []
                   Just (n,bs') -> n : parseInts (k-1) bs'

main = do
  n <- fmap read getLine
  nums <- fmap (parseInts n) BS.getLine
  let sorted = sort (zip nums [1..]) :: [(Int,Int)]

  ans <- newArray (1,n) 0 :: IO (IOUArray Int Int)

  let go _ [] = return ()
      go m ((v,j):rest) = do let m' = max m v
                             writeArray ans j m'; go (m'+1) rest
  go 0 sorted
  forM_ [1..n] $ \i -> do
    v <- readArray ans i
    putStr $ show v ++ " "
  putStrLn ""

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

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

import qualified Data.ByteString.Lazy.Builder as BB

import Data.Monoid
import System.IO

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

main = do
  getLine
  as <- getInts

  putStrLn $ unwords $ map show $ map snd $ sort $ map swap $ concat $ map (zipWith (\a (b, i) -> (b+a, i)) [0..]) $ groupBy ((==) `on` fst) $ sort $ zip as [1..]


Vlad, like everyone else, loves to sleep very much.Every day Vlad has to do $$$n$$$ things, each at a certain time. For each of these things, he has an alarm clock set, the $$$i$$$-th of them is triggered on $$$h_i$$$ hours $$$m_i$$$ minutes every day ($$$0 \le h_i < 24, 0 \le m_i < 60$$$). Vlad uses the $$$24$$$-hour time format, so after $$$h=12, m=59$$$ comes $$$h=13, m=0$$$ and after $$$h=23, m=59$$$ comes $$$h=0, m=0$$$.This time Vlad went to bed at $$$H$$$ hours $$$M$$$ minutes ($$$0 \le H < 24, 0 \le M < 60$$$) and asks you to answer: how much he will be able to sleep until the next alarm clock.If any alarm clock rings at the time when he went to bed, then he will sleep for a period of time of length $$$0$$$.

The first line of input data contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the test. The first line of the case contains three integers $$$n$$$, $$$H$$$ and $$$M$$$ ($$$1 \le n \le 10, 0 \le H < 24, 0 \le M < 60$$$) — the number of alarms and the time Vlad went to bed. The following $$$n$$$ lines contain two numbers each $$$h_i$$$ and $$$m_i$$$ ($$$0 \le h_i < 24, 0 \le m_i < 60$$$) — the time of the $$$i$$$ alarm. It is acceptable that two or more alarms will trigger at the same time. Numbers describing time do not contain leading zeros.

Output $$$t$$$ lines, each containing the answer to the corresponding test case. As an answer, output two numbers  — the number of hours and minutes that Vlad will sleep, respectively. If any alarm clock rings at the time when he went to bed, the answer will be 0 0.

module Main
    ( main )
    where
import Control.Monad
import Data.List
timeToMin::Int->Int->Int
timeToMin a b=60*a+b

minToTime::Int->[Int]
minToTime t=[a,b]
  where a=t`div`60
        b=t-a*60
doTime::Int->[Int]->Int
doTime sleepTime y
  |(last y)-sleepTime<0 =(y!! 0)+(1440-sleepTime)
  |otherwise =minimum ynew
  where ynew=filter (>=0) (map ((+(-sleepTime))) y)

printTime::[Int]->IO ()
printTime (x:y:_)=putStrLn$(show x)++" "++(show y)
main = do
  line<-getLine
  let nTerm=read line::Int
  replicateM_ nTerm$do
    line<-getLine
    let (n:h:m:_)=map read (words line)::[Int]
    time<-replicateM n$do
      color<-getLine
      let (h:m:_)=map read (words color)::[Int]
      return (timeToMin h m)
    let timeNew=sort time
    let sleepTime=timeToMin h m
    printTime $minToTime$doTime sleepTime timeNew

import Control.Monad (forM)

type Time = (Int, Int)
type Case = (Time, [Time])

-- i have no idea what i'm doing starts here
main :: IO ()
main = do
    res <- map solve <$> parseIn
    putStr $ write res

parseIn :: IO [Case]
parseIn = do
    n <- read <$> getLine
    forM [1..n] $ \_ -> do
        [l, nowH, nowM] <- map read . words <$> getLine
        alarms <- forM [1..l] $ \_ -> do
            [alarmH, alarmM] <- map read . words <$> getLine
            return (alarmH, alarmM)
        return ((nowH, nowM), alarms)

-- i have idea what i'm doing
write :: [Time] -> String
write list = unlines $ map writeLine list

writeLine :: Time -> String
writeLine time = show (fst time) ++ " " ++ show (snd time)

toMinutes :: Time -> Int
toMinutes t = 60 * fst t + snd t

fromMinutes :: Int -> Time
fromMinutes number
    | number >= 24 * 60 = fromMinutes (number - 24 * 60)
    | otherwise = divMod number 60

moveToNextDay :: Int -> Int
moveToNextDay number = number + 24 * 60

getClosestAlarm :: Int -> [Int] -> Int
getClosestAlarm now alarms =
    let past = [t | t <- alarms, t < now]
        future = [t | t <- alarms, t >= now]
        closest = minimum (map moveToNextDay past ++ future)
    in closest - now

-- TODO write more beautifully (?)
solve :: Case -> Time
solve testcase = fromMinutes $ getClosestAlarm (toMinutes (fst testcase)) (map toMinutes (snd testcase))

import System.IO
import Control.Monad
import Data.List
import Data.Maybe
main = do
    [t] <- ri
    tcs <- replicateM t rtc
    mapM (putStrLn . showHM . solve) tcs
ri = map read . words <$> getLine :: IO [Int]
rtc = do
    [n,h,m] <- ri
    als <- replicateM n (toM <$> ri)
    return (toM [h,m], sort als)
toM [h,m] = h*60 + m
solve (s, als) = flip (-) s . fromJust . find (>=s) $ a2
  where
    a2 = als ++ map (+ (24*60)) als
showHM mm = show h ++ " " ++ show m
  where
    h = mm `div` 60
    m = mm `mod` 60

{-
Whatever you do, work heartily, as for the Lord and not for men,
knowing that from the Lord you will receive the inheritance as your reward.
You are serving the Lord Christ.
- Colossians 3:23-24
-}

module Main
    ( main )
    where

import Control.Monad
import Data.List

data Time = Time
          { hours   :: Int
          , minutes :: Int
          }
          deriving (Eq, Ord, Show)

orderAfterTime :: [Time] -> Time -> [Time]
orderAfterTime ts t = sort after ++ sort (map addHours before)
    where (before, after) = partition (< t) ts

addHours :: Time -> Time
addHours (Time h m) = Time (h + 24) m

firstAlarm :: [Time] -> Time -> Time
firstAlarm ts t = head $ orderAfterTime ts t

timeUntil :: Time -> Time -> Time
timeUntil (Time h m) (Time h' m') = Time (h' - h) (m' - m)

addMinutes :: Time -> Time -> Time
addMinutes (Time h m) a@(Time h' m')
  | m <= m'   = a
  | otherwise = Time (h' - 1) (m' + 60)

putTimeLn :: Time -> IO ()
putTimeLn (Time h m) = putStrLn $ (show h) ++ " " ++ (show m)

main :: IO ()
main = do
  line <- getLine
  let testCases = read line

  replicateM_ testCases $ do
    line <- getLine
    let (n:h:m:_) = map read $ words line
        vladTime = Time h m

    alarms <- replicateM n $ do
      line <- getLine
      let (h:m:_) = map read $ words line
      return (Time h m)

    putTimeLn . timeUntil vladTime . addMinutes vladTime . firstAlarm alarms $ vladTime

  return ()

module Main
    ( main )
    where
import Control.Monad
import Data.List
timeToMin::Int->Int->Int
timeToMin a b=60*a+b

minToTime::Int->[Int]
minToTime t=[a,b]
  where a=t`div`60
        b=t-a*60
doTime::Int->[Int]->Int
doTime sleepTime y
  |(last y)-sleepTime<0 =(y!! 0)+(1440-sleepTime)
  |otherwise =(minimum ynew)-sleepTime
  where ynew=filter (>=0) y

printTime::[Int]->IO ()
printTime (x:y:_)=putStrLn$(show x)++" "++(show y)
main = do
  line<-getLine
  let nTerm=read line::Int
  replicateM_ nTerm$do
    line<-getLine
    let (n:h:m:_)=map read (words line)::[Int]
    time<-replicateM n$do
      color<-getLine
      let (h:m:_)=map read (words color)::[Int]
      return (timeToMin h m)
    let timeNew=sort time
    let sleepTime=timeToMin h m
    printTime $minToTime$doTime sleepTime timeNew

module Main
    ( main )
    where
import Control.Monad
import Data.List
timeToMin::Int->Int->Int
timeToMin a b=60*a+b

minToTime::Int->[Int]
minToTime t=[a,b]
  where a=t`div`60
        b=t-a*60
doTime::Int->[Int]->Int
doTime sleepTime y
  |(last y)-sleepTime<0 =(doTime sleepTime (map (+3600) y))+(3600-sleepTime)
  |otherwise =(minimum ynew)-sleepTime
  where ynew=filter (>=0) y

main = do
  line<-getLine
  let nTerm=read line::Int
  replicateM_ nTerm$do
    line<-getLine
    let (n:h:m:_)=map read (words line)::[Int]
    time<-replicateM n$do
      color<-getLine
      let (h:m:_)=map read (words color)::[Int]
      return (timeToMin h m)
    let timeNew=sort time
    let sleepTime=timeToMin h m
    print$minToTime$doTime sleepTime timeNew

module Main
    ( main )
    where
import Control.Monad
import Data.List
timeToMin::Int->Int->Int
timeToMin a b=60*a+b

minToTime::Int->[Int]
minToTime t=[a,b]
  where a=t`div`60
        b=t-a*60
doTime::Int->[Int]->Int
doTime sleepTime y
  |(last y)-sleepTime<0 =(doTime sleepTime (map (+3600) y))+(3600-sleepTime)
  |otherwise =(minimum ynew)-sleepTime
  where ynew=filter (>=0) y

main = do
  line<-getLine
  let nTerm=read line::Int
  print nTerm
  replicateM_ nTerm$do
    line<-getLine
    let (n:h:m:_)=map read (words line)::[Int]
    print [n,h,m]
    time<-replicateM n$do
      color<-getLine
      let (h:m:_)=map read (words color)::[Int]
      print [h,m]
      return (timeToMin h m)
    let timeNew=sort time
    let sleepTime=timeToMin h m
    print$minToTime$doTime sleepTime timeNew


A sequence $$$(b_1, b_2, \ldots, b_k)$$$ is called strange, if the absolute difference between any pair of its elements is greater than or equal to the maximum element in the sequence. Formally speaking, it's strange if for every pair $$$(i, j)$$$ with $$$1 \le i<j \le k$$$, we have $$$|a_i-a_j|\geq MAX$$$, where $$$MAX$$$ is the largest element of the sequence. In particular, any sequence of length at most $$$1$$$ is strange.For example, the sequences $$$(-2021, -1, -1, -1)$$$ and $$$(-1, 0, 1)$$$ are strange, but $$$(3, 0, 1)$$$ is not, because $$$|0 - 1| < 3$$$.Sifid has an array $$$a$$$ of $$$n$$$ integers. Sifid likes everything big, so among all the strange subsequences of $$$a$$$, he wants to find the length of the longest one. Can you help him?A sequence $$$c$$$ is a subsequence of an array $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements.

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

For each test case output a single integer — the length of the longest strange subsequence of $$$a$$$.

NoteIn the first test case, one of the longest strange subsequences is $$$(a_1, a_2, a_3, a_4)$$$In the second test case, one of the longest strange subsequences is $$$(a_1, a_3, a_4, a_5, a_7)$$$.In the third test case, one of the longest strange subsequences is $$$(a_1, a_3, a_4, a_5)$$$.In the fourth test case, one of the longest strange subsequences is $$$(a_2)$$$.In the fifth test case, one of the longest strange subsequences is $$$(a_1, a_2, a_4)$$$.

-- uninhm
-- https://codeforces.com/contest/1529/problem/B
-- greedy

import Data.List (sort)

odds (x:xs) = x : evens xs
odds [] = []

evens (_:xs) = odds xs
evens [] = []

(.>) = flip (.)
infixl 8 .>

firstdiff [x] = x
firstdiff (x:y:_) = y - x

solve l = go (length l) (firstdiff $ map snd l) l where
  go n mindiff (x':y':xs)
    | y > 0 && y <= mindiff = fst y'
    | y > 0 = fst x'
    | otherwise = go n (min mindiff (y-x)) (y':xs)
      where
        y = snd y'
        x = snd x'

  go n mindiff [x] = n

main = interact $ lines
  .> tail
  .> evens
  .> map (show . solve . zip [1..] . sort . map read . words)
  .> unlines

-- uninhm
-- https://codeforces.com/contest/1529/problem/B
-- greedy

import Data.List (sort)

odds (x:xs) = x : evens xs
odds [] = []

evens (_:xs) = odds xs
evens [] = []

(.>) = flip (.)
infixl 8 .>

solve :: [Int] -> Int
solve = (\l -> go (length l) (abs $ snd (l!!1) - snd (l!!0)) l) . zip [1..] . sort where
  go n mindiff (x':y':xs)
    | y > 0 && y <= mindiff = fst y'
    | y > 0 = fst x'
    | otherwise = go n (min mindiff (y-x)) (y':xs)
      where
        y = snd y'
        x = snd x'

  go n mindiff [x] = n

main = interact $ lines
  .> tail
  .> evens
  .> map (show . solve . map read . words)
  .> unlines

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

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

printArray [] = ""
printArray (x:xs) = show(x) ++" " ++ printArray xs

solve [] po = True
solve [x] po = True
solve (x:xs) po
    | x > 0 = True
    | (head xs) - x < po = False
    | otherwise = solve xs po

printS = do
    n<-readLn :: IO Int
    a<-readInts
    let z = sort a
        ne = sum[1|x<-z,x<=0]
        po = if (n-ne>0) then minimum[x|x<-z, x>0] else 0
        r = ne + if (solve ( z) po) && po>0 then 1 else 0
    print r

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

import Control.Monad
import Data.List (sort)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t $ do
        n <- getLine
        a <- reverse . sort . map read . words <$> getLine :: IO [Int]
        let x = takeWhile (> 0) a
            y = dropWhile (> 0) a
        print $ max (length y) $ if null x then 0 else 1 + check y (last x) (last x)

check :: [Int] -> Int -> Int -> Int
check [] _ _ = 0
check (x:xs) p d
               | p - x >= d = 1 + check xs x d
               | otherwise  = check xs p d

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

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

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

calcMinInterval :: [Int] -> Int
calcMinInterval [x1, x2] = x2 - x1
calcMinInterval (x1 : x2 : xs) = min (x2 - x1) $ calcMinInterval (x2 : xs)
calcMinInterval _ = error ""

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    _ <- getInts
    (xs, ys) <- partition (<=0) . sort <$> getInts
    let lx = length xs
        ly = length ys
        result
          | lx <= 1 = lx + min 1 ly
          | ly == 0 = lx
          | calcMinInterval xs >= head ys = lx + 1
          | otherwise = lx
    return $ intDec result `mappend` charUtf8 '\n'
  hPutBuilder stdout output

-- uninhm
-- https://codeforces.com/contest/1529/problem/B
-- greedy

import Data.List (sort)

odds (x:xs) = x : evens xs
odds [] = []

evens (_:xs) = odds xs
evens [] = []

(.>) = flip (.)
infixl 8 .>

bignum = 2^20

solve l = go (length l) bignum . zip [1..] . sort $ l where
  go n mindiff (x:xs) | mindiff == bignum && snd x > 0 = 1

  go n mindiff (x':y':xs)
    | y > 0 && y <= mindiff = fst y'
    | y > 0 = fst x'
    | otherwise = go n (min mindiff (y-x)) (y':xs)
      where
        y = snd y'
        x = snd x'

  go n mindiff [x']
    | x <= 0 || x <= mindiff = fst x'
    | otherwise = n
      where x = snd x'

main = interact $ lines
  .> tail
  .> evens
  .> map (show . solve . map read . words)
  .> unlines

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

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

printArray [] = ""
printArray (x:xs) = show(x) ++" " ++ printArray xs

solve [] po = True
solve [x] po = True
solve (x:xs) po
    | x > 0 = True
    | (head xs) - x < po = False
    | otherwise = solve xs po

printS = do
    n<-readLn :: IO Int
    a<-readInts
    let z = sort a
        ne = sum[1|x<-z,x<=0]
        po = if (n-ne>0) then minimum[x|x<-z, x>0] else 0
        r = ne + if (solve (tail z) po) && po>0 then 1 else 0
    print r

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


You are given an array $$$a$$$ of length $$$n$$$, which initially is a permutation of numbers from $$$1$$$ to $$$n$$$. In one operation, you can choose an index $$$i$$$ ($$$1 \leq i < n$$$) such that $$$a_i < a_{i + 1}$$$, and remove either $$$a_i$$$ or $$$a_{i + 1}$$$ from the array (after the removal, the remaining parts are concatenated). For example, if you have the array $$$[1, 3, 2]$$$, you can choose $$$i = 1$$$ (since $$$a_1 = 1 < a_2 = 3$$$), then either remove $$$a_1$$$ which gives the new array $$$[3, 2]$$$, or remove $$$a_2$$$ which gives the new array $$$[1, 2]$$$.Is it possible to make the length of this array equal to $$$1$$$ with these operations?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2 \cdot 10^4$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$2 \leq n \leq 3 \cdot 10^5$$$)  — the length of the array. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq n$$$, $$$a_i$$$ are pairwise distinct) — elements of the array. It is guaranteed that the sum of $$$n$$$ over all test cases doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, output on a single line the word "YES" if it is possible to reduce the array to a single element using the aforementioned operation, or "NO" if it is impossible to do so.

NoteFor the first two test cases and the fourth test case, we can operate as follow (the bolded elements are the pair chosen for that operation):$$$[\text{1}, \textbf{2}, \textbf{3}] \rightarrow [\textbf{1}, \textbf{2}] \rightarrow [\text{1}]$$$$$$[\text{3}, \textbf{1}, \textbf{2}, \text{4}] \rightarrow [\text{3}, \textbf{1}, \textbf{4}] \rightarrow [\textbf{3}, \textbf{4}] \rightarrow [\text{4}]$$$$$$[\textbf{2}, \textbf{4}, \text{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\textbf{4}, \textbf{6}, \text{1}, \text{3}, \text{5}] \rightarrow [\text{4}, \text{1}, \textbf{3}, \textbf{5}] \rightarrow [\text{4}, \textbf{1}, \textbf{5}] \rightarrow [\textbf{4}, \textbf{5}] \rightarrow [\text{4}]$$$

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

main = getLine >>= flip replicateM_ test . read

test = do
  getLine
  as <- map read . words <$> getLine :: IO [Integer]
  putStrLn $ bool "NO" "YES" (head as < last as)


Petya is the most responsible worker in the Research Institute. So he was asked to make a very important experiment: to melt the chocolate bar with a new laser device. The device consists of a rectangular field of n × m cells and a robotic arm. Each cell of the field is a 1 × 1 square. The robotic arm has two lasers pointed at the field perpendicularly to its surface. At any one time lasers are pointed at the centres of some two cells. Since the lasers are on the robotic hand, their movements are synchronized — if you move one of the lasers by a vector, another one moves by the same vector.The following facts about the experiment are known:   initially the whole field is covered with a chocolate bar of the size n × m, both lasers are located above the field and are active;  the chocolate melts within one cell of the field at which the laser is pointed;  all moves of the robotic arm should be parallel to the sides of the field, after each move the lasers should be pointed at the centres of some two cells;  at any one time both lasers should be pointed at the field. Petya doesn't want to become a second Gordon Freeman. You are given n, m and the cells (x1, y1) and (x2, y2), where the lasers are initially pointed at (xi is a column number, yi is a row number). Rows are numbered from 1 to m from top to bottom and columns are numbered from 1 to n from left to right. You are to find the amount of cells of the field on which the chocolate can't be melted in the given conditions.

The first line contains one integer number t (1 ≤ t ≤ 10000) — the number of test sets. Each of the following t lines describes one test set. Each line contains integer numbers n, m, x1, y1, x2, y2, separated by a space (2 ≤ n, m ≤ 109, 1 ≤ x1, x2 ≤ n, 1 ≤ y1, y2 ≤ m). Cells (x1, y1) and (x2, y2) are distinct.

Each of the t lines of the output should contain the answer to the corresponding input test set.

import System.Environment
import Control.Monad
import Data.Set

rr :: [Char] -> Integer
rr = read

ri :: [Char] -> Int
ri = read

each = do
    s <- getLine
    let (n:m:x1:y1:x2:y2:null) = Prelude.map rr $ words s
    let dx=abs(x1-x2)
    let dy=abs(y1-y2)
    putStrLn $ show $ n*m - 2*(n-dx)*(m-dy)  + (max 0 (n-2*dx)) * (max 0 (m-2*dy) )

main = do
    s <- getLine
    let n = ri s
    replicateM n each

import List
import Control.Monad
import Data.Int

solve :: [Int64] -> String
solve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i
    where dx = abs(x2-x1)+1
          dy = abs(y2-y1)+1
          i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)

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

main = do
    [t] <- ints
    replicateM (t) ints >>= mapM_ (putStrLn.solve)

import List
import Control.Monad

--solve ::  [Integer] -> String
solve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i
    where dx = abs(x2-x1)+1
          dy = abs(y2-y1)+1
          i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)

--ints :: IO [Integer]
ints = fmap (map read . words) getLine

main = do
    [t] <- ints
    replicateM (fromIntegral t) ints >>= mapM_ (putStrLn.solve)

import System.Environment
import Control.Monad
import Data.Set

rr :: [Char] -> Integer
rr = read

ri :: [Char] -> Int
ri = read

each = do
    s <- getLine
    let (n:m:x1:y1:x2:y2:null) = Prelude.map rr $ words s
    putStrLn $ show $ abs(x1-x2)*2*abs(y1-y2)

main = do
    s <- getLine
    let n = ri s
    replicateM n each

import List
import Control.Monad

solve ::  [Int] -> String
solve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i
    where dx = abs(x2-x1)+1
          dy = abs(y2-y1)+1
          i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)

ints = fmap (map read . words) getLine

main = do
    [t] <- ints
    replicateM t ints >>= mapM_ (putStrLn.solve)

import List
import Control.Monad

solve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i
    where dx = abs(x2-x1)+1
          dy = abs(y2-y1)+1
          i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)

ints = fmap (map read . words) getLine

main = do
    [t] <- ints
    replicateM t ints >>= mapM_ (putStrLn.solve)