{-# LANGUAGE ScopedTypeVariables #-}

import qualified Data.ByteString.Char8 as C
import Data.Int (Int)
import Data.List (sort)
import Debug.Trace

readMultipleFromLine :: IO [Int]
readMultipleFromLine = map parse . C.words <$> C.getLine
  where
    parse s = let Just (n, _) = C.readInt s in n

joints :: Int -> [Int] -> [Int]
joints x a = [j - i | (i, j) <- zip a $ tail a, j - i > x]

uniteCount :: Int -> Int -> [Int] -> Int
uniteCount _ _ [] = 0
uniteCount x k a =
  let need = head a `div` x - (if head a `mod` x == 0 then 1 else 0)
   in if need <= k
        then uniteCount x (k - need) $ tail a
        else length a

main = do
  [n, k, x] :: [Int] <- readMultipleFromLine
  a :: [Int] <- readMultipleFromLine
  print $ 1 + uniteCount x k (sort $ joints x $ sort a)

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P

import Data.Word (Word8)
import Data.Int (Int64)
import qualified Data.Bits as Bits
import qualified Data.Char as Char

import Data.List as L
import qualified Data.Set as Set
import qualified Data.Map as Map

import qualified Data.ByteString as Bs
import qualified System.IO as Io
--import Data.IntSet

solve :: IO ()
solve = do
  [n, k, x] <- readInts :: IO [Int64]
  ys <- readInts :: IO [Int64]
  let diffs = filter (>x) $ map snd $ drop 2 $ scanl (\(bef, diff) x -> (x, x-bef)) (0, 0) $ sort ys
      xs = sort diffs
      res = foldl (\(r, cnt) y -> if ceil y x <= r then (r-ceil y x, cnt) else (r, cnt+1)) (k, 1::Int) xs
    in print $ snd res
    where ceil x r = div (x-1) r

parseInt :: Bs.ByteString -> Int64
parseInt xs = snd $ Bs.foldr (\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48) :: Int64))) (1::Int64, 0::Int64) xs

readInts :: IO [Int64]
readInts =  map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine
  where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs

--parseInt = f . Char8.readInt where f (Just (i, _)) = i
--readInts = map parseInt . Char8.words <$> Char8.getLine

main = do
  let t = 1
  replicateM_ t $ solve

{-# LANGUAGE ScopedTypeVariables #-}

import qualified Data.ByteString.Char8 as C
import Data.Int (Int)
import Data.List (sort)
import Debug.Trace

readMultipleFromLine :: IO [Int]
readMultipleFromLine = map parse . C.words <$> C.getLine
  where
    parse s = let Just (n, _) = C.readInt s in n

joints :: Int -> [Int] -> [Int]
joints x a = [j - i | (i, j) <- zip a $ tail a, j - i > x]

computeExtraNeed :: Int -> Int -> Int
computeExtraNeed ai x = ai `div` x - (if ai `mod` x == 0 then 1 else 0)

countRemainingJoint :: Int -> (Int, Int) -> Int -> (Int, Int)
countRemainingJoint x (k, acc) ai =
  let need = computeExtraNeed ai x
   in if k > 0 && need <= k
        then (k - need, acc)
        else (k, acc + 1)

uniteCount :: Int -> Int -> [Int] -> Int
uniteCount x k a = snd $ foldl (countRemainingJoint x) (k, 0) a

main = do
  [n, k, x] :: [Int] <- readMultipleFromLine
  a :: [Int] <- readMultipleFromLine
  print $ 1 + uniteCount x k (sort $ joints x $ sort a)

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P

import Data.Word (Word8)
import Data.Int (Int64)
import qualified Data.Bits as Bits
import qualified Data.Char as Char

import Data.List as L
import qualified Data.Set as Set
import qualified Data.Map as Map

import qualified Data.ByteString as Bs
import qualified System.IO as Io
--import Data.IntSet

solve :: IO ()
solve = do
  [n, k, x] <- readInts :: IO [Int64]
  ys <- readInts :: IO [Int64]
  print [n, k, x]
  print ys
  let diffs = filter (>x) $ map snd $ drop 2 $ scanl (\(bef, diff) x -> (x, x-bef)) (0, 0) $ sort ys
      xs = sort diffs
      res = foldl (\(r, cnt) y -> if ceil y x <= r then (r-ceil y x, cnt) else (r, cnt+1)) (k, 1::Int) xs
    in print $ snd res
    where ceil x r = div (x-1) r

parseInt :: Bs.ByteString -> Int64
parseInt xs = snd $ Bs.foldr (\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48) :: Int64))) (1::Int64, 0::Int64) xs

readInts :: IO [Int64]
readInts =  map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) <$> Bs.getLine

--parseInt = f . Char8.readInt where f (Just (i, _)) = i
--readInts = map parseInt . Char8.words <$> Char8.getLine

main = do
  let t = 1
  replicateM_ t $ solve

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P

import Data.Word (Word8)
import Data.Int (Int64)
import qualified Data.Bits as Bits
import qualified Data.Char as Char

import Data.List as L
import qualified Data.Set as Set
import qualified Data.Map as Map

import qualified Data.ByteString as Bs
import qualified System.IO as Io
--import Data.IntSet

solve :: IO ()
solve = do
  [n, k, x] <- readInts :: IO [Int64]
  ys <- readInts :: IO [Int64]
  let diffs = filter (>x) $ map snd $ drop 2 $ scanl (\(bef, diff) x -> (x, x-bef)) (0, 0) $ sort ys
      xs = sort diffs
      res = foldl (\(r, cnt) y -> if ceil y x <= r then (r-ceil y x, cnt) else (r, cnt+1)) (k, 1::Int) xs
    in print $ snd res
    where ceil x r = div (x-1) r

parseInt :: Bs.ByteString -> Int64
parseInt xs = snd $ Bs.foldr (\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48) :: Int64))) (1::Int64, 0::Int64) xs

readInts :: IO [Int64]
readInts =  map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) <$> Bs.getLine

--parseInt = f . Char8.readInt where f (Just (i, _)) = i
--readInts = map parseInt . Char8.words <$> Char8.getLine

main = do
  let t = 1
  replicateM_ t $ solve

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P

import Data.Word (Word8)
import Data.Int (Int64)
import qualified Data.Bits as Bits
import qualified Data.Char as Char

import Data.List as L
import qualified Data.Set as Set
import qualified Data.Map as Map

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as Char8
import qualified System.IO as Io
--import Data.IntSet

solve :: IO ()
solve = do
  s1 <- readInts
  s2 <- readInts
  let [n, k, x] = map fromIntegral s1 :: [Int64]
      ys = map fromIntegral s2 :: [Int64]
      diffs = filter (>x) $ map snd $ drop 2 $ scanl (\(bef, diff) x -> (x, x-bef)) (0, 0) $ sort ys
      xs = sort diffs
      res = foldl (\(r, cnt) y -> if ceil y x <= r then (r-ceil y x, cnt) else (r, cnt+1)) (k, 1::Int) xs
    in print $ snd res
    where ceil x r = div (x-1) r

parseInt = f . Char8.readInt where f (Just (i, _)) = i
readInts = map parseInt . Char8.words <$> Char8.getLine

main = do
  let t = 1
  replicateM_ t $ solve

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P

import Data.Word (Word8)
import Data.Int (Int64)
import qualified Data.Bits as Bits
import qualified Data.Char as Char

import Data.List as L
import qualified Data.Set as Set
import qualified Data.Map as Map

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as Char8
import qualified System.IO as Io
--import Data.IntSet

solve :: IO ()
solve = do
  [n, k, x] <- readInts
  ys <- readInts
  let diffs = filter (>x) $ map snd $ drop 2 $ scanl (\(bef, diff) x -> (x, x-bef)) (0, 0) $ sort ys
      xs = sort diffs
      res = foldl (\(r, cnt) y -> if ceil y x <= r then (r-ceil y x, cnt) else (r, cnt+1)) (k, 1::Int) xs
    in print $ snd res
    where ceil x r = div (x-1) r

parseInt = f . Char8.readInt where f (Just (i, _)) = i
readInts = map parseInt . Char8.words <$> Char8.getLine

main = do
  let t = 1
  replicateM_ t $ solve

{-# LANGUAGE ScopedTypeVariables #-}

import Data.List (sort)
import GHC.Natural (intToNatural)
import Numeric.Natural (Natural)

readMultipleFromLine = fmap (map read . words) getLine

joints :: Natural -> [Natural] -> [Natural]
joints x a = [j - i | (i, j) <- zip a $ tail a, j - i > x]

uniteCount :: Natural -> Natural -> [Natural] -> Natural
uniteCount _ _ [] = 0
uniteCount x k a =
  let need = head a `div` x - (if head a `mod` x == 0 then 1 else 0)
   in if need <= k
        then uniteCount x (k - need) $ tail a
        else intToNatural $ length a + 1

main = do
  [n, k, x] :: [Natural] <- readMultipleFromLine
  a :: [Natural] <- readMultipleFromLine
  print $ uniteCount x k $ sort $ joints x $ sort a


solve :: String -> Int
solve [] = 0
solve ('P':queue) = solve queue
solve ('A':queue) = max pAhead (solve nextQueue)
  where pAhead = length $ takeWhile (== 'P') queue
        nextQueue = dropWhile (== 'P') queue

groupByTwo :: [String] -> [(String, String)]
groupByTwo [] = []
groupByTwo (n:as:rest) = [(n, as)] ++ groupByTwo rest

parse :: (String, String) -> String
parse (n, as) = show $ solve as

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

main = getLine >> getContents >>= output.lines

output (_:s:t) = (print $ f $ (== 'A') <$> s) >> output t
output _ = return ()

f (True:t) = max (length $ takeWhile not t) (f $ dropWhile not t)
f (_:t) = f t
f _ = 0

import Control.Monad
import Data.List (group)

maximumOr :: Ord a => a -> [a] -> a
maximumOr def [] = def
maximumOr _ xs = maximum xs

solve :: String -> Int
solve = maximumOr 0
      . map length
      . filter ((== 'P') . head)
      . group
      . dropWhile (/= 'A')

main = do
  cases <- read <$> getLine
  replicateM_ cases $ do
    getLine
    print . solve =<< getLine

import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import qualified Data.Text as T

onecase = do
		getLine
		a<-T.pack <$> getLine
		print $ maximum $ map T.length $ T.split (=='A') $ T.dropWhile (=='P') a

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

import Data.List (group)

process :: [Char] -> Int
process = maximum . map (\x -> if head x == 'A' then 0 else length x) . group . dropWhile (=='P') . (++"A")

readInt :: String -> Int
readInt = read

run :: Int -> IO ()
run 0 = return ()
run t = do
    n <- fmap readInt getLine
    s <- getLine
    print $ process s
    run (t-1)

main :: IO ()
main = do
    t <- fmap readInt getLine
    run t

solve [] = (0, 0)
solve (x:s) | x == 'P' = (a + 1, b)
            | x == 'A' = (0, max a b)
    where (a, b) = solve s

go n = do
    k <- getLine
    a <- getLine
    putStrLn $ show $ snd $ solve a
    if n > 1 then do
        go $ n - 1
    else
        return ()

main = do
    s <- getLine
    let n = read s
    go n


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

printResult = do
    n <- readLn :: IO Int
    a <- readInts
    let z = zipWith (*) (tail a) (init a)
    print $ maximum z

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

{-# LANGUAGE LambdaCase #-}

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

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

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

solve :: [Integer] -> Integer
solve xs = maximum [min u v * max u v | (u, v) <- zip xs (tail xs)]

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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


import Data.List

main=interact$show.solve.map ((\[x,y]->(-x,y)).map read.words).lines

solve :: [(Int,Int)] -> Int
solve ((_,k):pts) = length.head.filter (((p,t)==).head).group $ xs
   where (p,t) = xs !! (k-1)
         xs = sort pts

import Data.List
s([_,k]:t)=[q|x<-map length.group.sort$map(\[a,b]->(-a,b))t,q<-replicate x x]!!(k-1)
main=interact$show.s.map(map read.words).lines

import Data.List

parse :: String -> [(Int, Int)]
parse stuff =
    map parse_line (lines stuff)
    where parse_line l = t2 $ map (read::String->Int) (words l)
          t2 [a, b] = (a, b)
          t2 _ = error "unexpected input"

solve :: [(Int, Int)] -> Int
solve ((_, k):teams) = findKth k sorted
    where
      sorted = group . (sortBy cmp) $ teams
cmp (a, b) (c, d)
    | a == c     = compare b d
    | otherwise  = compare c a
findKth _ [] = 0
findKth k (x:xs)
    | length x >= k = length x
    | otherwise     = findKth (k - length x) xs
      -- findKth _ _ = 0

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

{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}
{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Control.Applicative
import Text.Printf
import Debug.Trace
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Char as C

atoi :: B.ByteString -> Int
atoi = B.foldl' (\a c -> a*10 + C.ord c - C.ord '0') 0

solve :: Int -> [(Int, Int)] -> Int
solve k ps = length $ filter (== p) ps
  where p = (sort ps) !! (k-1)

main = do
    [n, k] <- map atoi . B.words <$> B.getLine
    ps <- replicateM n $ do
        [x, y] <- map atoi . B.words <$> B.getLine
        return (-x, y)
    putStrLn . show $ solve k ps

import Data.List
import Control.Applicative
readi = read::String->Int
getParams = map readi . words <$> getLine
getDesc = zip' . map readi . words <$> getContents
  where zip' [] = []
        zip' (x:y:xs) = (x,y):zip' xs
rsort = sortBy (\(a,a') (b, b') -> if a == b then compare a' b'
                                   else compare b a)
solve k (x:xs)
  | y <= 0 = length x
  | otherwise = solve y xs
  where y = k - (length x)
main=do
  [_,k] <- getParams
  rsorted <- rsort <$> getDesc
  putStrLn $ show ((solve k).group $ rsorted)

module Main where

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

import Data.Time.Calendar

main = interact (show . solve . map (map read . words) . lines)

solve :: [[Int]] -> Int
solve ([_, k] : raw_results) = length winners where
    winners = filter (== winResult) sortedResults
    winResult = sortedResults !! (k - 1)

    sortedResults = reverse $ sortBy comp results

    results = map (\[a, b] -> (a, b)) raw_results

comp :: (Int, Int) -> (Int, Int) -> Ordering
comp (a, b) (c, d)
    | a == c && b == d = EQ
    | a > c || a == c && b < d = GT
    | otherwise = LT

import Data.List
inputTeam1 = [(4,10),(4,10),(4,10),(3,20),(2,1),(2,1),(1,10)]
inputTeam2 = [(3,1),(3,1),(5,3),(3,1),(3,1)]
inputTeam3 = "7 2\n4 10\n4 10\n4 10\n3 20\n2 1\n1 10\n"
inputTeam4 = "5 4\n3 1\n 3 1\n5 3\n3 1\n3 1\n"
main = do
	x <- getContents
	putStrLn (show (j x))
f (x,y) = x*(-100)+y
g x = sort $ map f x
h x y = count ((!!) (g x) (y-1)) (g x)
i :: String -> [Int]
i x = map read $ words x
j x = h (k (tail (tail (i x)))) (head (tail (i x)))
k [] = []
k (x:y:zs) = (x,y):k zs
count _ [] = 0
count y (x:xs) = if y==x then 1 + count y xs
						 else count y xs

import IO
import Data.List

main = print . solve =<< parse stdin

solve (n, k, pts) = length $ filter (==score) pts
   where
      score = sort pts !! (k-1)

parse h = do
   [n, k] <- readIntList h
   pts <- mapM (fmap f . readIntList) $ replicate n h
   return (n, k, pts)
   where
      f [a,b] = (-a, b)

-- lib
readIntList = fmap (map read . words) . hGetLine

-- vim: set expandtab:

import List

{-
import HUnit

testOneTeam :: Test
testOneTeam  =  Test "TestOneTeam" $
    assertEq 1 (solve 1 [(1,1)])

testInput :: Test
testInput  =  TestList "TestInput"
    [Test "1" $
        assertEq 3 (solve 2 [(4,10),(4,10),(4,10),(3,20),(2,1),(2,1),(1,10)]),
     Test "2" $
        assertEq 4 (solve 4 [(3,1),(3,1),(5,2),(3,1),(3,1)])
    ]

tests :: Test
tests  =  TestList "Testing ... "
    [testOneTeam,
     testInput
    ]

test :: IO ()
test  =  run tests

--------------------------------------------------------------------------------

-}

reads :: Read a => IO [a]
reads = getLine >>= sequence . map readIO . words

readPair :: Read a => IO (a, a)
readPair  =  do
    [x, y]  <-  Main.reads
    return (x, y)

solve :: Int -> [(Int, Int)] -> Int
solve k xs  =  length (filter (== xk) xs)
  where
    xk  =  (sortBy compareTeam xs) !! (k-1)
    compareTeam (pa, ta) (pb, tb)
      | pa > pb  =  LT
      | pa < pb  =  GT
      | ta < tb  =  LT
      | ta > tb  =  GT
      | otherwise  =  EQ

main :: IO ()
main  =  do
    [n, k] <- Main.reads
    rankList <- mapM (const readPair) [1..n]
    print $ solve k rankList

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

import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph

data Team = Team Int Int deriving Eq

instance Ord Team where
    Team a b `compare` Team c d
        | a == c    = compare b d
        | otherwise = compare c a

parseInput = do
    n <- readInt
    k <- readInt
    teams <- replicateM n (Team <$> readInt <*> readInt)
    return (k, teams)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

main = print =<< solve . evalState parseInput <$> BS.getContents

solve (k, teams) = length [team | team <- teams, team == kth]
  where
    sorted = sort teams

    kth = sorted !! (k-1)

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

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

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

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

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

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

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

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

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

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

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

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

state = State
-- }}}

import Data.List
import Data.Ord
import Data.Monoid
import Control.Monad
import Control.Monad.Instances
main = do
  [n,k] <- liftM (map read . words) getLine
  rs <- liftM ( map length . group .
                sortBy (liftM2 mappend (comparing (negate . (!!0)))
                                       (comparing (!!1))) ) $
        replicateM n $
        liftM (map read . words) getLine
  print $ solve rs k
solve (n:ns) i | i <= n    = n
               | otherwise = solve ns (i-n)

module Main where

import Prelude hiding (lookup)
import Data.Array (listArray, (!))
import Data.Map (Map, fromList, lookup)
import Data.List (sortBy, group)
import Control.Monad (replicateM)
import Data.Maybe (fromJust)
import qualified Data.ByteString.Char8 as BS

readNumbers :: IO [Int]
readNumbers =
 (fromJust
  . fmap (map fst)
  . sequence
  . map BS.readInt
  . BS.words) `fmap` BS.getLine

flipOrdering LT = GT
flipOrdering EQ = EQ
flipOrdering GT = LT

calcScoreGroupings :: [(Int, Int)] -> Map (Int, Int) Int
calcScoreGroupings =
  fromList .
  map (\groups -> (head groups, length groups)) .
  group

main :: IO ()
main = do
  (n:k:_) <- readNumbers
  -- negative to keep reverse ordering
  -- lower problems means lower score
  -- lower timing means greater score
  scoreList0 <- fmap (sortBy (\(i1, t1) (i2, t2) ->
                               compare (-i1 * 1000 + t1)
                                       (-i2 * 1000 + t2)) .
                      map (\(a:b:_) -> (a,b)))
                     (replicateM n readNumbers)

  let scoreGroupings = calcScoreGroupings scoreList0
      scoreListArray = listArray (1, n) scoreList0

  print (fromJust
         (lookup (scoreListArray ! k)
                  scoreGroupings))

import Data.List
q k l=fst$head$dropWhile(\(a,b) -> a+b<k)$zip l (scanl (+) 0 l)
s([_,k]:t)=q k.map length.group.sort$map(\[a,b]->(-a,b))t
main=interact$show.s.map(map read.words).lines

import Data.List

parse :: String -> [(Int, Int)]
parse stuff =
    map parse_line (lines stuff)
    where parse_line l = t2 $ map (read::String->Int) (words l)
          t2 [a, b] = (a, b)
          t2 _ = error "unexpected input"

solve :: [(Int, Int)] -> Int
solve ((_, k):teams) = findKth k sorted
    where
      sorted = reverse . group . sort $ teams
      findKth _ [] = 0
      findKth k (x:xs)
          | length x >= k = length x
          | otherwise     = findKth (k - length x) xs
      -- findKth _ _ = 0

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

import Data.List

parse :: String -> [(Int, Int)]
parse stuff =
    map parse_line (lines stuff)
    where parse_line l = t2 $ map (read::String->Int) (words l)
          t2 [a, b] = (a, b)
          t2 _ = error "unexpected input"

solve :: [(Int, Int)] -> Int
solve ((_, k):teams) = findKth k sorted
    where
      sorted = reverse . group . sort $ teams
      findKth _ [] = 0
      findKth k (x:xs)
          | length x > k = length x
          | otherwise     = findKth (k - length x) xs
      -- findKth _ _ = 0

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

import Data.List
import Control.Applicative
readi = read::String->Int
getParams = map readi . words <$> getLine
getDesc = zip' . map readi . words <$> getContents
  where zip' [] = []
        zip' (x:y:xs) = (x,y):zip' xs
sort' = sortBy (\(a,b) (a', b') -> if a == b then compare b a
                                   else compare a' b')
solve k (x:xs)
  | y <= 0 = length x
  | otherwise = solve y xs
  where y = k - (length x)
main=do
  [_,k] <- getParams
  rsorted <- sort' <$> getDesc
  putStrLn $ show ((solve k).group $ rsorted)

import Data.List
import Control.Applicative
readi = read::String->Int
getParams = map readi . words <$> getLine
getDesc = zip' . map readi . words <$> getContents
  where zip' [] = []
        zip' (x:y:xs) = (x,y):zip' xs
solve k (x:xs)
  | y <= 0 = length x
  | otherwise = solve y xs
  where y = k - (length x)
main=do
  [_,k] <- getParams
  sorted <- sort <$> getDesc
  putStrLn $ show ((solve k).reverse.group $ sorted)

module Main where

import Prelude hiding (lookup)
import Data.Array (listArray, (!))
import Data.Map (Map, fromList, lookup)
import Data.List (sortBy, group)
import Control.Monad (replicateM)
import Data.Maybe (fromJust)
import qualified Data.ByteString.Char8 as BS

readNumbers :: IO [Int]
readNumbers =
 (fromJust
  . fmap (map fst)
  . sequence
  . map BS.readInt
  . BS.words) `fmap` BS.getLine

flipOrdering LT = GT
flipOrdering EQ = EQ
flipOrdering GT = LT

calcScoreGroupings :: [(Int, Int)] -> Map (Int, Int) Int
calcScoreGroupings =
  fromList .
  map (\groups -> (head groups, length groups)) .
  group

main :: IO ()
main = do
  (n:k:_) <- readNumbers
  scoreList0 <- fmap (sortBy (\a b -> flipOrdering $ compare a b) .
                      map (\(a:b:_) -> (a,b)))
                     (replicateM n readNumbers)

  let scoreGroupings = calcScoreGroupings scoreList0
      scoreListArray = listArray (1, n) scoreList0

  print (fromJust (lookup (scoreListArray ! k) scoreGroupings))

import Data.List
s([_,k]:t)=[q|x<-map length.group.sort$map(\[a,b]->(-a,b))t,q<-replicate x x]!!(k+1)
main=interact$show.s.map(map read.words).lines


module Main where

solve :: [Int] -> Int
solve (_ : timeLimit : restaurants) = maximum $ map pleasure (makePairs restaurants)
    where pleasure (rating, realTime) = rating - max 0 (realTime - timeLimit)
          makePairs [] = []
          makePairs (x:y:ys) = (x, y) : (makePairs ys)

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

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

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

main :: IO ()
main = do
  (_:k:a) <- map (fst . fromJust . C.readInt) <$> C.words <$> C.getContents
  print $ maximum $ [f - max 0 (t - k) | (f, t) <- pairs a]

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

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

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

main = do
  [n, k] <- getInts
  os <- replicateM n getInts

  print $ maximum $ map (\[f, t] -> if t >= k then f - (t-k) else f) os

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

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

solve :: Int -> [[Int]] -> Int
solve k xs  =  maximum $ map (\[f, t] -> if t > k then f - (t - k) else f) xs

main :: IO ()
main  =  do
    [n, k]  <-  reads
    xs  <-  replicateM n reads
    print $ solve k xs

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

process::Integer->Integer->[[String]]->String
process x n [] = (show x) ++ " " ++ (show n)
process x n ((a:b:[]):cs) | a=="+" = process (x+bb) n cs
                          | bb<= x = process (x-bb) n cs
                          | otherwise = process x (n+1) cs
      where bb = read b ::Integer

main = do
   [a,k]<-map read <$> words <$> getLine ::IO [Int]
   d<- map (map read) <$> map words <$> lines <$> getContents ::IO [[Int]]
   print $ maximum $ map (\[z1,z2]-> z1 - (if z2>k then z2-k else 0)) d

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

main = do
  [n, k] <- getList
  a <- replicateM n getList
  let b = map (\[f, t] -> if t > k then f-(t-k) else f) a
  print $ maximum b
  where
    getList = fmap (map read . words) getLine

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

solve :: [[Integer]] -> Integer
solve ([_, k] : fts) = maximum [ f - max 0 (t - k) | [ f, t ] <- fts ]
solve _ = undefined

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

solve :: [[Integer]] -> Integer
solve ([_, k] : fts) = maximum [ if t > k then f - (t - k) else f | [ f, t ] <- fts ]
solve _ = undefined

main = interact $ show . solve . parse . map read . tail . words
parse (n:xs) = (n,pairs xs) where
  pairs (a:b:xs) = (a,b) : pairs xs
  pairs [] = []
solve (k,ps) = maximum $ map g ps where
  g (f,t) = f - max 0 (t-k)

import Control.Monad
main = do
    s <- getLine
    let [n, k] = map read $ words s
    restaurants <- forM [1..n] (\_ -> do
        s_i <- getLine
        let [f, t] = map read $ words s_i
        return (f, t))
    print . maximum . satisfactions k $ restaurants

satisfactions :: Int -> [(Int, Int)] -> [Int]
satisfactions k = foldl (\acc (f, t) -> (if t > k then (f - (t - k)) else f) : acc) []

main=interact$show.f.map read.words
f :: [Integer] -> Integer
f(n:k:fts) = maximum $ g fts
   where
     g (f:t:xs) = if t > k then (f - (t - k)) : g xs
                           else f : g xs
     g _ = []

module Main where

satisfaction :: Int -> [Int] -> Int
{- satisfaction TimeLimit RestaurantParams -}
satisfaction limit params = let [sat, time] = params
                            in
                            if time > limit then sat - time + limit else sat

main = do
  paramStr <- getLine
  restaurantsStr <- getContents
  let [_, timeLimit] = map read $ words paramStr
      restaurants = (map (map read . words)) $ lines restaurantsStr
  print $ maximum $ map (satisfaction timeLimit) restaurants

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

main= do
	[n,m]<- map read .words <$> getLine::IO [Int]
	s<- map (map read). map words. lines <$> getContents ::IO [[Int]]
	print $ maximum $ map (\[a, b]-> if b<=m then a else a+m-b) s

import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Char

main :: IO ()
main = do
	line1 <- getLine
	content <- getContents
	let
		[n, k] = map (\x -> read x :: Integer). words $ line1
		arr =  map (\[x, y] -> (read x :: Integer, read y :: Integer) ). map words. lines $ content
		solve [] = []
		solve ((f, t): xs)
		 | t > k = (f - t + k) : solve (xs)
		 | otherwise = f : solve (xs)
--	print content
--	print arr
	print $ maximum. solve $ arr

import qualified Data.ByteString.Char8 as B

readInt bs = case B.readInt bs of Just (n,_) -> n
main = B.getContents >>= putStr . show . solve . map readInt . B.words

pairs [] = []
pairs (x:y:xs) = (x,y) : pairs xs

solve (n:k:fts) = maximum . map eat . pairs $ fts
    where
        eat (f, t)
            | t > k = f - (t - k)
            | otherwise = f

import Data.List
import Control.Applicative
import Data.Function
main = do
    [n,k] <- map read . words <$> getLine
    rs <- partition (\[f,t] -> t <= k) . map (map read . words) . take n . lines <$> getContents
    case fst rs of
        [] -> print $ maximum $ map (\[f,t] -> f + k - t) $ snd $ rs
        lst -> case snd rs of
                [] -> print $ maximum $ map head $ lst
                lst' -> print$max (maximum $ map head $ lst) $ (maximum $ map (\[f,t] -> f + k - t) $ snd $ rs)

import Data.List
import Control.Applicative
import Data.Function
main = do
    [n,k] <- map read . words <$> getLine
    rs <- partition (\[f,t] -> t <= k) . map (map read . words) . take n . lines <$> getContents
    case fst rs of
        [] -> print $ maximum $ map (\[f,t] -> f + k - t) $ snd $ rs
        lst -> print $ maximum $ map head $ lst

import Data.List
import Control.Applicative
import Data.Function
main = do
    [n,k] <- map read . words <$> getLine
    rs <- partition (\[f,t] -> t <= k) . map (map read . words) . take n . lines <$> getContents
    case fst rs of
        [] -> print $ minimum $ map (\[f,t] -> f + k - t) $ snd $ rs
        lst -> print $ maximum $ map head $ lst


{-# LANGUAGE BlockArguments #-}

import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.List

main = do
  [t] <- getInts
  replicateM_ t do
    [n] <- getInts
    a <- getInts
    b <- getInts
    let result = sorted a || (elem 0 b && elem 1 b)
    putStrLn if result then "Yes" else "No"
    where
    sorted xs = all id  $ zipWith (<=) xs (tail xs)

getInts :: IO [Int]
getInts = go <$> BS.getLine
  where
    go s = case BS.readInt s of
      Nothing -> []
      Just (x, s') -> x : go (BS.drop 1 s')

import Control.Monad
import Data.List

main :: IO()
main = do
  [t] <- readInts
  replicateM_ t setup

readInts :: IO [Int]
readInts = map read.words <$> getLine

isType :: Int -> (Int, Int) -> Bool
isType t x = t == (snd x)

setup :: IO()
setup = do
  [n] <- readInts
  a <- readInts
  b <- readInts
  let c = zip a b
  let zeros = filter (isType 0) c
  let ones = filter (isType 1) c
  putStrLn (if solve a zeros ones then "Yes" else "No")

solve :: [Int] -> [(Int, Int)] -> [(Int, Int)] -> Bool
solve a zeros ones
  | length zeros > 0 && length ones > 0 = True
  | otherwise = a == (sort a)

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE BangPatterns #-}

import Data.List

_split acc "" [] = reverse acc
_split acc curr [] = reverse $ reverse curr : acc
_split acc curr (ch:rest)
  | (any (== ch) [' ', '\n']) = _split (reverse curr : acc) "" rest
  | otherwise = _split acc (ch:curr) rest

split = _split [] ""

(|>) = flip ($)

main = do
  input <- getContents
  let _:vals = read <$> split input :: [Int]
      res = vals |> unfoldr (\case
        []  -> Nothing
        n:rest0   ->
          let (subInput, rest1) = splitAt (2*n) rest0
              (vals, types) = splitAt n subInput
              isSorted = all (uncurry (<=)) adjPairs where
                adjPairs = zip vals $ tail vals
              hasBoth = hasZero && hasOne where
                hasZero = any (== 0) types
                hasOne = any (== 1) types
              subRes = if hasBoth || isSorted then "Yes" else "No"
          in Just (subRes, rest1)
        )
  sequence_ $ putStrLn <$> res


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

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

------

type Hopper r = State [r]

type HopperT r = StateT [r]

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

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

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

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

type MonadHopper r m = MonadState [r] m

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

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

------

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

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

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

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

------

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

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

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

------

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

run1 = do
  ~[n, m] <- popInts
  as <- popIntegers
  xs <- popIntegers
  return $ B.unwords $ map bshow $ solve n m as xs

solve n m as0 xs = map calc xs
  where
    a0 = head as0
    as = tail as0 ++ [a0]

    (csum, cmax, cmap) = foldl' foldf (0, 0, Map.empty) $ zip [0..] as

    foldf (s, mx, mp) (i, a) =
      let s' = s + a in
        if s' > mx
        then (s', s', Map.insert s' i mp)
        else (s', mx, mp)

    calc x | x <= a0 = 0
           | x <= a0 + cmax = 1 + calcSteps (x - a0)
           | csum <= 0 = -1
           | otherwise =
               let c = (x - a0 - cmax + csum - 1) `quot` csum in
                 1 + c * (fromIntegral n) + calcSteps (x - a0 - c * csum)

    calcSteps x = snd $ Map.findMin $ Map.dropWhileAntitone (< x) cmap

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

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

import Data.Int
import qualified Data.Map.Strict as M

type SIO = StateT P.ByteString IO

ceilDiv :: Integral t => t -> t -> t
ceilDiv n k = div (n + k - 1) k

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n, _m] <- readInts
    a <- readInts
    let
      sa = tail $ scanl (\x y -> x + fromIntegral y) 0 a
      cycleIncr = last sa
      possibleStops = M.fromAscList $ do
        (i, val, score) <- zip3 [0..] sa $ scanl max minBound sa
        [(val, i) | val > score]
      highestStop = fst $ M.findMax possibleStops
      n64 = fromIntegral n
    x <- map fromIntegral <$> readInts
    putInt64s $ flip map x $ \xi -> case  M.lookupGE xi possibleStops  of
      Just (_, i) -> i
      Nothing -> if  cycleIncr <= 0
        then  0 - 1
        else  let
        wastedCycles = ceilDiv (xi - highestStop) cycleIncr
        nxi = xi - wastedCycles * cycleIncr
        in  case  M.lookupGE nxi possibleStops  of
        Just (_, i) -> wastedCycles * n64 + i
        Nothing     -> error "some arithmetic overflow or mistake?"

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.dropWhile (<= '\r') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

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


import Data.List
import Data.Word

main :: IO ()
main = do
    getLine
    answers <- map (solve . map read . words) <$> lines <$> getContents :: IO [String]
    mapM_ putStrLn answers

solve :: [Word64] -> String
solve [c,d] = intercalate "b" [genrep a1 'a', genrep a2 'a' , genrep a3 'a' ]
    where
        (a2,a1) = f d' (c-1) 0
        total = c*(c-1) `div` 2
        d' = total - d
        a3 = c - a1 - a2 - 2
        genrep = genericReplicate

f :: Word64 -> Word64 -> Word64 -> (Word64, Word64)
f d c i
    | d < c = (d,i)
    | otherwise = f (d-c) (c-1) (i+1)

import Control.Arrow

main = interact $
  lines >>> drop 1
  >>> map ((words >>> map read) >>> solve)
  >>> unlines

solve :: [Integer] -> String
solve [n, k] = reverse $ foldl1 (++) $ map copy
  [(j - 1, 'a'), (1, 'b'), (i - j - 1, 'a'), (1, 'b'), (n - i, 'a')]
  where
    copy (n, c)
      | n <= 0 = ""
      | otherwise = take (fromIntegral n) $ repeat c
    c2 v = (v * (v - 1)) `div` 2
    getfirst len rank
      | c2 len < rank = max len $ getfirst (len + 1) rank
      | otherwise = 0
    i = (getfirst 0 k) + 1
    j = k - (c2 (i - 1))

module Main where

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = words <$> getLine

getIntList :: IO [Int]
getIntList = map read <$> getStrList

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, k] <- getIntList
        putStrLn . reverse . get n $ f n k

f :: Int -> Int -> (Int, Int)
f n k =
    let p = head . filter (\x -> k <= cal x) $ [1 .. n - 1]
        q = k - cal (p - 1) - 1
    in (q, p)

cal :: Int -> Int
cal x = case x `mod` 2 of
    0 -> x `div` 2 * (x + 1)
    1 -> (x + 1) `div` 2 * x

get :: Int -> (Int, Int) -> String
get n (p, q) = (replicate p 'a')
               ++ "b"
               ++ (replicate (q - p - 1) 'a')
               ++ "b"
               ++ (replicate (n - q - 1) 'a')

import Control.Monad (replicateM_)
import Data.List (genericReplicate)

getList :: Read b => IO [b]
getList = map read . words <$> getLine

main = readLn >>= flip replicateM_ solveIO

solveIO = do
    [n,k] <- getList
    putStrLn $ solve n k

solve :: Integer -> Integer -> String
solve 2 _ = "bb"
solve n k | k <= (n-1)*(n-2) `div` 2 = 'a' : solve (n-1) k
          | otherwise = let p = k - (n-1)*(n-2) `div` 2 - 1; q = n - 2 - p
                in "b" ++ genericReplicate q 'a' ++ "b" ++ genericReplicate p 'a'

import Data.Maybe
import Control.Monad

work :: IO ()
work = do
  [n, k] <- map read . words <$> getLine
  let a = head $ filter (\x -> (1 + x) * x `div` 2 >= k) [1 .. ]
      b = k - (a - 1) * a `div` 2 - 1
  putStrLn [let i = n - j in if i == a || i == b then 'b' else 'a' | j <- [1 .. n]]

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

import Control.Monad

main = do
    numTests <- read <$> getLine
    replicateM_ numTests $ do
        [n, k] <- map read . words <$> getLine
        let i1' = getidx 1 k
        let i2 = k - div (i1'*(i1'-1)) 2
        let i1 = i1' + 1
        putStrLn $
            replicate (fromInteger $ n - i1) 'a' ++
            "b" ++
            replicate (fromInteger $ i1 - i2 - 1) 'a' ++
            "b" ++
            replicate (fromInteger $ i2 - 1) 'a'

getidx :: Integer -> Integer -> Integer
getidx n k =
    if k <= n then
        n
    else
        getidx (n + 1) (k - n)

convertToString :: Int -> (Int,Int) -> String
convertToString l (b1,b2) = (replicate b1 'a')++"b"++(replicate (b2-b1-1) 'a')++"b"++(replicate (l-b2-1) 'a')

nextString :: Int -> Int -> (Int,Int) -> (Int,Int)
nextString 1 _ found = found
nextString k l (lfirstB,lsecondB) = if (lsecondB-lfirstB)==1
                                       then nextString (k-1) l (lfirstB-1,l-1)
                                       else nextString (k-d) l (lfirstB,lsecondB-d)
                                           where diff = (lsecondB-lfirstB-1)
                                                 d = if diff > (k-1)
                                                        then (k-1)
                                                        else diff

kthString :: [Int] -> String
kthString (n:k:[]) = convertToString n $ nextString k n (n-2,n-1)

main :: IO()
main = do
    interact $ unlines . map (kthString . (map read) . words) . tail . lines

import Control.Monad (replicateM_)

getList :: Read b => IO [b]
getList = map read . words <$> getLine

main = readLn >>= flip replicateM_ solveIO

solveIO = do
    [n,k] <- getList
    putStrLn $ solve n k

solve :: Int -> Int -> String
solve 2 _ = "bb"
solve n k | k <= (n-1)*(n-2) `div` 2 = 'a' : solve (n-1) k
          | otherwise = let p = k - (n-1)*(n-2) `div` 2 - 1; q = n - 2 - p
                in "b" ++ replicate q 'a' ++ "b" ++ replicate p 'a'

import Control.Monad

main = do
    numTests <- read <$> getLine
    replicateM_ numTests $ do
        [n, k] <- map read . words <$> getLine
        let i1' = getidx 1 k
        let i2 = k - div (i1'*(i1'-1)) 2
        let i1 = i1' + 1
        putStrLn $
            replicate (n - i1) 'a' ++
            "b" ++
            replicate (i1 - i2 - 1) 'a' ++
            "b" ++
            replicate (i2 - 1) 'a'

getidx n k =
    if k <= n then
        n
    else
        getidx (n + 1) (k - n)


{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}

output as k =
  let
    small = minimum as
    large = maximum as
  in if large - small > 2 * k
  then print $ -1
  else print $ small + k

inspect 0 = putStr ""
inspect n = do
  line <- getLine
  let _:k:_ = map read $ words line
  line2 <- getLine
  let as = map read $ words line2
  output as k
  inspect $ n - 1

main = do
  line <- getLine
  inspect $ read line

readInt :: String -> Int
readInt = read

main = interact $ solve . (map ((map readInt) . words)) . tail . lines

solve :: [[Int]] -> String
solve [] = ""
solve ([n, k]:a:rest) = (solveInstance [n, k] a) ++ solve rest

validRange :: (Int, Int) -> Bool
validRange (a, b) = a <= b

maxElem :: (Int, Int) -> Int
maxElem (a, b) | validRange (a, b) = b
               | otherwise = -1

solveInstance :: [Int] -> [Int] -> String
solveInstance [_, k] a =
    let ranges = (map (\x -> (max 1 (x-k), x+k)) a) in
    let range = foldl (\(a, b) (c, d) -> (max a c, min b d)) (head ranges) ranges in
    ((++"\n") . show . maxElem) range

import Control.Monad
main = do
  q <- readLn
  replicateM_ q $ do
    [n,k] <- map read . words <$> getLine
    as <- map read . words <$> getLine
    let m = minimum as
    print $ if maximum as - m > 2*k then -1
            else m + k


main = do
	[a, b, n] <- fmap (map read . words) getLine
	putStrLn $ last $ "No solution" : [show x | x <- [-1000 .. 1000], a * x ^ n == b]

module Main where

import Control.Monad
import Data.Maybe

main = do
    [a, b, n] <- ( map read . words ) `liftM` getLine

    putStrLn $ maybe "No solution" show $ do
        if a == 0
            then if b == 0
                then return 1
                else fail ""
            else do
                if b `mod` a == 0
                    then return ()
                    else fail ""

                let b' = abs $ b `div` a
                    sign = b `div` a < 0
                    x = round $ ( fromIntegral b' ) ** ( 1 / fromIntegral n )

                if sign && even n
                    then fail ""
                    else return ()

                if x ^ n == b'
                    then return ()
                    else fail ""

                if sign
                    then return (-x)
                    else return x

import Maybe (listToMaybe)

solve :: Integer -> Integer -> Integer -> Maybe Integer
solve a b n  =  listToMaybe $ [x | x <- [-1000 .. 1000], a * x^n == b]

main :: IO ()
main  =  do
    [a, b, n]  <-  fmap (map read . words) getLine
    putStrLn $ maybe "No solution" show $ solve a b n

findAllBases target exponent = filter (\x -> x ^ exponent == target) [minBound..maxBound]
    where minBound = min (-target) target
          maxBound = max target (-target)

findBase target exponent = if (length solutions == 0) then "No solution" else show (head solutions)
    where solutions = findAllBases target exponent

solve _ 0 _ = "0"
solve 0 _ _ = "No solution"
solve a b n | (mod b a) /= 0 = "No solution"
            | otherwise = findBase (div b a) n

main = do
       inputLine <- getLine
       let tmp = words inputLine
       let a = read (tmp !! 0) :: Int
       let b = read (tmp !! 1) :: Int
       let n = read (tmp !! 2) :: Int
       putStrLn (solve a b n)

import Control.Applicative

solve a b n = map fst $ filter ((==b).snd) [(x, a*(x^n)) | x <- [-1500..1500]]

ints = map read . words <$> getLine

main = do
    [a, b, n] <- ints
    case solve a b n of
        x:xs -> print x
        []   -> putStrLn "No solution"

import Data.Maybe (listToMaybe)
import Control.Applicative ((<|>))

main :: IO ()
main = getContents >>= putStrLn . maybe "No solution" show . (\[ a, b, x ] -> solve a b x) . map read . words

solve :: Integer -> Integer -> Integer -> Maybe Integer
solve a b n = listToMaybe [ 1 | a == 0 && b == 0 ] <|> listToMaybe [ x | a /= 0 && a * x ^ n == b ]
  where x = signum (a * b) * round (exp (log (abs $ fromIntegral $ b `div` a) / fromIntegral n) :: Double)

import Data.Maybe (listToMaybe)

main :: IO ()
main = getContents >>= putStrLn . maybe "No solution" show . (\[ a, b, x ] -> solve a b x) . map read . words

solve :: Integer -> Integer -> Integer -> Maybe Integer
solve a b n = listToMaybe [ x | x <- [-1000..1000], a * x ^ n == b ]

import Control.Applicative
import Control.Monad
import Data.List
import Data.Bits
import Data.Ord
import Data.Function
import Text.Printf

main :: IO ()
main = do
  a : b : n :_ <- map read . words <$> getLine
  case [x | x <- [-1000 .. 1000], a * x ^ n == b] of
    x : _ -> print x
    _     -> putStrLn "No solution"

main = interact (ans)
a x = read((words x)!!0)::Integer
b x = read((words x)!!1)::Integer
n x = read((words x)!!2)::Integer
sol x=[y|y<-[1000,999..(-1000)], a x*y^n x==b x]
tmp []="No solution"
tmp xs=show(head xs)
ans x = tmp(sol(x))

import Maybe (listToMaybe)

solve :: Int -> Int -> Int -> Maybe Int
solve a b n  =  listToMaybe $ [x | x <- [-1000 .. 1000], a * x^n == b]

main :: IO ()
main  =  do
    [a, b, n]  <-  fmap (map read . words) getLine
    putStrLn $ maybe "No solution" show $ solve a b n

import Control.Applicative

solve a b n = map fst $ filter ((==b).snd) [(x, a*x^n) | x <- [-1000..1000]]

ints = map read . words <$> getLine :: IO [Int]

main = do
    [a, b, n] <- ints
    case solve a b n of
        x:xs -> print x
        []   -> putStrLn "No solution"


{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust, fromMaybe)
import Data.List (inits, tails)

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

testCase :: Scanner String
testCase = show <$> (compute <$> string <*> string)

substrings :: [a] -> [[a]]
substrings = tail . inits <=< tails

compute :: String -> String -> Int
compute a b = length a + length b - 2 * foldl max 0 [length s | s <- substrings a, t <- substrings b, s == t]

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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

import qualified Data.Map as M
import Data.Map((!))

import qualified Data.Set as S
import qualified Data.List as L
import Data.Bits((.&.), (.|.), xor)
import Data.Maybe

data Trie = Trie (M.Map Char Trie)

makeTrieWith :: String -> [String] -> Trie
makeTrieWith alpha str = Trie $ M.fromList $ alpha >>= \a-> case [xs | x:xs <- str , x == a] of
	s@(_:_) -> [(a, makeTrieWith alpha s)]
	[] -> []

lazyTrie str = makeTrieWith "azertyuiopqsdfghjklmwxcvbn" $ suffixes str
suffixes [] = [[]]
suffixes (x:xs) = (x:xs) : suffixes xs

result a b = (length a) + (length b) - 2 * val where
	treeA = lazyTrie a
	treeB = lazyTrie b

	aux0 (Trie t1) (Trie t2) = if null t3 then 0 else 1 + foldr max 0 t3 where
		t3 = M.intersectionWith aux0 t1 t2

	val = aux0 treeA treeB

main = do
	t <- getLine >>= return . read :: IO Integer
	let loop t = if t == 0 then return () else do
		a <- getLine
		b <- getLine
		print $ result a b
		loop $ t - 1
	loop t


main = do
  [p,q,l,r] <- fmap (map read . words) getLine
  z <- mapM g [1..p]
  x <- mapM g [1..q]
  print (solve (l, r) x z)
      where
        g _ = do
          [x,y] <- fmap (map read . words) getLine
          return (x, y)

solve :: (Int, Int) -> [(Int, Int)] -> [(Int, Int)] -> Int
solve (l, r) x z = length . filter f $ [l..r]
    where
      f v = any g x
          where
            g (ci, di) = intersect (ci +v) (di + v) z
      intersect c d z = any h z
          where
            h (a,b) = (c <= a && d >= a) || (c >= a && c <= b)

import Data.List
import Data.Function
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B

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

main = B.interact $ B.pack . show . getAns . getIntArray

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

getAns :: [Int] -> Int
getAns (p:q:l:r:xs) = calSum l r ps qs
		where ps = reAssign ls;
			  qs = reAssign rs;
			  (ls, rs) = splitAt (p * 2) xs

calSum l r ps qs = sum [haveCommon ps $ map (\(a, b) -> (a + t, b + t)) qs | t <- [l .. r]]

overLap :: ((Int, Int), (Int, Int)) -> Bool
overLap ((x1, y1), (x2, y2)) = (x1 >= x2 && x1 <= y2) || (y1 >= x2 && y1 <= y2) || (x2 >= x1 && x2 <= y1) || (y2 >= x1 && y2 <= y1)

haveCommon ps qs = if any overLap [(p, q) | p <- ps, q <- qs] then 1 else 0

import Control.Monad
import Data.List

main = do
  [p, q, l, r] <- fmap (map read . words) getLine
  abs <- replicateM p $ (fmap (map read . words)) getLine
  cds <- replicateM q $ (fmap (map read . words)) getLine

  let
    check x = f (sort abs) (sort cds)
      where
        f [] _ = False
        f _ [] = False
        f ([a, b]:abs) ([c, d]:cds)
          | b < c+x = f abs ([c, d]:cds)
          | d+x < a = f ([a, b]:abs) cds
          | otherwise = True

  print $ length $ filter check [l..r]

import Control.Applicative
import Control.Monad

toTuple :: [String] -> (Int,Int)
toTuple [x,y] = (read x, read y)

inInt :: [(Int,Int)] -> [(Int,Int)] -> Bool
inInt xs ys = or [x2 >= y1 && x1 <= y2| (x1,x2) <- xs, (y1,y2) <- ys]

main = do
  [p,q,l,r] <- map read . words <$> getLine
  zs <- map (toTuple . words) <$> replicateM p getLine
  xs <- map (toTuple . words) <$> replicateM q getLine
  print . sum $ [if inInt (map (\(x,y) -> (x+i,y+i)) xs) zs then 1 else 0 | i <- [l..r]]

import Control.Applicative ((<$>), (<*>))

main :: IO ()
main = print =<< solve <$> (toQuadruple . map read . words <$> getLine)
                       <*> (map (toTuple . map read . words) . lines <$> getContents)

solve :: (Int, Int, Int, Int) -> [(Int, Int)] -> Int
solve (p, _, l, r) abcd
  = sum [ fromEnum $ or [ c + t <= b && a <= d + t | (a, b) <- ab, (c, d) <- cd ] | t <- [l..r] ]
  where (ab, cd) = splitAt p abcd

toTuple :: [a] -> (a, a)
toTuple xs = (head xs, xs !! 1)

toQuadruple :: [a] -> (a, a, a, a)
toQuadruple xs = (head xs, xs !! 1, xs !! 2, xs !! 3)

import Control.Monad (liftM, forM)
import Data.Array (listArray, (!))

for = flip map

trues = repeat True
falses = repeat False

input = do
  ln <- getLine
  return $ map read $ words ln

mor :: [[Bool]] -> [Bool]
mor = foldl1 $ zipWith (||)

main = do
  [p, q, l, r] <- input
  let g n = liftM mor $ forM [1..n] $ \_ -> do
      [a, b] <- input
      return $ (take a falses ++ take (b-a+1) trues ++ take (1001-b) falses)
  ipx <- g p
  iqx <- g q
  let ip = listArray (0, 1001) ipx
  let iq = listArray (0, 1001) iqx
  let li = for [l..r] (\i -> fromEnum $ or $ for [0..1001-i-1] (\j -> ip ! (i+j) && iq ! j))
  putStrLn $ show $ sum li

import Control.Monad (liftM, forM)
import Data.Array

main = do
  return ()


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

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

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

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    wood <- take n . C.unpack <$> C.getLine
    let (_, _, _, rs) = foldl' acc (M.empty, 0, 0, []) wood
        acc (mp, x, y, results) name =
          case M.lookup frac mp of
            Nothing -> (M.insert frac 1 mp, x', y', 1 : results)
            Just num -> (M.insert frac (num + 1) mp, x', y', (num + 1) : results)
          where
          (x', y')
            | name == 'D' = (x + 1, y)
            | otherwise = (x, y + 1)
          frac = (x' `div` g, y' `div` g)
            where g = gcd x' y'
    return $ mconcat (intersperse (charUtf8 ' ') $ map intDec $ reverse rs) `mappend` charUtf8 '\n'
  hPutBuilder stdout output

import qualified Data.Map.Strict as M
import Data.Ratio
import Control.Monad
import Control.Monad.State
import Control.Arrow
import Data.Maybe (fromJust)

--type Tracker = (State )

type Tracker = State (Int, Int, M.Map (Ratio Int) Int)

helper :: Maybe Int -> Maybe Int
helper Nothing = Just 1
helper (Just x) = Just (x + 1)

goOne :: Char -> Tracker Int
goOne c = do (ds, ks, mm) <- get
             if c == 'D'
                then put (ds + 1, ks, mm)
                else put (ds, ks + 1, mm)
             (ds1, ks1, mm1) <- get
             let key = if ks1 == 0 then (-1) % 1 else ds1 % ks1
                 mmm = M.alter helper key mm1
                 --nt = fromJust $ M.lookup key mmm
                 nt = mmm M.! key
              in do put (ds1, ks1, mmm)
                    return nt

goMany :: String -> Tracker [Int]
goMany = mapM goOne

dropEvrySnd [] = []
dropEvrySnd (x:y:xs) = y : dropEvrySnd xs

runner :: String -> String
runner = words
         >>> drop 1
         >>> dropEvrySnd
         >>> map goMany
         >>> map (flip evalState (0, 0, M.empty))
         >>> map (map show >>> unwords)
         >>> unlines

main = interact runner

import qualified Data.Map.Strict as M
import Data.Ratio
import Control.Monad
import Control.Monad.State
import Control.Arrow
import Data.Maybe (fromJust)

--type Tracker = (State )

type Tracker = State (Int, Int, M.Map (Ratio Int) Int)

helper :: Maybe Int -> Maybe Int
helper Nothing = Just 1
helper (Just x) = Just (x + 1)

goOne :: Char -> Tracker Int
goOne c = do (ds, ks, mm) <- get
             if c == 'D'
                then put (ds + 1, ks, mm)
                else put (ds, ks + 1, mm)
             (ds1, ks1, mm1) <- get
             let key = if ks1 == 0 then (-1) % 1 else ds1 % ks1
                 mmm = M.alter helper key mm1
                 nt = fromJust $ M.lookup key mmm
              in do put (ds1, ks1, mmm)
                    return nt

goMany :: String -> Tracker [Int]
goMany = mapM goOne

dropEvrySnd [] = []
dropEvrySnd (x:y:xs) = y : dropEvrySnd xs

runner :: String -> String
runner = words
         >>> drop 1
         >>> dropEvrySnd
         >>> map goMany
         >>> map (flip evalState (0, 0, M.empty))
         >>> map (map show >>> unwords)
         >>> unlines

main = interact runner

import qualified Data.Map as Map
import Control.Monad
import Data.List

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

evaluate s = dfs s Map.empty 0 0
  where dfs :: String -> Map.Map (Integer, Integer) Integer -> Integer -> Integer -> [Integer]
        dfs "" _ _ _ = []
        dfs (a:as) mp d k = value : dfs as mp' d' k'
          where d' = if a == 'D' then (d + 1) else d
                k' = if a == 'K' then (k + 1) else k
                g = gcd d' k'
                value =(+) 1 $ match $ Map.lookup (d' `div` g, k' `div` g) mp
                  where match Nothing = 0
                        match (Just a) = a
                mp' = Map.insert (d' `div` g, k' `div` g) value mp

solve = do
  [n] <- readIntLine
  s <- getLine
  putStrLn (intercalate " " $ Prelude.map show $ evaluate s)
  return ()

main = do
  [t] <- readIntLine
  replicateM t solve
  return ()

import Control.Monad (replicateM)
import qualified Data.Map.Strict as Map

main = do t <- read <$> getLine
          replicateM t solve

solve = do t <- getLine
           arr <- getLine
           let ans = iterateOver 0 0 (Map.fromList []) arr
           putStrLn $ unwords $ map show ans

iterateOver :: Int -> Int -> Map.Map (Int,Int) Int -> String -> [Int]
iterateOver dcnt kcnt _map [] = []
iterateOver dcnt kcnt _map ('D':xs) = sub : (iterateOver (dcnt+1) kcnt new_map xs)
    where key_gcd = gcd (dcnt+1) kcnt
          key = ((dcnt+1) `div` key_gcd,kcnt `div` key_gcd)
          sub = Map.findWithDefault 0 key _map + 1
          new_map = Map.insertWith (+) key 1 _map

iterateOver dcnt kcnt _map ('K':xs) = sub : (iterateOver dcnt (kcnt+1) new_map xs)
    where key_gcd = gcd (dcnt) (kcnt+1)
          key = (dcnt `div` key_gcd,(kcnt+1) `div` key_gcd)
          sub = Map.findWithDefault 0 key _map + 1
          new_map = Map.insertWith (+) key 1 _map

import Data.List (intercalate)
import Control.Monad (mapM, replicateM)
import Data.Ratio ((%))
import Data.Map (empty, findWithDefault, insert)

main = do t <- read <$> getLine
          replicateM t solve

solve = do getLine
           s <- getLine
           putStrLn (intercalate " " (map show (maxBlocks s)))

maxBlocks s = helper s empty 0 0
  where helper "" _ _ _ = []
        helper (c:s) prev d k = x : helper s prev' d' k'
          where (d', k') | c == 'D' = (d + 1, k)
                         | c == 'K' = (d, k + 1)
                r | k' == 0   = 69000000 % 1
                  | otherwise = d' % k'
                x = (findWithDefault 0 r prev) + 1
                prev' = insert r x prev


import Data.List

unique = map head . group . sort

main = do
    [n, k] <- fmap (map (read :: String -> Integer) . words) $ getLine
    a <- fmap (map ((`mod` k) . (read :: String -> Integer)) . words) $ getLine

    let d = foldl1 gcd (unique a)
    let answer = unique $ map (\x -> x * d `mod` k) [0..k - 1]

    print . length $ answer
    putStrLn . unwords . map show $ answer

import Data.List

main = do
  [_, k] <- fmap (map read . words) getLine
  a <- fmap (map read . words) getLine
  let g = foldl' gcd k a
  print $ k `div` g
  putStrLn $ unwords . map show . takeWhile (< k) $ iterate (+g) 0

import Data.List

toint s = (read s) :: Int

solve::String -> String
solve ss =
  let (n:k:aa) = map toint $ words ss in
  let a = map (\x -> (mod x k)) aa in
  let g = gcd (foldr gcd 0 a) k in
  (show (div k g)) ++ "\n" ++ (intercalate " " $ map show [0,g..k-1]) ++ "\n"

main = interact solve

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

-- gcd :: Int -> Int -> Int
-- gcd a 0 = a
-- gcd a b = gcd b $ a `div` b

gen :: [Int] -> Int -> Int -> Int -> [Int]
gen res denom k x | denom == x = res
gen res denom k x = gen (x:res) denom k $ (x + denom) `mod` k

main = do
    n:k:[] <- fmap (map read . words) getLine
    a <- fmap (map read . words) getLine
    let vals = filter (/=0) $ map (`mod` k) a
    if null vals then do
        print 1
        print 0
    else do
        let denom = foldl1 gcd vals
        let res = sort $ gen [denom] denom k ((denom * 2) `mod` k)
        print $ length res
        forM_ res $ \x-> do
            putStr $ show x
            putStr " "
        putStrLn ""

import Data.List

main = do
    [n, k] <- fmap (map (read :: String -> Int) . words) $ getLine
    a <- fmap (map ((`mod` k) . (read :: String -> Int)) . words) $ getLine

    let d = foldl1 gcd a
    let answerCandidate = map (* d) [0..k - 1]

    let answer = if 0 `elem` a then [0] else answerCandidate

    print . length $ answer
    putStrLn . unwords . map show . sort $ answer

main = do
    [n, k] <- fmap (map (read :: String -> Int) . words) $ getLine
    a <- fmap (map ((`mod` k) . (read :: String -> Int)) . words) $ getLine

    let d = foldl1 gcd a
    let answer = map (* d) [0..(k - 1) `div` d]

    let (l1, l2) = if 0 `elem` a then (1, [0]) else (length answer, answer)

    print l1
    putStrLn . unwords . map show $ l2

import Data.List

main = do
    [n, k] <- fmap (map (read :: String -> Integer) . words) $ getLine
    a <- fmap (map ((`mod` k) . (read :: String -> Integer)) . words) $ getLine

    let d = foldl1 gcd a
    let answerCandidate = map (\x -> x * d `mod` k) [0..k - 1]

    let answer = if 0 `elem` a then [0] else map head . group . sort $ answerCandidate

    print . length $ answer
    putStrLn . unwords . map show $ answer

import Data.List

main = do
    [n, k] <- fmap (map (read :: String -> Int) . words) $ getLine
    a <- fmap (map ((`mod` k) . (read :: String -> Int)) . words) $ getLine

    let d = foldl1 gcd a
    let answerCandidate = map (\x -> x * d `mod` k) [0..k - 1]

    let answer = if 0 `elem` a then [0] else map head . group . sort $ answerCandidate

    print . length $ answer
    putStrLn . unwords . map show $ answer


-- 1687A
{-# LANGUAGE Strict  #-}
{-# LANGUAGE ParallelListComp  #-}

import Control.Monad (replicateM_)
import Data.Array.IArray

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

run :: IO ()
run = do
  [n, k] <- map read . words <$> getLine :: IO [Int]
  as <- map read . words <$> getLine :: IO [Int]
  print $ if n < k then solve2 n k as else solve1 n k as

solve1 :: Int -> Int -> [Int] -> Int
-- solve1 n k as = ((k-1)*k) `div` 2 + maximum (ksum n k as)
solve1 n k as = ((k-1)*k) `div` 2 + ksum'' k ss
  where
    -- ksum n k as = ksum' n k as
    ss = 0 : [a + s | a <- as | s <- ss]
    ksum'' k sums = maximum [s2 - s1 | s2 <- drop k ss | s1 <- ss]
    ksum n k as = ksum' as (drop (k-1) as) (sum (take (k-1) as))
    ksum' (p:prevs) (n:nexts) curr = (curr+n) : ksum' prevs nexts (curr+n-p)
    ksum' _ [] _ = []
    ksum' [] _ _ = []

solve2 :: Int -> Int -> [Int] -> Int
solve2 n k as = sum as + n*k - ((n*(n+1)) `div` 2)

-- 1687A
{-# LANGUAGE Strict  #-}

import Control.Monad (replicateM_)
import Data.Array.IArray

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

run :: IO ()
run = do
  [n, k] <- map read . words <$> getLine :: IO [Int]
  as <- map read . words <$> getLine :: IO [Int]
  print $ if n < k then solve2 n k as else solve1 n k as

solve1 :: Int -> Int -> [Int] -> Int
solve1 n k as = ((k-1)*k) `div` 2 + maximum (ksum n k as)
  where
    -- ksum n k as = ksum' n k as
    ksum n k as = ksum' as (drop (k-1) as) (sum (take (k-1) as))
    ksum' (p:prevs) (n:nexts) curr = (curr+n) : ksum' prevs nexts (curr+n-p)
    ksum' _ [] _ = []
    ksum' [] _ _ = []

solve2 :: Int -> Int -> [Int] -> Int
solve2 n k as = sum as + n*k - ((n*(n+1)) `div` 2)

-- 1687A

import Control.Monad (replicateM_)
import Data.Array.IArray

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

run :: IO ()
run = do
  [n, k] <- map read . words <$> getLine :: IO [Int]
  as <- map read . words <$> getLine :: IO [Int]
  print $ if n < k then solve2 n k as else solve1 n k as

solve1 :: Int -> Int -> [Int] -> Int
solve1 n k as = ((k-1)*k) `div` 2 + maximum (ksum n k as)
  where
    -- ksum n k as = ksum' n k as
    ksum n k as = ksum' as (drop (k-1) as) (sum (take (k-1) as))
    ksum' (p:prevs) (n:nexts) curr = (curr+n) : ksum' prevs nexts (curr+n-p)
    ksum' _ [] _ = []
    ksum' [] _ _ = []

solve2 :: Int -> Int -> [Int] -> Int
solve2 n k as = sum as + n*k - ((n*(n+1)) `div` 2)

-- 1687A
{-# LANGUAGE Strict  #-}
{-# LANGUAGE ParallelListComp  #-}

import Control.Monad (replicateM_)
import Data.Array.IArray

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

run :: IO ()
run = do
  [n, k] <- map read . words <$> getLine :: IO [Int]
  as <- map read . words <$> getLine :: IO [Int]
  print $ if n < k then solve2 n k as else solve1 n k as

solve1 :: Int -> Int -> [Int] -> Int
-- solve1 n k as = ((k-1)*k) `div` 2 + maximum (ksum n k as)
solve1 n k as = ((k-1)*k) `div` 2 + ksum'' k ss
  where
    -- ksum n k as = ksum' n k as
    ss = 0 : [a + s | a <- as | s <- ss]
    ksum'' k sums = maximum [s2 - s1 | s2 <- drop k ss | s1 <- ss]
    -- ksum n k as = ksum' as (drop (k-1) as) (sum (take (k-1) as))
    -- ksum' (p:prevs) (n:nexts) curr = (curr+n) : ksum' prevs nexts (curr+n-p)
    -- ksum' _ [] _ = []
    -- ksum' [] _ _ = []

solve2 :: Int -> Int -> [Int] -> Int
solve2 n k as = sum as + n*k - ((n*(n+1)) `div` 2)


import Data.Array as A
import Data.List

main = interact $ printAns. (\(a,b,c) -> solve a b c). readInp

readInp = prep. split. fmap (fmap read. words). lines
    where split a = (a !! 0 !! 0, init. tail $ a, last a)
          prep = fork (id, fmap toTpl, id)
            where fork (f, g, h) (a, b, c) = (f a, g b, h c)
                  toTpl a = (a !! 0, a !! 1)

printAns x = case x of
    Nothing -> "NO"
    Just v -> unlines ["YES", show v]

solve :: Int -> [(Int, Int)] -> [Int] -> Maybe Int
solve n edges colors =
    fmap fst. find sufficient. A.assocs. countForVertices $ importantEdges
    where
        importantEdges = filter isImportant edges
            where isImportant (u, v) = colorArr A.! u /= colorArr A.! v
                  colorArr = A.listArray bounds colors
        countForVertices = A.accumArray (\v _ -> v+1) 0 bounds. undirect
            where undirect = concatMap (\(u,v) -> [(u,v), (v,u)])
        sufficient = (== (length importantEdges)). snd
        bounds = (1, n)

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

import           System.IO hiding (char8)
import           Control.Applicative
import           Control.Monad
import           Data.List
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function (on)
import           Data.Array
-- import           Data.Array.Unboxed
-- import           Data.Array.IArray
-- import           Data.Array.ST
-- import           Data.Array.MArray
-- import           Data.Array.Unsafe
import           Data.Ix
import           Data.Maybe
import           Data.Monoid hiding ((<>))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import           Data.ByteString.Builder
import           Data.Graph
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntSet (IntSet)
-- import qualified Data.IntSet as S
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as M
-- import           Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))
-- import qualified Data.Sequence as S
-- import           Debug.Trace

main = do
  v <- readInt1 <$> BS.getLine
  es <- map readInt2 <$> replicateM (v-1) BS.getLine
  cs <- readIntN <$> BS.getLine
  -- print $ fst . maximumBy (compare `on` snd) . assocs . outdegree . buildG (1,v) $ es ++ map swap es
  format $ solve v es cs

format :: Maybe Int -> IO ()
format Nothing = putStrLn "NO"
format (Just a) = do
  putStrLn "YES"
  print a

hist :: (Ix a, Num b) => (a,a) -> [a] -> Array a b
hist bnds is = accumArray (+) 0 bnds [(i, 1) | i<-is, inRange bnds i]

solve :: Int -> [Edge] -> [Int] -> Maybe Int
solve v es cs = if
  | uniColor cs -> Just 1
  | maxDiffEdges == cntDiffColor (edges graph) -> Just maxDiffNode
  | otherwise -> Nothing
  where
    uniColor (c:cs) = all (==c) cs
    graph = buildG (1,v) $ es ++ map swap es
    -- maxDegNode = fst . maximumBy (compare `on` snd) . assocs $ outdegree graph
    -- maxDegEdges = map (,maxDegNode) $ graph!maxDegNode
    color = listArray (1,v) cs
    isDiffColor (a,b) = (color!a) /= (color!b)
    cntDiffColor = length . filter isDiffColor
    diffEdgeHist = hist (1,v) . concatMap fromTuple . filter isDiffColor $ edges graph
    maxDiffEdges = maximum $ elems diffEdgeHist
    maxDiffNode = fst . maximumBy (compare `on` snd) . assocs $ diffEdgeHist

--  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --

readInt1 :: BS.ByteString -> Int
readInt1 = fst . fromJust . BS.readInt

readInt2 :: BS.ByteString -> (Int,Int)
readInt2 = toTuple . readIntN

readInt3 :: BS.ByteString -> (Int,Int,Int)
readInt3 = toTriple . readIntN

readIntN :: BS.ByteString -> [Int]
readIntN =  map readInt1 . BS.words

readInt641 :: BS.ByteString -> Int64
readInt641 = fromIntegral . fst . fromJust . BS.readInteger

readInt642 :: BS.ByteString -> (Int64,Int64)
readInt642 = toTuple . readInt64N

readInt643 :: BS.ByteString -> (Int64,Int64,Int64)
readInt643 = toTriple . readInt64N

readInt64N :: BS.ByteString -> [Int64]
readInt64N =  map readInt641 . BS.words

readInteger1 :: BS.ByteString -> Integer
readInteger1 = fst . fromJust . BS.readInteger

readInteger2 :: BS.ByteString -> (Integer,Integer)
readInteger2 = toTuple . readIntegerN

readInteger3 :: BS.ByteString -> (Integer,Integer,Integer)
readInteger3 = toTriple . readIntegerN

readIntegerN :: BS.ByteString -> [Integer]
readIntegerN =  map readInteger1 . BS.words

toTuple :: [a] -> (a, a)
toTuple [x, y] = (x, y)

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

fromTuple :: (a, a) -> [a]
fromTuple (x, y) = [x, y]

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

-- if not applying, use "const"

applyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')
applyTuple f g (x, y) = (f x, g y)

applyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')
applyTriple f g h (x, y, z) = (f x, g y, h z)

import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Array
import Data.Tuple
import Data.List

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

solve :: Int -> [(Int, Int)] -> [Int] -> Maybe Int
solve n g cs' =
  let
    bnd = (1, n)
    cs = listArray bnd cs'
    diffs = filter (\(u, v) -> cs!u /= cs!v) g
    ln = length diffs
  in
    fst <$> (find (\(u, c) -> c == ln) . assocs . accumArray (\c u -> c + 1) 0 bnd $ concatMap (\(u, v) -> [(u, v), (v, u)]) diffs)

main = do
  n <- readInt <$> B.getLine
  g <- map ((\(u:v:_) -> (u, v)) . readInts) <$> replicateM (n - 1) B.getLine
  cs <- readInts <$> B.getLine
  putStrLn $ maybe "NO" (("YES\n" ++) . show) $ solve n g cs

import Data.Array as A
import Data.List

main = interact $ printAns. (\(a,b,c) -> solve a b c). readInp

readInp = prep. split. fmap (fmap read. words). lines
    where split a = (head a !! 0, init. tail $ a, last a)
          prep = fork (id, fmap toTpl, id)
            where fork (f, g, h) (a, b, c) = (f a, g b, h c)
                  toTpl a = (a !! 0, a !! 1)

printAns x = case x of
    Nothing -> "NO"
    Just v -> unlines ["YES", show v]

solve :: Int -> [(Int, Int)] -> [Int] -> Maybe Int
solve n edges colors =
    fmap fst. find sufficient. A.assocs. countForVertices $ importantEdges
    where
        importantEdges = filter isImportant edges
            where isImportant (u, v) = colorArr A.! u /= colorArr A.! v
                  colorArr = A.listArray bounds colors
        countForVertices = A.accumArray (\v _ -> v+1) 0 bounds. undirect
            where undirect = concatMap (\(u,v) -> [(u,v), (v,u)])
        sufficient = (==) importantCnt. snd
            where importantCnt = length importantEdges
        bounds = (1, n)


import qualified Data.List as L
import qualified Data.Map as M
import Data.Map (Map)
import qualified Data.Set as S
import Data.Set (Set)
import qualified Data.IntSet as IS
import Data.IntSet (IntSet)
import qualified Data.IntMap as IM
import Data.IntMap (IntMap)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)

type Long = Int

solve :: Double -> Double
solve n = r*2 * cos (pi * abs (i/n - 1/4))
    where
        r = 0.5 / sin (pi/2/n)
        i = fromIntegral $ round (n/4)

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    (n:_) <- readWords
    print $ solve n
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readWords
    testCases t

readWords :: (Read a) => IO [a]
readWords = map read . words <$> getLine

import Data.List

solve :: Double -> Double
solve n = cos(pi/(4*n))/sin(pi/(2*n))

main = interact $
          (intercalate "\n")
          . (map (show . solve . read))
          . (drop 1)
          . words


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

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

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

main :: IO ()
main = do
  [t] <- getInts
  result <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    str <- C.getLine
    let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if midZero then 1 else 0)
        midZero = odd n && C.index str (n `div` 2) == '0'
        z = C.count '0' str
        result
            | m == 0 = "BOB"
            | m == 1 && midZero && z > 1 = "ALICE"
            | m == 1 && midZero = "BOB"
            | m == 2 && midZero && z == 2 = "DRAW"
            | otherwise = "ALICE"
    return $ stringUtf8 result `mappend` charUtf8 '\n'
  hPutBuilder stdout result

import           Control.Monad

main = do
    t <- read <$> getLine
    replicateM_ t $ do
        _ <- getLine
        s <- getLine
        let winner = if reverse s == s
                        then solvePalin s
                        else solveNonPalin s
        putStrLn winner

countZeros :: String -> Int
countZeros = length . filter (== '0')

solvePalin :: String -> String
solvePalin s = let z = countZeros s in if even z || z == 1
                                        then "BOB"
                                        else "ALICE"

solveNonPalin :: String -> String
solveNonPalin s
  | even n || countZeros s /= 2  = "ALICE"
  | otherwise                    = if s !! quot n 2 == '0'
                                      then "DRAW"
                                      else "ALICE"
  where n = length s

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  result <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    str <- C.getLine
    let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if midZero then 1 else 0)
        midZero = odd n && C.index str (n `div` 2) == '0'
        z = C.count '0' str
        result
            | m == 0 = "BOB"
            | m == 1 && midZero && z > 1 = "ALICE"
            | m == 1 && midZero = "BOB"
            | m == 2 && midZero && z == 2 = "DRAW"
            | m == 2 && midZero = "BOB"
            | otherwise = "ALICE"
    return $ stringUtf8 result `mappend` charUtf8 '\n'
  hPutBuilder stdout result

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  result <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    str <- C.getLine
    let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if odd n && C.index str (n `div` 2) == '0' then 1 else 0)
        z = C.count '0' str
        result
            | m == 0 = "BOB"
            | m == 1 && (odd n && C.index str (n `div` 2) == '0') && z > 1 = "ALICE"
            | m == 1 && (odd n && C.index str (n `div` 2) == '0') = "BOB"
            | otherwise = "ALICE"
    return $ stringUtf8 result `mappend` charUtf8 '\n'
  hPutBuilder stdout result

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  result <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    str <- C.getLine
    let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if odd n && C.index str (n `div` 2) == '0' then 1 else 0)
        result
            | m == 1 && (odd n && C.index str (n `div` 2) == '0') || m == 0 = "BOB"
            | otherwise = "ALICE"
    return $ stringUtf8 result `mappend` charUtf8 '\n'
  hPutBuilder stdout result

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  result <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    str <- C.getLine
    let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if odd n && C.index str (n `div` 2) == '0' then 1 else 0)
        z = C.count '0' str
        result
            | z - m >= 2 && m == 0 = "BOB"
            | z == 1 && odd n && C.index str (n `div` 2) == '0' = "BOB"
            | otherwise = "ALICE"
    return $ stringUtf8 result `mappend` charUtf8 '\n'
  hPutBuilder stdout result

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  result <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    str <- C.getLine
    let m = length [() | i <- [0 .. (n - 2) `div` 2], C.index str i /= C.index str (n - 1 - i)] + (if odd n && C.index str (n `div` 2) == '0' then 1 else 0)
        z = C.count '0' str
        result
            | z - m >= 2 && m == 0 = "BOB"
            | otherwise = "ALICE"
    return $ stringUtf8 result `mappend` charUtf8 '\n'
  hPutBuilder stdout result


module Main where
import qualified Data.ByteString.Char8 as B
import Data.Array.Unboxed
main = B.interact exec
exec = B.pack . show . solve . map int . B.words
  where int = maybe undefined fst . B.readInt
solve (n:ls) = length $ filter (== 0) $ scanl1 (+) $  elems (accumArray (+) 0 (1, n) $ concat $ zipWith (\i l -> let lo = max 1 $ i -l in if lo > i - 1 then [] else [(max 1 $ i - l, 1), (i, -1)]) [1..] ls :: UArray Int Int)

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU
{-# LANGUAGE OverloadedStrings #-}

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

readI = fst . fromJust . C.readInt

main = C.interact $ C.pack . solve . map readI . C.words

solve (_:xs) = show ans
    where
        ans = fst $ foldl f (0, 0) $ reverse xs
        f (a, 0) x = (a + 1, x)
        f (a, k) x = (a, max (k-1) x)

module Main where
import Data.Array.Unboxed
main = interact exec
exec = show . solve . map read . words
solve (n:ls) = length $ filter (== 0) $ elems (accumArray (+) 0 (1, n) $ concat $ zipWith (\i l -> [(max 1 $ i - l, 1), (i, -1)]) [1..] ls :: UArray Int Int)


{-# OPTIONS_GHC -O3 -optc-O3 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, MagicHash #-}

import GHC.Prim (uncheckedIShiftL#,uncheckedIShiftRL#)
import GHC.Exts (Int(..))
import Control.Applicative ((<$>))
import Control.Monad (unless,when,forM_)
import Data.Array.Base
import Data.Array.IO (IOUArray)
import Data.Bits (testBit,shiftL,shiftR,xor,(.&.),(.|.))
import qualified Data.ByteString.Char8 as B (ByteString,readInt,words,getContents,getLine)
import Data.Int (Int64)
import Data.List (foldl')

infixl 8 .<<. , .>>.
(.<<.) :: Int -> Int -> Int
(I# x).<<.(I# i) = I# (uncheckedIShiftL# x i)
(.>>.) :: Int -> Int -> Int
(I# x).>>.(I# i) = I# (uncheckedIShiftRL# x i)
{-# INLINE (.<<.) #-}
{-# INLINE (.>>.) #-}

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
{-# INLINE readInt #-}

rep :: Int -> (Int -> IO ()) -> IO ()
rep !n f = go 0
   where
     go !i
       | i<n = f i >> go (i+1)
       | otherwise = return ()
{-# INLINE rep #-}

toDecimal :: [Int] -> Int64
toDecimal xs = foldl' (\x y->x`shiftL`1 + fromIntegral y) 0 xs
{-# INLINE toDecimal #-}

data SegTree = Node !Int !Int !(IOUArray Int Int) !(IOUArray Int Int) !SegTree !SegTree
             | Leaf !Int !(IOUArray Int Int)

merge :: SegTree -> SegTree -> IO SegTree
merge stx sty = do
  cnt <- newArray (0,19) 0 :: IO (IOUArray Int Int)
  f   <- newArray (0,19) 0 :: IO (IOUArray Int Int)
  rep 20 $ \b-> do
    x <- unsafeRead (getCnt stx) b
    y <- unsafeRead (getCnt sty) b
    unsafeWrite cnt b $! x+y
  return $! Node (getLeft stx) (getRight sty) cnt f stx sty

getLeft :: SegTree -> Int
getLeft (Node l _ _ _ _ _) = l
getLeft (Leaf k _) = k

getRight :: SegTree -> Int
getRight (Node _ r _ _ _ _) = r
getRight (Leaf k _ ) = k

getCnt :: SegTree -> IOUArray Int Int
getCnt (Node _ _ cnt _ _ _) = cnt
getCnt (Leaf _ cnt) = cnt

mkSegTree :: Int -> Int -> UArray Int Int  -> IO SegTree
mkSegTree l r arr
  | l/=r = do
      let !m = (l+r).>>.1
      lt <- mkSegTree l m arr
      rt <- mkSegTree (m+1) r arr
      merge lt rt
  | otherwise = do
      let !x = unsafeAt arr (l-1)
      cnt <- newListArray (0,19) $ map (\b->x.>>.b.&.1) [0..19]
      return $! Leaf l cnt

query :: Int -> Int -> SegTree -> IO ()
query kl kr segtree = mapM (go segtree) [19,18..0] >>= print.toDecimal
   where
     go (Node l r cnt flag lt rt) b = do
       if r<kl || kr<l
          then return 0
          else if kl<=l && r<=kr
                  then unsafeRead cnt b
                  else do
                    ql <- go lt b
                    qr <- go rt b
                    f <- unsafeRead flag b
                    if f==1
                       then  return $! min kr r-max kl l+1-ql-qr
                       else  return $! ql+qr
     go (Leaf k cnt) b
       | kl<=k && k<=kr = unsafeRead cnt b
       | otherwise = return 0

update :: Int -> Int -> Int -> SegTree -> IO ()
update kl kr x segtree = go segtree
   where
     !bs = filter (testBit x) [0..19]
     go (Node l r cnt flag lt rt) = do
       unless (r<kl || kr<l) $ do
         if kl<=l && r<=kr
            then do
              forM_ bs $ \b-> do
                f <- unsafeRead flag b
                unsafeWrite flag b $! xor 1 f
                c <- unsafeRead cnt b
                unsafeWrite cnt b $! r-l+1-c
            else do
              go lt
              go rt
              forM_ bs $ \b-> do
                cntl <- unsafeRead (getCnt lt) b
                cntr <- unsafeRead (getCnt rt) b
                f <- unsafeRead flag b
                if f==1
                   then unsafeWrite cnt b $! r-l+1-cntl-cntr
                   else unsafeWrite cnt b $! cntl+cntr
     go (Leaf k cnt) = do
       when (kl<=k && k<=kr) $ do
         forM_ bs $ \b-> do
           c <- unsafeRead cnt b
           unsafeWrite cnt b $! xor 1 c

main = do
  n <- readLn
  arr <- listArray(0,n-1).map readInt.B.words <$> B.getLine :: IO (UArray Int Int)
  segtree <- mkSegTree 1 n arr
  queries <- map readInt.tail.B.words <$> B.getContents
  let parse (1:rest) = parse1 rest
      parse (_:rest) = parse2 rest
      parse _ = []
      parse1 (l:r:rest)   = query  l r   segtree : parse rest
      parse2 (l:r:x:rest) = update l r x segtree : parse rest
  sequence_ $ parse queries

{-# OPTIONS_GHC -O3 -optc-O3 #-}
{-# LANGUAGE BangPatterns, MagicHash #-}

import GHC.Prim (uncheckedIShiftL#,uncheckedIShiftRL#)
import GHC.Exts (Int(..))
import Data.Bits (testBit,shiftL,shiftR,xor,(.&.),(.|.))
import qualified Data.ByteString.Char8 as B (ByteString,readInt,words,getContents,getLine)
import Data.Int (Int64)
import Data.List (foldl')
import Control.Applicative ((<$>),(<*>))
import Control.Monad (unless,forM_)
import Data.Array.Base (UArray,listArray,newArray,unsafeAt,unsafeRead,unsafeWrite)
import Data.Array.IO (IOUArray)

infixl 8 .<<. , .>>.
(.<<.) :: Int -> Int -> Int
(I# x).<<.(I# i) = I# (uncheckedIShiftL# x i)
(.>>.) :: Int -> Int -> Int
(I# x).>>.(I# i) = I# (uncheckedIShiftRL# x i)
{-# INLINE (.<<.) #-}
{-# INLINE (.>>.) #-}

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
{-# INLINE readInt #-}

rep :: Int -> (Int -> IO ()) -> IO ()
rep !n f = go 0
   where
     go !i
       | i<n = f i >> go (i+1)
       | otherwise = return ()
{-# INLINE rep #-}

toDecimal :: [Int] -> Int64
toDecimal xs = foldl' (\x y->x`shiftL`1 + fromIntegral y) 0 xs
{-# INLINE toDecimal #-}

main = do
  n <- readLn
  arr <- listArray(0,n-1).map readInt.B.words <$> B.getLine :: IO (UArray Int Int)

  segtree <- newArray (0,20*(1.<<.18)-1) 0 :: IO (IOUArray Int Int)
  flag    <- newArray (0,20*(1.<<.18)-1) 0 :: IO (IOUArray Int Int)

  let build node l r = do
        if r-l==1
           then do
             let !al = unsafeAt arr l
             rep 20 $ \b-> do
               unsafeWrite segtree (b.<<.18+ node) $! al.>>.b.&.1
           else do
             let !nodel = node.<<.1 .|. 1
                 !noder = node.<<.1 + 2
                 !m = (l+r).>>.1
             build nodel l m
             build noder m r
             rep 20 $ \b-> do
               cntl <- unsafeRead segtree $! b.<<.18+nodel
               cntr <- unsafeRead segtree $! b.<<.18+noder
               unsafeWrite segtree (b.<<.18+ node)  $! cntl + cntr

  let query kl kr = mapM (go 0 0 n) [19,18..0] >>= print.toDecimal
        where
          go node l r b = do
            if r<=kl || kr<=l
               then return 0
               else if kl<=l && r<=kr
                       then unsafeRead segtree $! b.<<.18+node
                       else do
                         let !nodel = node.<<.1 .|. 1
                             !noder = node.<<.1 + 2
                             !m = (l+r).>>.1
                         ql <- go nodel l m b
                         qr <- go noder m r b
                         f <- unsafeRead flag $! b.<<.18+node
                         if f==1
                            then return $! min kr r-max kl l-ql-qr
                            else return $! ql+qr

  let update kl kr x = go 0 0 n
         where
           !bs = filter (testBit x) [0..19]
           go node l r = do
             unless (r<=kl || kr<=l) $ do
                if kl<=l && r<=kr
                   then do
                     forM_ bs $ \b-> do
                       let !i = b.<<.18 + node
                       f <- unsafeRead flag i
                       unsafeWrite flag i $! xor 1 f
                       cnt <- unsafeRead segtree i
                       unsafeWrite segtree i $! r-l-cnt
                   else do
                     let !nodel = node.<<.1 .|. 1
                         !noder = node.<<.1 + 2
                         !m = (l+r).>>.1
                     go nodel l m
                     go noder m r
                     forM_ bs $ \b-> do
                       cntl <- unsafeRead segtree $! b.<<.18+nodel
                       cntr <- unsafeRead segtree $! b.<<.18+noder
                       f <- unsafeRead flag $! b.<<.18 + node
                       if f==1
                          then unsafeWrite segtree (b.<<.18+node) $! r-l-cntl-cntr
                          else unsafeWrite segtree (b.<<.18+node) $! cntl+cntr

  let parse (1:rest) = parse1 rest
      parse (_:rest) = parse2 rest
      parse _ = []
      parse1 (l:r:rest)   = query  (l-1) r   : parse rest
      parse2 (l:r:x:rest) = update (l-1) r x : parse rest

  build 0 0 n
  queries <- map readInt.tail.B.words <$> B.getContents
  sequence_ $ parse queries


main :: IO ()
main = do
    inp <- getLine
    let l = map read $ words inp
        a = l!!0
        b = l!!1
        c = l!!2
    inp <- getLine
    let liste = map read $ words inp
    putStrLn $ show $ steps $ Just (liste,c,b,c,b)
    return ()
steps :: (Maybe ([Int],Int,Int,Int,Int)) -> Int
steps Nothing = -1
steps (Just x)  = 1+(steps $ step x)

step :: ([Int],Int,Int,Int,Int) -> Maybe ([Int],Int,Int,Int,Int)
step (liste,acc,batt,cacc,cbatt)
    |null liste        = Nothing
    |cacc==cbatt && cacc==0    = Nothing
    |(head liste) == 0 =
        if cacc==0
            then Just (tail liste,acc,batt,cacc,cbatt-1)
            else Just (tail liste,acc,batt,cacc-1,cbatt)
    |otherwise         =
        if cacc==acc || cbatt==0
            then Just (tail liste,acc,batt,cacc-1,cbatt)
            else Just (tail liste,acc,batt,cacc+1,cbatt-1)

analyze _ _ 0 0 _ = 0
analyze b a p q s
  | a == q = 1 + (analyze b a p (q - 1) (tail s))
  | p == 0 = 1 + (analyze b a p (q - 1) (tail s))
  | (head s) == 1 = 1 + (analyze b a (p - 1) (q + 1) (tail s))
  | q == 0 = 1 + (analyze b a (p - 1) q (tail s))
  | otherwise = 1 + (analyze b a p (q - 1) (tail s))

main = do
  line1 <- getLine
  line2 <- getLine
  let
    nums1 = map read (words line1)
    (n:b:a:_) = nums1
    s = (map read (words line2)) ++ (repeat 0)
  putStrLn (show (min n (analyze b a b a s)))

main :: IO ()
main = do
    inp <- getLine
    let l = map read $ words inp
        a = l!!0
        b = l!!1
        c = l!!2
    inp <- getLine
    let liste = map read $ words inp
    putStrLn $ show $ steps $ Just (liste,c,b,c,b)
    return ()
steps :: (Maybe ([Int],Int,Int,Int,Int)) -> Int
steps Nothing = -1
steps (Just x)  = 1+(steps $ step x)

step :: ([Int],Int,Int,Int,Int) -> Maybe ([Int],Int,Int,Int,Int)
step (liste,acc,batt,cacc,cbatt)
    |null liste        = Nothing
    |cacc==cbatt && cacc==0    = Nothing
    |(head liste) == 0 =
        if cacc==0
            then Just (tail liste,acc,batt,cacc,cbatt-1)
            else Just (tail liste,acc,batt,cacc-1,cbatt)
    |otherwise         =
        if cacc==acc
            then Just (tail liste,acc,batt,cacc-1,cbatt)
            else Just (tail liste,acc,batt,cacc+1,cbatt-1)

main :: IO ()
main = do
    inp <- getLine
    let l = map read $ words inp
        a = l!!0
        b = l!!1
        c = l!!2
    inp <- getLine
    let liste = map read $ words inp
    putStrLn $ show $ steps $ Just (liste,c,b,c,b)
    return ()
steps :: (Maybe ([Int],Int,Int,Int,Int)) -> Int
steps Nothing = 0
steps (Just x)  = 1+(steps $ step x)

step :: ([Int],Int,Int,Int,Int) -> Maybe ([Int],Int,Int,Int,Int)
step (liste,acc,batt,cacc,cbatt)
    |null liste        = Nothing
    |cacc==cbatt && cacc==0    = Nothing
    |(head liste) == 0 =
        if cacc==0
            then Just (tail liste,acc,batt,cacc,cbatt-1)
            else Just (tail liste,acc,batt,cacc-1,cbatt)
    |otherwise         =
        if cacc==acc
            then Just (tail liste,acc,batt,cacc-1,cbatt)
            else Just (tail liste,acc,batt,cacc+1,cbatt-1)

main :: IO ()
main = do
    inp <- getLine
    let l = map read $ words inp
        a = l!!0
        b = l!!1
        c = l!!2
    inp <- getLine
    let liste = map read $ words inp
    putStrLn $ show $ steps $ Just (liste,c,b,c,b)
    return ()
steps :: (Maybe ([Int],Int,Int,Int,Int)) -> Int
steps Nothing = -1
steps (Just x)  = 1+(steps $ step x)

step :: ([Int],Int,Int,Int,Int) -> Maybe ([Int],Int,Int,Int,Int)
step (liste,acc,batt,cacc,cbatt)
    |null liste        = Nothing
    |cacc==cbatt && cacc==0    = Nothing
    |(head liste) == 0 =
        if cacc==0
            then Just (tail liste,acc,batt,cacc,cbatt-1)
            else Just (tail liste,acc,batt,cacc-1,cbatt)
    |otherwise         =
        if cacc==acc || cacc==0
            then Just (tail liste,acc,batt,cacc-1,cbatt)
            else Just (tail liste,acc,batt,cacc+1,cbatt-1)


import Data.List

boolToAns :: Bool -> String
boolToAns x = if x then "YES" else "NO"

computeAnswer :: Integer -> String -> Bool
computeAnswer k str
    | any (=='x') firstSubstring = False
    | n0 + n1 + abs (n0-n1) > k = False
    | otherwise = True
  where
    classes :: [String]
    classes =
      map (map fst)
      $ groupBy (\x y -> snd x == snd y)
      $ sortOn (snd)
      $ zip str $ cycle [0..(k-1)]
    firstSubstring :: String
    firstSubstring = map repr classes
    repr :: String -> Char
    repr str
      | any (=='0') str && any (=='1') str = 'x'
      | any (=='1') str = '1'
      | any (=='0') str = '0'
      | otherwise = '?'
    count :: Char -> String -> Integer
    count c = genericLength . filter (==c)
    n0 = count '0' firstSubstring
    n1 = count '1' firstSubstring

answerTestcase :: IO ()
answerTestcase = do
  line1 <- getLine
  line2 <- getLine
  let k = readInt $ words line1 !! 1
  (putStrLn . boolToAns) $ computeAnswer k line2

readInt :: String -> Integer
readInt = read

main = (fmap readInt getLine) >>= (\t -> sequence (genericReplicate t answerTestcase))

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

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

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

solve :: Int -> Int -> B8.ByteString -> Bool
solve n k s = fromMaybe False result
    where
        result = do
            convolution <- convolution
            let zerosCount = B8.count '0' convolution
            let onesCount = B8.count '1' convolution
            let delta = k - zerosCount - onesCount
            return $ (abs $ zerosCount - onesCount) <= delta

        convolution = B8.pack <$> foldr (liftA2 (:)) (Just "") collapsedColumns
        collapsedColumns = map collapseColumn stripesColumns

        collapseColumn column
            | ('1' `B8.elem` column) && ('0' `B8.elem` column) = Nothing
            | ('1' `B8.elem` column) = Just '1'
            | ('0' `B8.elem` column) = Just '0'
            | otherwise = Just '?'

        stripesColumns = do
            groupId <- [0 .. k - 1]
            let columns = map (B8.index s) [groupId, groupId + k .. n - 1]
            return $ B8.pack columns

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    forM_ [1..t] $ \_ -> do
        [n, k] <- B8.getLine <&> B8.words <&> map readIntB8
        s <- B8.getLine
        let answer = solve n k s
        printf "%s\n" $ ((bool "NO" "YES" answer)::String)