On a history lesson the teacher asked Vasya to name the dates when n famous events took place. He doesn't remembers the exact dates but he remembers a segment of days [li, ri] (inclusive) on which the event could have taken place. However Vasya also remembers that there was at most one event in one day. Help him choose such n dates of famous events that will fulfill both conditions. It is guaranteed that it is possible.

The first line contains one integer n (1 ≤ n ≤ 100) — the number of known events. Then follow n lines containing two integers li and ri each (1 ≤ li ≤ ri ≤ 107) — the earliest acceptable date and the latest acceptable date of the i-th event.

Print n numbers — the dates on which the events took place. If there are several solutions, print any of them. It is guaranteed that a solution exists.

import List
main = interact solve
solve input = output where
  [num]:lrs = map (map (read::String->Int)) $ map words $ lines input
  output = unwords $ map (show . snd) $ sort $ answer ( sort $ zip lrs [1..num] ) 1
  answer :: [([Int],Int)] -> Int -> [(Int,Int)]
  answer [] _ = []
  answer xs d = (snd y,d'):(answer xs' (d'+1))  where
    ys = sortBy c $ filter (\x->(head $ fst x) <= d ) xs
      where c ([_,x],_) ([_,y],_) = if x<y then LT else GT
    (y,d') = if null ys then (x1,(head $ fst x1)) else (head ys,d) where x1 = head xs
    xs' = delete y xs

import List
main = interact solve
solve input = output where
  [num]:lrs = map (map (read::String->Int)) $ map words $ lines input
  output = unwords $ map (show . snd) (sort $ answer (sort $ zip lrs [1..num]) 1)
  answer [] _ = []
  answer (([l,r],i):xs) j = (i,k):(answer xs (j + 1)) where k = max l j

import List
main = interact solve
solve input = output where
  [num]:lrs = map (map (read::String->Int)) $ map words $ lines input
  output = unwords $ map (show . snd) (sort $ answer (sort $ zip lrs [1..num]) 1)
  answer [] _ = []
  answer (([l,r],i):xs) j = (i,k):(answer xs (k + 1)) where k = max l j


Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the Internet, he learned about the Hamming distance between two strings S and T of the same length, which is defined as the number of positions in which S and T have different characters. For example, the Hamming distance between words "permanent" and "pergament" is two, as these words differ in the fourth and sixth letters.Moreover, as he was searching for information, he also noticed that modern search engines have powerful mechanisms to correct errors in the request to improve the quality of search. Ford doesn't know much about human beings, so he assumed that the most common mistake in a request is swapping two arbitrary letters of the string (not necessarily adjacent). Now he wants to write a function that determines which two letters should be swapped in string S, so that the Hamming distance between a new string S and string T would be as small as possible, or otherwise, determine that such a replacement cannot reduce the distance between the strings.Help him do this!

The first line contains integer n (1 ≤ n ≤ 200 000) — the length of strings S and T. The second line contains string S. The third line contains string T. Each of the lines only contains lowercase Latin letters.

In the first line, print number x — the minimum possible Hamming distance between strings S and T if you swap at most one pair of letters in S. In the second line, either print the indexes i and j (1 ≤ i, j ≤ n, i ≠ j), if reaching the minimum possible distance is possible by swapping letters on positions i and j, or print "-1 -1", if it is not necessary to swap characters. If there are multiple possible answers, print any of them.

NoteIn the second test it is acceptable to print i = 2, j = 3.

import qualified Data.Map as Map

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

solve :: [String] -> String
solve (s:t:[]) = let (v, i, j) = foldl1 min options in unlines [show (v + v0), show i ++ " " ++ show j]
    where table = getTable s t
          options = (0, -1, -1) : concat [zipWith getOption table $ drop i table | i <- [1..length table]]
          v0 = diff s t

diff :: String -> String -> Int
diff s t = length . filter (uncurry (/=)) $ zip s t

getTable :: String -> String -> [(Char, Char, Int)]
getTable s t = map (\((c1, c2), i) -> (c1, c2, i)) . Map.toList $ foldl f Map.empty (zip3 s t [1..])
    where f m (c1, c2, i) = Map.insert (c1, c2) i m

getOption :: (Char, Char, Int) -> (Char, Char, Int) -> (Int, Int, Int)
getOption (a1, a2, ai) (b1, b2, bi) = (v12 + v21 - v11 - v22, ai, bi)
    where v11 = if a1 == b1 then 1 else 2
          v12 = if a1 == b2 then 1 else 2
          v21 = if a2 == b1 then 1 else 2
          v22 = if a2 == b2 then 1 else 2

import Data.List
import Data.Int
import Data.Map

getDifference :: String -> String -> Int
getDifference xs ys = length . Data.List.filter (\ (a, b) -> a /= b) $ zip xs ys

getPositions :: String -> String -> Map (Char, Char) Int
getPositions xs ys =
    Data.List.foldl' (\ acc (x, y, pos) -> Data.Map.insert (x, y) pos acc)
           empty (zip3 xs ys [1..])

findBest :: [((Char, Char), Int)] -> (Int, Int, Int)
findBest entries =
    let res@(delta, p1, p2) =
            Data.List.foldl' max (0, -1, -1)
            [getCost x y | x <- entries, y <- entries]
    in if delta == 0 then (0, -1, -1) else res
    where
        getMatching :: (Char, Char) -> (Char, Char) -> Int
        getMatching (a1, b1) (a2, b2) =
            let m1 = if a1 == b1 then 1 else 0
                m2 = if a2 == b2 then 1 else 0
            in m1 + m2
        getCost :: ((Char, Char), Int) -> ((Char, Char), Int) -> (Int, Int, Int)
        getCost ((a1, b1), p1) ((a2, b2), p2) =
            (getMatching (a1, b2) (a2, b1) - getMatching (a1, b1) (a2, b2), p1, p2)

main = do
    getLine
    s <- getLine
    t <- getLine
    let positions = getPositions s t
    let entries = zip (keys positions) (elems positions)
    let (delta, p1, p2) = findBest entries
    putStrLn $ show (getDifference s t - delta)
    putStrLn $ show p1 ++ " " ++ show p2


You are given two integers $$$n$$$ and $$$m$$$. Find the $$$\operatorname{MEX}$$$ of the sequence $$$n \oplus 0, n \oplus 1, \ldots, n \oplus m$$$. Here, $$$\oplus$$$ is the bitwise XOR operator.$$$\operatorname{MEX}$$$ of the sequence of non-negative integers is the smallest non-negative integer that doesn't appear in this sequence. For example, $$$\operatorname{MEX}(0, 1, 2, 4) = 3$$$, and $$$\operatorname{MEX}(1, 2021) = 0$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 30\,000$$$)  — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$0 \le n, m \le 10^9$$$).

For each test case, print a single integer  — the answer to the problem.

NoteIn the first test case, the sequence is $$$3 \oplus 0, 3 \oplus 1, 3 \oplus 2, 3 \oplus 3, 3 \oplus 4, 3 \oplus 5$$$, or $$$3, 2, 1, 0, 7, 6$$$. The smallest non-negative integer which isn't present in the sequence i. e. the $$$\operatorname{MEX}$$$ of the sequence is $$$4$$$.In the second test case, the sequence is $$$4 \oplus 0, 4 \oplus 1, 4 \oplus 2, 4 \oplus 3, 4 \oplus 4, 4 \oplus 5, 4 \oplus 6$$$, or $$$4, 5, 6, 7, 0, 1, 2$$$. The smallest non-negative integer which isn't present in the sequence i. e. the $$$\operatorname{MEX}$$$ of the sequence is $$$3$$$.In the third test case, the sequence is $$$3 \oplus 0, 3 \oplus 1, 3 \oplus 2$$$, or $$$3, 2, 1$$$. The smallest non-negative integer which isn't present in the sequence i. e. the $$$\operatorname{MEX}$$$ of the sequence is $$$0$$$.

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

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

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

testCase :: Scanner String
testCase = show . solve <$> pair integer integer

solve :: (Integer, Integer) -> Integer
solve (n, m) = xor n . either id id $ foldM update n [62, 61 .. 0]
  where
    update n b
      | nb == mb = Right n
      | mb = Right $ n `setBit` b
      | otherwise = Left n
      where
        nb = n `testBit` b
        mb = (m + 1) `testBit` b

-- 1 + smallest i st. n xor i >= m

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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

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

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

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

testCase :: Scanner String
testCase = show . solve <$> pair integer integer

solve :: (Integer, Integer) -> Integer
solve (n, m) =
  case foldM update n [62, 61 .. 0] of
    Left x -> xor n x
    Right x -> xor n x + 1
  where
    update n b
      | nb == mb = Right n
      | mb = Right $ n `setBit` b
      | otherwise = Left n
      where
        nb = n `testBit` b
        mb = m `testBit` b

-- 1 + smallest i st. n xor i >= m

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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


You are given four integers $$$a$$$, $$$b$$$, $$$x$$$ and $$$y$$$. Initially, $$$a \ge x$$$ and $$$b \ge y$$$. You can do the following operation no more than $$$n$$$ times:  Choose either $$$a$$$ or $$$b$$$ and decrease it by one. However, as a result of this operation, value of $$$a$$$ cannot become less than $$$x$$$, and value of $$$b$$$ cannot become less than $$$y$$$. Your task is to find the minimum possible product of $$$a$$$ and $$$b$$$ ($$$a \cdot b$$$) you can achieve by applying the given operation no more than $$$n$$$ times.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The only line of the test case contains five integers $$$a$$$, $$$b$$$, $$$x$$$, $$$y$$$ and $$$n$$$ ($$$1 \le a, b, x, y, n \le 10^9$$$). Additional constraint on the input: $$$a \ge x$$$ and $$$b \ge y$$$ always holds.

For each test case, print one integer: the minimum possible product of $$$a$$$ and $$$b$$$ ($$$a \cdot b$$$) you can achieve by applying the given operation no more than $$$n$$$ times.

NoteIn the first test case of the example, you need to decrease $$$b$$$ three times and obtain $$$10 \cdot 7 = 70$$$.In the second test case of the example, you need to decrease $$$a$$$ one time, $$$b$$$ one time and obtain $$$11 \cdot 7 = 77$$$.In the sixth test case of the example, you need to decrease $$$a$$$ five times and obtain $$$5 \cdot 11 = 55$$$.In the seventh test case of the example, you need to decrease $$$b$$$ ten times and obtain $$$10 \cdot 1 = 10$$$.

import Control.Monad

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [a, b, x, y, n] <- map read . words <$> getLine
    let
      (a1, b1)
        | a - x >= n = (a - n, b)
        | b - y >= n - (a - x) = (x, b - (n - (a - x)))
        | otherwise = (x, y)
      (a2, b2)
        | b - y >= n = (a, b - n)
        | a - x >= (n - (b - y)) = (a - (n - (b - y)), y)
        | otherwise = (x, y)
      ans = min (a1 * b1) (a2 * b2)

    putStrLn $ show ans

{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
module Main (main) where
import System.IO
import Data.Ord
import Data.Int
import Data.Bits
import Data.Char
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Class
import Control.Monad.Trans.State.Strict (StateT)
import qualified Control.Monad.Trans.State.Strict as StateT
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as C

getNewLine :: SIO ByteString
getNewLine = (lift $ C.hGetLine stdin) >>= (\z -> let x = C.dropWhile isSpace z in if C.null x then getNewLine else return x)

getRemain :: ByteString -> SIO ByteString
getRemain b = let bns = C.dropWhile isSpace b in
                if C.null bns then getNewLine >>= liftM2 (>>=) StateT.put (const . return)
                else return bns

data HInt
data HInt64
data HNormal
data HString
data HList

type SIO a = StateT ByteString IO a

class IOInteract a where
    convert :: ByteString -> (a, ByteString)
    toShowS :: a -> String -> String
    toShow :: a -> String
    toShow x = toShowS x []

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

type family IOType x where
    IOType Int = HInt
    IOType Int64 = HInt64
    IOType String = HString
    IOType [x] = HList
    IOType x = HNormal

class IOInteractp flag a where
    convertp :: flag -> ByteString -> (a, ByteString)
    toShowSp :: flag -> a -> String -> String

instance (Show a, Read a) => IOInteractp HNormal a where
    convertp _ x = let (a, b) = C.break isSpace x in (read $ C.unpack a, b)
    toShowSp _ x = shows x

instance IOInteractp HInt Int where
    convertp _ x = fromMaybe (error "parse") $ C.readInt x
    toShowSp _ x = shows x

instance IOInteractp HInt64 Int64 where
    convertp _ x = let (a, b) = fromMaybe (error "parse") $ C.readInteger x in (fromIntegral a, b)
    toShowSp _ x = shows x

instance IOInteractp HString String where
    convertp _ x = let (a, b) = C.break isSpace x in (C.unpack a, b)
    toShowSp _ x = showString x

instance (IOInteract a) => IOInteractp HList [a] where
    convertp _ x = let (a, b) = convert x in ([a], b)
    toShowSp _ [] = id
    toShowSp _ (x : []) = toShowS x
    toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs

get :: IOInteract a => SIO a
get = uncurry (flip (liftM2 seq . StateT.put) . return) =<< fmap convert . getRemain =<< StateT.get
put :: IOInteract a => a -> SIO ()
put = lift . (hPutStr stdout) . toShow
putln :: IOInteract a => a -> SIO ()
putln = lift . (hPutStrLn stdout) . toShow
flush :: SIO ()
flush = lift (hFlush stdout)

main :: IO ()
main = StateT.evalStateT main_ C.empty

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

f1 :: SIO ()
f1 = do
  (a, b, x, y, n) <- liftM5 (,,,,) get get get get get
  putln $ f2 a b x y n

f2 :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
f2 a b x y n = let n1 = a - x in let n2 = b - y in
              let v1 = if n > n1 then x * (if n - n1 > n2 then y else (b - (n - n1))) else (a - n) * b in
              let v2 = if n > n2 then y * (if n - n2 > n1 then x else (a - (n - n2))) else a * (b - n) in
              min v1 v2

import Control.Monad ( replicateM_ )

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [a,b,x,y,n] <- map read . words <$> getLine
    let
      s1 = a - x
      s2 = b - y
      t1 = if  (n <= s1)  then  (a-n)*b
        else  if  (n <= s1 + s2)  then  x*(b-(n-s1))
        else  x*y
      t2 = if  (n <= s2)  then  a*(b-n)
        else  if  (n <= s1 + s2)  then  (a-(n-s2))*y
        else  x*y
    print (min t1 t2 :: Integer)


A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.

The first line of the input contains an integer n (1 ≤ n ≤ 100 000) — the length of the string s. The second line contains the string s of length n consisting of only lowercase English letters.

If it's impossible to change the string s such that all its substring are distinct print -1. Otherwise print the minimum required number of changes.

NoteIn the first sample one of the possible solutions is to change the first character to 'b'.In the second sample, one may change the first character to 'a' and second character to 'b', so the string becomes "abko".

import Data.List (group, sort)
main = getLine >> getLine >>= (\x -> do
  let cs = (group . sort) x
  print $ if length x > 26 then -1 else length x - length cs)

import Data.List

main :: IO()
main = do
    sn <- getLine
    let n = read sn
    s <- getLine
    print $ solve n s

solve :: Int -> String -> Int
solve n s | n > 26 = -1
          | otherwise = n - length (nub s)

import qualified Data.ByteString.Char8 as B
import Control.Arrow
import Data.Char

main = print =<< (\(x,y) -> if x+y <= 26 then x else -1) . (sum &&& length)  . map (pred . B.length ) . B.group . B.sort .  B.filter isLower <$> (B.getLine >> B.getLine)

{-# OPTIONS_GHC -fno-warn-tabs #-}
import Data.List;
import System.IO;
import Data.Maybe;

solve :: String -> String -> Int;
solve [] a = length a;
solve s a
	| length s > 26 = -1
	| elem (head s) a = solve (tail s) a
	| otherwise = solve (tail s) ((head s):a);

main = do
	getLine;
	str <- getLine;
	if(solve str "" == (-1))
		then print (-1)
		else print (length str - solve str "");

import Data.List
main = do
  n <- readLn
  s <- getLine
  let ls = length $ group $ sort s
  print $ if n > 26 then -1 else n - ls

import Data.List
main = do
  n <- readLn
  if n > 26 then print (-1)
  else getLine >>= print.solve

solve :: String -> Int
solve cs = sum.map (pred.length).group$ sort cs

import Data.List( nub)
main = do
    tokens <- return . words =<< getContents
    let n = read $ tokens!!0
        str = tokens!!1
    if n>26 then print (negate 1) else print $ n - length (nub str)

import Data.List
main = do
        tmp <- getLine
        str <- getLine
        let n = read tmp::Int
        if n > 26 then
            putStrLn "-1"
        else
            putStrLn $ show ((length str) - (length $ nub str))

import Data.List(nub)
import Control.Arrow

solve =
    (\x -> case x of {
        (_, y) | y > 26 -> (-1);
        (x, y) -> y - x
    })
    . (length . nub &&& length)

main = getLine >> getLine >>= (print . solve)

import Data.List
main = do
    s <- getLine >> getLine
    let n = length . group . sort $ s
        ls = length s
    print $ if ls <= 26 then ls - n else -1

import Data.List (group, sort)
main = getLine >>= (\x -> do
  let cs = (group . sort) x
  print $ if length x > 26 then -1 else length cs - length x)

import Data.List (group, sort)
main = getLine >>= (\x -> do
  let cs = (group . sort) x
  print $ if length x > 26 then -1 else length x - length cs)

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

main = print =<< (\(x,y) -> if x+y <= 26 then x else -1) . (sum &&& length)  . map (pred . B.length ) . B.group . B.sort  <$> (B.getLine >> B.getLine)

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

main = print =<< (\(x,y) -> if x+y <= 26 then x else -1) . (sum &&& length)  . map (pred . B.length ) . B.group  <$> (B.getLine >> B.getLine)

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

main = print =<< (\(x,y) -> if x+y <= 26 then x else -1) . (sum &&& length)  . map (pred . B.length ) . B.group  <$> B.getLine <* B.getLine

import Data.List
main = do
  n <- readLn
  if n > 26 then print (-1)
  else getLine >>= print.solve

solve :: String -> Int
solve cs = go ['a'..'z'] $ sort cs
  where
    go rest (x:xs)
      | elem x rest = go (delete x rest) xs
      | otherwise = 1 + go (tail rest) xs
    go _ _ = 0

import Data.List(nub)
import Control.Arrow

solve =
    (\x -> case x of {
        (_, y) | y > 27 -> (-1);
        (x, y) -> y - x
    })
    . (length . nub &&& length)

main = getLine >> getLine >>= (print . solve)

import Data.List
main = do
    s <- getLine >> getLine
    let n = length . group . sort $ s
    print $ length s - n


Valera is a collector. Once he wanted to expand his collection with exactly one antique item.Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if he outbids the current price of one of the items in the auction (in other words, offers the seller the money that is strictly greater than the current price of the item at the auction), the seller of the object will immediately sign a contract with him.Unfortunately, Valera has only v units of money. Help him to determine which of the n sellers he can make a deal with.

The first line contains two space-separated integers n, v (1 ≤ n ≤ 50; 104 ≤ v ≤ 106) — the number of sellers and the units of money the Valera has. Then n lines follow. The i-th line first contains integer ki (1 ≤ ki ≤ 50) the number of items of the i-th seller. Then go ki space-separated integers si1, si2, ..., siki (104 ≤ sij ≤ 106) — the current prices of the items of the i-th seller.

In the first line, print integer p — the number of sellers with who Valera can make a deal. In the second line print p space-separated integers q1, q2, ..., qp (1 ≤ qi ≤ n) — the numbers of the sellers with who Valera can make a deal. Print the numbers of the sellers in the increasing order.

NoteIn the first sample Valera can bargain with each of the sellers. He can outbid the following items: a 40000 item from the first seller, a 20000 item from the second seller, and a 10000 item from the third seller.In the second sample Valera can not make a deal with any of the sellers, as the prices of all items in the auction too big for him.

{-# LANGUAGE NPlusKPatterns #-}

module Main where

main :: IO ()
main = do
    [n, v] <- getVec
    s <- getVecN n
    output $ solve v $ map tail s

type Nat = Integer
type Vector = [Nat]
type Predicate a = a -> Bool
type Selector a = [a] -> [Nat]

getVec :: IO Vector
getVec = fmap readVec getLine

readVec :: String -> Vector
readVec = map read . words

getVecN :: Integer -> IO [Vector]
getVecN 0       = return []
getVecN (n + 1) = do
    vc  <- getVec
    vcs <- getVecN n
    return (vc : vcs)

solve :: Nat -> [Vector] -> [Nat]
solve v = countUpFilter (accepts v)

countUpFilter :: Predicate a -> Selector a
countUpFilter = countUpFilter' 1

countUpFilter' :: Nat -> Predicate a -> Selector a
countUpFilter' _ _ [] = []
countUpFilter' n p (a : as) = if p a
    then n : countUpFilter' (n + 1) p as
    else     countUpFilter' (n + 1) p as

accepts :: Nat -> Predicate Vector
accepts v = any (< v)

output :: Vector -> IO ()
output vecs = do
    print $ length vecs
    putStrLn $ unwords $ map show vecs

import Data.List

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

output :: [Int] -> IO()
output (a:ax) = putStrLn ((show a) ++ "\n" ++ (unwords (map show ax)))

solve :: [[Int]] -> [Int]
solve ([n, v]:a) =
    let ans = solve' a 1
    in ((length ans):ans)
    where solve' :: [[Int]] -> Int -> [Int]
          solve' []          _ = []
          solve' ((w:ws):ax) i | v > (minimum ws) = (i:(solve' ax (i + 1)))
                               | otherwise        = solve' ax (i + 1)

import Data.List
import Data.Function

main = interact $ unlines . map (unwords . map show) . getAns . map (map read . words) . lines

getAns :: [[Int]] -> [[Int]]
getAns ((_:v:_):xs) =
	let ans = map succ $ findIndices (any (<v) . tail) xs
	in [[length ans], ans]

import Data.List
import Data.Function

main = interact $ unlines . map (unwords . map show) . getAns . getArrays

getArrays :: String -> [[Int]]
getArrays = map (map read . words) . lines

getAns :: [[Int]] -> [[Int]]
getAns ((n:v:_):xs) =
	let ans = getSellers v $ zip [1..n] xs
	in [[length ans], ans]

getSellers :: Int -> [(Int, [Int])] -> [Int]
getSellers _ [] = []
getSellers v (x:xs) = if (any (<v) . tail . snd) x then (fst x) : getSellers v xs else getSellers v xs

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

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

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

main = do
  [n, v] <- getInts
  xss <- replicateM n $ tail <$> getInts

  let r = map snd $ filter (\(xs, _) -> any (< v) xs) $ zip xss [1..]
  print $ length r
  putStrLn $ unwords $ map show r

import Control.Monad

main = do
  (n:v:_) <- fmap (map read . words) getLine
  items <- forM [1..n] $ \i -> do is <- fmap (tail . map read . words) getLine; return (i,is)
  let _ = items :: [(Int,[Int])]
  let answer = [ i | (i,is) <- items, any (<v) is ]
  print $ length answer
  putStrLn $ unwords (map show answer)

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

import qualified    Data.ByteString.Char8 as C
import              Data.ByteString.Lazy.Builder
import              Data.Maybe
import              Data.Monoid
import              System.IO

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

main = do
    [n, v] <- getIntList
    ps <- replicateM n getIntList
    let qs = sol n v ps
    print $ length qs
    putStrLn $ foldr (\c s -> show c ++ (' ':s)) "" $ qs

sol n v ps = [i+1 | i <- [0..n-1], bs!!i]
    where
    bs = map bid ps
    bid (_:ss) =  or $ map (< v) ss

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

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

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

main = do
  [n, v] <- getInts
  xs <- zip [1..] <$> (replicateM n $ tail <$> getInts)
  let
    can (_,ss) = head (sort ss) < v
    xs' = map fst . filter can $ xs
   in putStrLn $ (show (length xs')) ++ "\n" ++ unwords (map show xs')

main :: IO ()
main = getContents >>= mapM_ (putStrLn . unwords . map show) . solve . map (map read . words) . lines

solve :: [[Int]] -> [[Int]]
solve ([_, v] : kss) = [ [ length is ], is ]
  where is = [ i | (i, _:ss) <- zip [1..] kss, any (<v) ss ]
solve _ = undefined

import Data.List (findIndices)
import Control.Monad (replicateM)
readInts = fmap (map read . words) getLine
main = do
  [n,v] <- readInts
  ks <- fmap (findIndices (any (< v)) . ([]:) . map tail) (replicateM n readInts)
  print (length ks)
  putStrLn $ unwords $ map show ks

module Main where

import Control.Monad

rv:: String -> (Int, Int)
rv str = let xs = map read $ words str in
                (head xs, xs !! 1)

rm:: String -> [Int]
rm str = map read $ words str

pa:: [Int] -> String
pa ans = show (length ans) ++ "\n" ++
            unwords (map show ans)

solve:: (Int, Int) -> [[Int]] -> [Int]
solve valera merchants = map fst $ filter buyable zmerchants where
            budget = snd valera
            zmerchants = zip [1..] $ map tail merchants
            buyable merchant = not $ null buyablegoods  where
                goods = snd merchant
                buyablegoods = filter (< budget) goods

main :: IO ()
main = do
        valera <- getLine
        merchants <- replicateM (fst $ rv valera) getLine
        putStrLn $ pa $ solve (rv valera) (map rm merchants)

import Control.Monad
import Data.List

main = do
    [n,v] <- fmap (map read . words) getLine
    sellers <- forM [1..n] (\_ -> fmap (tail . map read . words) getLine)
    let solution = solve sellers v
    print $ length solution
    putStrLn . intercalate " " . map show $ solution

solve :: [[Integer]] -> Integer -> [Integer]
solve sellers v = [ snd x | x <- pairs, deal (fst x) v ]
    where pairs = zip sellers [1..]

deal :: [Integer] -> Integer -> Bool
deal xs v = any (<v) xs

import Data.List

main = do
  [_,v] <- fmap(map read.words)getLine
  xss <- fmap(map(map read.tail.words).lines)getContents :: IO [[Int]]
  case findIndices (any (<v)) xss of
       [] -> putStrLn "0\n"
       xs -> do
         print $ length xs
         putStrLn.unwords.map(show.succ) $ xs

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

main=do
	[n,a]<-map read. words <$> getLine:: IO [Int]
	s<-map (minimum.tail) .map (map read). map words. lines <$> getContents:: IO [Int]
	let t=  map snd $ filter (\z->fst z <a) $ zip s [1..]
	print $ length t
        putStrLn $ intercalate " " $ map show t

main :: IO ()
main = interact selesaian

selesaian :: String -> String
selesaian s = let
    (kep:ekor) = angkaify s
    [_, v]     = kep
    beli       = dibeli v ekor
    -- Jawaban Disini
    in show (length beli)
    ++ "\n"
    ++ (unwords . map show) beli
    ++ "\n"

angkaify :: String -> [[Int]]
angkaify = map (map read . words) . lines

lolos :: Int -> [Int] -> Bool
lolos n = any (< n) . tail

asli :: [Int]
asli = [1..]

dibeli :: Int -> [[Int]] -> [Int]
dibeli v = map fst . filter (lolos v . snd) . zip asli

main :: IO ()
main = interact selesaian

nat :: [Int]
nat = [1..]

selesaian :: String -> String
selesaian s = let
    baris = lines s
    (kep:ekor) = angkaify baris
    (_:v:_) = kep
    beli =  map snd . filter (\(x, _) -> lolos v x) $ zip ekor nat
    in show (length beli)
    ++ "\n"
    ++ (unwords . map show) beli
    ++ "\n"

angkaify :: [String] -> [[Int]]
angkaify = map (map read . words)

lolos :: Int -> [Int] -> Bool
lolos n xs = any (< n) $ tail xs

main :: IO ()
main = interact selesaian

selesaian :: String -> String
selesaian s = let
    baris = lines s
    (kep:ekor) = angkaify baris
    (_:v:_) = kep
    beli =  map snd . filter (\(x, _) -> lolos v x) $ zip ekor [1..]
    in show (length beli)
    ++ "\n"
    ++ (unwords . map show) beli
    ++ "\n"

angkaify :: [String] -> [[Integer]]
angkaify = map (map read . words)

lolos :: Integer -> [Integer] -> Bool
lolos n xs = any (< n) $ tail xs

{-# LANGUAGE NPlusKPatterns #-}

module Main where

main :: IO ()
main = do
    [n, v] <- getVec
    s <- getVecN n
    output $ solve v $ map tail s

type Nat = Integer
type Vector = [Nat]
type Predicate a = a -> Bool

getVec :: IO Vector
getVec = fmap readVec getLine

readVec :: String -> Vector
readVec = map read . words

getVecN :: Integer -> IO [Vector]
getVecN 0       = return []
getVecN (n + 1) = do
    vc  <- getVec
    vcs <- getVecN n
    return (vc : vcs)

solve :: Nat -> [Vector] -> [Nat]
solve v = countUp . filter (accepts v)

countUp :: [a] -> [Nat]
countUp = countUp' 1

countUp' :: Nat -> [a] -> [Nat]
countUp' _ [] = []
countUp' n (_ : as) = n : countUp' (n + 1) as

accepts :: Nat -> Predicate Vector
accepts v = any (< v)

output :: Vector -> IO ()
output vecs = do
    print $ length vecs
    putStrLn $ unwords $ map show vecs

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

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

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

main = do
  [n, v] <- getInts
  xs <- replicateM n $ do {(k:ss) <- getInts; return (k, ss);}
  let
    can (_,ss) = head (sort ss) < v
    xs' = map fst . filter can $ xs
   in putStrLn $ (show (length xs')) ++ "\n" ++ unwords (map show xs')

module Main where

import Control.Monad

rv:: String -> (Int, Int)
rv str = let xs = map read $ words str in
                (head xs, xs !! 1)

rm:: String -> [Int]
rm str = map read $ words str

pa:: [Int] -> String
pa ans = show (length ans) ++ "\n" ++
            unwords (map show ans)

solve:: (Int, Int) -> [[Int]] -> [Int]
solve valera merchants = map fst $ filter buyable zmerchants where
            budget = snd valera
            zmerchants = zip [1..] $ map tail merchants
            buyable merchant = not $ null buyablegoods  where
                goods = snd merchant
                buyablegoods = filter (< budget) goods

main :: IO ()
main = do
        valera <- getLine
        merchants <- replicateM (fst $ rv valera) getLine
        print $ pa $ solve (rv valera) (map rm merchants)

module Main where

import Control.Monad

rv:: String -> (Int, Int)
rv str = let xs = map read $ words str in
                (head xs, xs !! 1)

rm:: String -> [Int]
rm str = map read $ words str

pa:: [Int] -> String
pa ans = show (length ans) ++ "\n" ++
            unwords (map show ans)

solve:: (Int, Int) -> [[Int]] -> [Int]
solve valera merchants = map fst $ filter buyable zmerchants where
            budget = snd valera
            zmerchants = zip [1..] $ map tail merchants
            buyable merchant = not $ null buyablegoods  where
                goods = snd merchant
                buyablegoods = filter (< budget) goods

main :: IO ()
main = do
        valera <- getLine
        merchants <- replicateM (fst $ rv valera) getLine
        print $ solve (rv valera) (map rm merchants)

main :: IO ()
main = interact selesaian

selesaian :: String -> String
selesaian s = let
    baris = lines s
    (kep:ekor) = angkaify baris
    (_:v:_) = kep
    beli = map head . filter (lolos v) $ ekor
    in show (length beli)
    ++ "\n"
    ++ (unwords . map show) beli
    ++ "\n"

angkaify :: [String] -> [[Int]]
angkaify = map (map read . words)

lolos :: Int -> [Int] -> Bool
lolos n xs = any (< n) $ tail xs

main :: IO ()
main = interact selesaian

selesaian :: String -> String
selesaian s = let
    baris = lines s
    (kep:ekor) = angkaify baris
    (_:v:_) = kep
    beli = map head . filter (lolos v) $ ekor
    in show (length beli)
    ++ "\n"
    ++ (unwords . map show) beli
    ++ "\n"

angkaify :: [String] -> [[Integer]]
angkaify = map (map read . words)

lolos :: Integer -> [Integer] -> Bool
lolos n xs = any (< n) $ tail xs


The sequence of $$$m$$$ integers is called the permutation if it contains all integers from $$$1$$$ to $$$m$$$ exactly once. The number $$$m$$$ is called the length of the permutation.Dreamoon has two permutations $$$p_1$$$ and $$$p_2$$$ of non-zero lengths $$$l_1$$$ and $$$l_2$$$.Now Dreamoon concatenates these two permutations into another sequence $$$a$$$ of length $$$l_1 + l_2$$$. First $$$l_1$$$ elements of $$$a$$$ is the permutation $$$p_1$$$ and next $$$l_2$$$ elements of $$$a$$$ is the permutation $$$p_2$$$. You are given the sequence $$$a$$$, and you need to find two permutations $$$p_1$$$ and $$$p_2$$$. If there are several possible ways to restore them, you should find all of them. (Note that it is also possible that there will be no ways.)

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) denoting the number of test cases in the input. Each test case contains two lines. The first line contains one integer $$$n$$$ ($$$2 \leq n \leq 200\,000$$$): the length of $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq n-1$$$). The total sum of $$$n$$$ is less than $$$200\,000$$$.

For each test case, the first line of output should contain one integer $$$k$$$: the number of ways to divide $$$a$$$ into permutations $$$p_1$$$ and $$$p_2$$$. Each of the next $$$k$$$ lines should contain two integers $$$l_1$$$ and $$$l_2$$$ ($$$1 \leq l_1, l_2 \leq n, l_1 + l_2 = n$$$), denoting, that it is possible to divide $$$a$$$ into two permutations of length $$$l_1$$$ and $$$l_2$$$ ($$$p_1$$$ is the first $$$l_1$$$ elements of $$$a$$$, and $$$p_2$$$ is the last $$$l_2$$$ elements of $$$a$$$). You can print solutions in any order.

NoteIn the first example, two possible ways to divide $$$a$$$ into permutations are $$$\{1\} + \{4, 3, 2, 1\}$$$ and $$$\{1,4,3,2\} + \{1\}$$$.In the second example, the only way to divide $$$a$$$ into permutations is $$$\{2,4,1,3\} + \{2,1\}$$$.In the third example, there are no possible ways.

import Control.Arrow
import Data.List (sort)

main = interact $
  lines >>> drop 1
  >>> map (words >>> map read)
  >>> process
  >>> map (map show >>> unwords) >>> unlines

process :: [[Int]] -> [[Int]]
process [] = []
process ([n]:a:ps) = solve n a ++ process ps

solve :: Int -> [Int] -> [[Int]]
solve n a
  | length ans > 2 = [[0]]
  | and (map (check a) ans) = [length ans] : ans
  | otherwise = [[0]]
  where
    ans =
      map(\(i, _, _) -> [i, n - i])
        $ filter (\(i, (mnl, mxl), (mnr, mxr)) ->
                    mnl == 1 && mnr == 1 && mxl == i && mxr == n - i)
          $ zip3 [1..]
            (zip (scanl1 min a) (scanl1 max a))
            $ tail (zip (scanr1 min a) (scanr1 max a))

check a [l,_] = valid (take l a) && valid (drop l a)
  where
    valid a = and $ zipWith (==) (sort a) [1..]

import Control.Monad
import Data.List

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

routine :: IO ()
routine = do
    n <- readLn
    xs <- (map read.words) <$> getLine
    putStr $ solve n xs

getOptions :: Int -> [Int] -> [Int]
getOptions n xs = nub [m,n-m]
  where
    m = maximum xs

solve :: Int -> [Int] -> String
solve n xs= unlines $ (show k) : c
  where
    a = filter (check xs) (getOptions n xs)
    k = length a
    b = map (\x -> [x,n-x]) a
    c =  map (unwords.map show) b

checkPerm :: [Int] -> Bool
checkPerm perm = and $ zipWith (==) (sort perm) [1..]

check :: [Int] -> Int -> Bool
check xs l1 = (checkPerm (take l1 xs)) && (checkPerm (drop l1 xs))

import Control.Arrow
import Data.List (sort)

main = interact $
  lines >>> drop 1
  >>> map (words >>> map read)
  >>> process
  >>> map (map show >>> unwords) >>> unlines

process :: [[Int]] -> [[Int]]
process [] = []
process ([n]:a:ps) = solve n a ++ process ps

solve :: Int -> [Int] -> [[Int]]
solve n a
  | length ans > 2 = [[0]]
  | null ans = [[0]]
  | let l = head (last ans) in sort (take l a) /= [1..l] = [[0]]
  | otherwise = [length ans] : ans
  where
    ans =
      map(\(i, _, _) -> [i, n - i])
        $ filter (\(i, (mnl, mxl), (mnr, mxr)) ->
                    mnl == 1 && mnr == 1 && mxl == i && mxr == n - i)
          $ zip3 [1..]
            (zip (scanl1 min a) (scanl1 max a))
            $ tail (zip (scanr1 min a) (scanr1 max a))

import Control.Monad
import Data.List

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

routine :: IO ()
routine = do
    n <- readLn
    xs <- (map read.words) <$> getLine
    putStr $ solve n xs

getOptions :: Int -> [Int] -> [Int]
getOptions n xs = [m,n-m]
  where
    m = maximum xs

solve :: Int -> [Int] -> String
solve n xs= unlines $ (show k) : c
  where
    a = filter (check xs) (getOptions n xs)
    k = length a
    b = map (\x -> [x,n-x]) a
    c =  map (unwords.map show) b

checkPerm :: [Int] -> Bool
checkPerm perm = and $ zipWith (==) (sort perm) [1..]

check :: [Int] -> Int -> Bool
check xs l1 = (checkPerm (take l1 xs)) && (checkPerm (drop l1 xs))