import Data.List
import Data.Maybe

main = interact f

f ss = case result of
         Nothing -> "NO"
         Just (t,x) -> (++) "YES\n" $ unlines $ map (unwords . map show) $ [t, length x]:(map (take 2) x)
  where
    ([n,max,reg]:l) = map (map (read :: String -> Int)) $ map words $ lines ss
    ls = sortBy (\[_,i,_] [_,j,_] -> compare j i) $ zipWith (:) [1..] l
    result = g 0 max max [] max reg ls

g time hp prevHP hist maxHP reg ls
  | hp <= 0 = Just (time, reverse hist)
  | otherwise =
      if (not canAttack && hp >= prevHP)
      then Nothing
      else g (time+1) newHP hp newHist maxHP reg newList
  where
    (possible, unpossible) = break (\[i,pow,dmg] -> pow*maxHP < hp*100) ls
    canAttack = possible /= []
    use = maximumBy (\[_,_,dmg1] [_,_,dmg2] -> compare dmg1 dmg2) possible
    (newL, newR) = break (== use) possible
    (newList,newHist) = if canAttack
                        then (newL++(tail newR)++unpossible, ((time:use):hist))
                        else (ls, hist)
    damage = sum $ map (head . drop 3) newHist
    newHP = min maxHP $ hp - damage + reg

import Control.Monad
import Data.List
import Data.Function

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

sndTpl (a,b,c) = b

go max hp dhp l ans sec
	| hp <= 0 = (sec, reverse ans)
	| otherwise = if null l' then last else go max (up $ dhp-d) (dhp-d) l'' ((sec,i):ans) (sec+1)
		where
			l' = [(p,d,i) | (p,d,i) <- l, hp*100 <= p * max]
			el@(p,d,i) = maximumBy (compare `on` sndTpl) l'
			l'' = delete el l
			last
				| dhp < 0 = go max (up dhp) dhp l ans (sec+1)
				| otherwise = (-1,[])
			up dx = min (hp+dx) max

solve n max reg pd = go max max reg pd' [] 0
	where
		pd' = [(p,d,i) | ([p,d],i) <- zip pd [1..n]]

pprint (sec,l) = yn ++ lprint
	where
		yn = if null l then ["NO"] else ["YES", show sec ++ " " ++ show (length l)]
		lprint = [show s ++ " " ++ show i | (s,i) <- l]

main = do
	[n,max,reg] <- ri
	pd <- forM [1..n] (\_ -> ri)
	let ans = solve n max reg pd
	putStrLn $ intercalate "\n" (pprint ans)

import Data.List
import Data.Maybe

main = interact f

f ss = case result of
         Nothing -> "NO"
         Just (t,x) -> (++) "YES\n" $ unlines $ map (unwords . map show) $ [t, length x]:(map (take 2) x)
  where
    ([n,max,reg]:l) = map (map (read :: String -> Int)) $ map words $ lines ss
    ls = sortBy (\[_,i,_] [_,j,_] -> compare i j) $ zipWith (:) [1..] l
    result = g 0 max max [] max reg ls

g time hp prevHP hist maxHP reg ls
  | hp <= 0 = Just (time, reverse hist)
  | otherwise =
      if (not canAttack && hp >= prevHP)
      then Nothing
      else g (time+1) newHP hp newHist maxHP reg newList
  where
    (possible, unpossible) = break (\[i,pow,dmg] -> pow*maxHP < hp*100) ls
    canAttack = possible /= []
    use = maximumBy (\[_,_,dmg1] [_,_,dmg2] -> compare dmg1 dmg2) possible
    (newL, newR) = break (== use) possible
    (newList,newHist) = if canAttack
                        then (newL++(tail newR)++unpossible, ((time:use):hist))
                        else (ls, hist)
    damage = sum $ map (head . drop 3) newHist
    newHP = min maxHP $ hp - damage + reg

import Data.List
import Data.Maybe

main = interact f

f ss = case result of
         Nothing -> "NO"
         Just (t,x) -> unlines $ map (unwords . map show) $ [t, length x]:(map (take 2) x)
  where
    ([n,max,reg]:l) = map (map (read :: String -> Int)) $ map words $ lines ss
    ls = sortBy (\[i,_,_] [j,_,_] -> compare i j) $ zipWith (:) [1..] l
    result = g 0 max max [] max reg ls

g time hp prevHP hist maxHP reg ls
  | hp <= 0 = Just (time, reverse hist)
  | otherwise =
      if (not canAttack && hp >= prevHP)
      then Nothing
      else g (time+1) newHP hp newHist maxHP reg newList
  where
    (possible, unpossible) = break (\[i,pow,dmg] -> pow*maxHP < hp*100) ls
    canAttack = possible /= []
    use = maximumBy (\[_,_,dmg1] [_,_,dmg2] -> compare dmg1 dmg2) possible
    (newL, newR) = break (== use) possible
    (newList,newHist) = if canAttack
                        then (newL++(tail newR)++unpossible, ((time:use):hist))
                        else (ls, hist)
    damage = sum $ map (head . drop 3) newHist
    newHP = min maxHP $ hp - damage + reg

import Data.List
import Data.Maybe

main = interact f

f ss = case result of
         Nothing -> "NO"
         Just (t,x) -> unlines $ map (unwords . map show) $ [t, length x]:(map (take 2) x)
  where
    ([n,max,reg]:l) = map (map (read :: String -> Int)) $ map words $ lines ss
    ls = sortBy (\[i,_,_] [j,_,_] -> compare i j) $ zipWith (:) [1..] l
    result = g 0 max max [] max reg ls

g time hp prevHP hist maxHP reg ls
  | hp <= 0 = Just (time, reverse hist)
  | otherwise =
      if (not canAttack && hp >= prevHP)
      then Nothing
      else g (time+1) newHP hp newHist maxHP reg newList
  where
    (possible, unpossible) = break (\[i,pow,dmg] -> pow < hp) ls
    canAttack = possible /= []
    use = maximumBy (\[_,_,dmg1] [_,_,dmg2] -> compare dmg1 dmg2) possible
    (newL, newR) = break (== use) possible
    (newList,newHist) = if canAttack
                        then (newL++(tail newR)++unpossible, ((time:use):hist))
                        else (ls, hist)
    damage = sum $ map (head . drop 3) newHist
    newHP = min maxHP $ hp - damage + reg

import Data.List
import Data.Maybe

main = interact f

f ss = case result of
         Nothing -> "NO"
         Just (t,x) -> (++) "YES\n" $ unlines $ map (unwords . map show) $ [t, length x]:(map (take 2) x)
  where
    ([n,max,reg]:l) = map (map (read :: String -> Int)) $ map words $ lines ss
    ls = sortBy (\[i,_,_] [j,_,_] -> compare i j) $ zipWith (:) [1..] l
    result = g 0 max max [] max reg ls

g time hp prevHP hist maxHP reg ls
  | hp <= 0 = Just (time, reverse hist)
  | otherwise =
      if (not canAttack && hp >= prevHP)
      then Nothing
      else g (time+1) newHP hp newHist maxHP reg newList
  where
    (possible, unpossible) = break (\[i,pow,dmg] -> pow*maxHP < hp*100) ls
    canAttack = possible /= []
    use = maximumBy (\[_,_,dmg1] [_,_,dmg2] -> compare dmg1 dmg2) possible
    (newL, newR) = break (== use) possible
    (newList,newHist) = if canAttack
                        then (newL++(tail newR)++unpossible, ((time:use):hist))
                        else (ls, hist)
    damage = sum $ map (head . drop 3) newHist
    newHP = min maxHP $ hp - damage + reg

import Control.Monad
import Data.List

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

go max hp dhp l@((p,d,i):ls) ans sec
	| hp <= 0 = (sec, reverse ans)
	| hp * 100 <= p * max = go max (up $ dhp-d) (dhp-d) ls ((sec,i):ans) (sec+1)
	| dhp < 0 = go max (up dhp) dhp l ans (sec+1)
	| otherwise = (-1,[])
	where
		up dx = min (hp+dx) max

solve n max reg pd = go max max reg pd' [] 0
	where
		pd' = reverse $ (0,0,0) : (sort $ [(p,d,i) | ([p,d],i) <- zip pd [1..n]])

pprint (sec,l) = yn ++ lprint
	where
		yn = if null l then ["NO"] else ["YES", show sec ++ " " ++ show (length l)]
		lprint = [show s ++ " " ++ show i | (s,i) <- l]

main = do
	[n,max,reg] <- ri
	pd <- forM [1..n] (\_ -> ri)
	let ans = solve n max reg pd
	putStrLn $ intercalate "\n" (pprint ans)


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

main = do
  s <- getLine
  when (s == "start") play

play = do
  lower <- findLower 1
  v <- search (lower `div` 2) lower
  if v == 1
    then do
      response <- query (0, 1)
      if response == "x" then answer 1 else answer 2
    else do
      response <- query (1, 2 * v - 1)
      if response == "x" then answer $ 2 * v - 1 else answer $ 2 * v
  main

findLower v = do
  response <- query (v, 2 * v)
  if response == "x" then return v else findLower (2 * v)

search l r = do
  if l == r - 1
    then return r
    else do
      let m = (l + r) `div` 2
      response <- query (m, 2 * m)
      if response == "x" then search l m else search m r

query (x, y) = do
  putStrLn $ "? " ++ show x ++ " " ++ show y
  hFlush stdout
  getLine

answer v = do
  putStrLn $ "! " ++ show v
  hFlush stdout

-- Codeforces Round #534 Div.2 (D), Contest 1104, Problem set ?.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit

main :: IO ()
main = do
  comm <- getLine
  case comm of
    "start" -> do res <- doQueries
                  putStrLn $ "! " ++ show res
                  hFlush stdout
                  main
    "mistake" -> exitFailure
    "end" -> exitSuccess

doQueries :: IO Int
doQueries = do
  is0 <- checkLt 0 1
  if not is0
    then
      return 1
    else do
      (l,u) <- searchMag 1 2
      binSearch l u
  where
    searchMag !l !u | u >= 10^9 = return (l,u)
                    | otherwise = do
                        ans <- checkLt l u
                        if ans
                          then searchMag u (u `shiftL` 1)
                          else return (l,u)
    binSearch lt geq
      | geq - lt <= 1 = return geq
      | otherwise = do ans <- checkLt lt mid
                       if ans then binSearch mid geq else binSearch lt mid
      where
        mid = (lt + geq) `shiftR` 1

checkLt :: Int -> Int -> IO Bool
checkLt x y = do
  putStrLn $ ("? " ++) $ shows x $ ' ' : show y
  hFlush stdout
  waitAns
  where waitAns = do ans:_ <- getLine
                     case ans of
                       'y' -> return True
                       'x' -> return False
                       'e' -> exitFailure
                       _   -> waitAns

-- Codeforces Round #534 Div.2 (D), Contest 1104, Problem set ?.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit

main :: IO ()
main = do
  comm <- getLine
  case comm of
    "start" -> do res <- doQueries
                  putStrLn $ "! " ++ show res
                  hFlush stdout
                  main
    "mistake" -> exitFailure
    "end" -> exitSuccess

doQueries :: IO Int
doQueries = do
  is0 <- checkLt 0 1
  if not is0
    then
      return 1
    else do
      (l,u) <- searchMag 1 3
      binSearch l u
  where
    searchMag !l !u | u >= 10^9 = return (l,u)
                    | otherwise = do
                        ans <- checkLt l u
                        if ans
                          then searchMag u (u `shiftL` 1 + 1)
                          else return (l,u)
    binSearch lt geq
      | geq - lt <= 1 = return geq
      | otherwise = do ans <- checkLt lt mid
                       if ans then binSearch mid geq else binSearch lt mid
      where
        mid = fromIntegral $
          (fromIntegral lt + fromIntegral geq :: Word) `shiftR` 1

checkLt :: Int -> Int -> IO Bool
checkLt x y = do
  putStrLn $ ("? " ++) $ shows x $ ' ' : show y
  hFlush stdout
  waitAns
  where waitAns = do ans:_ <- getLine
                     case ans of
                       'y' -> return True
                       'x' -> return False
                       'e' -> exitFailure
                       _   -> waitAns

-- Codeforces Round #534 Div.2 (D), Contest 1104, Problem set ?.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit

main :: IO ()
main = do
  comm <- getLine
  case comm of
    "start" -> do res <- doQueries
                  putStrLn $ "! " ++ show res
                  hFlush stdout
                  main
    "mistake" -> exitFailure
    "end" -> exitSuccess

doQueries :: IO Int
doQueries = do
  is0 <- checkLt 0 1
  if not is0
    then
      return 1
    else do
      (l,u) <- searchMag 1 2
      binSearch l u
  where
    db = (`shiftL` 1)
    searchMag !l !u | u >= 10^9 = return (l,u)
                    | otherwise = do
                        ans <- checkLt l u
                        if ans then searchMag (db l) (db u) else return (l,u)
    binSearch lt geq
      | geq - lt <= 1 = return geq
      | otherwise = do ans <- checkLt lt mid
                       if ans then binSearch mid geq else binSearch lt mid
      where
        mid = (lt + geq) `shiftR` 1

checkLt :: Int -> Int -> IO Bool
checkLt x y = do
  putStrLn $ ("? " ++) $ shows x $ ' ' : show y
  hFlush stdout
  waitAns
  where waitAns = do ans:_ <- getLine
                     case ans of
                       'y' -> return True
                       'x' -> return False
                       'e' -> exitFailure
                       _   -> waitAns

-- Codeforces Round #534 Div.2 (D), Contest 1104, Problem set ?.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit

main :: IO ()
main = do
  comm <- getLine
  case comm of
    "start" -> do res <- doQueries
                  putStrLn $ "! " ++ show res
                  hFlush stdout
                  main
    "mistake" -> exitFailure
    "end" -> exitSuccess

doQueries :: IO Int
doQueries = do
  is0 <- checkLt 0 1
  if not is0
    then
      return 1
    else do
      (l,u) <- searchMag 1 2
      binSearch l u
  where
    searchMag !l !u | u >= 10^9 = return (l,u)
                    | otherwise = do
                        ans <- checkLt l u
                        if ans
                          then searchMag u (u `shiftL` 1 + 1)
                          else return (l,u)
    binSearch lt geq
      | geq - lt <= 1 = return geq
      | otherwise = do ans <- checkLt lt mid
                       if ans then binSearch mid geq else binSearch lt mid
      where
        mid = (lt + geq) `shiftR` 1

checkLt :: Int -> Int -> IO Bool
checkLt x y = do
  putStrLn $ ("? " ++) $ shows x $ ' ' : show y
  hFlush stdout
  waitAns
  where waitAns = do ans:_ <- getLine
                     case ans of
                       'y' -> return True
                       'x' -> return False
                       'e' -> exitFailure
                       _   -> waitAns

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

main = do
  s <- getLine
  when (s == "start") play

play = do
  lower <- findLower 1
  v <- search (lower `div` 2) lower
  if v == 1
    then do
      response <- query (1, 0)
      if response == "x" then answer 1 else answer 2
    else do
      response <- query (1, 2 * v - 1)
      if response == "x" then answer $ 2 * v - 1 else answer $ 2 * v
  main

findLower v = do
  response <- query (v, 2 * v)
  if response == "x" then return v else findLower (2 * v)

search l r = do
  if l == r - 1
    then return r
    else do
      let m = (l + r) `div` 2
      response <- query (m, 2 * m)
      if response == "x" then search l m else search m r

query (x, y) = do
  putStrLn $ "? " ++ show x ++ " " ++ show y
  hFlush stdout
  getLine

answer v = do
  putStrLn $ "! " ++ show v
  hFlush stdout


{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Debug.Trace
import Data.List
import Data.Char
import Data.Array.ST
import Data.Array.Unboxed
import Data.Array.Base (unsafeWrite,unsafeRead,unsafeAt)
import Data.Bits((.|.),xor)
import Monad

class Scan a where scan' :: String -> a
instance Scan Int where scan' = read
instance Scan Char where scan' (x:_) = x
instance Scan Float where scan' = read
instance Scan Double where scan' = read
instance Scan Integer where scan' = read
instance Scan String where scan' x = x
instance (Scan a,Scan b) => Scan (a,b) where scan' x = (\(x:y:_) -> (scan' x,scan' y)) (words x)
instance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)) (words x)
instance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = (\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)) (words x)
instance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = (\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)) (words x)
class Ans a where showans :: a -> String
instance Ans Int where showans x = show x
instance Ans Char where showans x = [x]
instance Ans Float where showans x = show x
instance Ans Double where showans x = show x
instance Ans Integer where showans x = show x
instance Ans String where showans x = x
instance (Ans a, Ans b) => Ans (a,b) where showans (x,y) = showans x ++ " " ++ showans y
instance (Ans a, Ans b,Ans c) => Ans (a,b,c) where showans (x,y,z) = showans x ++ " " ++ showans y ++ " " ++ showans z
scan :: (Scan a) => IO a
scan = getLine>>=(return.scan')
scans :: (Scan a) => Int -> IO [a]
scans n = if n==0 then return [] else scan>>=(\x->scans (n-1)>>=return.(x:))
scanlist :: (Scan a) => IO [a]
scanlist = getLine>>=return.(map scan').words
scanlists :: (Scan a) => Int -> IO [[a]]
scanlists n = if n==0 then return [] else scanlist>>=(\x->scanlists (n-1)>>=return.(x:))
putAnsLn :: (Ans a) => a -> IO ()
putAnsLn = putStrLn.showans
putAnsLns :: (Ans a) => [a] -> IO ()
putAnsLns = mapM_ putAnsLn

sieve :: Int -> UArray Int Bool
sieve n = runSTUArray $ do
            t <- newArray (0,n) True
            unsafeWrite t 1 False
            let sqn = (floor.sqrt.fromIntegral) (n::Int)
            mapM_ (\i -> unsafeRead t i >>= (flip when) (mapM_ (\j -> (unsafeWrite t j False)) [i*i,i*(i+2)..n])) [3,5..sqn]
            return t

solve l r = rec beg 0
    where
      sve = sieve r
      beg = case mod l 4 of
              0 -> l+1
              1 -> l
              2 -> l+3
              3 -> l+2
      rec i n |i>r = n + (if l<=2&&r>=2 then 1 else 0)
              |unsafeAt sve i = rec (i+4) (n+1)
              |otherwise = rec (i+4) n

main = do (l,r) <- scan :: IO (Int,Int)
          print (solve l r)

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

import Data.Array.Base (unsafeRead,unsafeWrite,unsafeAt)
import Data.Array.ST
import Data.Array.Unboxed
import Data.Bits
import Control.Applicative
import Control.Monad
import Control.Monad.ST

main = do
  [l,r] <- map read.words <$> getLine
  print $ solve l r

solve :: Int -> Int -> Int
solve l r = go (fromEnum $ l<=2 && 2<=r) $ (l+2)`div`4
   where
     !isPrime = sieve r
     !end = (r-1)`div`4
     go !ans !x
       | end < x = ans
       | unsafeAt isPrime x = go (ans+1) (x+1)
       | otherwise = go ans (x+1)

sieve :: Int -> UArray Int Bool
sieve num = runSTUArray $ do
  isSmallPrime <- newArray (0,isqrt num`div`2) True :: ST s (STUArray s Int Bool)
  isLargePrime <- newArray (0,num`div`4) True
  unsafeWrite isSmallPrime 0 False
  unsafeWrite isLargePrime 0 False
  let !sqrtNum2 = isqrt num`div`2
      !num4 = num`div`4
  forM_ [1..sqrtNum2] $ \i-> do
    isPrime <- unsafeRead isSmallPrime i
    when isPrime $ do
      let !p = i`shiftL`1 + 1
          !pp = i*(p+1)
          !ii = i*(i+1)
      forM_ [pp,pp+p..sqrtNum2] $ \j-> do
        unsafeWrite isSmallPrime j False
      forM_ [ii,ii+p..num4] $ \j-> do
        unsafeWrite isLargePrime j False
  return isLargePrime

isqrt :: Int -> Int
isqrt x = floor.(1e-8+).sqrt $ fromIntegral x

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Debug.Trace
import Data.List
import Data.Char
import Data.Array.ST
import Data.Array.Unboxed
import Data.Array.Base (unsafeWrite,unsafeRead,unsafeAt)
import Data.Bits((.|.),xor)
import Monad

class Scan a where scan' :: String -> a
instance Scan Int where scan' = read
instance Scan Char where scan' (x:_) = x
instance Scan Float where scan' = read
instance Scan Double where scan' = read
instance Scan Integer where scan' = read
instance Scan String where scan' x = x
instance (Scan a,Scan b) => Scan (a,b) where scan' x = (\(x:y:_) -> (scan' x,scan' y)) (words x)
instance (Scan a,Scan b,Scan c) => Scan (a,b,c) where scan' x = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)) (words x)
instance (Scan a,Scan b,Scan c,Scan d) => Scan (a,b,c,d) where scan' x = (\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)) (words x)
instance (Scan a,Scan b,Scan c,Scan d,Scan e) => Scan (a,b,c,d,e) where scan' x = (\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)) (words x)
class Ans a where showans :: a -> String
instance Ans Int where showans x = show x
instance Ans Char where showans x = [x]
instance Ans Float where showans x = show x
instance Ans Double where showans x = show x
instance Ans Integer where showans x = show x
instance Ans String where showans x = x
instance (Ans a, Ans b) => Ans (a,b) where showans (x,y) = showans x ++ " " ++ showans y
instance (Ans a, Ans b,Ans c) => Ans (a,b,c) where showans (x,y,z) = showans x ++ " " ++ showans y ++ " " ++ showans z
scan :: (Scan a) => IO a
scan = getLine>>=(return.scan')
scans :: (Scan a) => Int -> IO [a]
scans n = if n==0 then return [] else scan>>=(\x->scans (n-1)>>=return.(x:))
scanlist :: (Scan a) => IO [a]
scanlist = getLine>>=return.(map scan').words
scanlists :: (Scan a) => Int -> IO [[a]]
scanlists n = if n==0 then return [] else scanlist>>=(\x->scanlists (n-1)>>=return.(x:))
putAnsLn :: (Ans a) => a -> IO ()
putAnsLn = putStrLn.showans
putAnsLns :: (Ans a) => [a] -> IO ()
putAnsLns = mapM_ putAnsLn

sieve :: Int -> UArray Int Bool
sieve n = runSTUArray $ do
            t <- newArray (0,n) True
            unsafeWrite t 1 False
            let sqn = (floor.sqrt.fromIntegral) (n::Int)
            mapM_ (\i -> unsafeRead t i >>= (flip when) (mapM_ (\j -> (unsafeWrite t j False)) [i*i,i*(i+2)..n])) [3,5..sqn]
            return t

solve l r = rec beg 0
    where
      sve = sieve r
      beg = case mod l 4 of
              0 -> l+1
              1 -> l
              2 -> l+3
              3 -> l+2
      rec i n |i>r = n + (if l<=2 then 1 else 0)
              |unsafeAt sve i = rec (i+4) (n+1)
              |otherwise = rec (i+4) n

main = do (l,r) <- scan :: IO (Int,Int)
          print (solve l r)


import Control.Monad

f :: Int -> (Int,Int) -> Int
f 1 (a,b)
  | a <= b = b - a + b
  | otherwise = -1
f n (a,b)
  | even n = f (div n 2) (a+1,b)
  | mod n 3 == 0 = f (div n 3) (a,b+1)
  | otherwise = -1

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    n <- read <$> getLine
    print $ f n (0,0)

solve :: Int -> Int -> Int
solve k n
  | n == 1         = k
  | n `mod` 6 == 0 = solve (k + 1) (n `div` 6)
  | n `mod` 3 == 0 = solve (k + 1) (2 * n)
  | otherwise      = -1

main :: IO ()
main = interact $ unlines . map show . map (solve 0) . map read . tail . lines

import Control.Monad (replicateM_)
import Data.Maybe (fromMaybe)

main = readLn >>= flip replicateM_ (getLine >>= print . fromMaybe (-1) . f . read)

f :: Int -> Maybe Int
f 1 = Just 0
f n | n `mod` 6 == 0 = (1+) <$> f (n `div` 6)
    | n `mod` 3 == 0 = (2+) <$> f (n `div` 3)
    | otherwise = Nothing

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List
import Data.Maybe

main :: IO ()
main =  interact $  lines >>> drop 1 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (l : rest) = (itoline . solve . linetoi) l : tcio rest
  linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois
  itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

fac :: Int -> [Int]
fac = unfoldr firstfac where
  firstfac n = listToMaybe [ (f, n `div` f) | f <- [6,3,(max n 2)], n `mod` f == 0]

solve :: Int -> Int
solve n | n==1 = 0
        | (not.null) [x | x <-fac n, x /=6, x/=3] = -1
        | otherwise = sum [6 `div` x | x<-fac n]

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
--import safe Data.List (sort)
import Data.List
import Data.Maybe

main :: IO ()
main =  interact $  lines >>> drop 1 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (l : rest) = (itoline . solve . linetoi) l : tcio rest
  linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois
  itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

solve :: Int -> Int
solve = (fromMaybe (-1)).solve' where
  solve' n | n == 1 = Just 0
           | n `mod` 6 == 0 = pure (+) <*> Just 1 <*> solve' (n `div` 6)
           | n `mod` 3 == 0 = pure (+) <*> Just 2 <*> solve' (n `div` 3)
           | otherwise = Nothing

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

process 1 n = n
process x n | mod x 3 >0 = -1
            | mod x 6==0 = process (div x 6) (n+1)
            | otherwise = process (x+x) (n+1)

onecase = do
		x<- read <$> getLine ::IO Int
		print $ process x 0

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


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

main = getLine >>= test.read
test 0 = return ()
test i = do
  s <- ((++ "R").('R' :)) <$> getLine
  print $ maximum $ zipWith subtract <*> tail $ map snd $ filter ((== 'R').fst) $ zip s [0..]
  test (i - 1)

import Data.List

main :: IO ()

main = interact (format' . solve . format)

solve :: [[Int]] -> [Int]
solve = map solver

format' = unlines . map show

solver :: [Int] -> Int
solver xs = f 0 0 xs

f i l [] = i -- last
f i l (x:xs)
    | i < (x - l)   = f (x - l) x xs
    | otherwise     = f i x xs

format :: String -> [[Int]]
format xs = map (map fst . filter ((=='R') . snd) . zip [1..] . foldr (:) "R") . tail . lines $ xs

import Control.Monad
import Data.List
main = do
  t <- readLn
  replicateM t $ getLine >>= print.solve
solve = (+1).foldl max 0.map length.filter((=='L').head).group

import Control.Monad

main = do
    numTests <- read <$> getLine
    replicateM_ numTests $ do
        str <- getLine
        print $ maxDist 1 str

maxDist n "" = n
maxDist n ('R':xs) = max n $ maxDist 1 xs
maxDist n (_:xs) = maxDist (succ n) xs

import Data.List
import Control.Monad

solve xs = dist rs
  where
    l = length xs
    rs = sort $ (elemIndices 'R' xs) ++ [-1,l]
    dist [_] = 0
    dist (x:y:xs) = max (y-x) (dist (y:xs))

main = do
  t <- readLn :: IO Int
  xss <- replicateM t $ do
    getLine >>= return
  mapM_ (print . solve) xss


import Control.Applicative ((<$>), (<*>))
import Data.Graph (buildG, components)
import Data.List ((\\))
import Data.Tree (flatten)

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

solve :: (Int, Int) -> [[Int]] -> Int
solve (n, m) xs | all null xs = n
                | otherwise = length (map flatten (components graph) \\ map (:[]) [n + 1 .. n + m]) - 1
  where graph = buildG (1, n + m) $ concatMap (\(i, ys) -> map (\y -> (i, n + y)) ys) $ zip [1..] xs

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

import qualified Data.Map as M
import Data.List

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

solve :: [[Int]] -> Int
solve lss  = emp + (max 0 $ length (group $ sort $ map (root disjointSet) $ M.elems disjointSet) - 1)
  where
  (emp, disjointSet) = foldl f (0, M.empty) $ zip [101..] lss
  f (e, set) (n, []) = (e + 1, set)
  f (e, set) (n, ls) = (e, foldl (g n) set $ map (root set) ls)
  g n set r = M.insert r n set

root set l
    | M.member l set = root set (set M.! l)
    | otherwise = l

import Control.Monad (liftM, replicateM)
import Data.Graph
import Data.Tree
import Data.Char (ord)
import Data.List ((\\), intercalate)

solve :: Int -> Int -> [[Int]] -> Int
solve n m xss
  | all (== [0]) xss  =  n
  | otherwise  =  length (map flatten (components graph) \\ (map toList [n+1 .. n+m])) - 1
  where
    toList x  =  [x]
    xss'   =  zip [1..] $ map (tail . map (+n)) xss
    graph  =  buildG (1, n + m) $ concatMap (\(i, ls) -> zip (repeat i) ls) xss'

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

  where
{-
    prints :: Show a => [a] -> IO ()
    prints  =  putStrLn . intercalate " " . map show

    readPair :: Num a => IO (a, a)
    readPair  =  do
        [a, b]  <-  reads
        return (a, 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')

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, TupleSections #-}

import Control.Applicative
import Control.Monad
import Data.Array.Base
import Data.Array (Array)
import Data.Array.IO (IOUArray)
import qualified Data.ByteString.Char8 as B
import Data.List hiding (find)
import Data.Ord

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

mkGraph :: Int -> [(Int,Int)] -> Array Int [Int]
mkGraph vnum edges = unsafeAccumArray (flip (:)) [] (0,vnum-1) edges

main = do
  [n,m] <- map read.words <$> getLine :: IO [Int]
  let f i [] = [(m,i)]
      f i xs = xs
  langToPerson <- mkGraph (m+1).concat.zipWith(\i (_:xs)->f i$map((,i).pred)xs)[0..].map(map readInt.B.words).B.lines <$> B.getContents :: IO (Array Int [Int])
  uf <- mkUnionFind n
  mapM_ (unites uf.unsafeAt langToPerson) [0..m]
  tmp <- pred.length.unique.sort <$> mapM (flip find uf) [0..n-1]
  let zeros = length $ unsafeAt langToPerson m
      res | tmp == 0 = zeros
          | zeros <= 1 = tmp
          | otherwise = tmp + zeros - 1
  print $ res

unique (x:xs) = x : unique (dropWhile (x==) xs)
unique [] = []

unites uf (x:y:xs) = unite x y uf >> unites uf (y:xs)
unites _ _ = return ()

type Parent = Int
type Rank = Int
data UnionFind = UF !(IOUArray Int Parent) !(IOUArray Int Rank)

mkUnionFind :: Int -> IO UnionFind
mkUnionFind n = do
  parent <- newListArray (0,n-1) [0..n-1] :: IO (IOUArray Int Parent)
  rank   <- newArray (0,n-1) 0            :: IO (IOUArray Int Rank)
  return $! UF parent rank

find :: Int -> UnionFind -> IO Parent
find x uf@(UF parent _) = do
  px <- unsafeRead parent x
  if x==px
     then return x
     else do
       ppx <- find px uf
       unsafeWrite parent x ppx
       return ppx

unite :: Int -> Int -> UnionFind -> IO ()
unite x y uf@(UF parent rank) = do
  px <- find x uf
  py <- find y uf
  when (px/=py) $ do
    rx <- unsafeRead rank px
    ry <- unsafeRead rank py
    case compare rx ry of
      LT -> unsafeWrite parent px py
      GT -> unsafeWrite parent py px
      EQ -> do
        unsafeWrite parent px py
        unsafeWrite rank py $! ry+1

import Control.Monad (liftM, replicateM)
import Data.Graph
import Data.Tree
import Data.Char (ord)
import Data.List ((\\), intercalate)

solve :: Int -> Int -> [[Int]] -> Int
solve n m xss  =  length (map flatten (components graph) \\ (map toList [n+1 .. n+m])) - 1
  where
    toList x  =  [x]
    xss'   =  zip [1..] $ map (tail . map (+n)) xss
    graph  =  buildG (1, n + m) $ concatMap (\(i, ls) -> zip (repeat i) ls) xss'

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

  where
{-
    prints :: Show a => [a] -> IO ()
    prints  =  putStrLn . intercalate " " . map show

    readPair :: Num a => IO (a, a)
    readPair  =  do
        [a, b]  <-  reads
        return (a, 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 Control.Applicative ((<$>), (<*>))
import Data.Graph (buildG, components)
import Data.List ((\\))
import Data.Tree (flatten)

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

solve :: (Int, Int) -> [[Int]] -> Int
solve (n, m) xs = length (map flatten (components graph) \\ map (:[]) [n + 1 .. n + m]) - 1
  where graph = buildG (1, n + m) $ concatMap (\(i, ys) -> map (\y -> (i, n + y)) ys) $ zip [1..] xs

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

import qualified Data.Map as M
import Data.List

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

solve :: [[Int]] -> Int
solve lss  = length (group $ sort $ map (root disjointSet) $ M.elems disjointSet) - 1
  where
  disjointSet = foldl f M.empty $ zip [101..] lss
  f set (n, []) = M.insert (n * n) n set
  f set (n, ls) = foldl (g n) set ls
  g n set l = M.insert (root set l) n set

root set l
    | M.member l set = root set (set M.! l)
    | otherwise = l

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, TupleSections #-}

import Control.Applicative
import Control.Monad
import Data.Array.Base
import Data.Array (Array)
import Data.Array.IO (IOUArray)
import qualified Data.ByteString.Char8 as B
import Data.List hiding (find)
import Data.Ord

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

mkGraph :: Int -> [(Int,Int)] -> Array Int [Int]
mkGraph vnum edges = unsafeAccumArray (flip (:)) [] (0,vnum-1) edges

main = do
  [n,m] <- map read.words <$> getLine :: IO [Int]
  langToPerson <- mkGraph m.concat.zipWith(\i (_:xs)->map((,i).pred)xs)[0..].map(map readInt.B.words).B.lines <$> B.getContents :: IO (Array Int [Int])
  uf <- mkUnionFind n
  mapM_ (unites uf.unsafeAt langToPerson) [0..m-1]
  res <- pred.length.unique.sort <$> mapM (flip find uf) [0..n-1]
  print res

unique (x:xs) = x : unique (dropWhile (x==) xs)
unique [] = []

unites uf (x:y:xs) = unite x y uf >> unites uf (y:xs)
unites _ _ = return ()

type Parent = Int
type Rank = Int
data UnionFind = UF !(IOUArray Int Parent) !(IOUArray Int Rank)

mkUnionFind :: Int -> IO UnionFind
mkUnionFind n = do
  parent <- newListArray (0,n-1) [0..n-1] :: IO (IOUArray Int Parent)
  rank   <- newArray (0,n-1) 0            :: IO (IOUArray Int Rank)
  return $! UF parent rank

find :: Int -> UnionFind -> IO Parent
find x uf@(UF parent _) = do
  px <- unsafeRead parent x
  if x==px
     then return x
     else do
       ppx <- find px uf
       unsafeWrite parent x ppx
       return ppx

unite :: Int -> Int -> UnionFind -> IO ()
unite x y uf@(UF parent rank) = do
  px <- find x uf
  py <- find y uf
  when (px/=py) $ do
    rx <- unsafeRead rank px
    ry <- unsafeRead rank py
    case compare rx ry of
      LT -> unsafeWrite parent px py
      GT -> unsafeWrite parent py px
      EQ -> do
        unsafeWrite parent px py
        unsafeWrite rank py $! ry+1


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

import           Control.Applicative
import           Control.Monad
import           Control.Monad.State.Strict
import           Data.Array.Unboxed
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.Strict         as IM
import qualified Data.IntSet                as IS
import           Data.List
import           Data.List.Split
import qualified Data.Map.Strict            as M
import           Data.Monoid
import           Data.Ord
import qualified Data.Set                   as S
import           Data.Tuple
import           Data.Word

readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
readInteger :: B.ByteString -> Integer
readInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$"readInteger error : bs = "++show bs;}

main :: IO ()
main = getLine >> B.getContents >>= print.solve.B.words

solve :: [B.ByteString] -> Int
solve bss = go 0 1 [] IS.empty bss
  where
    go !res !num (top:stock) set ("remove":rest)
      | top == num = go res (num + 1) stock set rest
      | set' <- foldl' (flip IS.insert) set (top:stock) =
           go (res + 1) (num + 1) [] (IS.deleteMin set') rest
    go !res !num [] set ("remove":rest) =
        go res (num + 1) [] (IS.deleteMin set) rest
    go res num stock set ("add":x:rest) =
        go res num (readInt x:stock) set rest
    go res _ _ _ [] = res

{-# LANGUAGE OverloadedStrings, BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad

data Command = Add {-# UNPACK #-} !Int | Remove

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

solve n cs = (\(a, _, _, _) -> a) $ foldl go (0, 1, [], []) cs
  where
    go (!cnt, !i, s, !sorted) c = case c of
      Add x -> (cnt, i, x:s, False:sorted)
      Remove -> if head sorted || i == head s
                then (cnt, i + 1, tail s, tail sorted)
                else (cnt + 1, i + 1, tail s, repeat True)

main = do
  n <- fmap readInt B.getLine
  cs <- replicateM (2 * n) (fmap (\l -> case B.words l of { ["add", x] -> Add (readInt x); _ -> Remove }) B.getLine)
  print $ solve n cs

{-# LANGUAGE OverloadedStrings, BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad

data Command = Add Int | Remove

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

solve n cs = (\(a, _, _, _) -> a) $ foldl go (0, 1, [], []) cs
  where
    go (!cnt, !i, s, !sorted) c = case c of
      Add x -> (cnt, i, x:s, False:sorted)
      Remove -> if head sorted || i == head s
                then (cnt, i + 1, tail s, tail sorted)
                else (cnt + 1, i + 1, tail s, repeat True)

main = do
  n <- fmap readInt B.getLine
  cs <- replicateM (2 * n) (fmap (\l -> case B.words l of { ["add", x] -> Add (readInt x); _ -> Remove }) B.getLine)
  print $ solve n cs

{-# LANGUAGE OverloadedStrings, BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad

data Command = Add {-# UNPACK #-} !Int | Remove

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

solve n cs = (\(a, _, _, _) -> a) $ foldl go (0, 1, [], []) cs
  where
    go (!cnt, !i, s, sorted) c = case c of
      Add x -> (cnt, i, x:s, False:sorted)
      Remove -> if head sorted || i == head s
                then (cnt, i + 1, tail s, tail sorted)
                else (cnt + 1, i + 1, tail s, repeat True)

main = do
  n <- fmap readInt B.getLine
  cs <- replicateM (2 * n) (fmap (\l -> case B.words l of { ["add", x] -> Add (readInt x); _ -> Remove }) B.getLine)
  print $ solve n cs

import Data.List
import Data.Char

-- -- O( n^2 * log n ) method
-- boxes lst commands srts pos
--   | (null commands) = srts
--   | (take 3 (head commands)) == "add"  = boxes (((read (drop 4 (head commands)))::Int) : lst) (tail commands) srts pos
--   | (take 3 (head commands)) == "rem" && (head lst) /= pos = boxes (sort lst) commands (succ srts) pos
--   | (head lst) == pos = boxes (tail lst) (tail commands) srts (succ pos)

boxes lst commands srts pos
  | (null commands) = srts
  | (take 3 (head commands)) == "add" = boxes (((read (drop 4 (head commands)))::Int) : lst) (tail commands) srts pos
  | (null lst) = boxes [] (tail commands) (srts) (succ pos)
  | (head lst) /= pos = boxes [] (tail commands) (succ srts) (succ pos)
  | (head lst) == pos = boxes (tail lst) (tail commands) srts (succ pos)

main = do
  ff <- getLine
  let n = (read (ff)) :: Int
      hh = replicate (2*n) getLine

  gg <- sequence hh
  let ans = boxes [] gg 0 1
  putStrLn (show ans)

solve :: [Int] -> Int -> [String] -> Int
solve _ _ [] = 0
solve s j ("remove":t)
  | s == [] = sub
  | (head s) == j = solve (tail s) (j+1) t
  | otherwise = sub+1
    where sub = solve [] (j+1) t
solve s j (h:t) = solve (i:s) j t
  where i = read $ head $ tail $ words h

main = do
  sn <- getLine
  let n = read sn :: Int
  q <- sequence [getLine | i <- [1..(2*n)]]
  putStr $ show $ solve [] 1 q


import Data.List (sort)
main = interact $ unlines . map solve . drop 1 . lines
solve t = solve' $ map read $ words t
solve' :: [Int] -> String
solve' [a, b, c, m] =
  if m >= minReachable && m <= maxReachable then "YES" else "NO"
    where minReachable = c' - 1 - a' - b'
          maxReachable = a + b + c - 3
          [a', b', c'] = sort [a, b, c]
solve' _ = "INVALID TEST CASE"

import Control.Monad
import Data.List

calc :: [Int] -> Int -> String
calc [a,b,c] m =
  if c - (a + b + 1) <= m && m <= a + b + c  - 3 then "YES"
  else "NO"

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let [a,b,c,m] = map read $ words line :: [Int]
    putStrLn $ calc (sort [a,b,c]) m

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

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

solve :: IO ()
solve = do
    arr <- rl
    let m = last arr
    let f = sort . take 3 $ arr
    if max 0 (2 * maximum f - sum f - 1) <= m && m <= sum f - 3
        then putStrLn "YES" else putStrLn "NO"

main :: IO ()
main = do
    [t] <- rl
    replicateM_ t solve

{-# LANGUAGE DeriveFunctor     #-}
{-# LANGUAGE FlexibleContexts  #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs             #-}
{-# LANGUAGE LambdaCase        #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards   #-}
{-# LANGUAGE TupleSections     #-}
{-# LANGUAGE TypeApplications  #-}

import           Control.Arrow
import           Control.Monad.State
import           Data.Array.Unboxed
import           Data.Bits
import           Data.Bool
import           Data.ByteString.Lazy.Char8 (ByteString)
import qualified Data.ByteString.Lazy.Char8 as C
import           Data.Char
import qualified Data.Foldable              as F
import           Data.Function
import           Data.Graph
import           Data.List
import           Data.Map                   (Map, (!))
import qualified Data.Map                   as M
import           Data.Maybe
import           Data.Ord
import           Data.Ratio
import           Data.Sequence              (Seq, ViewL (..), ViewR (..), (<|),
                                             (|>))
import qualified Data.Sequence              as Seq
import           Data.Set                   (Set)
import qualified Data.Set                   as S
import           Data.Tree
import           Text.Printf

-- import Text.Parsec
-- import Text.Parsec.Expr
-- import Text.Parsec.Language (emptyDef)
-- import Text.Parsec.String
-- import qualified Text.Parsec.Token as T

infixl 0 >$>
(>$>) = flip ($)

readB = C.unpack >>> read

main = C.interact $
  C.lines >>> drop 1 >>> map (C.words >>> map readB >>> solve >>> bool "NO" "YES") >>> C.unlines

solve :: [Int] -> Bool
solve [a,b,c,m] = a + b + c - m >= 3 && m >= z - (x+y) - 1
  where
    [x,y,z] = sort [a,b,c]

import Control.Monad
import Data.List

calc :: [Int] -> Int -> String
calc [a,b,c] m =
  if c - (a + b - 1) <= m && m <= a + b + c  - 3 then "YES"
  else "NO"

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let [a,b,c,m] = map read $ words line :: [Int]
    putStrLn $ calc (sort [a,b,c]) m


{-
Famil Door wants to celebrate his birthday with his friends from Far Far Away.
He has n friends and each of them can come to the party in a specific range of
days of the year from ai to bi. Of course, Famil Door wants to have as many
friends celebrating together with him as possible.

Far cars are as weird as Far Far Away citizens, so they can only carry two people
of opposite gender, that is exactly one male and one female. However, Far is so
far from here that no other transportation may be used to get to the party.

Famil Door should select some day of the year and invite some of his friends,
such that they all are available at this moment and the number of male friends
invited is equal to the number of female friends invited. Find the maximum
number of friends that may present at the party.

Input
The first line of the input contains a single integer n (1 ≤ n ≤ 5000) — then
number of Famil Door's friends.

Then follow n lines, that describe the friends. Each line starts with a capital
letter 'F' for female friends and with a capital letter 'M' for male friends.
Then follow two integers ai and bi (1 ≤ ai ≤ bi ≤ 366), providing that the i-th
friend can come to the party from day ai to day bi inclusive.

Output
Print the maximum number of people that may come to Famil Door's party.

Found at: http://codeforces.com/contest/629/problem/B
-}

module Main where

solve :: [(Char, Int, Int)] -> Int
solve friends = 2 * (maximum $ zipWith (\m f -> min m f) mTotal fTotal)
  where mFriends = filter (\(g,_,_) -> g == 'M') friends
        mMasks = map mask mFriends
        mTotal = foldl addMasks mask0 mMasks
        fFriends = filter (\(g,_,_) -> g == 'F') friends
        fMasks = map mask fFriends
        fTotal = foldl addMasks mask0 fMasks

mask :: (Char,Int,Int) -> [Int]
mask (_,a,b) = [if a <= i && i <= b then 1 else 0 | i <- [1..366]]

mask0 = [0 | i <- [1..366]]

addMasks [] [] = []
addMasks (x:xs) (y:ys) = (x+y) : addMasks xs ys

getLines :: Int -> IO [String]
getLines n = sequence $ replicate n getLine

parseFriend :: [String] -> (Char, Int, Int)
parseFriend [genderStr, aStr, bStr] = (head genderStr, read aStr, read bStr)

main :: IO ()
main = do
  friendCountStr <- getLine
  let n = read friendCountStr :: Int
  friendLines <- getLines n
  let friends = map (parseFriend . words) friendLines
  putStrLn $ show (solve friends)

import Data.Maybe
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Function as F
import Control.Monad
import Control.Applicative
import Data.List
readInt :: C.ByteString -> Int

readInt = fst . fromJust . C.readInt

getInts = map readInt . C.words <$> C.getLine

countLetters :: String -> Char -> Int
countLetters str c = length $ filter (== c) str

fst3 (a,b,c) = a
rd3 (_,_, c) = c

main :: IO ()
main = do
    (n:_) <- getInts
    rawInput <- replicateM n getLine
    let wordedInp = map words rawInput
    --print wordedInp
    let procInput = map processInput wordedInp
    let events = concatMap procEvent procInput
    let sEvents = sort events
    let groupedEvents = groupBy ((==) `F.on` fst3) sEvents
    let procEvents = map procList groupedEvents
    print $ rd3 $ foldl procSeries (0,0, 0) procEvents
    where
        processInput line = case line of
            [[c], n1, n2] -> (c, read n1 :: Int, read n2 :: Int)
        procEvent (c, n1, n2) = [(n1,c,1), (n2 + 1, c,-1)]
        procEl (men, women) (_, c, x)
            | c == 'M' = (men + x, women)
            | c == 'F' = (men, women + x)
        procList =
            foldl procEl (0,0)
        procSeries (men, women, score) (men2, women2) =
            (newMen, newWomen, trueScore)
            where
                newMen = men + men2
                newWomen = women + women2
                newScore = 2 * min newMen newWomen
                trueScore = max newScore score

import Control.Monad
import Control.Arrow
import Data.List
import Control.Applicative
import Data.Maybe

import qualified Data.ByteString.Char8 as C

data Person = Person Int Int Bool
  deriving Show

instance Eq Person where
   (Person _ a aa) == (Person _ b bb) = (a == b) && (aa == bb)

instance Ord Person where
   (Person _ a aa) <= (Person _ b bb) = (a < b) || ((a == b) && aa) || ((a == b) && (not aa) && (not bb))

findRes :: [Person] -> (Int, Int) -> Int
findRes [] a = 0
findRes ((Person i j k):xs) (a, b) =
    max (min a b) (findRes xs (c, d))
  where
    (c, d) = if i == 0 then if k then (a+1,b) else (a-1,b) else if k then (a, b+1) else (a, b-1)

tr :: C.ByteString -> [Person]
tr = fromJust . f . C.unpack
  where
    f (a:y:ys) =
        if (a == 'M')
        then
            (C.readInt.C.pack $ ys) >>=
                \x -> Just $ [ Person 0 (fst x) True
                             , Person 0 ((fst . fromJust . C.readInt . C.pack . tail . C.unpack . snd) x) False]
        else
            (C.readInt.C.pack $ ys) >>=
                \x -> Just $ [ Person 1 (fst x) True
                             , Person 1 ((fst . fromJust . C.readInt . C.pack . tail . C.unpack . snd) x) False]

main :: IO ()
main = do
    a <- (fst.fromJust.C.readInt) <$> C.getLine
    b <- sequence $ replicate a $ tr <$> C.getLine
    print $ (*2) $ flip findRes (0, 0) $ sort . concat $ b

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

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

main = do
  t <- fmap read getLine
  inp <- forM [1..t] $ \_ -> do
         [s, a, b] <- fmap words getLine
         case s of
           "F" -> return (Friend F (read a) (read b))
           _ -> return (Friend M (read a) (read b))
  print $ solve inp

data Gender = M | F deriving (Show)
type Start = Int
type End = Int
data Friend = Friend Gender Start End deriving (Show)
data Interval = Open Int Gender | Close Int Gender deriving (Show)

instance Ord Interval where
    compare x y = compare (getIntervalVal x) (getIntervalVal y)

getIntervalVal (Open x _) = x
getIntervalVal (Close x _) = x

instance Eq Interval where
    x == y = getIntervalVal x == getIntervalVal y

--solve :: [Friend] -> Int
solve fs = maximum . map f' . scanl f st .  group . sort $ fs >>= intervals
    where
      f' (x, y) = (min x y)*2
      st = (0,0)
      g (a, b) = a == b
      intervals (Friend x s e) = [Open s x, Close (e+1) x]
      f (m, f) l = foldl g (m,f) l
          where
            g (m,f) (Open _ M) = (m + 1, f)
            g (m,f) (Close _ M) = (m - 1, f)
            g (m,f) (Open _ F) = (m, f + 1)
            g (m,f) (Close _ F) = (m, f - 1)

inp = [Friend M 128(1 + 130),
      Friend F 128 (1 +131),
      Friend F 131 (1 +140),
      Friend F 131 (1 +141),
      Friend M 131 (1 +200),
      Friend M 140 (1 +200)]

inp2 = [Friend M 151(1 +  307),
        Friend F 343(1 +  352),
        Friend F 117(1 +  145),
        Friend M 24 (1 + 128)]

inp3 = [Friend M 157 160, Friend F 151 160, Friend F 155 159, Friend M 12 157]

inp4 = [Friend M 1 2, Friend F 2 3, Friend M 0 3, Friend F 0 3, Friend M 2 2, Friend F 2 2]

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
import           Control.Applicative
import           Control.Monad
import           Data.List
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function
-- import           Data.Array
-- import           Data.ByteString (ByteString)
-- import qualified Data.ByteString.Char8 as C
-- import           Data.ByteString.Char8 ()
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as IntMap
-- import           Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))
-- import qualified Data.Sequence as S

myread = read :: String -> Int
main = do
  n <- readLn
  ns <- map ((\[x,a,b]->(head x,myread a,myread b)).words) <$> replicateM n getLine
  print $ solve n ns

solve :: Int -> [(Char,Int,Int)] -> Int
solve n ns = maximum . map (go (partition (\(x,_,_)->x=='M') ns)) $ [1..366] where
  go !(ms,fs) !d = 2 * min (go2 d ms) (go2 d fs) where
    go2 d rs = length . filter (\(_,a,b) -> a<=d && d<=b) $ rs

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

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

main = do
  t <- fmap read getLine
  inp <- forM [1..t] $ \_ -> do
         [s, a, b] <- fmap words getLine
         case s of
           "F" -> return (Friend F (read a) (read b + 1))
           _ -> return (Friend M (read a) (read b + 1))
  print $ solve inp

data Gender = M | F deriving (Show)
type Start = Int
type End = Int
data Friend = Friend Gender Start End deriving (Show)
data Interval = Open Int Gender | Close Int Gender deriving (Show)

instance Ord Interval where
    compare x y = compare (getIntervalVal x) (getIntervalVal y)

getIntervalVal (Open x _) = x
getIntervalVal (Close x _) = x

instance Eq Interval where
    x == y = getIntervalVal x == getIntervalVal y

--solve :: [Friend] -> Int
solve fs = maximum . map (uncurry (+)) . filter g . scanl f st .  group . sort $ fs >>= intervals
    where
      st = (0,0)
      g (a, b) = a == b
      intervals (Friend x s e) = [Open s x, Close e x]
      f (m, f) l = foldl g (m,f) l
          where

            g (m,f) (Open _ M) = (m + 1, f)
            g (m,f) (Close _ M) = (m - 1, f)
            g (m,f) (Open _ F) = (m, f + 1)
            g (m,f) (Close _ F) = (m, f - 1)

inp = [Friend M 128(1 + 130),
      Friend F 128 (1 +131),
      Friend F 131 (1 +140),
      Friend F 131 (1 +141),
      Friend M 131 (1 +200),
      Friend M 140 (1 +200)]

inp2 = [Friend M 151(1 +  307),
        Friend F 343(1 +  352),
        Friend F 117(1 +  145),
        Friend M 24 (1 + 128)]

inp3 = [Friend M 157 160, Friend F 151 160, Friend F 155 159, Friend M 12 157]

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

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

main = do
  t <- fmap read getLine
  inp <- forM [1..t] $ \_ -> do
         [s, a, b] <- fmap words getLine
         case s of
           "F" -> return (Friend F (read a) (read b + 1))
           _ -> return (Friend M (read a) (read b + 1))
  print $ solve inp

data Gender = M | F deriving (Show)
type Start = Int
type End = Int
data Friend = Friend Gender Start End deriving (Show)
data Interval = Open Int Gender | Close Int Gender deriving (Show)

instance Ord Interval where
    compare x y = compare (getIntervalVal x) (getIntervalVal y)

getIntervalVal (Open x _) = x
getIntervalVal (Close x _) = x

instance Eq Interval where
    x == y = getIntervalVal x == getIntervalVal y

--solve :: [Friend] -> Int
solve fs = {-maximum . map (uncurry (+)) . filter g .-} scanl f st .  group . sort $ fs >>= intervals
    where
      st = (0,0)
      g (a, b) = a == b
      intervals (Friend x s e) = [Open s x, Close e x]
      f (m, f) l = foldl g (m,f) l
          where

            g (m,f) (Open _ M) = (m + 1, f)
            g (m,f) (Close _ M) = (m - 1, f)
            g (m,f) (Open _ F) = (m, f + 1)
            g (m,f) (Close _ F) = (m, f - 1)

inp = [Friend M 128(1 + 130),
      Friend F 128 (1 +131),
      Friend F 131 (1 +140),
      Friend F 131 (1 +141),
      Friend M 131 (1 +200),
      Friend M 140 (1 +200)]

inp2 = [Friend M 151(1 +  307),
        Friend F 343(1 +  352),
        Friend F 117(1 +  145),
        Friend M 24 (1 + 128)]

inp3 = [Friend M 157 160, Friend F 151 160, Friend F 155 159, Friend M 12 157]


import qualified Data.IntMap as IM
import qualified Data.List as L
import qualified Data.Maybe as May
import qualified Data.Tuple as Tup

main = do
    firstLine <- getLine
    let [numLines, memSize] = map read $ words firstLine
    procRequest numLines $ makeInitMem memSize

procRequest 0 _ = return ()
procRequest n memStruct = do
    request <- getLine
    let (maybeCode, newMemStruct) = request2Instr request memStruct
    maybePrint maybeCode
    procRequest (n - 1) newMemStruct

maybePrint (Just code) = print code
maybePrint Nothing = return ()

request2Instr :: String -> MemStruct -> (Maybe ReturnCode, MemStruct)
request2Instr req = case words req of
    ["alloc", bytes] -> Tup.swap . fmap Just . Tup.swap . allocate (read bytes)
    ["erase", id] -> erase (read id)
    ["defragment"] -> (,) Nothing . defragment

-- invariant: end - begin == size of the block
data Block = Block {begin :: Int,
                               end :: Int,
                               bid :: Maybe Int}
                    deriving (Show)
data MemStruct = MemStruct {id2loc :: IM.IntMap Int,
                               loc2alloc :: IM.IntMap Block,
                               loc2free :: IM.IntMap Block,
                               nextId :: Int,
                               size :: Int}
                               deriving (Show)

data ReturnCode = Id Int | NULL | ILLEGAL_ERASE_ARGUMENT
instance Show ReturnCode where
    show (Id n) = show n
    show NULL = "NULL"
    show ILLEGAL_ERASE_ARGUMENT = "ILLEGAL_ERASE_ARGUMENT"

makeInitMem memSize = MemStruct {id2loc = IM.empty,
                                 loc2alloc = IM.empty,
                                 loc2free = IM.singleton 0 (Block {begin = 0, end = memSize, bid = Nothing}),
                                 nextId = 1,
                                 size = memSize}

defragment :: MemStruct -> MemStruct
defragment memStruct = if IM.null $ loc2free memStruct
                       then memStruct
                       else MemStruct {id2loc = newIdAllocs,
                                       loc2alloc = newLocAllocs,
                                       loc2free = newFrees,
                                       nextId = nextId memStruct,
                                       size = size memStruct}
                        where add2Top (allocTop, currAllocs) (Block {begin = b, end = e, bid = sameBID}) =
                                    (allocTop + (e - b), IM.insert allocTop
                                                                   (Block {begin = allocTop, end = (e - b) + allocTop, bid = sameBID})
                                                                   currAllocs)
                              (finalTop, newLocAllocs) = IM.foldl add2Top (0, IM.empty) $ loc2alloc memStruct
                              newIdAllocs = IM.foldl' (\newIds (Block {begin = b, end = _, bid = Just bd}) -> IM.insert bd b newIds)
                                                      IM.empty newLocAllocs
                              newFrees = IM.singleton finalTop $ Block {begin = finalTop, end = size memStruct, bid = Nothing}

erase :: Int -> MemStruct -> (Maybe ReturnCode, MemStruct)
erase blkId memStruct = case IM.lookup blkId (id2loc memStruct) of
                             Nothing -> (Just ILLEGAL_ERASE_ARGUMENT, memStruct)
                             Just blkLoc -> let eraseBlk =  (loc2alloc memStruct) IM.! blkLoc
                                                newIds = IM.delete blkId (id2loc memStruct)
                                                newAllocs = IM.delete blkLoc (loc2alloc memStruct)
                                                newFrees = insertIntoFrees eraseBlk (loc2free memStruct)
                                            in  (Nothing, MemStruct {id2loc = newIds,
                                                                     loc2alloc = newAllocs,
                                                                     loc2free = newFrees,
                                                                     nextId = nextId memStruct,
                                                                     size = size memStruct})
                        where insertIntoFrees fr@(Block {begin = b,
                                                      end = e,
                                                      bid = _})
                                              frees = let toMergeBs = (May.maybeToList $
                                                                        (IM.lookupLT b frees) >>=
                                                                        return . snd >>=
                                                                        (\blk@(Block {begin = _, end = e', bid = _})
                                                                            -> if b == e'
                                                                               then Just blk
                                                                               else Nothing)) ++
                                                                        [fr] ++
                                                                        (May.maybeToList $ IM.lookup e frees)
                                                          newBlock = foldl1 mergeBlock toMergeBs
                                                          mergeBlock (Block {begin = b1, end = e1, bid =_})
                                                                     (Block {begin = b2, end = e2, bid = _}) =
                                                                        Block {begin = b1, end = e2, bid = Nothing}
                                                      in IM.insert (begin newBlock) newBlock $ foldl (flip $ IM.delete . begin) frees toMergeBs

allocate :: Int -> MemStruct -> (ReturnCode, MemStruct)
allocate bytes memStruct = case maybeBlock of
                                Nothing -> (NULL, memStruct)
                                Just Block {begin = bg,
                                      end = ed,
                                      bid = _} -> let allocBlock = Block {begin = bg,
                                                                        end = bytes + bg,
                                                                        bid = Just newId}
                                                      freesMinus1 = IM.delete bg $ loc2free memStruct
                                                      newFrees = if (bytes + bg < ed)
                                                               then IM.insert (bytes + bg) (Block {begin = bytes + bg,
                                                                                end = ed,
                                                                                bid = Nothing})
                                                                                freesMinus1
                                                               else freesMinus1
                                                      newId2locs = IM.insert newId bg $ id2loc memStruct
                                                      newLoc2allocs = IM.insert bg allocBlock $ loc2alloc memStruct
                                                      newId = nextId memStruct
                                                   in (Id newId, MemStruct {id2loc = newId2locs,
                                                                         loc2alloc = newLoc2allocs,
                                                                         loc2free = newFrees,
                                                                         nextId = newId + 1,
                                                                         size = size memStruct})
                           where maybeBlock = L.find (\blk -> (end blk - begin blk) >= bytes) $ IM.elems $ loc2free memStruct

import Data.Map (Map)
import qualified Data.Map as M
import Data.List
import Data.Ord

type State = (Int , Map Int (Int, Int))

alloc :: Int -> State -> Int -> (State, [String])
alloc m (nextId, mem) n = res where
  go :: Int -> [(Int, Int)] -> Int
  go i ((st, l):t) | i + n <= st = i
   | otherwise = go (st+l) t
  go i [] = i

  went = go 1 (sort $ map snd $ M.toList mem)

  res | went + n > m+1 = ((nextId, mem) , ["NULL"])
    | otherwise = ((nextId + 1, M.insert nextId (went, n) mem), [show nextId])

defrag m (i, mem) = (i, M.fromList $ go 1 $ sortBy (comparing (fst.snd)) $ M.toList mem) where
  go i ((id, (from, len)):t) = (id, (i, len)):go (i+len) t
  go _ [] = []

step :: Int -> State -> [String] -> (State, [String])
step m state ["defragment"] = (defrag m state, [])
step m state ["alloc", n] = alloc m state (read n)
step m (i, mem) ["erase", x] | M.member (read x) mem = ((i, M.delete (read x) mem), [])
  | otherwise = ((i, mem), ["ILLEGAL_ERASE_ARGUMENT"])

initial = (1, M.empty)

s :: [[String]] -> [String]
s([_,m]:cmds)=concat$snd$mapAccumL (step (read m)) initial cmds

main=interact$unlines.s.map words.lines

{-
    Not in scope: `Data.Map.erase'
    Perhaps you meant one of these:
      `Data.Map.map' (imported from Data.Map),
      `Data.Map.delete' (imported from Data.Map),
      `Data.Map.elems' (imported from Data.Map)-}

import Array
import Char (toUpper)
import Monad (liftM)
import Prelude hiding (print)

data Query  =  Alloc Int | Erase Int | Defragment deriving Read
data Answer  =  Success Int | Null | IllegalErase | Empty deriving Show

solve :: Int -> [Query] -> [Answer]
solve m qs  =  solve' 1 (accumArray undefined 0 (1, m) []) qs
  where
    solve' _ _ []  =  []
    solve' n memory ((Alloc s) : qs)  =  case findEmptyMemory memory s of
        Just start  ->  Success n : solve' (n+1) (memory // (map (\i -> (i, n)) [start .. start + s - 1])) qs
        Nothing  ->  Null : solve' n memory qs
      where
        findEmptyMemory memory s  =  findEmptyMemory' 1 0
          where
            findEmptyMemory' k l
              | l == s  =  Just k
              | k + l > m  =  Nothing
              | memory ! (k+l) == 0  =  findEmptyMemory' k (l+1)
              | otherwise  =  findEmptyMemory' (k+l+1) 0
    solve' n memory ((Erase 0) : qs)  =  IllegalErase : solve' n memory qs
    solve' n memory ((Erase s) : qs)  =  case findMemory memory s of
        Just (start, length)  ->  Empty : solve' n (memory // (map (\i -> (i, 0)) [start .. start + length - 1])) qs
        Nothing  ->  IllegalErase : solve' n memory qs
      where
        findMemory memory s  =  findMemory' 1 0
          where
            findMemory' k l
              | k + l > m && l == 0  =  Nothing
              | k + l > m  =  Just (k, l)
              | memory ! (k+l) == s  =  findMemory' k (l+1)
              | memory ! (k+l) /= s && l == 0  =  findMemory' (k+1) 0
              | otherwise  =  Just (k, l)
    solve' n memory (Defragment : qs)  =  solve' n (defragment memory) qs
      where
        defragment memory  =  defragment' 1 1 memory
          where
            defragment' start current memory
              | current > m  =  memory // (map (\i -> (i, 0)) [start .. m])
              | memory ! current == 0  =  defragment' start (current + 1) memory
              | otherwise  =  defragment' (start + 1) (current + 1) (memory // [(start, memory ! current)])

parseQuery :: String -> Query
parseQuery (c:s)  =  read (toUpper c : s)

print :: Answer -> IO ()
print (Success n)   =  putStrLn (show n)
print Null          =  putStrLn "NULL"
print IllegalErase  =  putStrLn "ILLEGAL_ERASE_ARGUMENT"
print Empty         =  return ()

main :: IO ()
main  =  do
    [n, m]  <-  liftM (map read . words) getLine
    qs  <-  liftM (map parseQuery . take n . lines) getContents
    mapM_ print $ solve m qs

module Main where

import Data.Maybe (maybe)

main :: IO ()
main = interact $ unlines . solve . lines

ints :: String -> [Int]
ints = map read . words

solve :: [String] -> [String]
solve (meta:commands) = go commands (Mem 0 [Free (read m)])
  where
    [_, m] = words meta
    go [] _ = []
    go (c:cs) mem = case words c of
      ["defragment"] -> go cs (defragment mem)
      ["alloc", m] -> x:go cs nextMem where (x, nextMem) = alloc (read m) mem
      ["erase", m] -> maybe ("ILLEGAL_ERASE_ARGUMENT":go cs mem) (go cs) (erase (read m) mem)

data MemState = Free Int | Allocated Int Int deriving (Show)
data Mem = Mem Int [MemState] deriving (Show)

alloc :: Int -> Mem -> (String, Mem)
alloc x mem@(Mem m st) = case go x st of
    Just ms -> (show nextM, Mem nextM ms)
    Nothing -> ("NULL", mem)
  where
    nextM = m + 1
    go :: Int -> [MemState] -> Maybe [MemState]
    go _ [] = Nothing
    go x (Free c:xs) | c == x = Just $ Allocated nextM x:xs
    go x (Free c:xs) | c > x = Just $ Allocated nextM x:Free (c -x):xs
    go x (y:xs) = (y :) <$> go x xs

erase :: Int -> Mem -> Maybe Mem
erase x (Mem m st) = Mem m <$> go x st
  where
    go _ [] = Nothing
    go x (Allocated y c:Free d:xs) | x == y = Just $ Free (c + d):xs
    go x (Allocated y c:xs) | x == y = Just $ Free c:xs
    go x (y:xs) = (y :) <$> go x xs

defragment :: Mem -> Mem
defragment (Mem m st) = Mem m (go st 0)
  where
    go [] 0 = []
    go [] acc = [Free acc]
    go (Free a:xs) acc = go xs (acc + a)
    go (a:xs) acc = a:go xs acc

module Main where

import Data.Maybe (maybe)

main :: IO ()
main = interact $ unlines . solve . lines

ints :: String -> [Int]
ints = map read . words

solve :: [String] -> [String]
solve (meta:commands) = go commands (Mem 0 [Free (read m)])
  where
    [_, m] = words meta
    go [] _ = []
    go (c:cs) mem = case words c of
      ["defragment"] -> go cs (defragment mem)
      ["alloc", m] -> x:go cs nextMem where (x, nextMem) = alloc (read m) mem
      ["erase", m] -> maybe ("ILLEGAL_ERASE_ARGUMENT":go cs mem) (go cs) (erase (read m) mem)

data MemState = Free Int | Allocated Int Int deriving (Show)
data Mem = Mem Int [MemState] deriving (Show)

alloc :: Int -> Mem -> (String, Mem)
alloc x mem@(Mem m st) = case go x st of
    Just ms -> (show nextM, Mem nextM ms)
    Nothing -> ("NULL", mem)
  where
    nextM = m + 1
    go :: Int -> [MemState] -> Maybe [MemState]
    go _ [] = Nothing
    go x (Free c:xs) | c == x = Just $ Allocated nextM x:xs
    go x (Free c:xs) | c > x = Just $ Allocated nextM x:Free (c -x):xs
    go x (y:xs) = (y :) <$> go x xs

erase :: Int -> Mem -> Maybe Mem
erase x (Mem m st) = Mem m <$> go x st
  where
    go _ [] = Nothing
    go x (Allocated y c:Free d:xs) | x == y = Just $ Free (c + d): xs
    go x (Allocated y c:xs) | x == y = Just $ Free c: xs
    go x (_:xs) = go x xs

defragment :: Mem -> Mem
defragment (Mem m st) = Mem m (go st 0)
  where
    go [] 0 = []
    go [] acc = [Free acc]
    go (Free a:xs) acc = go xs (acc + a)
    go (a:xs) acc = a:go xs acc

import Data.Map (Map)
import qualified Data.Map as M
import Data.List
import Data.Ord

type State = (Int , Map Int (Int, Int))

alloc :: Int -> State -> Int -> (State, [String])
alloc m (nextId, mem) n = res where
  go :: Int -> [(Int, Int)] -> Int
  go i ((st, l):t) | i + n <= st = i
   | otherwise = go (st+l) t
  go i [] = i

  went = go 1 (sort $ map snd $ M.toList mem)

  res | went + n > m = ((nextId, mem) , ["NULL"])
    | otherwise = ((nextId + 1, M.insert nextId (went, n) mem), [show nextId])

defrag m (i, mem) = (i, M.fromList $ go 1 $ sortBy (comparing (fst.snd)) $ M.toList mem) where
  go i ((id, (from, len)):t) = (id, (i, len)):go (i+len) t
  go _ [] = []

step :: Int -> State -> [String] -> (State, [String])
step m state ["defragment"] = (defrag m state, [])
step m state ["alloc", n] = alloc m state (read n)
step m (i, mem) ["erase", x] | M.member (read x) mem = ((i, M.delete (read x) mem), [])
  | otherwise = ((i, mem), ["ILLEGAL_ERASE_ARGUMENT"])

initial = (1, M.empty)

s :: [[String]] -> [String]
s([_,m]:cmds)=concat$snd$mapAccumL (step (read m)) initial cmds

main=interact$unlines.s.map words.lines

{-
    Not in scope: `Data.Map.erase'
    Perhaps you meant one of these:
      `Data.Map.map' (imported from Data.Map),
      `Data.Map.delete' (imported from Data.Map),
      `Data.Map.elems' (imported from Data.Map)-}


--{-# OPTIONS_GHC -O2 #-}

import Control.Monad
--import Prelude as P
--import Data.Char as C
--import Data.List as L
--import Data.IntSet as S

solve :: IO ()
solve = do
  n <- readLn :: IO Int
  sxs <- getLine
  let xs = map read $ words sxs :: [Int]
      odds = length $ filter odd xs in
    putStrLn (if odds == n then "Yes" else "No")

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

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

printResult = do
    n <- readLn :: IO Int
    a <- readInts
    let ce = length $ filter even a
    putStrLn $ if ce == n then "Yes" else "No"

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

module Main where

import Data.List
import Control.Monad

solve :: [Int] -> String
solve lst
    | e == o = "Yes"
    | otherwise = "No"
    where
        e = length (filter even lst)
        o = length (filter odd lst)

readTestcase :: IO [Int]
readTestcase =
    getLine >> getLine >>= \l ->
        return $ map read (words l)

main :: IO ()
main = getLine >>= \nstr ->
    let n = read nstr in
        replicateM n readTestcase >>= \tests ->
        putStrLn (unlines $ map solve tests)

module Main where

import Data.List
import Control.Monad

splitPar :: [Int] -> ([Int], [Int])
splitPar lst = (filter even lst, filter odd lst)

solve :: [Int] -> String
solve lst
    | length e == length o = "Yes"
    | otherwise = "No"
    where (e, o) = splitPar lst

readTestcase :: IO [Int]
readTestcase =
    getLine >> getLine >>= \l ->
        return $ map read (words l)

main :: IO ()
main = getLine >>= \nstr ->
    let n = read nstr in
        replicateM n readTestcase >>= \tests ->
        putStrLn (unlines $ map solve tests)

{-# LANGUAGE BangPatterns #-}
import Data.Bool
import Control.Monad

countOddEven = foldl (\(o, e) a -> if odd a then (o + 1, e) else (o, e + 1))
               (0, 0)

solve lst = bool "NO" "YES" $ odd == even
  where
    !counter = countOddEven lst
    !odd = fst counter
    !even = snd counter

readInt :: String -> Int
readInt = read

main = do
  n <- readInt <$> getLine
  replicateM_ n $ do
    _ <- getLine
    lst <- map readInt . words <$> getLine
    putStrLn $ solve lst

import Control.Monad (replicateM_)

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

canPartition :: [Int] -> Bool
canPartition xs = numEven == numOdd where
  numEven = length $ filter even xs
  numOdd = length $ filter odd xs

solve :: IO ()
solve = do
  n <- getLine
  ans <- canPartition <$> readInts
  putStrLn (if ans then "YES" else "NO")

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

import Control.Monad

oddSets :: [Int]-> Bool

oddSets xs = (length xs) == 2*(length [x | x <- xs, (x `mod` 2) == 0])

it = do
	n_s <- getLine
	ln_s <-getLine

	let ans = oddSets(fmap read (words ln_s))
	let ans_s = if ans == True
		then "Yes"
		else "No"

	putStrLn ans_s

main = do
	n_s <- getLine
	let n = read n_s :: Int
	let prog = take n (repeat it)
	sequence prog
	return ()

import Control.Arrow ((>>>))
import Data.Bool (bool)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromMaybe)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts

main :: IO ()
main = interact $
  lines
    >>> drop 1
    >>> map (words >>> map read)
    >>> chunksOf 2
    >>> map (solve >>> bool "No" "Yes")
    >>> unlines

solve :: [[Int]] -> Bool
solve [[n], xs] = length (filter odd xs) == n

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

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

printS = do
    n <- readLn::IO Int
    a<-readInts
    let o = sum[1|x<-a,mod x 2 == 1]
    putStrLn $ if (o == n) then "Yes" else "No"

main = do
    t<-readLn
    replicateM_ t printS


import Data.Ord
import Data.List

main :: IO ()
main = interact solve

solve :: String -> String
solve = unlines . map f . readInput . tail . lines
  where
    readInput [] = []
    readInput (s:t:ts) = (s,t) : readInput ts

f :: (String, String) -> String
f (s, t)
  | no as || no bs || no cs || t /= "abc" = sort s
  | otherwise = sortBy (comparing g) s
  where
    no = not . flip any s
    as = (== 'a')
    bs = (== 'b')
    cs = (== 'c')

g :: Char -> Char
g 'c' = 'b'
g 'b' = 'c'
g chr = chr

-- https://codeforces.com/contest/1617/problem/A
import Data.List

count char string = length $ filter (== char) string
getCountAbc str = [count 'a' str, count 'b' str, count 'c' str]
excludeAbc = filter (`notElem` "abc")
duplicate char 0 = ""
duplicate char n = char : duplicate char (n-1)
abcAnswer perm countAbc =
    duplicate 'a' (countAbc!!0) ++
    if perm /= "abc" || countAbc!!0 == 0 then
        duplicate 'b' (countAbc!!1) ++
        duplicate 'c' (countAbc!!2)
    else
        duplicate 'c' (countAbc!!2) ++
        duplicate 'b' (countAbc!!1)

run 0 = return 0
run n = do
    s <- getLine
    perm <- getLine
    putStrLn $ abcAnswer perm (getCountAbc s) ++ sort (excludeAbc s)
    run $ n-1
main = getLine >>= run . read

-- https://codeforces.com/contest/1617/problem/A
import Data.List

count char string = length $ filter (== char) string
getCountAbc str = [count 'a' str, count 'b' str, count 'c' str]
excludeAbc = filter (`notElem` "abc")
duplicate char 0 = ""
duplicate char n = char : duplicate char (n-1)
abcAnswer perm countAbc =
    duplicate (perm!!0) (countAbc!!0) ++
    if perm /= "abc" || countAbc!!0 == 0 then
        duplicate 'b' (countAbc!!1) ++
        duplicate 'c' (countAbc!!2)
    else
        duplicate 'c' (countAbc!!2) ++
        duplicate 'b' (countAbc!!1)

run 0 = return 0
run n = do
    s <- getLine
    perm <- getLine
    putStrLn $ abcAnswer perm (getCountAbc s) ++ sort (excludeAbc s)
    run $ n-1
main = getLine >>= run . read


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

readInts :: IO [Int]
readInts = fmap (map (foldl (\x y -> 10*x + digitToInt y) 0) . words) getLine

textRepresentation :: Show a => [a] -> String
textRepresentation row = unwords . map show $ row

main :: IO ()
main = do
    n:k:m:_ <- readInts
    a <- readInts
    let  func = take k . fromMaybe [] . find (\l -> length l >= k)
         c = func . groupBy (on (==) (`mod` m)) . sortBy (on compare (`mod` m)) $ a
    if null c
    then putStr "No"
    else putStr $ "Yes\n" ++ textRepresentation c

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import qualified Data.IntMap as M

main = B.interact (B.pack . evalState app . B.words)

app = do
  n <- poi
  maybe "No" (("Yes\n" ++ ) . unwords . map show) `fmap` liftM3 solve poi poi (replicateM n poi)
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve k m = msum . map (takeAtLeast k) . M.elems . M.fromListWith (++) . map (\x -> (x `rem` m, [x]))

takeAtLeast = go id
  where
  go xs k []
    | k > 0 = Nothing
    | otherwise = Just $ xs []
  go xs 0 _ = Just $ xs []
  go xs k (y:ys) = go (xs . (y:)) (k - 1) ys

-- 1 4 8
--  3 4
--

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

readInts :: IO [Int]
readInts = fmap (map (foldl' (\x y -> 10*x + digitToInt y) 0) . words) getLine

textRepresentation :: Show a => [a] -> String
textRepresentation row = unwords . map show $ row

main :: IO ()
main = do
    n:k:m:_ <- readInts
    a <- readInts
    let  func = take k . fromMaybe [] . find (\l -> length l >= k)
         c = func . groupBy (on (==) (`mod` m)) . sortBy (on compare (`mod` m)) $ a
    if null c
    then putStr "No"
    else putStr $ "Yes\n" ++ textRepresentation c

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import qualified Data.IntMap as M

main = B.interact (B.pack . evalState app . B.words)

app = do
  n <- poi
  maybe "NO" (("YES\n" ++ ) . unwords . map show) `fmap` liftM3 solve poi poi (replicateM n poi)
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve k m = msum . map (takeAtLeast k) . M.elems . M.fromListWith (++) . map (\x -> (x `rem` m, [x]))

takeAtLeast = go id
  where
  go xs k []
    | k > 0 = Nothing
    | otherwise = Just $ xs []
  go xs 0 _ = Just $ xs []
  go xs k (y:ys) = go (xs . (y:)) (k - 1) ys

-- 1 4 8
--  3 4
--

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import qualified Data.IntMap as M

main = B.putStr . B.pack . evalState app . B.words =<< B.getContents

app = do
  n <- poi
  maybe "NO" (("YES\n" ++ ) . unwords . map show) `fmap` liftM3 solve poi poi (replicateM n poi)
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve k m = msum . map (takeAtLeast k) . M.elems . M.fromListWith (++) . map (\x -> (x `rem` m, [x]))

takeAtLeast = go id
  where
  go xs k []
    | k > 0 = Nothing
    | otherwise = Just $ xs []
  go xs 0 _ = Just $ xs []
  go xs k (y:ys) = go (xs . (y:)) (k - 1) ys

-- 1 4 8
--  3 4
--

import Prelude
import Data.List
import Data.Maybe

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

textRepresentation :: Show a => [a] -> String
textRepresentation row = foldl (\acc y -> acc ++ (show y) ++ " ") "" row

main :: IO ()
main = do
    (n:k:m:_) <- readInts
    a <- readInts
    let c = (take k . fromMaybe [] . find (\l -> length l >= k) . groupBy (\x y -> mod x m == mod y m) . sortBy (\x y -> compare(mod x m) (mod y m)) . map head . group . sort) a
    if null c
    then putStr "No"
    else putStr ("Yes\n" ++ textRepresentation c)

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

readInts :: IO [Int]
readInts = fmap (map (foldl (\x y -> 10*x+ (digitToInt y)) 0) . words) getLine

textRepresentation :: Show a => [a] -> String
textRepresentation row = (unwords . map show) row

main :: IO ()
main = do
    (n:k:m:_) <- readInts
    a <- readInts
    let  temp = (group . sort) a
         func = take k . fromMaybe [] . find (\l -> length l >= k)
         cc = func temp
         c = func . groupBy (on (==) (`mod` m)) . sortBy (on compare (`mod` m)) . map head $ temp
    if null c && null cc
    then putStr "No"
    else putStr ("Yes\n" ++ (textRepresentation (if null cc then c else cc)))


import Data.Ord
import Control.Applicative
import Data.List
import Data.Char
import Data.Array
import Debug.Trace
import Test.QuickCheck

solve :: String -> String -> Integer
solve a b =
  sum $ map (toInteger . contribution) $ [1..k]
  where
    k = length a
    delta = length b - length a
    convert x = listArray (1, length x) $ map digitToInt x
    a' = convert a
    b' = convert b
    numOnes = listArray (1, k) $ [f i | i <- [1..k]]
    numZeros i = delta + 1 - numOnes ! i
    f 1 = sum [b' ! i | i <- [1..delta+1]]
    f i = numOnes ! (i - 1) - b' ! (i - 1) + b' ! (i+delta)
    contribution i
      | a' ! i == 0 = numOnes ! i
      | otherwise = numZeros i

bruteHamming :: String -> String -> Int
bruteHamming a b =
  sum $ map hamming $ subs
  where
    subs = substrings (length a) b
    substrings n x =
      [take n (drop i x) | i <- [0..length x - n]]
    hamming :: String -> Int
    hamming b' = sum $ map fromEnum $ zipWith (/=) a b'

{-
runChecks :: IO ()
runChecks =
  let
    genVec = do
      let vals = vectorOf 2 $ listOf $ elements "01"
      sortBy (comparing length) <$> vals
    prop_hammings [a, b] =
      solve a b == bruteHamming a b
  in quickCheck $ forAll genVec prop_hammings
-}

main :: IO ()
main = do
  a <- getLine
  b <- getLine
  putStrLn $ show $ solve a b

import Data.List
import Data.Array
import Data.Int

main = do
    interact solve

solve input = (show (do_solve as 0)) --  ++ " " ++ (intercalate "," (map show (elems dp_bs_1)))
    where
        as:bs:_ = words input
        as_length::Int64
        as_length = fromIntegral(length as)
        bs_length::Int64
        bs_length = fromIntegral(length bs)
        dp_bs_0 = listArray (0,bs_length) (0:(make_dp_sum bs '0' 0))
        dp_bs_1 = listArray (0,bs_length) (0:(make_dp_sum bs '1' 0))

        -- ca current element cid is the current index
        do_solve::[Char] -> Int64 -> Int64
        do_solve [] _ = 0
        do_solve (ca:cas) cid = cur_sum + (do_solve cas (cid+1) )
            where
                hi_idx = min (cid + (bs_length-as_length+1) ) bs_length
                lo_idx = cid
                cur_sum
                    | (ca == '1') = (dp_bs_0!hi_idx) - (dp_bs_0!lo_idx)
                    -- | (ca == '1') = 0
                    | (ca == '0') = (dp_bs_1!hi_idx) - (dp_bs_1!lo_idx)
                    -- | (ca == '0') = 0

as_string::(Show a) => [a] -> [String]
as_string arr = map show arr

make_dp_sum::(Eq a) => [a] -> a -> Int64 -> [Int64]
make_dp_sum [] item csum = []
make_dp_sum (x:xs) item csum
    | x == item = (csum+1):(make_dp_sum xs item (csum+1))
    | otherwise = csum:(make_dp_sum xs item csum)

-- Michael V. Antosha  <Michael.Antosha@gmail.com>
-- 2016
-- http://mivael.in.ua

type HSumType = Integer  -- sum of hamming distances
type LenType = Integer  -- string length

main :: IO ()
main = do
  interact (show . solve . lines)

solve :: [String] -> HSumType
solve = solveStringPair
  where
    solveStringPair (a:b:[]) = solveStrAB a b
    solveStringPair _ = error "Pair of strings expected."
    solveStrAB a b =
      solvePreparsed lenA lenB psums bits
      where
        (lenA, psums) = revPSumA a (0,[0])
        (lenB, bits) = revB b (0,[])
    revPSumA = pa
    revB = pb
    pa [] result = result
    pa (ch:rest) (cnt, psums@(psum:_)) =
      pa rest (cnt + 1, psum + ch2int ch : psums)
    ch2int '0' = 0
    ch2int '1' = 1
    ch2int _ = error "ch2int: bad input"
    pb [] result = result
    pb (ch:rest) (cnt, bits) =
      pb rest (cnt + 1, ch2bool ch : bits)
    ch2bool '0' = False
    ch2bool '1' = True
    ch2bool _ = error "ch2bool: bad input"

solvePreparsed :: LenType -> LenType -> [LenType] -> [Bool] -> HSumType
solvePreparsed lenA lenB psums bits =
  f (0 :: HSumType) (1 :: LenType) (1 :: LenType) psums psums_prev bits
  where
    (_:psums_prev) = psums
    delta | (lenB >= lenA) = lenB - lenA
          | otherwise = error "Bad delta."
    f hsum cnt len c2 c1 (bit:bits) = g
      where
        g | cnt == lenB = newsum
          | cnt < lenB = f newsum (cnt + 1) newlen h2 h1 bits
          | otherwise = error "cnt is too large"
        (c1head:c1tail) = c1
        (c2head:c2tail) = c2
        ones = c2head - c1head
        zeros = len - ones
        s | bit == True = zeros
          | otherwise = ones
        newsum = hsum + s
        choose1 x y | cnt >= lenA = y | otherwise = x
        choose2 x y | cnt > delta = y | otherwise = x
        h1 = choose1 c1tail [0]
        h2 = choose2 c2 c2tail
        newlen = len - (choose2 0 1) + (choose1 1 0)
    f _ _ _ _ _ _ =
      error "Internal error (wrong data for solvePreparsed/f?)."
solvePreparsed _ _ _ _ =
  error "Internal error (wrong data for solvePreparsed?)."

import Control.Applicative
import Data.Char

solve :: [Int] -> [Int] -> Integer
solve a b = g a lst
    where
        lst = f cnt b $ drop (lenb - lena + 1) b
        f c _ [] = [c]
        f c (x:xs) (y:ys) = c : f (c-x+y) xs ys
        g [] [] = 0
        g (x:xs) (y:ys)
            | x == 1 = (fromIntegral lenb) - (fromIntegral lena) + 1 - (fromIntegral y) + g xs ys
            | otherwise = (fromIntegral y) + g xs ys
        lena = length a
        lenb = length b
        cnt = length . filter (==1) $ take (lenb - lena + 1) b

main :: IO ()
main = do
    a <- map digitToInt <$> getLine
    b <- map digitToInt <$> getLine
    print $ solve a b

import Control.Applicative
import Data.Char

solve :: [Int] -> [Int] -> Int
solve a b = g a lst
    where
        lst = f cnt b $ drop (lenb - lena + 1) b
        f c _ [] = [c]
        f c (x:xs) (y:ys) = c : f (c-x+y) xs ys
        g [] [] = 0
        g (x:xs) (y:ys)
            | x == 1 = lenb - lena + 1 - y + g xs ys
            | otherwise = y + g xs ys
        lena = length a
        lenb = length b
        cnt = length . filter (==1) $ take (lenb - lena + 1) b

main :: IO ()
main = do
    a <- map digitToInt <$> getLine
    b <- map digitToInt <$> getLine
    print $ solve a b

import Data.Ord
import Control.Applicative
import Data.List
import Data.Char
import Data.Array
import Debug.Trace
import Test.QuickCheck

solve :: String -> String -> Int
solve a b =
  sum $ map contribution $ [1..k]
  where
    k = length a
    delta = length b - length a
    convert x = listArray (1, length x) $ map digitToInt x
    a' = convert a
    b' = convert b
    numOnes = listArray (1, k) $ [f i | i <- [1..k]]
    numZeros i = delta + 1 - numOnes ! i
    f 1 = sum [b' ! i | i <- [1..delta+1]]
    f i = numOnes ! (i - 1) - b' ! (i - 1) + b' ! (i+delta)
    contribution i
      | a' ! i == 0 = numOnes ! i
      | otherwise = numZeros i

bruteHamming :: String -> String -> Int
bruteHamming a b =
  sum $ map hamming $ subs
  where
    subs = substrings (length a) b
    substrings n x =
      [take n (drop i x) | i <- [0..length x - n]]
    hamming :: String -> Int
    hamming b' = sum $ map fromEnum $ zipWith (/=) a b'

{-
runChecks :: IO ()
runChecks =
  let
    genVec = do
      let vals = vectorOf 2 $ listOf $ elements "01"
      sortBy (comparing length) <$> vals
    prop_hammings [a, b] =
      solve a b == bruteHamming a b
  in quickCheck $ forAll genVec prop_hammings
-}

main :: IO ()
main = do
  a <- getLine
  b <- getLine
  putStrLn $ show $ solve a b

import Data.List
import Data.Array

main = do
    interact solve

solve input = (show (do_solve as 0)) --  ++ " " ++ (intercalate "," (map show (elems dp_bs_1)))
    where
        as:bs:_ = words input
        as_length = length as
        bs_length = length bs
        dp_bs_0 = listArray (0,bs_length) (0:(make_dp_sum bs '0' 0))
        dp_bs_1 = listArray (0,bs_length) (0:(make_dp_sum bs '1' 0))

        -- ca current element cid is the current index
        do_solve [] _ = 0
        do_solve (ca:cas) cid = cur_sum + (do_solve cas (cid+1) )
            where
                hi_idx = min (cid + (bs_length-as_length+1) ) bs_length
                lo_idx = cid
                cur_sum
                    | ca == '1' = (dp_bs_0!hi_idx) - (dp_bs_0!lo_idx)
                    -- | (ca == '1') = 0
                    | (ca == '0') = (dp_bs_1!hi_idx) - (dp_bs_1!lo_idx)
                    -- | (ca == '0') = 0

as_string::(Show a) => [a] -> [String]
as_string arr = map show arr

make_dp_sum::(Eq a) => [a] -> a -> Int -> [Int]
make_dp_sum [] item csum = []
make_dp_sum (x:xs) item csum
    | x == item = (csum+1):(make_dp_sum xs item (csum+1))
    | otherwise = csum:(make_dp_sum xs item csum)

main :: IO ()
main = do
  putStrLn (replicate 60000 '9')

-- Michael V. Antosha  <Michael.Antosha@gmail.com>
-- 2016
-- http://mivael.in.ua

type HSumType = Int  -- sum of hamming distances
type LenType = Int  -- string length

main :: IO ()
main = do
  interact (show . solve . lines)

solve :: [String] -> HSumType
solve = solveStringPair
  where
    solveStringPair (a:b:[]) = solveStrAB a b
    solveStringPair _ = error "Pair of strings expected."
    solveStrAB a b =
      solvePreparsed lenA lenB psums bits
      where
        (lenA, psums) = revPSumA a (0,[0])
        (lenB, bits) = revB b (0,[])
    revPSumA = pa
    revB = pb
    pa [] result = result
    pa (ch:rest) (cnt, psums@(psum:_)) =
      pa rest (cnt + 1, psum + ch2int ch : psums)
    ch2int '0' = 0
    ch2int '1' = 1
    ch2int _ = error "ch2int: bad input"
    pb [] result = result
    pb (ch:rest) (cnt, bits) =
      pb rest (cnt + 1, ch2bool ch : bits)
    ch2bool '0' = False
    ch2bool '1' = True
    ch2bool _ = error "ch2bool: bad input"

solvePreparsed :: LenType -> LenType -> [LenType] -> [Bool] -> HSumType
solvePreparsed lenA lenB psums bits =
  f (0 :: HSumType) (1 :: LenType) (1 :: LenType) psums psums_prev bits
  where
    (_:psums_prev) = psums
    delta | (lenB >= lenA) = lenB - lenA
          | otherwise = error "Bad delta."
    f hsum cnt len c2 c1 (bit:bits) = g
      where
        g | cnt == lenB = newsum
          | cnt < lenB = f newsum (cnt + 1) newlen h2 h1 bits
          | otherwise = error "cnt is too large"
        (c1head:c1tail) = c1
        (c2head:c2tail) = c2
        ones = c2head - c1head
        zeros = len - ones
        s | bit == True = zeros
          | otherwise = ones
        newsum = hsum + s
        choose1 x y | cnt >= lenA = y | otherwise = x
        choose2 x y | cnt > delta = y | otherwise = x
        h1 = choose1 c1tail [0]
        h2 = choose2 c2 c2tail
        newlen = len - (choose2 0 1) + (choose1 1 0)
    f _ _ _ _ _ _ =
      error "Internal error (wrong data for solvePreparsed/f?)."
solvePreparsed _ _ _ _ =
  error "Internal error (wrong data for solvePreparsed?)."


{-# LANGUAGE OverloadedStrings #-}

import Prelude
import Control.Monad
import Data.Functor
import Data.List
import Data.Maybe
import Data.Int
import Data.Char
import qualified Data.ByteString.Char8 as B8
import Text.Printf

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

solve :: Int -> [Int] -> Int
solve n as =
    if foldr1 min as == foldr1 max as
        then n
        else 1

main :: IO ()
main = do
    t <- readIntB8 <$> B8.getLine
    forM_ [1..t] $ \_ -> do
        n <- readIntB8 <$> B8.getLine
        as <- map readIntB8 <$> B8.words <$> B8.getLine
        let answer = solve n as
        printf "%d\n" answer

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

main = getLine >>= flip replicateM_ test . read

test = do
  getLine
  as <- map read . words <$> getLine :: IO [Int]
  if all (== head as) as then print $ length as else print 1

import Control.Monad

soln :: [Int] -> Int
soln li
  | minimum li == maximum li  = length li
  | otherwise  = 1

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _nStr <- getLine
    li <- map read . words <$> getLine
    print (soln li)

{-# LANGUAGE OverloadedStrings #-}

import Prelude
import Control.Monad
import Data.Functor
import Data.List
import Data.Maybe
import Data.Int
import Data.Char
import qualified Data.ByteString.Char8 as B8
import Text.Printf

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

solve :: String -> Int64
solve digitsString = pairsCount
    where
        pairsCount = sum $ map (\cnt -> (cnt * (cnt - 1)) `div` (2 :: Int64)) countGroups
        countGroups = map (\group -> (fromIntegral $ length group) :: Int64) . group $ sort digitSums
        digitSums = scanl' (+) 0 digits
        digits = map (\c -> (fromIntegral ((ord c) - (ord '0') - 1)) :: Int64) digitsString

main :: IO ()
main = do
    t <- readIntB8 <$> B8.getLine
    forM_ [1..t] $ \_ -> do
        n <- readIntB8 <$> B8.getLine
        digits <- (head . B8.words) <$> B8.getLine
        let answer = solve $ B8.unpack digits
        printf "%s\n" $ show answer