Sam is a kindergartener, and there are $$$n$$$ children in his group. He decided to create a team with some of his children to play "brawl:go 2".Sam has $$$n$$$ power-ups, the $$$i$$$-th has type $$$a_i$$$. A child's strength is equal to the number of different types among power-ups he has.For a team of size $$$k$$$, Sam will distribute all $$$n$$$ power-ups to $$$k$$$ children in such a way that each of the $$$k$$$ children receives at least one power-up, and each power-up is given to someone.For each integer $$$k$$$ from $$$1$$$ to $$$n$$$, find the minimum sum of strengths of a team of $$$k$$$ children Sam can get.

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 3 \cdot 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$).  The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — types of Sam's power-ups. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$3 \cdot 10^5$$$.

For every test case print $$$n$$$ integers. The $$$k$$$-th integer should be equal to the minimum sum of strengths of children in the team of size $$$k$$$ that Sam can get.

import Control.Monad
import Data.List
import Data.Containers.ListUtils

solve = do
  n <- readLn :: IO Int
  arr <- map (read::String -> Int) . words <$> getLine
  let cnt = length $ nubInt arr
  forM [1..n] (\a -> do putStr $ show (max a cnt) ++ " ")

main = do
n <- readLn::IO Int
forM [1..n] (\t -> do solve)


A one-dimensional Japanese crossword can be represented as a binary string of length x. An encoding of this crossword is an array a of size n, where n is the number of segments formed completely of 1's, and ai is the length of i-th segment. No two segments touch or intersect.For example:   If x = 6 and the crossword is 111011, then its encoding is an array {3, 2};  If x = 8 and the crossword is 01101010, then its encoding is an array {2, 1, 1};  If x = 5 and the crossword is 11111, then its encoding is an array {5};  If x = 5 and the crossword is 00000, then its encoding is an empty array. Mishka wants to create a new one-dimensional Japanese crossword. He has already picked the length and the encoding for this crossword. And now he needs to check if there is exactly one crossword such that its length and encoding are equal to the length and encoding he picked. Help him to check it!

The first line contains two integer numbers n and x (1 ≤ n ≤ 100000, 1 ≤ x ≤ 109) — the number of elements in the encoding and the length of the crossword Mishka picked. The second line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 10000) — the encoding.

Print YES if there exists exaclty one crossword with chosen length and encoding. Otherwise, print NO.

module Main where

import Control.Applicative
import Control.Monad

data Problem = Problem { target :: Integer
                       , parts :: [Integer]
                       } deriving (Show, Eq)

singleton :: Problem -> Bool
singleton (Problem n []) = True
singleton (Problem n ps) = sum ps + (pred . fromIntegral $ length ps) == n

test0 = Problem{target = 4, parts = [1, 3]}
test1 = Problem{target = 10, parts = [3, 3, 2]}
test2 = Problem{target = 10, parts = [1, 3]}

main :: IO ()
main = do
  [n, t] <- map read . words <$> getLine
  ps <- map read . words <$> getLine
  let problem = Problem { target = t, parts = ps }
  putStrLn $ if singleton problem then "YES" else "NO"

import Data.Maybe
import qualified Data.ByteString.Char8 as BS8

getInts = (map parseInteger . BS8.words) `fmap` BS8.getLine :: IO [Integer]
parseInteger = fst . fromJust . BS8.readInteger

main = do
    [n,x] <- getInts
    as <- getInts
    if (sum as + (n-1) == x)
    then putStrLn "YES"
    else putStrLn "NO"

import Data.Bool
main = getContents >>= putStr . exec
exec = bool "NO" "YES" . solve . map read . words
solve (n:k:xs) = sum xs - (1 :: Int) + n == k

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

solve :: [Int] -> IO ()
solve (n:x:a) = putStrLn (if x == sum a + n - 1 then  "YES" else "NO")

import Data.Maybe
import qualified Data.ByteString.Char8 as BS8

getInts = (map parseInteger . BS8.words) `fmap` BS8.getLine :: IO [Integer]
parseInteger = fst . fromJust . BS8.readInteger

main = do
    [n,x] <- getInts
    as <- getInts
    if (sum as + (n-1) == x) || (sum as + (n+1) == x)
    then putStrLn "YES"
    else putStrLn "NO"

import Data.Bool
main = getContents >>= print . exec
exec = bool "NO" "YES" . solve . map read . words
solve (n:k:xs) = sum xs - (1 :: Int) + n == k


There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl.

The first line contains two positive space-separated integers, n and k (1 ≤ k ≤ n ≤ 2·105) — the initial number of cities in Westeros and the number of cities at which the game ends.  The second line contains n space-separated positive integers ai (1 ≤ ai ≤ 106), which represent the population of each city in Westeros.

Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins.

NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins.

import Control.Applicative ((<$>), liftA)
import Data.Bits ((.&.))
import Data.Foldable (foldl')
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8

stan = "Stannis" :: String  -- goes first
dan = "Daenerys" :: String  -- even

parity :: Int -> Int -> Int -> String
parity n k odd
    | n == k = if odd .&. 1 == 1 then stan else dan -- end of game
    | odd < j + 1 = dan -- remove all odds
    | k .&. 1 == 1 && n - odd < i + 1 = stan  -- remove all even
    | k .&. 1 == 0 && n - odd < j + 1 = dan  -- remove all even
    | odd .&. 1 == 0 && n .&. 1 == 0 && i == j = dan  -- dan can pair out
    | j < i  && j < min n (n - odd) = stan -- stan will decide ultimately
    | j == i && i < n - odd = dan -- dan will decide ultimately
    | otherwise = stan
    where
    j = (n - k) `div` 2
    i = n - k - j

parse :: C8.ByteString -> Maybe [Int]
parse = liftA (fst <$>) . sequence . fmap C8.readInt . C8.words

oddCount :: [Int] -> Int
oddCount = foldl' loop 0
    where
    loop n i | i .&. 1 == 1 = n + 1
             | otherwise = n

main :: IO ()
main = fmap read . words <$> getLine >>= \[n, k] ->
     liftA oddCount . parse <$> B.getLine >>= \(Just odd) ->
        putStrLn $ parity n k odd

import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.Array as Arr
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import Data.List
import Control.Applicative
import Control.Monad
import Data.Function

readInt = fst . fromJust . B.readInt

solve (_ : k : cities) =
  if k == length cities
  then
    if odd odds then stannis else daenerys
  else
  let totalMoves = length cities - k in
  let stannisMoves = (totalMoves + 1) `div` 2 in
  let daenerysMoves = totalMoves - stannisMoves in
  if even totalMoves
  then
    -- Daenerys' last move: she wins if number of towns is even or if any even town remain
    if even k || stannisMoves < evens then daenerys else stannis
  else
    if (if even k
    then
      daenerysMoves < evens && daenerysMoves < odds
    else
      daenerysMoves < odds) then stannis else daenerys
  where
    odds = length (filter odd cities)
    evens = length (filter even cities)

stannis = B.pack "Stannis"
daenerys = B.pack "Daenerys"

main = B.interact $ solve . map readInt . B.words

import Data.Char (ord)
import Data.List
import Debug.Trace

type Input  = (Int, [Int])
type Output = Bool

readInt :: String -> Int
readInt = foldl' (\s d -> s * 10 + ord d - 48) 0

parse :: String -> Input
parse contents = (k, a)
                 where [[_, k], a] = map (map readInt . words) . lines $ contents

sum' :: [[Maybe Bool]] -> Bool
sum' = last . foldl' byRow (repeat False)
       where byRow p          = tail . scanl f True . zip p
             f _ (_, Just b)  = b
             f s (b, Nothing) = not s || not b

initVal :: Int -> Int -> Int -> Int -> Maybe Bool
initVal k p i j
    | i < 0 || j < 0 || i + j < k = Just True
    | i + j == k                  = Just (odd (j + p))
    | otherwise                   = Nothing

fastReduce :: Int -> Int -> Int -> Bool
fastReduce k n m
    | n >= 2 && m >= 2 && n + m >= k + 4 = fastReduce k (n - 1) (m - 1)
    | otherwise                          = sum' initVals
    where initVals = [[initVal k (n + m - k) i j | j <- [m0 .. m]] | i <- [n0 .. n]]
          n0       = max 0 (k - m) - 1
          m0       = max 0 (k - n) - 1

solve :: Input -> Output
solve (k, a) = fastReduce k (count even a) (count odd a)
               where count f = length . filter f

bool :: a -> a -> Bool -> a
bool f _ False = f
bool _ t True  = t

main :: IO ()
main = putStrLn . bool "Daenerys" "Stannis" . solve . parse =<< getContents

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array.ST
import Data.Bits
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Control.Applicative
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Function as F
import Debug.Trace

import qualified Numeric as N

readInt :: String -> Int
readInt ('-':s) = case N.readDec s of [(n, "")] -> -n
readInt s = case N.readDec s of [(n, "")] -> n

readFloat :: String -> Double
readFloat ('-':s) = case N.readFloat s of [(x, "")] -> -x
readFloat s = case N.readFloat s of [(x, "")] -> x

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

count acc [] = acc
count (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs

main = do
  [n, k] <- getInts
  (zeroes, ones) <- count (0, 0) <$> getInts
  putStrLn $ solve zeroes ones (n - k)

p2 = "Daenerys"
p1 = "Stannis"

solve _ ones 0 = if even ones then p2 else p1
solve zeroes ones moves =
  if
  | ones <= moves `div` 2 -> p2
  | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2
  | zeroes <= moves `div` 2, odd (ones - (moves - zeroes)) -> p1
  | even moves -> p2
  | otherwise -> p1

import Control.Applicative ((<$>), liftA)
import Data.Bits ((.&.))
import Data.Foldable (foldl')
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8

stan = "Stannis" :: String  -- goes first
dan = "Daenerys" :: String  -- even

parity :: Int -> Int -> Int -> String
parity n k odd
    | k .&. 1 == 0 || odd < j + 1 = dan -- remove all odds | k is even
    | n - odd < i + 1 = stan  -- remove all even
    | odd .&. 1 == 0 && n .&. 1 == 0 && i == j = dan  -- dan can pair out
    | j < i  && j < min n (n - odd) = stan -- stan will decide ultimately
    | j == i && i < min n (n - odd) = dan -- dan will decide ultimately
    | otherwise = stan
    where
    j = (n - k) `div` 2
    i = n - k - j

parse :: C8.ByteString -> Maybe [Int]
parse = liftA (fst <$>) . sequence . fmap C8.readInt . C8.words

oddCount :: [Int] -> Int
oddCount = foldl' loop 0
    where
    loop n i | i .&. 1 == 1 = n + 1
             | otherwise = n

main :: IO ()
main = fmap read . words <$> getLine >>= \[n, k] ->
     liftA oddCount . parse <$> B.getLine >>= \(Just odd) ->
        putStrLn $ parity n k odd

import Control.Applicative ((<$>), liftA)
import Data.Bits ((.&.))
import Data.Foldable (foldl')
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8

stan = "Stannis" :: String  -- goes first
dan = "Daenerys" :: String  -- even

parity :: Int -> Int -> Int -> String
parity n k odd
    | n == k = if odd .&. 1 == 1 then stan else dan -- end of game
    | k .&. 1 == 0 && odd < j + 1 = dan -- remove all odds & k is even
    | k .&. 1 == 1 && n - odd < i + 1 = stan  -- remove all even
    | odd .&. 1 == 0 && n .&. 1 == 0 && i == j = dan  -- dan can pair out
    | j < i  && j < min n (n - odd) = stan -- stan will decide ultimately
    | j == i && i < n - odd = dan -- dan will decide ultimately
    | otherwise = stan
    where
    j = (n - k) `div` 2
    i = n - k - j

parse :: C8.ByteString -> Maybe [Int]
parse = liftA (fst <$>) . sequence . fmap C8.readInt . C8.words

oddCount :: [Int] -> Int
oddCount = foldl' loop 0
    where
    loop n i | i .&. 1 == 1 = n + 1
             | otherwise = n

main :: IO ()
main = fmap read . words <$> getLine >>= \[n, k] ->
     liftA oddCount . parse <$> B.getLine >>= \(Just odd) ->
        putStrLn $ parity n k odd

import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.Array as Arr
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import Data.List
import Control.Applicative
import Control.Monad
import Data.Function

readInt = fst . fromJust . B.readInt

solve (_ : k : cities) =
  let totalMoves = length cities - k in
  let stannisMoves = (totalMoves + 1) `div` 2 in
  let daenerysMoves = totalMoves - stannisMoves in
  if even totalMoves
  then
    -- Daenerys' last move: she wins if number of towns is even or if any even town remain
    if even k || stannisMoves < evens then daenerys else stannis
  else
    if (if even k
    then
      daenerysMoves < evens && daenerysMoves < odds
    else
      daenerysMoves < odds) then stannis else daenerys
  where
    odds = length (filter odd cities)
    evens = length (filter even cities)

stannis = B.pack "Stannis"
daenerys = B.pack "Daenerys"

main = B.interact $ solve . map readInt . B.words

type Input  = (Int, [Int])
type Output = Bool

parse :: String -> Input
parse contents = (k, a)
                 where [[_, k], a] = map (map read . words) . lines $ contents

solveCase :: Int -> Bool -> Int -> Int -> Bool
solveCase k f e o
    | e < 0 || o < 0 = True
    | t == k         = f /= even o
    | t >= k + 4     = s (e - 1) (o - 1)
    | otherwise      = any not [s (e - 1) o, s e (o - 1)]
    where s = solveCase k (not f)
          t = e + o

solve :: Input -> Output
solve (m, a) = solveCase m True (count even a) (count odd a)
               where count f = length . filter f

bool :: a -> a -> Bool -> a
bool f _ False = f
bool _ t True  = t

main :: IO ()
main = putStrLn . bool "Daenerys" "Stannis" . solve . parse =<< getContents

import Data.Char (ord)
import Data.List
import Debug.Trace

type Input  = (Int, [Int])
type Output = Bool

readInt :: String -> Int
readInt = foldl' (\s d -> s * 10 + ord d - 48) 0

parse :: String -> Input
parse contents = (k, a)
                 where [[_, k], a] = map (map readInt . words) . lines $ contents

sum' :: [[Maybe Bool]] -> Bool
sum' = last . foldl' byRow (repeat False)
       where byRow p          = tail . scanl f True . zip p
             f _ (_, Just b)  = b
             f s (b, Nothing) = not s || not b

initVal :: Int -> Int -> Int -> Int -> Maybe Bool
initVal k p i j
    | i < 0 || j < 0 || i + j < k = Just True
    | i + j == k                  = Just (even (j + p))
    | otherwise                   = Nothing

fastReduce :: Int -> Int -> Int -> Bool
fastReduce k n m
    | n >= 2 && m >= 2 && n + m >= k + 4 = fastReduce k (n - 1) (m - 1)
    | otherwise                          = sum' initVals
    where initVals = [[initVal k (n + m) i j | j <- [k - n - 1 .. m]] | i <- [k - m - 1 .. n]]

solve :: Input -> Output
solve (k, a) = fastReduce k (count even a) (count odd a)
               where count f = length . filter f

bool :: a -> a -> Bool -> a
bool f _ False = f
bool _ t True  = t

main :: IO ()
main = putStrLn . bool "Daenerys" "Stannis" . solve . parse =<< getContents

type Input  = (Int, [Int])
type Output = Bool

parse :: String -> Input
parse contents = (k, a)
                 where [[_, k], a] = map (map read . words) . lines $ contents

solveCase :: Int -> Bool -> Int -> Int -> Bool
solveCase k f e o
    | t == k                         = f /= even o
    | t >= k + 4 && e >= 2 && o >= 2 = s (e - 1) (o - 1)
    | otherwise                      = any not moves
    where s     = solveCase k (not f)
          t     = e + o
          moves = [s (e - 1) o | e >= 1] ++ [s e (o - 1) | o >= 1]

solve :: Input -> Output
solve (m, a) = solveCase m True (count even a) (count odd a)
               where count f = length . filter f

bool :: a -> a -> Bool -> a
bool f _ False = f
bool _ t True  = t

main :: IO ()
main = putStrLn . bool "Daenerys" "Stannis" . solve . parse =<< getContents

import Data.Char (ord)

type Input  = (Int, [Int])
type Output = Bool

readInt :: String -> Int
readInt = foldr (\d s -> s * 10 + ord d - 48) 0

parse :: String -> Input
parse contents = (k, a)
                 where [[_, k], a] = map (map readInt . words) . lines $ contents

solveCase :: Int -> Bool -> Int -> Int -> Bool
solveCase k f e o
    | t == k                         = f /= even o
    | t >= k + 4 && e >= 2 && o >= 2 = solveCase k f (e - 1) (o - 1)
    | otherwise                      = any not moves
    where s     = solveCase k (not f)
          t     = e + o
          moves = [s (e - 1) o | e >= 1] ++ [s e (o - 1) | o >= 1]

solve :: Input -> Output
solve (m, a) = solveCase m True (count even a) (count odd a)
               where count f = length . filter f

bool :: a -> a -> Bool -> a
bool f _ False = f
bool _ t True  = t

main :: IO ()
main = putStrLn . bool "Daenerys" "Stannis" . solve . parse =<< getContents

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array.ST
import Data.Bits
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Control.Applicative
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Function as F
import Debug.Trace

import qualified Numeric as N

readInt :: String -> Int
readInt ('-':s) = case N.readDec s of [(n, "")] -> -n
readInt s = case N.readDec s of [(n, "")] -> n

readFloat :: String -> Double
readFloat ('-':s) = case N.readFloat s of [(x, "")] -> -x
readFloat s = case N.readFloat s of [(x, "")] -> x

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

count acc [] = acc
count (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs

main = do
  [n, k] <- getInts
  (zeroes, ones) <- count (0, 0) <$> getInts
  putStrLn $ solve zeroes ones (n - k)

p2 = "Daenerys"
p1 = "Stannis"

solve zeroes ones moves =
  if
  | ones <= moves `div` 2 -> p2
  | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2
  | otherwise -> p1

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array.ST
import Data.Bits
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Control.Applicative
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Function as F
import Debug.Trace

import qualified Numeric as N

readInt :: String -> Int
readInt ('-':s) = case N.readDec s of [(n, "")] -> -n
readInt s = case N.readDec s of [(n, "")] -> n

readFloat :: String -> Double
readFloat ('-':s) = case N.readFloat s of [(x, "")] -> -x
readFloat s = case N.readFloat s of [(x, "")] -> x

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

count acc [] = acc
count (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs

main = do
  [n, k] <- getInts
  (zeroes, ones) <- count (0, 0) <$> getInts
  putStrLn $ solve zeroes ones (n - k)

p2 = "Daenerys"
p1 = "Stannis"

solve _ ones 0 = if even ones then p2 else p1
solve zeroes ones moves =
  if
  | ones <= moves `div` 2 -> p2
  | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2
  | otherwise -> p1

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array.ST
import Data.Bits
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Control.Applicative
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Function as F
import Debug.Trace

import qualified Numeric as N

readInt :: String -> Int
readInt ('-':s) = case N.readDec s of [(n, "")] -> -n
readInt s = case N.readDec s of [(n, "")] -> n

readFloat :: String -> Double
readFloat ('-':s) = case N.readFloat s of [(x, "")] -> -x
readFloat s = case N.readFloat s of [(x, "")] -> x

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

count acc [] = acc
count (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs

main = do
  [n, k] <- getInts
  (zeroes, ones) <- count (0, 0) <$> getInts
  putStrLn $ solve zeroes ones (n - k)

p2 = "Daenerys"
p1 = "Stannis"

solve _ ones 0 = if even ones then p2 else p1
solve zeroes ones moves =
  if
  | ones <= moves `div` 2 -> p2
  | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2
  | even moves -> p2
  | otherwise -> p1

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array.ST
import Data.Bits
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Control.Applicative
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Function as F
import Debug.Trace

import qualified Numeric as N

readInt :: String -> Int
readInt ('-':s) = case N.readDec s of [(n, "")] -> -n
readInt s = case N.readDec s of [(n, "")] -> n

readFloat :: String -> Double
readFloat ('-':s) = case N.readFloat s of [(x, "")] -> -x
readFloat s = case N.readFloat s of [(x, "")] -> x

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

count acc [] = acc
count (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs

main = do
  [n, k] <- getInts
  (zeroes, ones) <- count (0, 0) <$> getInts
  putStrLn $ solve zeroes ones (n - k)

p2 = "Daenerys"
p1 = "Stannis"

solve _ _ 0 = p2
solve zeroes ones moves =
  if
  | ones <= moves `div` 2 -> p2
  | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2
  | otherwise -> p1

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array.ST
import Data.Bits
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Control.Applicative
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Function as F
import Debug.Trace

import qualified Numeric as N

readInt :: String -> Int
readInt ('-':s) = case N.readDec s of [(n, "")] -> -n
readInt s = case N.readDec s of [(n, "")] -> n

readFloat :: String -> Double
readFloat ('-':s) = case N.readFloat s of [(x, "")] -> -x
readFloat s = case N.readFloat s of [(x, "")] -> x

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

count acc [] = acc
count (a, b) (x:xs) = count (if even x then (a + 1, b) else (a, b + 1)) xs

main = do
  [n, k] <- getInts
  (zeroes, ones) <- count (0, 0) <$> getInts
  putStrLn $ solve zeroes ones (n - k)

p2 = "Daenerys"
p1 = "Stannis"

solve _ ones 0 = if even ones then p2 else p1
solve zeroes ones moves =
  if
  | ones <= moves `div` 2 -> p2
  | zeroes <= moves `div` 2, even (ones - (moves - zeroes)) -> p2
  | moves `div` 2 == 0 -> p2
  | otherwise -> p1


This is an interactive problem.Bob lives in a square grid of size $$$n \times n$$$, with rows numbered $$$1$$$ through $$$n$$$ from top to bottom, and columns numbered $$$1$$$ through $$$n$$$ from left to right. Every cell is either allowed or blocked, but you don't know the exact description of the grid. You are given only an integer $$$n$$$.Bob can move through allowed cells but only in some limited directions. When Bob is in an allowed cell in the grid, he can move down or right to an adjacent cell, if it is allowed.You can ask at most $$$4 \cdot n$$$ queries of form "? $$$r_1$$$ $$$c_1$$$ $$$r_2$$$ $$$c_2$$$" ($$$1 \le r_1 \le r_2 \le n$$$, $$$1 \le c_1 \le c_2 \le n$$$). The answer will be "YES" if Bob can get from a cell $$$(r_1, c_1)$$$ to a cell $$$(r_2, c_2)$$$, and "NO" otherwise. In particular, if one of the two cells (or both) is a blocked cell then the answer is "NO" for sure. Since Bob doesn't like short trips, you can only ask queries with the manhattan distance between the two cells at least $$$n - 1$$$, i.e. the following condition must be satisfied: $$$(r_2 - r_1) + (c_2 - c_1) \ge n - 1$$$.It's guaranteed that Bob can get from the top-left corner $$$(1, 1)$$$ to the bottom-right corner $$$(n, n)$$$ and your task is to find a way to do it. You should print the answer in form "! S" where $$$S$$$ is a string of length $$$2 \cdot n - 2$$$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The down move increases the first coordinate by $$$1$$$, the right move increases the second coordinate by $$$1$$$. If there are multiple solutions, any of them will be accepted. You should terminate immediately after printing the solution.

The only line of the input contains an integer $$$n$$$ ($$$2 \le n \le 500$$$) — the size of the grid.

When you are ready to print the answer, print a single line containing "! S" where where $$$S$$$ is a string of length $$$2 \cdot n - 2$$$ consisting of characters 'D' and 'R', denoting moves down and right respectively. The path should be a valid path going from the cell $$$(1, 1)$$$ to the cell $$$(n, n)$$$ passing only through allowed cells.

NoteThe first example is shown on the picture below.  To hack, use the following input format:The first line should contain a single integer $$$n$$$ ($$$2 \le n \le 500$$$) — the size of the grid.Each of the next $$$n$$$ lines should contain a string of $$$n$$$ characters '#' or '.', where '#' denotes a blocked cell, and '.' denotes an allowed cell.For example, the following text encodes the example shown above:4..#.#...###.....

import System.IO

toint s = (read s) :: Int

doit0 n x y ss =
  if (n-x)+(n-y) <= n-1 then
    ("","")
  else
    let q = "? " ++ show x ++ " " ++ show (y+1) ++ " " ++ show n ++ " " ++ show n ++ "\n" in
    let a = head $ head ss in
    let (r0,r1) = if a == 'Y' then doit0 n x (y+1) (tail ss) else doit0 n (x+1) y (tail ss) in
    (q ++ r0, (if a == 'Y' then 'R' else 'D'): r1)

doit1 n x y ss =
  if (x-1) + (y-1) <= n-1 then
    ("","")
  else
    let q = "? 1 1 " ++ show (x-1) ++ " " ++ show y ++ "\n" in
    let a = head $ head ss in
    let (r0,r1) = if a == 'Y' then doit1 n (x-1) y (tail ss) else doit1 n x (y-1) (tail ss) in
    (q ++ r0, (if a == 'Y' then 'D' else 'R'): r1)

doit n ss =
  let r0 = doit0 n 1 1 ss in
  let r1 = doit1 n n n (drop (length $ snd r0) ss) in
  (fst r0) ++ (fst r1) ++ (
    "! " ++ (snd r0) ++ (reverse $ snd r1) ++ "\n"
  )

solve::String->String
solve ss =
  let (nn:s) = words ss in
  let n = toint nn in
  doit n s

main = do
    hSetBuffering stdout LineBuffering
    interact solve


Anton is growing a tree in his garden. In case you forgot, the tree is a connected acyclic undirected graph.There are n vertices in the tree, each of them is painted black or white. Anton doesn't like multicolored trees, so he wants to change the tree such that all vertices have the same color (black or white).To change the colors Anton can use only operations of one type. We denote it as paint(v), where v is some vertex of the tree. This operation changes the color of all vertices u such that all vertices on the shortest path from v to u have the same color (including v and u). For example, consider the tree  and apply operation paint(3) to get the following:  Anton is interested in the minimum number of operation he needs to perform in order to make the colors of all vertices equal.

The first line of the input contains a single integer n (1 ≤ n ≤ 200 000) — the number of vertices in the tree. The second line contains n integers colori (0 ≤ colori ≤ 1) — colors of the vertices. colori = 0 means that the i-th vertex is initially painted white, while colori = 1 means it's initially painted black. Then follow n - 1 line, each of them contains a pair of integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — indices of vertices connected by the corresponding edge. It's guaranteed that all pairs (ui, vi) are distinct, i.e. there are no multiple edges.

Print one integer — the minimum number of operations Anton has to apply in order to make all vertices of the tree black or all vertices of the tree white.

NoteIn the first sample, the tree is the same as on the picture. If we first apply operation paint(3) and then apply paint(6), the tree will become completely black, so the answer is 2.In the second sample, the tree is already white, so there is no need to apply any operations and the answer is 0.

-- Codeforces Round #379 (Div. 2)
-- http://codeforces.com/contest/734

-- ID: 734E (Anton and Tree)

import Control.Monad
import qualified Data.Sequence as Seq
import Data.Array
import Data.List
import Data.Maybe
import Data.Tuple (swap)
import Data.Foldable (toList)
import qualified Data.IntSet as Set
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

getInt = read `fmap` getLine :: IO Int
getInts = (map parseInt . BS8.words) `fmap` BS.getLine :: IO [Int]
parseInt = fst . fromJust . BS8.readInt
type Graph = Array Int [Int]

main = do
    n <- getInt
    colors <- listArray (1,n) `fmap` getInts
    edges <- replicateM (n-1) $ do
        [u,v] <- getInts
        return (u,v)
    let edges' = edges ++ (map swap edges)
    let g = accumArray (flip (:)) [] (1,n) edges'
    print $ (diameter g colors n + 1) `div` 2

preorder :: Graph -> Int -> [(Int,Int)]
preorder g start = toList $ bfs Seq.empty [(start,start)] where
    bfs nodes [] = nodes
    bfs nodes queue = bfs (nodes Seq.>< Seq.fromList queue) (concatMap nexts queue)
    nexts (v,parent) = map (\u -> (u,v)) $ filter (/= parent) (g ! v)

levels :: Graph -> Array Int Int -> Int -> Int -> Array Int Int
levels g colors start n = a where
    a = array (1, n) [findLevel v | v <- order]
    findLevel (v, parent)
        | v == parent = (v, 0)
        | colors ! v == colors ! parent = (v, a ! parent)
        | otherwise = (v, (a ! parent) + 1)
    order = preorder g start

maxLevel g colors start n
    = maximumBy (\a b -> compare (snd a) (snd b)) $ assocs $ levels g colors start n

diameter :: Graph -> Array Int Int -> Int -> Int
diameter g colors n = snd $ maxLevel g colors (fst $ maxLevel g colors 1 n) n

module Main where

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Array
import Data.Tuple
import Prelude
import qualified Data.ByteString.Lazy.Char8 as L

type Tokenizer = State [L.ByteString]

nextInt :: Tokenizer Int
nextInt = state $ \(s:ss) -> case L.readInt s of
                                   Just (x, _) -> (x, ss)
                                   Nothing -> error $ "Can't parse Int:" ++ (show s)

updateTwoMax :: (Int, Int) -> Int -> (Int, Int)
updateTwoMax (m1, m2) x | x >= m1   = (x, m1)
                        | x >= m2   = (m1, x)
                        | otherwise = (m1, m2)

combine :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int)
combine (s1, m11, m12) (s2, m21, m22) = (maxSum, max1, max2)
    where maxSum = s1 `max` s2 `max` (max1 + max2)
          (max1, max2) = (m11, m12) `updateTwoMax` m21

dfs :: Array Int [Int] -> Array Int Int -> Int -> Int -> (Int, Int, Int)
dfs g col root parent = foldl combine (0, 0, 0) (zipWith addEdge childrenRes childrenEdges)
    where childrenRes = [(dfs g col child root) | child <- g!root, child /= parent]
          childrenEdges = [f child root | child <- g!root, child /= parent]
          f u v | col!u == col!v = 0
                | otherwise      = 1
          addEdge (m, m1, m2) x = (m, m1 + x, m2 + x)

solve :: Tokenizer Int
solve = do
    n <- nextInt
    col <- listArray (0, n - 1) <$> replicateM n nextInt
    edges <- replicateM (n - 1) $ do
             u <- nextInt
             v <- nextInt
             return (u - 1, v - 1)
    let g = accumArray (flip (:)) [] (0, n - 1) (edges ++ (map swap edges))
    let (ans, _, _) = dfs g col 0 (-1)
    return $ (ans + 1) `div` 2

main = do
    contents <- L.getContents
    print $ evalState solve (L.words contents)


Lee couldn't sleep lately, because he had nightmares. In one of his nightmares (which was about an unbalanced global round), he decided to fight back and propose a problem below (which you should solve) to balance the round, hopefully setting him free from the nightmares.A non-empty array $$$b_1, b_2, \ldots, b_m$$$ is called good, if there exist $$$m$$$ integer sequences which satisfy the following properties:  The $$$i$$$-th sequence consists of $$$b_i$$$ consecutive integers (for example if $$$b_i = 3$$$ then the $$$i$$$-th sequence can be $$$(-1, 0, 1)$$$ or $$$(-5, -4, -3)$$$ but not $$$(0, -1, 1)$$$ or $$$(1, 2, 3, 4)$$$).  Assuming the sum of integers in the $$$i$$$-th sequence is $$$sum_i$$$, we want $$$sum_1 + sum_2 + \ldots + sum_m$$$ to be equal to $$$0$$$. You are given an array $$$a_1, a_2, \ldots, a_n$$$. It has $$$2^n - 1$$$ nonempty subsequences. Find how many of them are good.As this number can be very large, output it modulo $$$10^9 + 7$$$.An array $$$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 a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the size of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array.

Print a single integer — the number of nonempty good subsequences of $$$a$$$, modulo $$$10^9 + 7$$$.

NoteFor the first test, two examples of good subsequences are $$$[2, 7]$$$ and $$$[2, 2, 4, 7]$$$:For $$$b = [2, 7]$$$ we can use $$$(-3, -4)$$$ as the first sequence and $$$(-2, -1, \ldots, 4)$$$ as the second. Note that subsequence $$$[2, 7]$$$ appears twice in $$$[2, 2, 4, 7]$$$, so we have to count it twice.  Green circles denote $$$(-3, -4)$$$ and orange squares denote $$$(-2, -1, \ldots, 4)$$$. For $$$b = [2, 2, 4, 7]$$$ the following sequences would satisfy the properties: $$$(-1, 0)$$$, $$$(-3, -2)$$$, $$$(0, 1, 2, 3)$$$ and $$$(-3, -2, \ldots, 3)$$$

{-# LANGUAGE BangPatterns #-}
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

import Data.Bits
import Data.Int
import Data.Semigroup

p :: Int
p = 10 ^ (9 :: Int) + 7

p64 :: Int64
p64 = fromIntegral p

cv :: Int -> Int
cv x = x - if  x >= p  then  p  else  0

(+!) :: Int -> Int -> Int
infixl 6 +!
x +! y = cv $ x + y

(-!) :: Int -> Int -> Int
infixl 6 -!
x -! y = cv $ x + p - y

(*!) :: Int -> Int -> Int
infixl 7 *!
x *! y = fromIntegral $ fromIntegral x * fromIntegral y `rem` p64

newtype ProdP = ProdP { unProdP :: Int }
instance Semigroup ProdP where
  ProdP x <> ProdP y = ProdP (x *! y)
  stimes = stimesMonoid
instance Monoid ProdP where
  mempty = ProdP 1

powP :: Int -> Int -> Int
powP x k = unProdP $ stimes k $ ProdP x

suffSums :: UArray Int Int -> UArray Int Int
suffSums arr = let
  (p, q) = bounds arr
  in  array (p, q) $ flip unfoldr (q, 0) $ \w@(!ii, !s) -> do
  guard $ ii >= p
  let  !ni = ii - 1
  pure (w, (ni, s + arr ! ii))

mainFun :: SP Builder
mainFun = do
  ~[n] <- getInts 1
  a <- getInts n
  let
    maxk = finiteBitSize (0 :: Int)
    cts = accumArray (+) 0 (0, maxk)
      $ [(countTrailingZeros ai, 1) | ai <- a]
    his = suffSums cts
    bad i = case  cts ! i  of
      0 -> 0
      q -> powP 2 (his ! i + q - 1) -- choose any ODD # with i trailing zeros
    good = foldl' (-!) (powP 2 n) [bad i | i <- [1 .. maxk]]
  pure $ putInts [good -! 1] -- "nonempty"

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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 $ P.words inp
  P.putStr $ toLazyByteString outp

import Control.Monad
import Data.Maybe
import Data.Bits
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    ~[n] <- readInts
    xs <- readInts
    let oc = length $ filter odd xs
        withOdd = (2 ^ oc - 1) * 2 ^ (n - oc)
        ecs = M.elems $ M.fromListWith (+) [(countTrailingZeros x, 1 :: Int) | x <- xs, even x]
        withoutOdd = sum $ zipWith f ecs (tail $ scanr (+) 0 ecs) where
            f c c' = 2 ^ c' * (2 ^ (c - 1) - 1)
    print $ toInt $ withOdd + withoutOdd

m :: Int
m = 1000000007

newtype MInt = MInt { toInt :: Int } deriving (Eq, Show)

instance Num MInt where
    MInt a + MInt b = MInt $ let c = a + b in if c >= m then c - m else c
    MInt a - MInt b = MInt $ let c = a - b in if c < 0 then c + m else c
    MInt a * MInt b = MInt $ a * b `mod` m
    abs             = id
    signum          = MInt . signum . toInt
    fromInteger     = MInt . fromInteger . (`mod` fromIntegral m)

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

main :: IO ()
main = solve

{-# LANGUAGE BangPatterns #-}
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

import Data.Bits
import Data.Int
import Data.Semigroup

p :: Int
p = 10 ^ (9 :: Int) + 7

p64 :: Int64
p64 = fromIntegral p

cv :: Int -> Int
cv x = x - if  x >= p  then  p  else  0

(+!) :: Int -> Int -> Int
infixl 6 +!
x +! y = cv $ x + y

(-!) :: Int -> Int -> Int
infixl 6 -!
x -! y = cv $ x + p - y

(*!) :: Int -> Int -> Int
infixl 7 *!
x *! y = fromIntegral $ fromIntegral x * fromIntegral y `rem` p64

newtype ProdP = ProdP { unProdP :: Int }
instance Semigroup ProdP where
  ProdP x <> ProdP y = ProdP (x *! y)
  stimes = stimesMonoid
instance Monoid ProdP where
  mempty = ProdP 1

powP :: Int -> Int -> Int
powP x k = unProdP $ stimes k $ ProdP x

suffSums :: UArray Int Int -> UArray Int Int
suffSums arr = let
  (p, q) = bounds arr
  in  array (p, q) $ flip unfoldr (q, 0) $ \w@(!ii, !s) -> do
  guard $ ii >= p
  let  !ni = ii - 1
  pure (w, (ni, s + arr ! ii))

mainFun :: SP Builder
mainFun = do
  ~[n] <- getInts 1
  a <- getInts n
  let
    maxk = finiteBitSize (0 :: Int)
    cts = accumArray (+) 0 (0, maxk)
      $ [(countTrailingZeros ai, 1) | ai <- a]
    his = suffSums cts
    bad i = cts ! i *! powP 2 (his ! i)
    good = foldl' (-!) (powP 2 n) [bad i | i <- [1 .. maxk]]
  pure $ putInts [good -! 1] -- "nonempty"

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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 $ P.words inp
  P.putStr $ toLazyByteString outp

{-# LANGUAGE BangPatterns #-}
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

import Data.Bits
import Data.Int
import Data.Semigroup

p :: Int
p = 10 ^ (9 :: Int) + 7

p64 :: Int64
p64 = fromIntegral p

cv :: Int -> Int
cv x = x - if  x >= p  then  p  else  0

(+!) :: Int -> Int -> Int
infixl 6 +!
x +! y = cv $ x + y

(-!) :: Int -> Int -> Int
infixl 6 -!
x -! y = cv $ x + p - y

(*!) :: Int -> Int -> Int
infixl 7 *!
x *! y = fromIntegral $ fromIntegral x * fromIntegral y `rem` p64

newtype ProdP = ProdP { unProdP :: Int }
instance Semigroup ProdP where
  ProdP x <> ProdP y = ProdP (x *! y)
  stimes = stimesMonoid
instance Monoid ProdP where
  mempty = ProdP 1

powP :: Int -> Int -> Int
powP x k = unProdP $ stimes k $ ProdP x

suffSums :: UArray Int Int -> UArray Int Int
suffSums arr = let
  (p, q) = bounds arr
  in  array (p, q) $ flip unfoldr (q, 0) $ \w@(!ii, !s) -> do
  guard $ ii >= p
  let  !ni = ii - 1
  pure (w, (ni, s + arr ! ii))

mainFun :: SP Builder
mainFun = do
  ~[n] <- getInts 1
  a <- getInts n
  let
    maxk = finiteBitSize (0 :: Int)
    cts = accumArray (+) 0 (0, maxk)
      $ [(countTrailingZeros ai, 1) | ai <- a]
    his = suffSums cts
    bad i = cts ! i *! powP 2 (his ! i)
    good = foldl' (-!) (powP 2 n) [bad i | i <- [1 .. maxk]]
  pure $ putInts (elems cts) <> putInts [good -! 1] -- "nonempty"

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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 $ P.words inp
  P.putStr $ toLazyByteString outp


Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 × 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.The morning has come. All n alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game:  First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal.  Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off. Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!

The first line of the input contains integer n (1 ≤ n ≤ 105) — the number of the alarm clocks. The next n lines describe the clocks: the i-th line contains two integers xi, yi — the coordinates of the i-th alarm clock (0 ≤ xi, yi ≤ 100). Note that a single point in the room can contain any number of alarm clocks and the alarm clocks can lie on the sides of the square that represents the room.

In a single line print a single integer — the minimum number of segments Inna will have to draw if she acts optimally.

NoteIn the first sample, Inna first chooses type "vertical segments", and then she makes segments with ends at : (0, 0), (0, 2); and, for example, (1, 0), (1, 1). If she paints horizontal segments, she will need at least 3 segments.In the third sample it is important to note that Inna doesn't have the right to change the type of the segments during the game. That's why she will need 3 horizontal or 3 vertical segments to end the game.

{-# LANGUAGE BangPatterns #-}

import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Data.Char
import qualified Data.IntSet as S

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'

diffCount xs = go 0 S.empty xs
  where go !c seen [] = c
        go c seen (x:xs) = if S.member x seen then go c seen xs else go (c+1) (S.insert x seen) xs

main = do
  n <- fmap read getLine
  clocks <- replicateM n $ fmap (parseInts 2) BS.getLine
  let v = diffCount $ map head clocks
      h = diffCount $ map (head . tail) clocks
  print $ (min v h :: Int)

import Data.List
fx::[[Int]]->[Int]
fx []=[]
fx ((x:y:[]):xs)=x:fx xs

fy::[[Int]]->[Int]
fy []=[]
fy ((x:y:[]):xs)=y:fy xs

main =do
      e<-getLine
      es<-getContents
      let xs=lines es
          ys=map (map read ) (map words xs)::[[Int]]
      print $ min (length (nub (fx ys))) (length (nub (fy ys)))

import Data.List
fx::[[Int]]->[Int]
fx []=[]
fx ((x:y:[]):xs)=x:fx xs

fy::[[Int]]->[Int]
fy []=[]
fy ((x:y:[]):xs)=y:fx xs

main =do
      e<-getLine
      es<-getContents
      let xs=lines es
          ys=map (map read ) (map words xs)::[[Int]]
      print $ min (length (nub (fx ys))) (length (nub (fy ys)))


Pak Chanek has a prime number$$$^\dagger$$$ $$$n$$$. Find a prime number $$$m$$$ such that $$$n + m$$$ is not prime.$$$^\dagger$$$ A prime number is a number with exactly $$$2$$$ factors. The first few prime numbers are $$$2,3,5,7,11,13,\ldots$$$. In particular, $$$1$$$ is not a prime number.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following lines contain the description of each test case. The only line of each test case contains a prime number $$$n$$$ ($$$2 \leq n \leq 10^5$$$).

For each test case, output a line containing a prime number $$$m$$$ ($$$2 \leq m \leq 10^5$$$) such that $$$n + m$$$ is not prime. It can be proven that under the constraints of the problem, such $$$m$$$ always exists. If there are multiple solutions, you can output any of them.

NoteIn the first test case, $$$m = 2$$$, which is prime, and $$$n + m = 7 + 2 = 9$$$, which is not prime.In the second test case, $$$m = 7$$$, which is prime, and $$$n + m = 2 + 7 = 9$$$, which is not prime.In the third test case, $$$m = 47837$$$, which is prime, and $$$n + m = 75619 + 47837 = 123456$$$, which is not prime.

main :: IO ()
main = interact $ unwords . tail . words

module Main where

import Control.Monad (replicateM_)

solve :: Int -> Int
solve 2 = 2
solve _ = 3

handleProblem :: IO ()
handleProblem = do
  input <- read <$> getLine
  print $ solve input

main :: IO ()
main = do
  numberProblems <- read <$> getLine
  replicateM_ numberProblems handleProblem

{-# LANGUAGE BangPatterns #-}
import System.IO
import Control.Applicative
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Function (fix)
import Data.Array (Array, array, (!))
import Data.Array.ST
import Data.Array.Unboxed
import Data.ByteString.Lazy.Builder
import Data.ByteString.Lazy.Builder.ASCII
import Control.Monad.ST as ST
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

construct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]
construct reader str
    | BS.null str = []
    | isSpace (BS8.head str) = construct reader (BS8.tail str)
    | otherwise = let Just (i, other) = reader str in i : construct reader other

getInts :: IO [Int]
getInts = construct BS8.readInt <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = construct BS8.readInteger <$> BS.getLine

printInts :: [Int] -> IO ()
printInts = putStrLn . intercalate " " . map show

sieve :: Int -> UArray Int Bool
sieve n = runSTUArray $ do
  sieve <- newArray (2, n) True
  forM_ [2..n] $ \p -> do
    isPrime <- readArray sieve p
    when isPrime $ do
      forM_ [p*2, p*3 .. n] $ \k -> do
        writeArray sieve k False
  return sieve

primesUpto :: Int -> [Int]
primesUpto n = [p | (p, True) <- assocs $ sieve n]

solve n primes primeSet = head $ [m | m <- primes, Set.notMember (n+m) primeSet]

isPrime x = all (\i -> x `mod` i /= 0) [2..x-1]

main = do
  let primes = primesUpto 200000
  let primeSet = Set.fromList primes
  [t] <- getInts
  forM_ [1..t] $ \_ -> do
    [n] <- getInts
    print $ solve n primes primeSet


You have an array $$$a$$$ of length $$$n$$$. You can exactly once select an integer $$$len$$$ between $$$1$$$ and $$$n - 1$$$ inclusively, and then sort in non-decreasing order the prefix of the array of length $$$len$$$ and the suffix of the array of length $$$n - len$$$ independently.For example, if the array is $$$a = [3, 1, 4, 5, 2]$$$, and you choose $$$len = 2$$$, then after that the array will be equal to $$$[1, 3, 2, 4, 5]$$$.Could it be that after performing this operation, the array will not be sorted in non-decreasing order?

There are several test cases in the input data. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. This is followed by the test cases description. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^4$$$) — the length of the array. The second line of the test case contains a sequence of integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the array elements. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case of input data, output "YES" (without quotes), if the array may be not sorted in non-decreasing order, output "NO" (without quotes) otherwise. You can output each letter in any case (uppercase or lowercase).

NoteIn the first test case, it's possible to select $$$len = 1$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[2, 1, 2]$$$.In the second test case, it's possible to select $$$len = 3$$$, then after operation, the array will not be sorted in non-decreasing order and will be equal to $$$[1, 2, 3, 1]$$$.In the third test case, the array will be sorted in non-decreasing order for every possible $$$len$$$.

import Control.Monad (forM_)
import Data.List (sort)
import Data.Maybe ( isNothing )

nonDec :: Ord a => [a] -> Bool
nonDec arr = helper arr 0 (length arr)
  where
    helper arr i l
        | i < l - 1 = arr !! i > arr !! (i + 1) || helper arr (i + 1) l
        | otherwise = False

main :: IO ()
main = do
    t <- readLn :: IO Int
    forM_ [1 .. t] $ \i -> do
        n <- readLn :: IO Int
        l <- getLine
        let arr = map read (words l) :: [Int]
        putStrLn $ if nonDec arr then "YES" else "NO"

parseInt :: String -> Int
parseInt number = (read number) :: Int

readInt :: IO Int
readInt = do
    number <- getLine
    pure $ parseInt number

readIntArr :: IO [Int]
readIntArr = do
    numbers <- getLine
    pure $ map parseInt $ words numbers

isSorted :: [Int] -> Bool
isSorted [] = True
isSorted (x: []) = True
isSorted (x: y: xs) = x <= y && isSorted (y: xs)

solve :: IO ()
solve = do
    n   <- readInt
    arr <- readIntArr
    if (isSorted arr)
        then putStrLn "NO"
        else putStrLn "YES"

readLoop :: Int -> IO ()
readLoop i =
    if (i == 0)
        then pure ()
        else do
            solve
            readLoop (i - 1)

main :: IO ()
main = do
    n <- readInt
    readLoop n

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 Data.List
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

enumerate = zip [0..]

argmin :: [Int] -> Int
argmin a = let t = enumerate a in
  fst $ foldl (\(mni, mn) (i, x) -> if x < mn then (i, x) else (mni, mn)) (0, 999999999) t

solve :: SP Builder
solve = do
  n <- getInt
  a <- replicateM n getInt
  let
    sorta = sort a
    sorted = (==) a sorta
  pure . str $  if sorted then "NO\n" else "YES\n"

main = interact $ unlines . map p . chunk 2 . drop 1 . lines

chunk n [] = []
chunk n xs = take n xs : chunk n (drop n xs)

check = foldl (\b c -> if (b == (-1)) || (c < b) then (-1) else c) 0

p xs = let ((n:_):s:_) = fmap (fmap read . words) xs :: [[Int]]
        in if check s == (-1) then "YES" else "NO"

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
    a <- replicateM n getInt
    pure $ string7 $ if  and $ zipWith (<=) a (tail a)
      then  "NO\n"
      else  "YES\n"

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

parseInt :: String -> Int
parseInt number = (read number) :: Int

readInt :: IO Int
readInt = do
    number <- getLine
    pure $ parseInt number

readIntArr :: IO [Int]
readIntArr = do
    numbers <- getLine
    pure $ map parseInt $ words numbers

isSorted :: [Int] -> Bool
isSorted [] = True
isSorted (x: []) = True
isSorted (x: y: xs) = x <= y && isSorted (y: xs)

solve :: IO ()
solve = do
    n   <- readInt
    arr <- readIntArr
    if (isSorted arr)
        then print "NO"
        else print "YES"

readLoop :: Int -> IO ()
readLoop i =
    if (i == 0)
        then pure ()
        else do
            solve
            readLoop (i - 1)

main :: IO ()
main = do
    n <- readInt
    readLoop n


There are $$$n$$$ boxers, the weight of the $$$i$$$-th boxer is $$$a_i$$$. Each of them can change the weight by no more than $$$1$$$ before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers' weights in the team are different (i.e. unique).Write a program that for given current values $$$a_i$$$ will find the maximum possible number of boxers in a team.It is possible that after some change the weight of some boxer is $$$150001$$$ (but no more).

The first line contains an integer $$$n$$$ ($$$1 \le n \le 150000$$$) — the number of boxers. The next line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$, where $$$a_i$$$ ($$$1 \le a_i \le 150000$$$) is the weight of the $$$i$$$-th boxer.

Print a single integer — the maximum possible number of people in a team.

NoteIn the first example, boxers should not change their weights — you can just make a team out of all of them.In the second example, one boxer with a weight of $$$1$$$ can be increased by one (get the weight of $$$2$$$), one boxer with a weight of $$$4$$$ can be reduced by one, and the other can be increased by one (resulting the boxers with a weight of $$$3$$$ and $$$5$$$, respectively). Thus, you can get a team consisting of boxers with weights of $$$5, 4, 3, 2, 1$$$.

import Control.Monad
import Data.List

readInt :: IO(Int)
readInt = fmap read getLine

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

loop :: Int -> IO() -> IO()
loop 0 f = do
    f; loop 0 f
loop 1 f = f
loop x f = do
    f; loop (x - 1) f

main = do
	sz <- readInt
	v <- readlist
	print (solve (sort v) 1)

solve _ 150002 = 0
solve [] _ = 0
solve x@(x0:xs) a
	| x0 < a - 1 = solve xs a
	| x0 > a + 1 = solve x (a + 1)
	| otherwise = 1 + solve xs (a + 1)

import Control.Monad
import Data.List

readInt :: IO(Int)
readInt = fmap read getLine

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

loop :: Int -> IO() -> IO()
loop 0 f = do
    f; loop 0 f
loop 1 f = f
loop x f = do
    f; loop (x - 1) f

main = do
	sz <- readInt
	v <- readlist
	print (solve (sort v) 1)

solve _ 150002 = 0
solve [] _ = 0
solve (x0:xs) a
	| x0 < a - 1 = solve xs a
	| x0 > a + 1 = solve xs (a + 1)
	| otherwise = 1 + solve xs (a + 1)

import Control.Monad
import Data.List

readInt :: IO(Int)
readInt = fmap read getLine

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

loop :: Int -> IO() -> IO()
loop 0 f = do
    f; loop 0 f
loop 1 f = f
loop x f = do
    f; loop (x - 1) f

main = do
	sz <- readInt
	v <- readlist
	print (solve (sort v) 1)

solve _ 15001 = 0
solve [] _ = 0
solve (x0:xs) a
	| x0 < a - 1 = solve xs a
	| x0 > a + 1 = solve xs (a + 1)
	| otherwise = 1 + solve xs (a + 1)


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

import Data.List

answer1 :: String -> Int
answer1 str = sum.map f $ group str
  where
    f = \x -> if length x `mod` 5 == 0 then length x `div` 5 else length x `div` 5 + 1

answer2 :: Int -> [Int] -> Int
answer2 n xs = sum.map f.group.sort $ xs
  where
    f v = if n < head v
                then length v
                else length v -1

main = do n <- getLine
          print.answer2 (read n).map read.words =<< getLine

import Data.List

solve (n:xs) = n - (length $ group $ sort $ filter (<=n) xs)

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

import Data.Array

solve n xs = length $ filter (==0) finalTable
  where finalTable = elems $ foldr updateTable initialTable xs
        initialTable = array (1, n) [(i, 0) | i <- [1..n]]
        updateTable x table = table // if x <= n then
                                         [(x, (table ! x) + 1)]
                                       else
                                         []

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

import List
main = interact $ show.s.sort.map read.tail.words
s xs = let n = length xs in n - (length $ group $ filter (<=n) xs)

import Control.Monad
import qualified Data.IntSet as S
main = do
  n <- readLn
  print . (n -) . S.size . S.fromList . filter (<= n) . map read . words =<< getLine

import Data.List

main :: IO()
main = do
	getLine
	x <- getLine
	putStr $ show $ getAnswer $ map (\x -> read x :: Integer) (words x)

getAnswer xs = length $ (sort xs) `minus` [1..fromIntegral $ length xs]

minus :: (Ord a) => [a] -> [a] -> [a]
minus = minusBy compare

-- |  'minusBy' is the non-overloaded version of 'minus'
minusBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
minusBy cmp = loop
  where
     loop [] _ys = []
     loop xs [] = xs
     loop (x:xs) (y:ys)
       = case cmp x y of
          LT -> x : loop xs (y:ys)
          EQ ->     loop xs ys
          GT ->     loop (x:xs) ys

main :: IO ()
main = do n <- getLine
          xs <- getLine
          print $ solve n xs

read' :: String -> Int
read' = read

solve ::  String -> String -> Int
solve n' xs' = length $ filter id $ map (flip notElem xs) [1..n]
   where n = read' n'
         xs = map read' $ words xs'

{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
import qualified Data.IntSet as Set

main :: IO ()
main = do
  n   <- readLn
  xs  <- map read . words <$> getLine
  let ys = takeWhile (<= n) $ Set.toList $ Set.fromList xs
  print $ n - length ys

import Data.List

main :: IO ()
main = do n <- getLine
          xs <- getLine
          print $ check (read n) $ map read $ words xs

check :: Int -> [Int] -> Int
check n xs = sum [f x | x <- group $ sort xs]
    where f x = length x - (if (head x) > n then 0 else 1)

import Data.List
import Data.Array

main = do
   n <- fmap read getLine :: IO Int
   a <- fmap (map read . words) getLine :: IO [Int]
   print . length . filter id . elems $ accumArray (&&) True (1, n) [(i, False) | i <- a, i >= 1 && i <= n]

-- vim: set expandtab:

f s x | null s = x | head s `elem` x = f (tail s) x | otherwise = f (tail s) (head s :x)
fu s n = n - length (f s [])
solve s = [x | x<-tail s, x `elem` [1..head s]]
check s | null $ solve s  = head s | otherwise = fu (solve s) (head s)
main = interact $ show . check . map read .words

import Control.Monad
solve :: Int -> [Int] -> Int
solve 0 _ = 0
solve n xs
    | n `elem` xs = solve (n-1) xs
    | otherwise = 1 + (solve (n-1) xs)
main = do
  n <- readLn
  getLine >>=
       (\str -> putStrLn $
                (show . solve n . map read. words) str)

{-# 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 qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
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 System.IO
-- import Debug.Trace

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

main = do
  n <- readLn
  xs <- getInts

  print $ sum $ map (\(i, x) -> if elem i [1..n] then max (x-1) 0 else x) $ assocs $ (accumArray (+) 0 (1, 5000) $ zip xs $ repeat (1 :: Int) :: UArray Int Int)

import List
main = interact $ show. gao. map read. words
gao (n:xs) = n - (length. takeWhile (<=n). map head.group.sort $ xs)

import Data.List

solve :: Int -> [Int] -> Int
solve m xs = sum $ map count $ group $ sort xs
  where
    count ys@(y:_) = if y > m then length ys else length ys - 1

(-->) = flip fmap

main = do
  m <- getLine --> read
  xs <- getLine --> words --> map read
  print $ solve m xs

-- rearranges
import Array

readL [] a akk = (read $ reverse a :: Int) : akk
readL (' ':xs) a akk = readL xs [] ((read $ reverse a :: Int) : akk)
readL (x:xs) a akk = readL xs (x:a) akk

solve [] a = a
solve (x:xs) a | (inRange (bounds a) x) = solve xs (a//[(x,0)])
               | otherwise = solve xs a

main = do
			qty <- readLn :: IO Int
			slist <- getLine
			print $ foldr (+) 0 (elems (solve (readL slist [] []) (array (1,qty) [(i,1) | i <- [1..qty]])))

module Main
    where

import IO

get_num :: Char -> Int

get_num c = case c of
    '0' -> 0
    '1' -> 1
    '2' -> 2
    '3' -> 3
    '4' -> 4
    '5' -> 5
    '6' -> 6
    '7' -> 7
    '8' -> 8
    '9' -> 9

strtoInt' :: Int -> String -> [Int]

strtoInt' tmp [] = [tmp]
strtoInt' tmp (s1:ss) =
    if (s1 == ' ')
        then tmp:(strtoInt' 0 ss)
        else strtoInt' (tmp * 10 + (get_num s1)) ss

strtoInt = strtoInt' 0

sort :: [Int] -> [Int]

sort [] = []
sort (x:xs) = (sort [k | k <- xs, k < x]) ++ [x] ++ (sort [k | k <- xs, k >= x])

count :: [Int] -> Int

count (x1:x2:xs) =
    if x1 /= x2
        then 1 + count (x2:xs)
        else count (x2:xs)
count list = length list

badnum :: [Int] -> Int
badnum list = len - count (filter (\x -> x <= len) list)
    where len = length list

res_function :: String -> String

res_function = show . badnum . sort . strtoInt

main = do
    hSetBuffering stdin LineBuffering
    tmp <- getLine
    tmp2 <- getLine
    putStrLn  (res_function tmp2)

import Data.List

solve :: [Int] -> Int
solve (n:xs) = n - (length (takeWhile (<= n) values))
    where
        values = map head.group.sort $ xs

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

import List
getAns a = (length a) - (length (intersect [1..(length a)] a))
main=interact$show.getAns.map read.tail.words

import List

readWords :: IO [String]
readWords = getLine >>= return . words

reads :: Read a => IO [a]
reads = readWords >>= return . (map read)

solve :: Int -> [Int] -> Int
solve n xs = n - length (nub (filter (<=n) xs))

main :: IO ()
main = do
    n <- readLn
    xs <- Main.reads
    print (solve n xs)

module Main where
import Data.List
main :: IO ()
main = do
    n <- readLn
    l <- getLine
    let ns = nub (map read $ words l :: [Integer])
        outside = fromInteger $ sum [1 | x <- ns, x > n]
    print (fromInteger n - length ns + fromInteger outside)

module Main where
import Data.List
main :: IO ()
main = do
    _ <- getLine
    l <- getLine
    let ns = sort $ (map read $ words l :: [Integer])
        folddat (changes, curr) x =
            if curr == x
                then (changes + 1, x)
                else (changes, x)
        (ans,_) = foldl folddat (0, head ns) (tail ns)
    print ans

module Main where
import Data.List
main :: IO ()
main = do
    n <- readLn
    l <- getLine
    let ns = nub (map read $ words l :: [Integer])
    print (n - length ns)

module Main where
import Data.List
main :: IO ()
main = do
    _ <- getLine
    l <- getLine
    let ns = sort $ (map read $ words l :: [Integer])
        folddat (changes, curr) x =
            if curr == x
                then (changes + 1, x)
                else (changes + x - curr - 1, x)
        (ans,_) = foldl folddat (0, head ns) (tail ns)
    print ans

import Data.List

answer1 :: String -> Int
answer1 str = sum.map f $ group str
  where
    f = \x -> if length x `mod` 5 == 0 then length x `div` 5 else length x `div` 5 + 1

answer2 :: Int -> [Int] -> Int
answer2 n xs = sum.map f.zip [1..n].sort $ xs
  where
    f (i,v) = if i==v then 0 else 1

main = do n <- getLine
          print.answer2 (read n).map read.words =<< getLine

import Data.List

answer1 :: String -> Int
answer1 str = sum.map f $ group str
  where
    f = \x -> if length x `mod` 5 == 0 then length x `div` 5 else length x `div` 5 + 1

answer2 :: String -> Int
answer2 str = f.foldl max 1.map length.group.sort.words $ str
  where
    f 1 = 0
    f n = n-1

main = getLine >> getLine >>= print.answer2

import Data.List

solve (n:xs) = n - (length $ group $ sort xs)

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

import List
main = interact $ show.length.filter id.(zipWith (/=) [1..]).sort.map read.tail.words

import Control.Monad
import qualified Data.IntSet as S
main = print =<< liftM2 (-) readLn (liftM (S.size . S.fromList . map read . words) getLine)

import Data.List

main :: IO()
main = do
	getLine
	x <- getLine
	putStr $ show $ getAnswer $ map (\x -> read x :: Integer) (words x)

getAnswer xs = length xs - length (nub xs)

import Data.List(sort)

main :: IO ()
main = do n <- getLine
          xs <- getLine
          print $ solve n xs

read' :: String -> Int
read' = read

solve ::  String -> String -> Int
solve n' xs' = length $ filter id $ zipWith (/=) (sort xs) [1..n]
   where n = read' n'
         xs = map read' $ words xs'

import Data.List

main :: IO ()
main = do n <- getLine
          xs <- getLine
          print $ check $ map read $ words xs

check :: [Int] -> Int
check xs = sum [length x - 1 | x <- group $ sort xs]

import Data.List
import Data.Array

main = do
   n <- fmap read getLine :: IO Int
   a <- fmap (map read . words) getLine :: IO [Int]
   print . length . filter id . elems $ accumArray (||) False (1, n) [(i, True) | i <- a]

-- vim: set expandtab:

import Data.List
import Data.Array

main = do
   n <- fmap read getLine :: IO Int
   a <- fmap (map read . words) getLine :: IO [Int]
   print . length . filter id . elems $ accumArray (&&) True (1, n) [(i, False) | i <- a, i <- [1..n]]

-- vim: set expandtab:

import Data.List

main = do
   n <- fmap read getLine :: IO Int
   a <- fmap (map read . words) getLine :: IO [Int]
   print . sum $ zipWith (\x y -> abs $ x - y) (sort a) [1..n]

-- vim: set expandtab:

import Data.List

main = do
   n <- fmap read getLine :: IO Int
   a <- fmap (map read . words) getLine :: IO [Int]
   print . length . filter id $ zipWith (/=) (sort a) [1..n]

-- vim: set expandtab:

f s x | null s = x | head s `elem` x = f (tail s) x | otherwise = f (tail s) (head s :x)
fu s = head s  - length (f s [])
solve s = [x | x<-tail s, x `elem` [1..head s]]
check s | null $ solve s  = head s | otherwise = fu s
main = interact $ show . check . map read .words

import List
main = interact $ show. gao. words
gao (n:xs) = (read n) - (length. group. sort $ xs)

module Main
    where

import IO

get_num :: Char -> Int

get_num c = case c of
    '0' -> 0
    '1' -> 1
    '2' -> 2
    '3' -> 3
    '4' -> 4
    '5' -> 5
    '6' -> 6
    '7' -> 7
    '8' -> 8
    '9' -> 9

strtoInt' :: Int -> String -> [Int]

strtoInt' tmp [] = [tmp]
strtoInt' tmp (s1:ss) =
    if (s1 == ' ')
        then tmp:(strtoInt' 0 ss)
        else strtoInt' (tmp * 10 + (get_num s1)) ss

strtoInt = strtoInt' 0

sort :: [Int] -> [Int]

sort [] = []
sort (x:xs) = [k | k <- xs, k < x] ++ [x] ++ [k | k <- xs, k >= x]

badnum :: [Int] -> Int

badnum (x1:x2:xs) =
    if x1 == x2
        then 1 + badnum (x2:xs)
        else badnum (x2:xs)
badnum _ = 0

res_function :: String -> String

res_function = show . badnum . sort . strtoInt

main = do
    hSetBuffering stdin LineBuffering
    tmp <- getLine
    tmp2 <- getLine
    putStrLn  (res_function tmp2)

import Data.List

solve :: [Int] -> Int
solve (n:xs) = n - (length (takeWhile (<= n) values))
    where values = head $ group $ sort $ xs

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


Sasha and Dima want to buy two $$$n$$$-tier cakes. Each cake should consist of $$$n$$$ different tiers: from the size of $$$1$$$ to the size of $$$n$$$. Tiers should go in order from the smallest to the biggest (from top to bottom).They live on the same street, there are $$$2 \cdot n$$$ houses in a row from left to right. Each house has a pastry shop where you can buy a cake tier. Unfortunately, in each pastry shop you can buy only one tier of only one specific size: in the $$$i$$$-th house you can buy a tier of the size $$$a_i$$$ ($$$1 \le a_i \le n$$$).Since the guys carry already purchased tiers, and it is impossible to insert a new tier in the middle of the cake, they agreed to buy tiers from the smallest to the biggest. That is, each of them buys tiers in order: $$$1$$$, then $$$2$$$, then $$$3$$$ and so on up to $$$n$$$.Initially, Sasha and Dima are located near the first (leftmost) house. Output the minimum distance that they will have to walk in total to buy both cakes. The distance between any two neighboring houses is exactly $$$1$$$.

The first line of the input contains an integer number $$$n$$$ — the number of tiers in each cake ($$$1 \le n \le 10^5$$$). The second line contains $$$2 \cdot n$$$ integers $$$a_1, a_2, \dots, a_{2n}$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is equal to the size of the tier, which can be bought in the $$$i$$$-th house. Remember that in each house you can buy only one tier. It is guaranteed that every number from $$$1$$$ to $$$n$$$ occurs in $$$a$$$ exactly two times.

Print one number  — the minimum distance that the guys have to walk in total to buy both cakes. Guys can be near same house at the same time. They begin near the first (leftmost) house. Each of the guys should buy $$$n$$$ tiers in ascending order of their sizes.

NoteIn the first example, the possible optimal sequence of actions is:  Sasha buys a tier of size $$$1$$$ near the $$$1$$$-st house ($$$a_1=1$$$);  Dima goes to the house $$$2$$$;  Dima buys a tier of size $$$1$$$ near the $$$2$$$-nd house ($$$a_2=1$$$);  Sasha goes to the house $$$4$$$;  Sasha buys a tier of size $$$2$$$ near the $$$4$$$-th house ($$$a_4=2$$$);  Sasha goes to the house $$$5$$$;  Sasha buys a tier of size $$$3$$$ near the $$$5$$$-th house ($$$a_5=3$$$);  Dima goes to the house $$$3$$$;  Dima buys a tier of size $$$2$$$ near the $$$3$$$-rd house ($$$a_3=2$$$);  Dima goes to the house $$$6$$$;  Dima buys a tier of size $$$3$$$ near the $$$6$$$-th house ($$$a_6=3$$$). So, Sasha goes the distance $$$3+1=4$$$, and Dima goes the distance $$$1+1+3=5$$$. In total, they cover a distance of $$$4+5=9$$$. You can make sure that with any other sequence of actions they will walk no less distance.

{-# 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.readInteger ) . 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
	let
		positions = map snd $ sort $ zip as [ 0 .. ]
	print $ solve ( 0, 0 ) positions

solve a b = solve' 0 a b

solve' res _ [] = res
solve' res ( x, y ) ( a : b : rest ) =　res `seq` solve' ( res + min d1 d2 ) ( a, b ) rest
	where
		d1 = abs ( a - x ) + abs ( b - y )
		d2 = abs ( b - x ) + abs ( a - y )

{-# 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.readInteger ) . 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
	let
		positions = map snd $ sort $ zip as [ 0 .. ]
	print $ solve ( 0, 0 ) positions

solve a b = solve' 0 a b

solve' res _ [] = res
solve' res ( x, y ) ( a : b : rest ) = solve' ( res + min d1 d2 ) ( a, b ) rest
	where
		d1 = abs ( a - x ) + abs ( b - y )
		d2 = abs ( b - x ) + abs ( a - y )

{-# 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.readInteger ) . 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
	let
		positions = map snd $ sort $ zip as [ 0 .. ]
	print $ solve ( 0, 0 ) positions

solve _ [] = 0
solve ( x, y ) ( a : b : rest ) = min d1 d2 + solve ( a, b ) rest
	where
		d1 = abs ( a - x ) + abs ( b - y )
		d2 = abs ( b - x ) + abs ( a - y )

{-# 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.readInteger ) . 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
	let
		positions = map snd $ sort $ zip as [ 0 .. ]
	print $ solve ( 0, 0 ) positions

solve a b = solve' 0 a b

solve' !res _ [] = res
solve' !res ( x, y ) ( a : b : rest ) = res `seq` solve' ( res + min d1 d2 ) ( a, b ) rest
	where
		d1 = abs ( a - x ) + abs ( b - y )
		d2 = abs ( b - x ) + abs ( a - y )

{-# 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.readInteger ) . 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
	let
		positions = map snd $ sort $ zip as [ 0 .. ]
	print $ solve ( 0, 0 ) positions

solve a b = solve' 0 a b

solve' !res _ [] = res
solve' !res !( x, y ) ( a : b : rest ) = solve' ( res + min d1 d2 ) ( a, b ) rest
	where
		d1 = abs ( a - x ) + abs ( b - y )
		d2 = abs ( b - x ) + abs ( a - y )

{-# 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 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 Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

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

process :: Int -> Map Int [Int] -> Integer
process n tiers = l where
    (_, l) = foldl walk ((1, 1), 0 :: Integer) [1..n]
    dist a b = abs (a - b)
    walk ((p1, p2), l) n = ret where
        [d1, d2] = tiers Map.! n
        case1 = dist p1 d1 + dist p2 d2
        case2 = dist p1 d2 + dist p2 d1
        ret = if case1 < case2 then ((d1, d2), l + toInteger case1) else ((d2, d1), l + toInteger case2)

main = do
    n <- getInt
    tiers <- makeMap n <$> getInts :: IO (Map Int [Int])
    print $ process n tiers

makeMap n (tiers ::[Int]) = foldl (\m (i, tier) -> Map.update (Just . (:) i) tier m) initMap (zip [1..] tiers) where
    initMap = Map.fromList $ zip [1..n] (repeat [])

{-# 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 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 Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

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

process :: Int -> Map Int [Int] -> Int
process n tiers = l1 + l2 where
    (tiers', _, l1) = foldl firstWalk (tiers , 1, 0) [1..n]
    (_     , _, l2) = foldl secondWalk (tiers', 1, 0) [1..n]
    dist a b = abs (a - b)
    firstWalk (m :: Map Int [Int], p, l) n = (m', p', l') where
        [d1, d2] = m Map.! n
        (dest, rest) = if dist p d1 < dist p d2 then (d1, d2) else (d2, d1)
        m' = Map.update (const $ Just [rest]) n m
        p' = dest
        l' = l + dist p p'
    secondWalk (m, p, l) n = (m, p', l') where
        [d] = m Map.! n
        p' = d
        l' = l + dist p p'

main = do
    n <- getInt
    tiers <- makeMap n <$> getInts :: IO (Map Int [Int])
    print $ process n tiers

makeMap n (tiers ::[Int]) = foldl (\m (i, tier) -> Map.update (Just . (:) i) tier m) initMap (zip [1..] tiers) where
    initMap = Map.fromList $ zip [1..n] (repeat [])

{-# 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 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 Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

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

process :: Int -> Map Int [Int] -> Int
process n tiers = l where
    (_, l) = foldl walk ((1, 1), 0) [1..n]
    dist a b = abs (a - b)
    walk ((p1, p2), l) n = ret where
        [d1, d2] = tiers Map.! n
        case1 = dist p1 d1 + dist p2 d2
        case2 = dist p1 d2 + dist p2 d1
        ret = if case1 < case2 then ((d1, d2), l + case1) else ((d2, d1), l + case2)

main = do
    n <- getInt
    tiers <- makeMap n <$> getInts :: IO (Map Int [Int])
    print $ process n tiers

makeMap n (tiers ::[Int]) = foldl (\m (i, tier) -> Map.update (Just . (:) i) tier m) initMap (zip [1..] tiers) where
    initMap = Map.fromList $ zip [1..n] (repeat [])


Rahul and Tina are looking forward to starting their new year at college. As they enter their new classroom, they observe the seats of students are arranged in a $$$n \times m$$$ grid. The seat in row $$$r$$$ and column $$$c$$$ is denoted by $$$(r, c)$$$, and the distance between two seats $$$(a,b)$$$ and $$$(c,d)$$$ is $$$|a-c| + |b-d|$$$. As the class president, Tina has access to exactly $$$k$$$ buckets of pink paint. The following process occurs.   First, Tina chooses exactly $$$k$$$ seats in the classroom to paint with pink paint. One bucket of paint can paint exactly one seat.  After Tina has painted $$$k$$$ seats in the previous step, Rahul chooses where he sits. He will not choose a seat that has been painted pink due to his hatred of the colour pink.  After Rahul has chosen his seat, Tina chooses a seat for herself. She can choose any of the seats, painted or not, other than the one chosen by Rahul. Rahul wants to choose a seat such that he sits as close to Tina as possible. However, Tina wants to sit as far away from Rahul as possible due to some complicated relationship history that we couldn't fit into the statement!Now, Rahul wonders for $$$k = 0, 1, \dots, n \cdot m - 1$$$, if Tina has $$$k$$$ buckets of paint, how close can Rahul sit to Tina, if both Rahul and Tina are aware of each other's intentions and they both act as strategically as possible? Please help satisfy Rahul's curiosity!

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 5 \cdot 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$2 \leq n \cdot m \leq 10^5$$$) — the number of rows and columns of seats in the classroom. The sum of $$$n \cdot m$$$ across all test cases does not exceed $$$10^5$$$.

For each test case, output $$$n \cdot m$$$ ordered integers — the distance between Rahul and Tina if both of them act optimally for every $$$k \in [0, n \cdot m - 1]$$$.

NoteOne possible sequence of choices for the first testcase where Tina has $$$k=3$$$ buckets of paints is as follows.Tina paints the seats at positions $$$(1, 2)$$$, $$$(2, 2)$$$, $$$(3, 2)$$$ with pink paint. Rahul chooses the seat at $$$(3, 1)$$$ after which Tina chooses to sit at $$$(1, 3)$$$. Therefore, the distance between Tina and Rahul is $$$|3-1| + |1-3| = 4$$$, and we can prove that this is indeed the minimum possible distance under the given constraints. There may be other choices of seats which lead to the same answer as well.For $$$k=0$$$ in the first test case, Rahul can decide to sit at $$$(2, 2)$$$ and Tina can decide to sit at $$$(4, 3)$$$ so the distance between them would be $$$|2 - 4| + |2 - 3| = 3$$$.Below are pictorial representations of the $$$k=3$$$ and $$$k=0$$$ cases for the first test case.  A possible seating arrangement for $$$k=3$$$.  A possible seating arrangement for $$$k=0$$$.

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  diff -sdu -- <(cat -- input.txt | ./a.out) output.txt  &&  cat -- *.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

import Prelude
import Control.Monad
import Data.List

main :: IO ()
main = do t <- readLn
          tcs <- replicateM t readTC

          (putStr . unlines . map (concat . map ((++" ").show) . solve)) tcs

readTC = do [n,m] <- map read . words <$> getLine    :: IO [Int]
            return (n,m)

solve (n,m) = sort [md n r + md m c | r <- [1..n],
                                      c <- [1..m]]
md n r = max (r-1) (n-r)

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  diff -sdu -- <(cat -- input.txt | ./a.out) output.txt  &&  cat -- *.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

import Prelude
import Control.Monad
import Data.List
import Data.Array

main :: IO ()
main = do
    t <- readLn
    tcs <- replicateM t readTC

    (putStr . unlines . map (concat . map ((++" ").show) . solve)) tcs

readTC = do
    [n,m] <- map read . words <$> getLine    :: IO [Int]
    return (n,m)

solve (n,m) | (n < m)   = solve (m,n)
            | otherwise = sort fld
  where
    (offV, offV_e) = centerProps n
    (offH, offH_e) = centerProps m

    maxDistFromCenter = (offV_e - 1) + (offH_e - 1)

    fld = bfs maxDistFromCenter (n,m) (offV, offH) (offV_e, offH_e)

centerProps :: Int -> (Int, Int)
centerProps n = (i, i+w)
                -- offsets of the center (start, past the end)
  where
    i = (n-w) `div` 2

    w = case (n`mod`2) of 0 -> 2
                          1 -> 1
                          _ -> error "bad parity"

bfs x (n, m) (r_b, c_b) (r_e, c_e) = elems arr
  where
    arr = array ((0,0), (n-1,m-1))
                [((r,c), f (r,c)) | r <- [0..n-1],
                                    c <- [0..m-1]]

    f (r,c) | (r_b <= r && r < r_e &&
               c_b <= c && c < c_e)    = x
            | otherwise                = 1 + (arr ! iprev (r,c))

    iprev (r,c) | (r' /= r)  = (r', c )
                | (c' /= c)  = (r , c')
                | otherwise  = error "no prev cell"
      where
        r' = iprev1D (r_b,r_e) r
        c' = iprev1D (c_b,c_e) c

iprev1D (b,e) n | (n <  b)   = n+1
                | (n >= e)   = n-1
                | otherwise  = n

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  diff -sdu -- <(cat -- input.txt | ./a.out) output.txt  &&  cat -- *.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

import Prelude
import Control.Monad
import Data.List
import Data.Array

main :: IO ()
main = do
    t <- readLn
    tcs <- replicateM t readTC

    (putStr . unlines . map (concat . map ((++" ").show) . solve)) tcs

readTC = do
    [n,m] <- map read . words <$> getLine    :: IO [Int]
    return (n,m)

solve (n,m) | (n < m)   = solve (m,n)
            | otherwise = sort fld
  where
    (offV, _lenV, offV_e) = centerProps n
    (offH, _lenH, offH_e) = centerProps m

    maxDistFromCenter = (offV_e - 1) + (offH_e - 1)

    fld = bfs maxDistFromCenter (n,m) (offV, offH) (offV_e, offH_e)

centerProps :: Int -> (Int, Int, Int)
centerProps n = (i, w, i+w)
                -- offset and length of the center,
                -- also offset past the center
  where
    i = (n-w) `div` 2

    w = case (n`mod`2) of 0 -> 2
                          1 -> 1
                          _ -> error "bad parity"

bfs x (n, m) (r_b, c_b) (r_e, c_e) = elems arr
  where
    arr = array ((0,0), (n-1,m-1))
                [((r,c), f (r,c)) | r <- [0..n-1],
                                    c <- [0..m-1]]

    f (r,c) | (r_b <= r && r < r_e &&
               c_b <= c && c < c_e)    = x
            | otherwise                = 1 + (arr ! iprev (r,c))

    iprev (r,c) | (r' /= r)  = (r', c )
                | (c' /= c)  = (r , c')
                | otherwise  = error "no prev cell"
      where
        r' = iprev1D (r_b,r_e) r
        c' = iprev1D (c_b,c_e) c

iprev1D (b,e) n | (n <  b)   = n+1
                | (n >= e)   = n-1
                | otherwise  = n

import Control.Monad
import Data.List

test :: IO ()
test = do
  [n, m] <- (<$>) read . words <$> getLine
  let a = (enumFromTo <*> (+ (m - 1))) <$> [0 .. n - 1]
  let grid = foldl1 (zipWith (zipWith max)) [a, reverse a, reverse <$> a, reverse $ reverse <$> a]
  let values = sort $ concat grid
  putStrLn $ unwords $ show <$> values

main :: IO ()
main = getLine >>= flip replicateM_ test . read

{-

1 2 3
2 3 4
3 4 5
4 5 6

4 5 6
3 4 5
2 3 4
1 2 3

3 2 1
4 3 2
5 4 3
6 5 4

6 5 4
5 4 3
4 3 2
3 2 1

6 5 6
5 4 5
5 4 5
6 5 6

-}

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] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n, m] <- getInts 2
    pure $ putInts $ sort [ (max i (n-1-i)) + (max j (m-1-j)) | i <- [0..n-1], j <- [0..m-1]]

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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 $ P.words inp
  P.putStr $ toLazyByteString outp


Polycarp is reading a book consisting of $$$n$$$ pages numbered from $$$1$$$ to $$$n$$$. Every time he finishes the page with the number divisible by $$$m$$$, he writes down the last digit of this page number. For example, if $$$n=15$$$ and $$$m=5$$$, pages divisible by $$$m$$$ are $$$5, 10, 15$$$. Their last digits are $$$5, 0, 5$$$ correspondingly, their sum is $$$10$$$.Your task is to calculate the sum of all digits Polycarp has written down.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The following $$$q$$$ lines contain queries, one per line. Each query is given as two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 10^{16}$$$) — the number of pages in the book and required divisor, respectively.

For each query print the answer for it — the sum of digits written down by Polycarp.

import           Control.Arrow ((>>>))
import           Control.Monad (liftM2, replicateM, replicateM_)

main :: IO ()
main = do
  n <- read <$> getLine :: IO Int
  replicateM_ n solveCase

solveCase :: IO ()
solveCase = do
  line <- getLine
  print $ solve ((words >>> map read >>> head) line) ((words >>> map read >>> last) line)

solve :: Integer -> Integer -> Integer
solve n m = quot n cycleSum * cycleValue + runCycle m (quot (mod n cycleSum) m) 1
  where
    cycleSum = m * 10
    cycleValue = runCycle m 10 1

runCycle :: Integer -> Integer -> Integer -> Integer
runCycle m times startAt
  | times == 0 = 0
  | otherwise = runCycle m (times - 1) (startAt + 1) + (show >>> last >>> (: []) >>> read) (m * startAt)

import           Control.Arrow ((>>>))
import           Control.Monad (liftM2, replicateM, replicateM_)

main :: IO ()
main = do
  n <- read <$> getLine :: IO Int
  replicateM_ n solveCase

solveCase :: IO ()
solveCase = do
  line <- getLine
  print $ solve ((words >>> map read >>> head) line) ((words >>> map read >>> last) line)

solve :: Int -> Int -> Int
solve n m = quot n cycleSum * cycleValue + runCycle m (quot (mod n cycleSum) m) 1
  where
    cycleSum = m * 10
    cycleValue = runCycle m 10 1

runCycle :: Int -> Int -> Int -> Int
runCycle m times startAt
  | times == 0 = 0
  | otherwise = runCycle m (times - 1) (startAt + 1) + (show >>> last >>> (: []) >>> read) (m * startAt)