main :: IO ()
main = do
       raw <- getContents
       let rows = map (map (read :: [Char] -> Integer) . words) $ tail $ lines raw
       putStr $ unlines $ map (show . process) rows

process :: [Integer] -> Integer
process [str, int, exp_] = max 0 (if exp_ < str - int then exp_ + 1 else (str - int + exp_ + 1) `div` 2)
process _ = error "Malformed line"

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> -n
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

solve input =
  let asNums :: [Int]
      asNums = map read $ words input
      idx:xs = asNums
      inp = asthree xs
      mapped = map solve' inp
  in intercalate "\n" $ map show mapped

asthree :: [Int] -> [(Int, Int, Int)]
asthree [] = []
asthree (a:b:c:xs) = (a, b, c):(asthree xs)

solve' :: (Int, Int, Int) -> Int
solve' (str, int, exp)
  | exp <= 0 && str > int = 1
  | left <= 0 && str <= int = 0
  | otherwise = max 0 (exp - adds + 1)
  -- | str >= int = min (div (base' + exp + 1) 2) exp
  -- | otherwise = div' left 2
  where
      base = min str int
      str' = str - base
      int' = int - base
      base' = max str' int'
      left = exp - base'
      adds = max 0 (div (exp + int - str + 2) 2)

div' it n2 = (div it n2) + (mod it n2)

main = mapM (print . solve) . parse . map read . tail . words =<< getContents
parse (a:b:c:xs) = (a,b,c) : parse xs
parse [] = []
solve (str,int,exp) | tip < 0 = 0
                    | tip > exp = exp + 1
                    | otherwise = tip + 1
  where tip = (str-int+exp-1) `div` 2

main = do
       s <- getContents
       let xss = tail $ lines s
       let rows = map (map (read :: [Char] -> Integer) . words) xss
       putStr $ unlines $ map (show . process) rows

process [str, int, exp] = max 0 (str + exp - (str + int + exp) `div` 2)

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> -n
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

solve input =
  let asNums :: [Int]
      asNums = map read $ words input
      idx:xs = asNums
      inp = asthree xs
      mapped = map solve' inp
  in intercalate "\n" $ map show mapped

asthree :: [Int] -> [(Int, Int, Int)]
asthree [] = []
asthree (a:b:c:xs) = (a, b, c):(asthree xs)

solve' :: (Int, Int, Int) -> Int
solve' (str, int, exp)
  | exp <= 0 && str > int = 1
  | left <= 0 && str <= int = 0
  | str >= int = min (quot (base' + exp) 2) exp
  | otherwise = (div left 2) + (mod left 2)
  where
      base = min str int
      str' = str - base
      int' = int - base
      base' = max str' int'
      left = exp - base'

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> -n
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

solve input =
  let asNums :: [Int]
      asNums = map read $ words input
      idx:xs = asNums
      inp = asthree xs
      mapped = map solve' inp
  in intercalate "\n" $ map show mapped

asthree :: [Int] -> [(Int, Int, Int)]
asthree [] = []
asthree (a:b:c:xs) = (a, b, c):(asthree xs)

solve' :: (Int, Int, Int) -> Int
solve' (str, int, exp)
  | exp <= 0 && str > int = 1
  | left <= 0 && str <= int = 0
  | str >= int = min (div (base' + exp) 2) exp
  | otherwise = div' left 2
  where
      base = min str int
      str' = str - base
      int' = int - base
      base' = max str' int'
      left = exp - base'

div' it n2 = (div it n2) + (mod it n2)

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> -n
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

solve input =
  let asNums :: [Int]
      asNums = map read $ words input
      idx:xs = asNums
      inp = asthree xs
      mapped = map solve' inp
  in intercalate "\n" $ map show mapped

asthree :: [Int] -> [(Int, Int, Int)]
asthree [] = []
asthree (a:b:c:xs) = (a, b, c):(asthree xs)

solve' :: (Int, Int, Int) -> Int
solve' (str, int, exp)
  | exp <= 0 && str > int = 1
  | left <= 0 && str <= int = 0
  | str >= int = min (div' (base' + exp) 2) exp
  | otherwise = div' left 2
  where
      base = min str int
      str' = str - base
      int' = int - base
      base' = max str' int'
      left = exp - base'

div' it n2 = (div it n2) + (mod it n2)

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> -n
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

solve input =
  let asNums :: [Int]
      asNums = map read $ words input
      idx:xs = asNums
      inp = asthree xs
      mapped = map solve' inp
  in intercalate "\n" $ map show mapped

asthree :: [Int] -> [(Int, Int, Int)]
asthree [] = []
asthree (a:b:c:xs) = (a, b, c):(asthree xs)

solve' :: (Int, Int, Int) -> Int
solve' (str, int, exp)
  | exp <= 0 && str > int = 1
  | left <= 0 && str <= int = 0
  | str >= int = min (div (base' + exp + 1) 2) exp
  | otherwise = div' left 2
  where
      base = min str int
      str' = str - base
      int' = int - base
      base' = max str' int'
      left = exp - base'

div' it n2 = (div it n2) + (mod it n2)

main = mapM (print . solve) . parse . map read . tail . words =<< getContents
parse (a:b:c:xs) = (a,b,c) : parse xs
parse [] = []
solve (str,int,exp) | tip < 0 = 0
                    | otherwise = tip + 1
  where tip = (str-int+exp-1) `div` 2

main = interact $ unlines . map (show . solve) . parse . map read . tail . words
parse (a:b:c:xs) = (a,b,c) : parse xs
parse [] = []
solve (str,int,exp) | tip < 0 = 0
                    | otherwise = tip + 1
  where tip = (str-int+exp-1) `div` 2


import Control.Monad (liftM, replicateM, mapM_)
import Data.Char (ord)
import Data.List (intercalate, sort, (\\))

solve :: [[Int]] -> [Bool]
solve carts  =  map maybeWin carts
  where
    maybeWin cart  =  all (not . elem' cart) (carts \\ [cart])
    elem' a b  =  elem'' (sort a) (sort b)
    elem'' _ []  =  True
    elem'' [] _  =  False
    elem'' (a:as) (b:bs)
      | a < b  =  elem'' as (b:bs)
      | a > b  =  False
      | otherwise  =  elem'' as bs

main :: IO ()
main  =  do
    n  <-  readLn
    as  <-  replicateM n $ liftM tail reads
    mapM_ (putStrLn . ("YES" <?> "NO")) $ solve as

  where
    (<?>) a b p  =  if p then a else b

    reads :: Num a => IO [a]
    reads  =  liftM (map read . words) getLine
      where
        read ('-':s)  =  (-1) * read s
        read s  =  read' 0 s
        read' a ""  =  a
        read' a (c:s)  =  read' a' s
          where
            a'  =  10 * a + fromIntegral (ord c - ord '0')

import Data.List

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

solve :: [[Int]] -> [String]
solve cards = go [] cards
   where
     go xs (y:ys)
       | all (not . null . (\\y)) xs && all (not . null . (\\y)) ys = "YES" : go (y:xs) ys
       | otherwise = "NO" : go (y:xs) ys
     go _ _ = []


import List
import Control.Monad
import Control.Applicative
solve x0 (a,b) | mx > mn = "-1"
               | mx <= x0 && x0 <= mn = "0"
               | True = show $ min (abs(x0-mx)) (abs(x0-mn))
      where mx = maximum a
            mn = minimum b

pair = map read . words <$> getLine

main = do
    [n, x0] <- pair
    (replicateM n pair) >>= (putStrLn . solve x0 . unzip. map ((\[a,b]->(a,b)).sort))

import List

un = map (read :: String -> Int) . words

getLines 0 = return []
getLines n = do
    s <- getLine
    ss <- getLines (n-1)
    return (s:ss)

main = do
    s <- getLine
    let n:x0:_ = un s
    l <- getLines n
    let xys_ = map un l
        xys = map (\(a:b:_) -> (min a b, max a b)) xys_
        x1 = maximum $ map fst xys
        x2 = minimum $ map snd xys
    if x1 > x2 then
            putStrLn "-1"
        else if x1 <= x0 && x0 <= x2 then
            putStrLn "0"
        else let m = min (abs (x1 - x0)) (abs (x2 - x0))
            in putStrLn $ show m

module Main where

-- import Test.Tasty
-- import Test.Tasty.HUnit
-- import Debug.Trace
import Data.List
import Control.Monad

run start positions =
    let enumerate begin end [a,b] = if a<b then [max begin a..min end b] else [max begin b.. min end a]
        [begin, end] = head positions
        fst3 = (\(x,_,_) -> x)
        commonPositions =
            fst3 $
            foldr (\x (acc,a,b) -> let e = enumerate a b x in (acc `intersect` e, head e, last e))
                  ([min begin end .. max begin end], min begin end, max begin end)
                  (tail positions)
    in if null commonPositions then -1 else minimum $ map (abs . ((-) start)) commonPositions

main = do
   let processLine = map (\x -> read x::Int) . words
   [len, start] <- (getLine >>= return . processLine)
   positions <- (replicateM len getLine >>= return . (map processLine))
   print $ run start positions

{-
main = defaultMain $
   testCase "Tests" $ do
    run 3 [[0,7],[14,2],[4,6]] @?= 1

-}

solve _ _ [] = True
solve d add ((a, b) : xs)
 | (d + add) >= min a b && (d + add) <= max a b = solve d add xs
 | otherwise = False

main = do
	line <- getLine
	arr' <- getContents
	let
		[n, x] = map (\x -> read x :: Integer ). words $ line
		arr = map (\x -> let [a, b] = map (\y -> read y :: Integer ). words $ x in (a, b)  ). lines $ arr'
		ans 1001 = -1
		ans d
		 | solve x d arr = d
		 | solve x (-d) arr = d
		 | otherwise = ans (d+1)
--	print x
--	print arr
	print $ ans 0

import List

un = map (read :: String -> Int) . words

getLines 0 = return []
getLines n = do
    s <- getLine
    ss <- getLines (n-1)
    return (s:ss)

main = do
    s <- getLine
    let n:x0:_ = un s
    l <- getLines n
    let xys_ = map un l
        xys = map (\(a:b:_) -> (min a b, max a b)) xys_
        x1 = maximum $ map fst xys
        x2 = minimum $ map snd xys
    if x1 > x2 then
        putStrLn "-1"
        else let m = min (abs (x1 - x0)) (abs (x2 - x0))
            in putStrLn $ show m


import Data.List (group, sort, sortBy)
import Data.Ord (comparing)
solve :: [String] -> String
solve [xs,k']
    | length xs <= k = "0\n"
    | otherwise = (show (length ps - maxl)) ++ "\n" ++ filter (`notElem` rmv) xs
    where sch = sort $ map (\x -> (length x, head x)) ps
          ps = group (sort xs)
          k = read k'
          maxl = length $ takeWhile (<=k) $ scanl1 (+) $ map fst sch
          rmv = map snd (take maxl sch)
main = putStrLn.solve.lines =<< getContents

module Main where

import Data.List
import Data.Ord
import qualified Data.Map as Map

main = do
    string <- getLine
    inputK <- getLine
    let k = read inputK :: Int
        letterCount = foldl' (\count letter -> Map.insertWith' (+) letter 1 count) Map.empty string
        orderLetter = sortBy ( comparing ( letterCount Map.! ) ) $ Map.keys letterCount
        eat :: Int -> [Char] -> [Char]
        eat _ [] = []
        eat k (letter:letters) =
            let head_count = letterCount Map.! letter in
            if k >= head_count
                then eat ( k - head_count ) letters
                else letter:letters
        remainLetter = eat k orderLetter

    putStrLn $ show ( length remainLetter )
    putStrLn $ filter ( `elem` remainLetter ) string

import List
import Data.Function
l=length
s[w,k]=[show$l$group$sort r,r]where r=map fst$sortBy(compare`on`snd)(drop(read k)$concat$sortBy(compare`on`l)$groupBy((==)`on`fst)$sort$zip w[0..])
main=interact$unlines.s.words

import Data.Array.ST
import Control.Monad.ST
import Control.Monad (foldM)
import Data.Array.Unboxed
import Data.List (sortBy)
import Data.Function (on)
main = do

    строка <- getLine
    k <- read `fmap` getLine
    let границы = ('a','z')
        символы = sortBy (compare `on` snd) $ filter ((>0).snd) $ assocs $ runSTUArray ((newArray границы 0 :: ST s (STUArray s Char Int)) >>=
            \a -> foldM (\a c -> readArray a c >>= \n -> writeArray a c (n+1) >> return a) a строка)

        (_, вычёркиваем) = foldl (\(k, l) (c, n) -> if k >= n then (k-n, c:l) else (k, l)) (k, []) символы
        фильтр = array границы $ map (\c -> (c, c `notElem` вычёркиваем)) $ range границы :: UArray Char Bool
    print (length символы - length вычёркиваем)
    putStrLn $ filter (фильтр !) строка

import List
f#p=(\x->f(p x).p)
l=length
z x=[show$l$group$sort x,x]
b x=sortBy$compare#x
s[w,k]=drop(read k)$id=<<(b l$groupBy((==)#fst)$sort$zip w[0..])
main=interact$unlines.z.map fst.b snd.s.words

import List
f#p=(.p).f.p
l=length
z x=[show$l$group$sort x,x]
b x=sortBy$compare#x
s[w,k]=drop(read k)$id=<<(b l$groupBy((==)#fst)$sort$zip w[0..])
main=interact$unlines.z.map fst.b snd.s.words

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

solve :: String -> Int -> (String, Int)
solve chars k =
    (solution, S.size $ S.fromList solution)
    where solution = filter (\x -> not $ S.member x dropped) chars
          chars2 :: [(Int, Char)]
          chars2 = L.sort [(length x, head x) | x <- L.group . L.sort $ chars]
          chars3 :: [(Int, Char)]
          chars3 = snd $ L.mapAccumL (\k (cnt, chr) -> (k - cnt, (k - cnt, chr))) k chars2
          dropped = S.fromList [chr | (cnt, chr) <- chars3, cnt >= 0]

main = do
  chars <- getLine
  k <- (getLine >>= return . (read::String->Int))
  let (solution, m) = solve chars k
  putStrLn $ show m
  putStrLn $ solution

import List
l=length
s[w,k]=[show$l$nub r,w\\r]where r=take(read k)$snd=<<(sort$map(\x->(l x,x))$group$sort w)
main=interact$show.unlines.s.words

import List
l=length
s[w,k]=[show$l$nub r,w\\r]where r=take(read k)$snd=<<(sort$map(\x->(l x,x))$group$sort w)
main=interact$unlines.s.words

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

solve :: String -> Int -> (String, Int)
solve chars k =
    (solution, S.size $ S.fromList solution)
    where solution = filter (\x -> not $ S.member x dropped) chars
          chars2 :: [(Int, Char)]
          chars2 = L.sort [(length x, head x) | x <- L.group . L.sort $ chars]
          chars3 :: [(Int, Char)]
          chars3 = snd $ L.mapAccumL (\k (cnt, chr) -> (k - cnt, (k - cnt, chr))) k chars2
          dropped = S.fromList [chr | (cnt, chr) <- chars3, cnt > 0]

main = do
  chars <- getLine
  k <- (getLine >>= return . (read::String->Int))
  let (solution, m) = solve chars k
  putStrLn $ solution
  putStrLn $ show m

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

solve :: String -> Int -> (String, Int)
solve chars k =
    (solution, S.size $ S.fromList solution)
    where solution = filter (\x -> not $ S.member x dropped) chars
          chars2 :: [(Int, Char)]
          chars2 = L.sort [(length x, head x) | x <- L.group . L.sort $ chars]
          chars3 :: [(Int, Char)]
          chars3 = snd $ L.mapAccumL (\k (cnt, chr) -> (k - cnt, (k - cnt, chr))) k chars2
          dropped = S.fromList [chr | (cnt, chr) <- chars3, cnt > 0]

main = do
  chars <- getLine
  k <- (getLine >>= return . (read::String->Int))
  let (solution, m) = solve chars k
  putStrLn $ show m
  putStrLn $ solution


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections     #-}

import           Control.Applicative
import           Control.Monad
import           Control.Monad.ST
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString.Char8       as B
import           Data.Char
import           Data.Function
import           Data.Int
import qualified Data.IntMap                 as IM
import qualified Data.IntSet                 as IS
import           Data.List
import qualified Data.Map                    as M
import           Data.Ord
import qualified Data.Set                    as S
import           Data.STRef
import           Data.Tuple
import qualified Data.Vector                 as V
import qualified Data.Vector.Generic         as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as UM
import           Data.Word
import           Debug.Trace

main :: IO ()
main = readLn >>= putStr.unlines.map (map$bool '*' '+').solve

solve :: Int -> [[Bool]]
solve 0 = [[True]]
solve k = zipWith (++) block0 block2 ++ zipWith (++) block0 block1
  where
    block0 = solve (k-1)
    block1 = map reverse block0
    block2 = map (map not) block1

import Data.List

readint :: String -> Int
readint = read

flipv :: Char -> Char
flipv '*' = '+'
flipv '+' = '*'

solve :: Int -> [String]
solve 0 = [['+']]
solve k = concat $ map (\s -> [s++s, s++(map flipv s)]) $ solve (k-1)

main = interact $ intercalate "\n" . solve . readint

import Data.List
expand s = [s++s, s++(map (*(-1)) s)]

hadamard 0 = [[1]]
hadamard k = concat $ map expand $ hadamard (k-1)

hf::Int -> Char
hf ( 1) = '+'
hf (-1) = '*'

toSymbols s = map hf s

hadamard' k = map toSymbols (hadamard k)

main = do
    k <- readLn :: IO Int
    putStr $ unlines (hadamard' k)

import Data.List
expand s = [s++s, s++(map (*(-1)) s)]

hadamard 0 = [[1]]
hadamard k = concat $ map expand $ hadamard (k-1)

hf::Int -> Char
hf ( 1) = '+'
hf (-1) = '-'

toSymbols s = map hf s

hadamard' k = map toSymbols (hadamard k)

main = do
    k <- readLn :: IO Int
    putStr $ unlines (hadamard' k)


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

readInt bs = case B.readInt bs of Just (n,_) -> n

main = do
  r1 <- fromIntegral.maximum.tail.map readInt.B.words <$> B.getLine
  p1 <- fromIntegral.maximum.tail.map readInt.B.words <$> B.getLine
  p2 <- fromIntegral.minimum.tail.map readInt.B.words <$> B.getLine
  [a,b] <- map read.words <$> getLine
  print $ sqrt $ (b*p1*r1*r1)/(a*p2+b*p1)

import Prelude hiding (reads)

reads :: Read a => IO [a]
reads  =  getLine >>= return . map read . words

solve :: (Double, Double) -> [Double] -> [Double] -> [Double] -> Double
solve (a, b) r1s p1s p2s  =  r1 * sqrt (p1 * b / (p2 * a + p1 * b))
  where
    r1  =  maximum r1s
    p1  =  maximum p1s
    p2  =  minimum p2s

main :: IO ()
main  =  do
    as  <-  reads
    bs  <-  reads
    cs  <-  reads
    [a, b]  <-  reads
    print $ solve (a,b) (tail as) (tail bs) (tail cs)

import Data.List
main = do
    [x, y, z] <- mapM (\_ -> (map read . tail . words) `fmap` getLine) [1..3] :: IO [[Double]]
    [a, b] <- (map read . words) `fmap` getLine
    let p1 = maximum y
    let p2 = minimum z
    let r1 = maximum x
    print $ sqrt $ r1 * r1 * p1/(a/b + p1/p2)/p2

solve :: ([Double], [Double], [Double], Double, Double) -> Double
solve (xs, ys, zs, a, b) = sqrt $ r1^2 * p1 * b / (p1 * b + p2 * a)
    where r1 = maximum xs
          p1 = maximum ys
          p2 = minimum zs

readInput :: IO ([Double], [Double], [Double], Double, Double)
readInput = do
    contents <- getContents
    let ns:ms:ks:ab:_ = lines contents
        xs = map read $ tail $ words ns
        ys = map read $ tail $ words ms
        zs = map read $ tail $ words ks
        a = read $ words ab !! 0
        b = read $ words ab !! 1
    return (xs, ys, zs, a, b)

showOutput :: Double -> IO ()
showOutput r = do
    print r

main :: IO ()
main = do
    input <- readInput
    showOutput $ solve input

solve :: ([Double], [Double], [Double], Double, Double) -> Double
solve (xs, ys, zs, a, b) = maximum [r2 | r1 <- xs, let p1 = maximum ys, let p2 = minimum zs, let r2 = sqrt $ r1^2 * p1 * b / (p1 * b + p2 * a)]

readInput :: IO ([Double], [Double], [Double], Double, Double)
readInput = do
    contents <- getContents
    let ns:ms:ks:ab:_ = lines contents
        xs = map read $ tail $ words ns
        ys = map read $ tail $ words ms
        zs = map read $ tail $ words ks
        a = read $ words ab !! 0
        b = read $ words ab !! 1
    return (xs, ys, zs, a, b)

showOutput :: Double -> IO ()
showOutput r = do
    print r

main :: IO ()
main = do
    input <- readInput
    showOutput $ solve input

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

import qualified Data.List as L
import qualified Data.Function as F
import qualified Data.Set as S
import qualified Data.Map as M

parse = map (map read) . map words . lines

-- xs~r1, ys~p1, zs~p2
solve [_:xs, _:ys, _:zs, [a, b]] =
  let
    r1 = maximum xs
    p1 = maximum ys
    p2 = minimum zs
  in
    sqrt ((b * p1 * r1 * r1)/(p2 * a + p1 * b))

present = show

main = interact $ present . solve . parse

main = do
  r1 <- fmap (maximum . tail) getArray
  p1 <- fmap (maximum . tail) getArray
  p2 <- fmap (minimum . tail) getArray
  [a, b] <- getArray
  print $ gao r1 p1 p2 a b
  where
    getArray = fmap (map read . words) getLine
    gao r1 p1 p2 a b = r1 / sqrt ((a * p2) / (b * p1) + 1)

calc::Double->Double->Double->Double->[Double]->Double
calc _ _ _ _ [] = 0
calc r1 p2 a b (y:ys) = max (sqrt ((r1 * r1 * y * b) / (p2 * a + y * b))) (calc r1 p2 a b ys)

main = do
     xs <- getLine
     let r1 = foldl max 0 (tail (map (read::String->Double) (words xs)))
     ys <- getLine
     let p1 = tail.map (read::String->Double) $ words ys
     zs <- getLine
     let p2 = foldl min 65535 (tail (map (read::String->Double) (words zs)))
     ab' <- getLine
     let ab = map (read::String->Double) $ words ab'
     putStrLn(show $ calc r1 p2 (ab !! 0) (ab !! 1) p1)

import qualified Data.ByteString.Char8 as BS
import Control.Applicative

ring a b = (circle a) - (circle b)
circle a = a * a

-- (r1 * r1 * pi - r2 * r2 * pi) * p1 * b == r2 * r2 * pi * p2 * a
solve x y z a b = let r1 = foldr max 0.0 x
                      p2 = foldr min 10000.0 z
                      cand = [ r1 * (sqrt ((p1 * b) / (p2 * a + p1 * b))) | p1 <- y ]
                  in  foldr max 0.0 cand

main = do
  x <- map fromIntegral <$> (tail <$> readInts)
  y <- map fromIntegral <$> (tail <$> readInts)
  z <- map fromIntegral <$> (tail <$> readInts)
  [a, b] <- map fromIntegral <$> readInts
  print $ solve x y z a b

toNumber (Just (x, _)) = x
toNumber Nothing       = 0
readInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))


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

main=do
 [n,m,x]<-map read.words<$>getLine
 keys<-replicateM n getLine
 let goodKeys = map head.group.sort $ do
       (i, row) <- zip [0..n-1] keys
       (j, 'S') <- zip [0..m-1] row
       (i', row') <- zip [0..n-1] keys
       (j', l) <- zip [0..m-1] row'
       let sq x = x*x
       guard (sq(i-i')+sq(j-j') <= sq x)
       return l
 getLine
 text<-getLine
 let badKeys = map toUpper$filter(`notElem` goodKeys)['a'..'z']
     veryBadLc = filter(\c -> all (c `notElem`) keys)['a'..'z']
     any2D p = any (any p)
     veryBadKeys | any2D (=='S') keys = veryBadLc ++ map toUpper veryBadLc
      | otherwise = veryBadLc ++ ['A'..'Z']
     cnt p = length.filter p

 putStrLn$show$case cnt (`elem` veryBadKeys) text of
    0 -> cnt(`elem` badKeys) text
    _ -> -1

import Data.Char (toLower, isUpper)
import qualified Data.Map as M
import Control.Monad (foldM, guard)
import Data.List (foldl')
main = do
    [n, m, x] <- (map read . words) `fmap` getLine
    cm <- foldM (\cm' i -> do
        l <- getLine
        return $ foldl (\cm (c, j) -> M.insertWith (++) c [(i, j)] cm) cm' $
                zip l [0..]) M.empty [0..n-1]
    let cm' = M.fromList $ (if M.notMember 'S' cm then map (\x -> (x, Nothing))
            else let xs = cm M.! 'S' in map (\c -> (c, Just $ (do
            (ix, jx) <- xs
            (i, j) <- cm M.! c
            let l = (i-ix)^2 + (j-jx)^2
            guard (l <= x^2)
            return l) /= []))) $ filter (/='S') $ M.keys cm
    _ <- getLine
    k <- (foldl' (\r c -> do
        r' <- r
        b <- M.lookup (toLower c) cm'
        r'' <- if isUpper c then do
            b' <- b
            return $ if b' then 0 else 1 else Just 0
        return (r' + r'')) (Just 0)) `fmap` getLine
    print $ case k of {Nothing -> (-1); Just x -> x}

import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8 as BS
import Data.Maybe
import Data.Char
import Data.Array

look :: (Eq e, Ix i) => Array i e -> e -> [i]
look ar el =  filter (\i ->(ar ! i) == el)  (indices ar)

main :: IO ()
main = do
   [n,m,x] <- map (fst.fromJust.BS.readInt) . BS.words <$> BS.getLine
   board <- listArray ((1,1), (n,m)) . BS.unpack .BS.filter isAlpha . BS.concat <$> replicateM n BS.getLine
   let epS c = c `elem` (elems board)
       wU c = if epS (toLower c) && ('S' `elem` (elems board))
              then if isPoss then 0 else 1
              else (-1)
          where sl = look board 'S'
                cl = look board (toLower c)
                isPoss = or [ ((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)) <= x*x  | (x1, y1) <- sl, (x2, y2) <- cl]
   q <- fst . fromJust . BS.readInt <$> BS.getLine
   let f (-1) _ = (-1)
       f n c | isLower c && epS c = n
             | isLower c = (-1)
             | temp == (-1) = (-1)
             | otherwise = n + temp
         where temp = wU' !  c
       wU' = listArray ('A','Z') [wU c | c <- ['A'..'Z']]
   ans <- BS.foldl' f 0 . BS.filter isAlpha <$> BS.getLine
   --print $ look board 'S'
   --print $ look board 'c'
   --print wU'
   print ans


import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ solve
solve = read <$> getLine >>= \x -> print $
    if x == 1 then 2 else
        let (a, r) = x `divMod` 3 in
            (if r == 0 then id else (1+)) a

module Main where
import Control.Monad
import Data.List
y::Bool->Bool->Int
y True True=2
y False False=0
y True False=1
y False True=1
solve::Int->Int
solve x= d+(y ((x`rem`3)/=0) (x==1))
    where d=x`div`3

main = do
  line<-getLine
  let nTerm=read line::Int
  replicateM_ nTerm$do
    line<-getLine
    let n=read line::Int
    print$solve n

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ solve
solve = read <$> getLine >>= \x -> print $
    if x == 1 then 2 else
        let (a, r) = x `divMod` 3 in
            if r == 0 then a else 1+a

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ solve
solve = read <$> getLine >>= \x -> print $
    if x == 1 then 2
    else x `div` 3 + case x `mod` 3 of
        0 -> 0
        1 -> 1
        2 -> 1

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

module Main
       ( main )
       where

import Control.Monad

minutesTo :: Int -> Int
minutesTo x
   | x == 1    = 2
   | rem == 0  = quot
   | otherwise = quot + 1
   where (quot, rem) = x `quotRem` 3

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

  replicateM_ testCases $ do
    line <- getLine
    let n = read line
    print $ minutesTo n

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

module Main
       ( main )
       where

import Control.Monad

minutesTo :: Int -> Int
minutesTo x
   | x == 1         = 2
   | x `mod` 3 == 0 = x `div` 3
   | otherwise      = x `div` 2

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

  replicateM_ testCases $ do
    line <- getLine
    let n = read line
    print $ minutesTo n


{-# 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)