The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the tickets strictly in the order people follow in the line?

The first line contains integer n (1 ≤ n ≤ 105) — the number of people in the line. The next line contains n integers, each of them equals 25, 50 or 100 — the values of the bills the people have. The numbers are given in the order from the beginning of the line (at the box office) to the end of the line.

Print "YES" (without the quotes) if the booking clerk can sell a ticket to each person and give the change. Otherwise print "NO".

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Char
import Text.Printf

main = do
	getLine
	as <- map read . words <$> getLine
	let
		res = solve 0 0 0 as
	putStrLn res

solve _ _ _ [] = "YES"
solve c25 c50 c100 (a:as)
	| a == 25 = solve ( c25 + 1 ) c50 c100 as
	| a == 50 = if c25 == 0
		then "NO"
		else solve ( c25 - 1 ) ( c50 + 1 ) c100 as
	| a == 100 && 1 <= c25 && 1 <= c50 = solve ( c25 - 1 ) ( c50 -1 ) ( c100 + 1 ) as
	| a == 100 && 3 <= c25 = solve ( c25 - 3 ) c50 ( c100 + 1 ) as
	| otherwise = "NO"

import Control.Applicative
get :: IO [Int]
get = fmap (map read.words) getContents

solve :: Int -> Int -> Int -> [Int] -> String
solve a b c []
  | a < 0 || b < 0 || c < 0 = "NO"
  | otherwise = "YES"
solve a b c (x:xs) -- 25, 50, 100 demonination change
  | a < 0 || b < 0 || c < 0 = "NO"
  | x == 25 = solve (a+1) b c xs
  | x == 50 = solve (a-1) (b+1) c xs
  | x == 100 = if b > 0
               then solve (a-1) (b-1) (c+1) xs
               else solve (a-3) b (c+1) xs

main :: IO ()
main=do
  (_:line) <- get
  putStrLn (solve 0 0 0 line)

import Control.Applicative
main :: IO ()
main = do
    getLine
    xs <- map read <$> words <$> getLine
    if solve 0 0 0 xs
        then putStrLn "YES"
        else putStrLn "NO"

solve :: Int -> Int -> Int -> [Int] -> Bool
solve _ _ _ []     = True
solve d100 d50 d25 (x:xs)
    | x == 25 = solve d100 d50 (d25 + 1) xs
    | x == 50 && d25 >= 1 = solve d100 (d50 + 1) (d25 - 1) xs
    | x == 100 && d50 >= 1 && d25 >= 1 = solve (d100 + 1) (d50 - 1) (d25 - 1) xs
    | x == 100 && d25 >= 3 = solve (d100 + 1) d50 (d25 - 3) xs
    | otherwise = False

check :: [Int] -> (Int, Int) -> String
check [] _                       = "YES"
check (x:xs) (d, p)
  | x == 25                      = check xs (d+1, p)
  | x == 50   && (d > 0)          = check xs (d-1, p+1)
  | x == 100  && (d > 0 && p > 0) = check xs (d-1, p-1)
  | x == 100  && (d > 2)          = check xs (d-3, p)
  | otherwise                    = "NO"

main = getLine >> getLine >>= return . (flip check) (0,0) . (map read) . words >>= putStrLn

{-# OPTIONS_GHC -O2 #-}

import qualified Data.ByteString.Char8 as B

main :: IO ()
main = do
  getLine
  putStrLn . solve (0, 0) . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents

solve :: (Int, Int) -> [Int] -> String
solve (q, h) _ | q <0 || h < 0 = "NO"
solve (q, h) [] = "YES"
solve (q, h) (25 : bs) = solve (q + 1, h) bs
solve (q, h) (50 : bs) = solve (q - 1, h + 1) bs
solve (q, 0) (100 : bs) = solve (q - 3, 0) bs
solve (q, h) (100 : bs) = solve (q - 1, h - 1) bs

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

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

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

main = do
  getLine
  xs <- getInts

  let
    r = f (0, 0, 0) xs
      where
        f _ [] = True
        f (a, b, c) (25:xs) = f (a+1, b, c) xs
        f (a, b, c) (50:xs)
          | a >= 1 = f (a-1, b+1, c) xs
          | otherwise = False
        f (a, b, c) (100:xs)
          | b >= 1 && a >= 1 = f (a-1, b-1, c+1) xs
          | a >= 3 = f (a-3, b, c+1) xs
          | otherwise = False

  putStrLn $ if r then "YES" else "NO"

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Data.Monoid
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = getLine >>=  \n-> (solve.concat =<< forM [1.. 1] ( \i -> map (fst.fromJust.C.readInteger).C.words<$>C.getLine))
solve xs =  if slv1 xs (0,0) then putStr "YES" else putStr "NO"
slv1 [] _ = True
slv1 (x:xs) (y25,y50)      | x ==25                    = slv1 xs (y25+1,y50)
                           | x ==50 && y25==0          = False
                           | x ==50 && y25/=0          = slv1 xs (y25-1,y50+1)
                           | x ==100 && y50>0 && y25>0 = slv1 xs (y25-1,y50-1)
                           | x ==100 && y50==0 && y25>2 = slv1 xs (y25-3,y50)
                           | otherwise                 = False

import Control.Monad (liftM)
import Data.Char (ord)
import Prelude hiding (reads)

reads :: IO [Int]
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 + ord c - ord '0'

solve :: [Int] -> Bool
solve as  =  solve' 0 0 as
  where
    solve' _ _ []  =  True
    solve' a b (25:as)  =  solve' (a+1) b as
    solve' a b (50:as)
        | a > 0  =  solve' (a-1) (b+1) as
        | otherwise  =  False
    solve' a b (100:as)
        | a > 0 && b > 0  =  solve' (a-1) (b-1) as
        | a > 2  =  solve' (a-3) b as
        | otherwise  =  False

main :: IO ()
main  =  do
    getLine
    as  <-  reads
    if solve as then
        putStrLn "YES"
    else
        putStrLn "NO"

module Main where
import Control.Applicative
import Control.Monad
import Data.ByteString.Lazy as B
import Data.ByteString.Lazy.Char8 as C
main :: IO ()
main = do
    _ <- getLine
    bills <- (Prelude.map ((\ (Just (i,_)) -> i) . C.readInt) . C.words) <$> B.getContents :: IO [Int]
    let cando (twfs,fifs) 25 = Just (twfs+1,fifs)
        cando (twfs,fifs) 50
          | twfs > 0 = Just (twfs-1,fifs+1)
          | otherwise = Nothing
        cando (twfs,fifs) 100
          | twfs >= 1 && fifs >= 1 = Just (twfs-1,fifs-1)
          | twfs >= 3 = Just (twfs-3,fifs)
          | otherwise = Nothing
    Prelude.putStrLn (case foldM cando (0,0) bills of
      Nothing -> "NO"
      _ -> "YES")

main = do
    getLine
    input <- getLine >>= return.(map read).words
    putStrLn $ solve input 0 0

solve :: [Int] -> Int -> Int -> String
solve [] _ _ = "YES"
solve (25:xs) a b = solve xs (a+1) b
solve (50:xs) a b
    | a==0      = "NO"
    | otherwise = solve xs (a-1) (b+1)
solve (100:xs) a b
    | a>0 && b>0 = solve xs (a-1) (b-1)
    | a>2        = solve xs (a-3) b
    | otherwise  = "NO"

main :: IO ()
main = getContents >>= putStrLn . yesno . solve . map read . words . (!!1) . lines

solve :: [Int] -> Bool
solve = all g . scanl f (0 :: Int, 0 :: Int)
  where f (a, b) 25 = (a + 1, b)
        f (a, b) 50 = (a - 1, b + 1)
        f (a, b) 100 | b > 0 = (a - 1, b - 1)
                     | otherwise = (a - 3, b)
        f ab _ = ab
        g (a, b) = a >= 0 && b >= 0

yesno :: Bool -> String
yesno True = "YES"
yesno _ = "NO"

main = putStrLn . solve 0 0 0 . map read . tail . words =<< getContents
solve f h q (25:bs) = solve f h (q+1) bs
solve f h 0 (50:bs) = "NO"
solve f h q (50:bs) = solve f (h+1) (q-1) bs
solve f 0 q (100:bs) | q >= 3 = solve (f+1) 0 (q-3) bs
                     | otherwise = "NO"
solve f h q (100:bs) | h >= 1 && q >= 1 = solve (f+1) (h-1) (q-1) bs
                     | otherwise = "NO"
solve _ _ _ [] = "YES"

import Control.Applicative
import Control.Monad

main = interact $ booking . tail . words

booking = maybe "NO" (const "YES") . foldM_ change (0, 0)

change (x, y) b = case b of
	"25" -> Just (x + 1, y)
	"50" -> guard (x > 0) >> Just (x - 1, y + 1)
	"100" -> (guard (x > 0 && y > 0) >> Just (x - 1, y - 1))
		<|>  (guard (x > 2) >> Just (x - 3, y))

import Control.Applicative ((<|>))
import Control.Monad (guard, foldM)

data Bill = R25 | R50 | R100
data Result = YES | NO deriving (Show)

main = interact $ show . booking . map readBill . tail . words

booking :: [Bill] -> Result
booking = maybe NO (const YES) . foldM change (0, 0)

change :: (Int, Int) -> Bill -> Maybe (Int, Int)
change (n25, n50) bill = case bill of
	R25 -> return (n25 + 1, n50)
	R50 -> guard (n25 > 0) >> return (n25 - 1, n50 + 1)
	R100 -> (guard (n50 > 0 && n25 > 0) >> return (n25 - 1, n50 - 1))
		<|> (guard (n25 > 2) >> return (n25 - 3, n50))

readBill :: String -> Bill
readBill s = case s of
	"25" -> R25
	"50" -> R50
	"100" -> R100

import Control.Monad (foldM)

data Bill = R25 | R50 | R100
data Result = YES | NO deriving (Show)

main = interact $ show . booking . map readBill . tail . words

booking :: [Bill] -> Result
booking = maybe NO (const YES) . foldM (flip change) (0, 0)

change :: Bill -> (Int, Int) -> Maybe (Int, Int)
change R25 (n25, n50) = Just (n25 + 1, n50)
change R50 (n25, n50)
	| n25 > 0 = Just (n25 - 1, n50 + 1)
	| otherwise = Nothing
change R100 (n25, n50)
	| n50 > 0 && n25 > 0 = Just (n25 - 1, n50 - 1)
	| n25 > 2 = Just (n25 - 3, n50)
	| otherwise = Nothing

readBill :: String -> Bill
readBill s = case s of
	"25" -> R25
	"50" -> R50
	"100" -> R100

data Bill = R25 | R50 | R100
data Result = YES | NO deriving (Show)

main = interact $ show . booking . map readBill . tail . words

booking :: [Bill] -> Result
booking = go (0, 0) where
	go _ [] = YES
	go n (x:xs) = case change x n of
		Just n' -> go n' xs
		Nothing -> NO

readBill :: String -> Bill
readBill s = case s of
	"25" -> R25
	"50" -> R50
	"100" -> R100

change :: Bill -> (Int, Int) -> Maybe (Int, Int)
change R25 (n25, n50) = Just (n25 + 1, n50)
change R50 (n25, n50) = if n25 > 0
	then Just (n25 - 1, n50 + 1)
	else Nothing
change R100 (n25, n50) = if n50 > 0
	then if n25 > 0
		then Just (n25 - 1, n50 - 1)
		else Nothing
	else if n25 > 2
		then Just (n25 - 3, n50)
		else Nothing

{-# LANGUAGE BangPatterns #-}
import Control.Applicative
import Control.Monad

main = interact $ booking . tail . words

booking = maybe "NO" (const "YES") . foldM_ change (0, 0)

change (!x, !y) b = case b of
	"25" -> Just (x + 1, y)
	"50" -> guard (x > 0) >> Just (x - 1, y + 1)
	"100" -> (guard (x > 0 && y > 0) >> Just (x - 1, y - 1))
		<|>  (guard (x > 2) >> Just (x - 3, y))

import Control.Applicative
import Control.Monad

main = interact $ booking . tail . words

booking = maybe "NO" (const "YES") . foldM change (0, 0)

change (x, y) b = case b of
	"25" -> Just (x + 1, y)
	"50" -> guard (x > 0) >> Just (x - 1, y + 1)
	"100" -> (guard (x > 0 && y > 0) >> Just (x - 1, y - 1))
		<|>  (guard (x > 2) >> Just (x - 3, y))

import Control.Applicative
import Control.Monad

main = interact $ booking . tail . words

booking = maybe "NO" (const "YES") . foldM change (0, 0)

change (x, y) b = case b of
	"25" -> Just $! (x + 1, y)
	"50" -> guard (x > 0) >> (Just $! (x - 1, y + 1))
	"100" -> (guard (x > 0 && y > 0) >> (Just $! (x - 1, y - 1)))
		<|>  (guard (x > 2) >> (Just $! (x - 3, y)))

import Control.Applicative ((<|>))
import Control.Monad (guard, foldM)

main = interact $ booking . tail . words

booking = maybe "NO" (const "YES") . foldM change (0, 0)

change (n25, n50) bill = case bill of
	"25" -> return (n25 + 1, n50)
	"50" -> guard (n25 > 0) >> return (n25 - 1, n50 + 1)
	"100" -> (guard (n50 > 0 && n25 > 0) >> return (n25 - 1, n50 - 1))
		<|>  (guard (n25 > 2) >> return (n25 - 3, n50))

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

-- |Model the change state. First entry is number of 25 notes, second number
-- of 50 notes
type Change = (Int,Int)

-- * Solver
-- |Solve a test case
solve :: [Int] -> String
solve xs = case solve' xs of
    (Just _) -> "YES"
    Nothing  -> "NO"
    where solve' xs = foldl (>>=) (return (0,0)) $ map process xs

-- |Process one consumer
process :: Int           -- ^ Note of consumer
        -> Change        -- ^ Old 'Change' state
        -> Maybe Change  -- ^ New 'Change' state or 'Nothing' if transaction is
                         -- impossible
process 25  (a,b) = return (a+1,b)
process 50  (a,b) = guard (a >= 1) >> return (a-1,b+1)
process 100 (a,b)
    | b > 0     = guard (a >= 1) >> return (a-1,b-1)
    | otherwise = guard (a >= 3) >> return (a-3,b)

-- * Input/Output
-- |Ignore the first line and parse the test case
main :: IO ()
main = do
    B.getLine
    xs <- getIntList
    putStrLn $ solve xs

-- |Read an Int list from the standard input device
getIntList :: IO [Int]
getIntList = readIntList `fmap` B.getLine

-- * Converting from ByteString
-- |Cast ByteString to Int
readInt :: C.ByteString -> Int
readInt = fst . fromJust . C.readInt

-- |Cast ByteString to Int list
readIntList :: C.ByteString -> [Int]
readIntList = map readInt . C.words

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

type Change = (Int,Int)

solve :: [Int] -> String
solve xs = case solve' xs of
    (Just _) -> "YES"
    Nothing  -> "NO"
    where solve' xs = foldM process (0,0) xs

process :: Change -> Int -> Maybe Change
process (a,b) 25 = return $! (a+1,b)
process (a,b) 50 = guard (a >= 1) >> (return $! (a-1,b+1))
process (a,b) 100
    | b > 0     = guard (a >= 1) >> (return $! (a-1,b-1))
    | otherwise = guard (a >= 3) >> (return $! (a-3,b))

main :: IO ()
main = do
    B.getLine
    xs <- getIntList
    putStrLn $ solve xs

getIntList :: IO [Int]
getIntList = readIntList `fmap` B.getLine

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

readIntList :: C.ByteString -> [Int]
readIntList = map readInt . C.words

module Main where
import System.IO
import Data.Maybe
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

solve :: [Int] -> String
solve xs = if solve' (0,0) xs then "YES" else "NO"

solve' :: (Int,Int) -> [Int] -> Bool
solve' (a,b) _ | a < 0 || b < 0 = False
solve' _ [] = True
solve' (a,b) (25:xs) = solve' (a+1,b) xs
solve' (a,b) (50:xs) = solve' (a-1,b+1) xs
solve' (a,b) (100:xs) = if b > 0 then solve' (a-1,b-1) xs else solve' (a-3,b) xs

main :: IO ()
main = do
	B.getLine
	ls <- B.getLine
	putStrLn . solve . map readInt . C.words $ ls

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

#!/usr/bin/env runghc
import Data.List
main = do
  c <- getContents
  putStr . unlines . solve . lines $ c

solve::[String]->[String]
solve [] = []
solve (c1:c2:cs) = (f (0,0) . map read . words $ c2): solve cs
  where
    f rs [] = "YES"
    f (r1,r2) (n:ns) =
      if n==25 then f (r1+1,r2) ns
      else if n==50 && r1>0 then f (r1-1,r2+1) ns
      else if n==100 && r1>0 && r2>0 then f (r1-1,r2-1) ns
      else if n==100 && r1>2 then f (r1-3,r2) ns
      else "NO"

solve :: [Integer] -> Integer -> Integer -> Bool
solve [] _ _ = True
solve (25:xs) q h = solve xs (q + 1) h
solve (50:xs) 0 _ = False
solve (50:xs) q h = solve xs (q - 1) (h + 1)
solve (100:xs) q h
    | q > 0 && h > 0 = solve xs (q - 1) (h - 1)
    | q > 2 = solve xs (q - 3) h
    | otherwise = False

main = do
    n <- getLine
    a <- getLine
    if solve (map read $ words a) 0 0 then
        putStrLn "YES"
    else
        putStrLn "NO"

work m n xs = if m < 0 || n < 0
              then "NO"
              else
                if null xs
                  then "YES"
                  else
                    case (head xs) of
                      100 -> if n > 0
                             then work (m-1) (n-1) (tail xs)
                             else work (m-3) n (tail xs)
                      50  -> work (m-1) (n+1) (tail xs)
                      25  -> work (m+1) n (tail xs)

main = do s <- getLine
          s <- getLine
          let xs = map (\x -> read x :: Int) (words s)
          putStrLn (work 0 0 xs)

module Main where

import Control.Applicative

data Result = YES | NO deriving (Eq,Show)

main = do
    getLine
    l <- map read <$>words <$> getLine
    print $ solve (0, 0) l

solve :: (Int, Int) -> [Int] -> Result
solve _ [] = YES
solve (a,b) (25:xs) = solve (a+1,b) xs
solve (a,b) (50:xs) | a > 0 = solve (a-1,b+1) xs
                    | otherwise = NO
solve (a,b) (100:xs)| b > 0 && a > 0 = solve (a-1, b-1) xs
                    | a > 2 = solve (a-3,b) xs
                    | otherwise = NO

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

process x y z [] = "YES"
process x y z (a:as) | a==25 = process (x+1) y z as
	             | a==50 && x>0 = process (x-1) (y+1) z as
		     | a==50 = "NO"
		     | a==100 && y>0 && x>0 = process (x-1) (y-1) (z+1) as
                     | a==100 && x>=3 = process (x-3) y (z+1) as
                     | otherwise = "NO"

main=do
	getLine
	s<-map (fst.fromJust.C.readInt). C.words<$> C.getLine::IO [Int]
	putStrLn $ process 0 0 0 s

main = do
    (_:a) <- fmap (map read . words) getContents :: IO [Int]
    putStrLn $ f 0 0 a
f _ _ [] = "YES"
f x y (a:as)
    | a == 25 = f (x + 1) y as
    | a == 50 = if x > 0 then f (x - 1) (y + 1) as else "NO"
    | otherwise = if y > 0 && x > 0 then f (x - 1) (y - 1) as else if x > 2 then f (x - 3) y as else "NO"

import Data.List

cal ls = let bills = map (+0) $ map read $ words $ ls !! 1
             neededChange = map ( + (-25)) bills
	 in sell bills 0 0

sell bills c25 c50
	| c25<0 || c50 <0 = "NO"
	| bills == [] = "YES"
	| (head bills) == 25 = sell (tail bills) (c25+1) c50
	| (head bills) == 50 = sell (tail bills) (c25-1) (c50+1)
	| c50 >0 = sell (tail bills) (c25 -1) (c50-1)
	| otherwise = sell (tail bills) (c25 -3) c50

main = interact ( cal . lines)

module Main where

import Data.Maybe
import Data.List (foldl')

type Change = (Int,Int)

rush :: [Int] -> Bool
rush = isJust . foldl' f (Just (0,0))
  where f :: Maybe Change -> Int -> Maybe Change
        f (Just (a,b)) 25 = Just (a+1,b)
        f (Just (a,b)) 50 = if a > 0 then Just (a - 1, b + 1)
                                else Nothing
        f (Just (a,b)) 100
          | b >= 1 && a >= 1 = Just (a - 1, b - 1)
          | a >= 3 = Just (a - 3, b)
          | otherwise = Nothing
        f _ _ = Nothing

main :: IO ()
main = do
  _:l <- fmap (map read . words) getContents
  putStrLn $ if rush l then "YES" else "NO"

import Data.List
import Data.Maybe
import Control.Applicative
import Debug.Trace

debug x = trace (show x) x
(|>) x f = f x; infixl 1 |>
(||>) x f = x >>= (return.f); infixl 1 ||>
ref = (!!)

go :: [Int] -> (Int,Int) -> Bool
go [] _ = True
go (25:xs) (a,b) = go xs (a+1,b)
go (50:xs) (a,b)
  | a < 1   = False
  | True    = go xs (a-1,b+1)
go (100:xs) (a,b)
  | a>0 && b>0   = go xs (a-1,b-1)
  | a >= 3  = go xs (a-3,b)
  | True    = False

main = do
  ls <- getContents ||> lines
  n  <- head ls |> readIO :: IO Int
  xs <- (ref ls 1) |> words |> map read |> return  :: IO [Int]
  putStrLn (if (go xs (0,0)) then "YES" else "NO")

-- vim: set ft=haskell:

import Data.List
import Data.Char
import Data.Maybe
import Control.Applicative
import Debug.Trace
import qualified Data.ByteString.Char8 as B

toDigit n = chr (48 + n)

debug x = trace (show x) x
(|>) x f = f x; infixl 1 |>
(||>) mx f = mx >>= (return . f); infixl 1 ||>
ref = (!!)

go :: [Int] -> (Int,Int) -> Bool
go [] _ = True
go (25:xs) (a,b) = go xs (a+1,b)
go (50:xs) (a,b)
  | a < 1   = False
  | True    = go xs (a-1,b+1)
go (100:xs) (a,b)
  | a>0 && b>0   = go xs (a-1,b-1)
  | a >= 3  = go xs (a-3,b)
  | True    = False

main = do
  ls <- B.getContents ||> B.lines
  n  <- head ls |> B.readInt |> fromJust |> fst |> return :: IO Int
  xs <- (ref ls 1) |> B.words |> map (fst . fromJust . B.readInt) |> return  :: IO [Int]
  putStrLn (if (go xs (0,0)) then "YES" else "NO")

-- vim: set ft=haskell:

import Data.List
import Data.Maybe
import Control.Applicative
import Debug.Trace
debug x = trace (show x) x
(|>) x f = f x; infixl 1 |>
(||>) x f = x >>= (return.f); infixl 1 ||>
ref = (!!)

go [] _ = True
go ("25":xs) (a,b) = go xs (a+1,b)
go ("50":xs) (a,b)
  | a < 1   = False
  | True    = go xs (a-1,b+1)
go ("100":xs) (a,b)
  | a>0 && b>0   = go xs (a-1,b-1)
  | a >= 3  = go xs (a-3,b)
  | True    = False

main = do
  ls <- getContents ||> lines
  n  <- head ls |> readIO :: IO Int
  xs <- (ref ls 1) |> words |> return  :: IO [String]
  putStrLn (if (go xs (0,0)) then "YES" else "NO")

-- vim: set ft=haskell:

main = do
  n <- getLine
  a <- getLine
  if (solve n $ words a) then putStrLn "YES"
    else putStrLn "NO"

solve _n _a = judge [0, 0, 0] _a where
  judge _ [] = True
  judge [c25, c50, c100] (a:as)
    | a == "100" =
        if c50 > 0 && c25 > 0 then judge [c25-1, c50-1, c100+1] as
          else if c25 > 2 then judge [c25-3, c50, c100+1] as
            else False
    | a == "50" =
        if c25 > 0 then judge [c25-1, c50+1, c100] as
          else False
    | otherwise = judge [c25+1, c50, c100] as

main = do
  n <- getLine
  a <- getLine
  if (solve n $ words a) then putStrLn "YES"
    else putStrLn "NO"

solve _n _a = judge [0, 0, 0] _a where
  judge _ [] = True
  judge (c25:c50:c100:[]) (a:as)
    | a == "100" =
        if c50 > 0 && c25 > 0 then judge (c25-1:c50-1:c100+1:[]) as
          else if c25 > 2 then judge (c25-3:c50:c100+1:[]) as
            else False
    | a == "50" =
        if c25 > 0 then judge (c25-1:c50+1:c100:[]) as
          else False
    | otherwise = judge (c25+1:c50:c100:[]) as

main = do
  n <- getLine
  a <- getLine
  if (solve n $ words a) then putStrLn "YES"
    else putStrLn "NO"

solve _n _a = judge 0 0 0 _a where
  judge _ _ _ [] = True
  judge c25 c50 c100 (a:as) =
    case a of
      "100" ->
        if c50 > 0 && c25 > 0 then (judge (c25-1) (c50-1) (c100+1) as)
          else if c25 > 2 then (judge (c25-3) c50 (c100+1) as)
            else False
      "50" ->
        if c25 > 0 then (judge (c25-1) (c50+1) c100 as)
          else False
      "25" -> (judge (c25+1) c50 c100 as)

main = do
  n <- getLine
  a <- getLine
  if (solve n $ words a) then putStrLn "YES"
    else putStrLn "NO"

solve _n _a = judge 0 0 0 _a where
  judge _ _ _ [] = True
  judge c25 c50 c100 (a:as)
    | a == "100" =
        if c50 > 0 && c25 > 0 then judge (c25-1) (c50-1) (c100+1) as
          else if c25 > 2 then judge (c25-3) c50 (c100+1) as
            else False
    | a == "50" =
        if c25 > 0 then judge (c25-1) (c50+1) c100 as
          else False
    | otherwise = judge (c25+1) c50 c100 as

import Data.List (foldl')

main = do
  n <- getLine
  a <- getLine
  let rv = (solve n $ words a)
  if snd rv == True then putStrLn "YES"
    else putStrLn "NO"

solve n xs = foldl' go ((0, 0, 0), True) xs where
  go ((_, _, _), b) "" = ((0, 0, 0), True && b)
  go ((c25, c50, c100), b) x
    | x == "100" =
        if c50 > 0 && c25 > 0 then ((c25-1, c50-1, c100+1), b)
          else if c25 > 2 then ((c25-3, c50, c100+1), b)
            else ((0, 0, 0), False)
    | x == "50" =
        if c25 > 0 then ((c25-1, c50+1, c100), b)
            else ((0, 0, 0), False)
    | otherwise = ((c25+1, c50, c100), b)

import Control.Applicative
get :: IO [Int]
get = fmap (map read.words) getContents

solve :: Int -> Int -> Int -> [Int] -> String
solve a b c []
  | a < 0 || b < 0 || c < 0 = "NO"
  | otherwise = "YES"
solve a b c (x:xs) -- 25, 50, 100 demonination change
  | a < 0 || b < 0 || c < 0 = "NO"
  | x == 25 = solve (a+1) b c xs
  | x == 50 = solve (a-1) (b+1) c xs
  | x == 100 = if b > 1
               then solve (a-1) (b-1) (c+1) xs
               else solve (a-3) b (c+1) xs

main :: IO ()
main=do
  (_:line) <- get
  putStrLn (solve 0 0 0 line)

check :: [Int] -> (Int, Int) -> String
check [] _                       = "YES"
check (x:xs) (d, p)
  | x == 25                      = check xs (d+1, p)
  | x == 50                      = check xs (d-1, p+1)
  | x == 100 && (d > 1 && p > 1) = check xs (d-1, p-1)
  | x == 10  && (d > 4)          = check xs (d-3, p)
  | otherwise                    = "NO"

main = getLine >> getLine >>= return . (flip check) (0,0) . (map read) . words >>= putStrLn

check :: [Int] -> (Int, Int) -> String
check [] _                       = "YES"
check (x:xs) (d, p)
  | x == 25                      = check xs (d+1, p)
  | x == 50  && (d > 0)          = check xs (d-1, p+1)
  | x == 100 && (d > 1 && p > 1) = check xs (d-1, p-1)
  | x == 10  && (d > 4)          = check xs (d-3, p)
  | otherwise                    = "NO"

main = getLine >> getLine >>= return . (flip check) (0,0) . (map read) . words >>= putStrLn

check :: [Int] -> (Int, Int) -> String
check [] _                       = "YES"
check (x:xs) (d, p)
  | x == 25                      = check xs (d+1, p)
  | x == 50  && (d > 1)          = check xs (d-1, p+1)
  | x == 100 && (d > 1 && p > 1) = check xs (d-1, p-1)
  | x == 10  && (d > 4)          = check xs (d-3, p)
  | otherwise                    = "NO"

main = getLine >> getLine >>= return . (flip check) (0,0) . (map read) . words >>= putStrLn

module Main where
-- import Control.Monad
-- import Data.List
-- import Data.Array
import Control.Applicative
import Control.Monad
main :: IO ()
main = do
    _ <- getLine
    bills <- (map read . words) <$> getLine :: IO [Int]
    let cando (twfs,fifs,hunnas) 25 = Just (twfs+1,fifs,hunnas)
        cando (twfs,fifs,hunnas) 50
          | twfs == 0 = Nothing
          | otherwise = Just (twfs-1,fifs,hunnas)
        cando (twfs,fifs,hunnas) 100
          | twfs >= 1 && fifs >= 1 = Just (twfs-1,fifs-1,hunnas)
          | twfs >= 3 = Just (twfs-3,fifs,hunnas)
          | otherwise = Nothing
    case foldM cando (0,0,0) bills of
      Nothing -> putStrLn "NO"
      _ -> putStrLn "YES"

main :: IO ()
main = getContents >>= putStrLn . yesno . solve . map read . words . (!!1) . lines

solve :: [Int] -> Bool
solve = all g . scanl f (0 :: Int, 0 :: Int)
  where f (a, b) 25 = (a + 1, b)
        f (a, b) 50 = (a - 1, b + 1)
        f (a, b) 100 | b >= 0 = (a - 1, b - 1)
                     | otherwise = (a - 3, b)
        f ab _ = ab
        g (a, b) = a >= 0 && b >= 0

yesno :: Bool -> String
yesno True = "YES"
yesno _ = "NO"

main :: IO ()
main = getContents >>= putStrLn . yesno . solve . map read . words . (!!1) . lines

solve :: [Int] -> Bool
solve = and . zipWith (>=) [25,50..]

yesno :: Bool -> String
yesno True = "YES"
yesno _ = "NO"

main :: IO ()
main = getContents >>= putStrLn . yesno . solve . map read . words . (!!1) . lines

solve :: [Int] -> Bool
solve = all (>=0) . scanl (\a b -> a + b - 25) 0

yesno :: Bool -> String
yesno True = "YES"
yesno _ = "NO"

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

-- |Model the change state. First entry is number of 25 notes, second number
-- of 50 notes
type Change = (Int,Int)

-- * Solver
-- |Solve a test case
solve :: [Int] -> String
solve xs = case solve' xs of
    (Just _) -> "YES"
    Nothing  -> "NO"
    where solve' xs = foldl (>>=) (return (0,0)) $ map process xs

-- |Process one consumer
process :: Int           -- ^ Note of consumer
        -> Change        -- ^ Old 'Change' state
        -> Maybe Change  -- ^ New 'Change' state or 'Nothing' if transaction is
                         -- impossible
process 25  (a,b) = return (a+1,b)
process 50  (a,b) = guard (a >= 1) >> return (a-1,b+1)
process 100 (a,b)
    | b > 0     = guard (a >= 0) >> return (a-1,b-1)
    | otherwise = guard (a >= 2) >> return (a-3,b)

-- * Input/Output
-- |Ignore the first line and parse the test case
main :: IO ()
main = do
    B.getLine
    xs <- getIntList
    putStrLn $ solve xs

-- |Read an Int list from the standard input device
getIntList :: IO [Int]
getIntList = readIntList `fmap` B.getLine

-- * Converting from ByteString
-- |Cast ByteString to Int
readInt :: C.ByteString -> Int
readInt = fst . fromJust . C.readInt

-- |Cast ByteString to Int list
readIntList :: C.ByteString -> [Int]
readIntList = map readInt . C.words

work m n xs = if m < 0 || n < 0
              then "NO"
              else
                if null xs
                  then "YES"
                  else
                    case (head xs) of
                      100 -> work (m-1) (n-1) (tail xs)
                      50  -> work (m-1) (n+1) (tail xs)
                      25  -> work (m+1) n (tail xs)

main = do s <- getLine
          s <- getLine
          let a = map (\x -> read x :: Int) (words s)
          putStrLn (work 0 0 a)

work m n xs = if m < 0 || n < 0
              then "NO"
              else
                if null xs
                  then "YES"
                  else
                    case (head xs) of
                      100 -> if n > 0
                             then work (m-1) (n-1) (tail xs)
                             else work (m-1) n (tail xs)
                      50  -> work (m-1) (n+1) (tail xs)
                      25  -> work (m+1) n (tail xs)

main = do s <- getLine
          s <- getLine
          let xs = map (\x -> read x :: Int) (words s)
          putStrLn (work 0 0 xs)

module Main where

import Control.Applicative

data Result = YES | NO deriving (Eq,Show)

main = do
    getLine
    l <- map read <$>words <$> getLine
    print $ solve (0, 0) l

solve :: (Int, Int) -> [Int] -> Result
solve _ [] = YES
solve (a,b) (25:xs) = solve (a+1,b) xs
solve (a,b) (50:xs) | a > 0 = solve (a-1,b+1) xs
                    | otherwise = NO
solve (a,b) (100:xs)| b > 0 && a > 0 = solve (a-1, b-1) xs
                    | a > 1 = solve (a-2,b) xs
                    | otherwise = NO

main = do
    (_:a) <- fmap (map read . words) getContents :: IO [Int]
    putStrLn $ f 0 0 a
f _ _ [] = "YES"
f x y (a:as)
    | a == 25 = f (x + 1) y as
    | a == 50 = if x > 0 then f (x - 1) (y - 1) as else "NO"
    | otherwise = if y > 0 && x > 0 then f (x - 1) (y - 1) as else if x > 2 then f (x - 3) y as else "NO"

import Data.List

cal ls = let bills = map (+0) $ map read $ words $ ls !! 1
             neededChange = map ( + (-25)) bills
	 in sell bills 0 0

sell bills c25 c50
	| c25<0 || c50 <0 = "NO"
	| bills == [] = "YES"
	| (head bills) == 25 = sell (tail bills) (c25+1) c50
	| (head bills) == 50 = sell (tail bills) (c25-1) (c50+1)
	| c50 >0 = sell (tail bills) (c25 -1) (c50-1)
	| otherwise = sell (tail bills) (c25 -3) c50

main = interact ( show . cal . lines)

import Data.List
import Data.Maybe
import Control.Applicative
import Debug.Trace

debug x = trace (show x) x
(|>) x f = f x; infixl 1 |>
(||>) x f = x >>= (return.f); infixl 1 ||>
ref = (!!)

go :: [Int] -> (Int,Int,Int) -> Bool
go [] _ = True
go (25:xs) (a,b,c) = go xs (a+1, b, c)
go (50:xs) (a,b,c)
  | a < 1 = False
  | True  = go xs (a-1, b+1, c)
go (100:xs) (a,b,c)
  | b > 0    = go xs (a, b-1, c+1)
  | a >= 3   = go xs (a-3, b, c+1)
  | True     = False

main = do
  ls <- getContents ||> lines
  n  <- head ls |> readIO :: IO Int
  xs <- (ref ls 1) |> words |> map read |> return  :: IO [Int]
  putStrLn (if (go xs (0,0,0)) then "YES" else "NO")

-- vim: set ft=haskell:


Qwerty the Ranger arrived to the Diatar system with a very important task. He should deliver a special carcinogen for scientific research to planet Persephone. This is urgent, so Qwerty has to get to the planet as soon as possible. A lost day may fail negotiations as nobody is going to pay for an overdue carcinogen.You can consider Qwerty's ship, the planet Persephone and the star Diatar points on a plane. Diatar is located in the origin of coordinate axes — at point (0, 0). Persephone goes round Diatar along a circular orbit with radius R in the counter-clockwise direction at constant linear speed vp (thus, for instance, a full circle around the star takes  of time). At the initial moment of time Persephone is located at point (xp, yp).At the initial moment of time Qwerty's ship is at point (x, y). Qwerty can move in any direction at speed of at most v (v > vp). The star Diatar is hot (as all stars), so Qwerty can't get too close to it. The ship's metal sheathing melts at distance r (r < R) from the star.Find the minimum time Qwerty needs to get the carcinogen to planet Persephone.

The first line contains space-separated integers xp, yp and vp ( - 104 ≤ xp, yp ≤ 104, 1 ≤ vp < 104) — Persephone's initial position and the speed at which it goes round Diatar. The second line contains space-separated integers x, y, v and r ( - 104 ≤ x, y ≤ 104, 1 < v ≤ 104, 1 ≤ r ≤ 104) — The intial position of Qwerty's ship, its maximum speed and the minimum safe distance to star Diatar. It is guaranteed that r2 < x2 + y2, r2 < xp2 + yp2 and vp < v.

Print a single real number — the minimum possible delivery time. The answer will be considered valid if its absolute or relative error does not exceed 10 - 6.

eps = 1e-9
tMax = 1e13
tau = 2 * pi

hypot a b = sqrt ( a^2 + b^2 )
fix q = q - tau * ( fromIntegral $ floor $ q / tau )

solve [xp0,yp0,vp,x,y,v,rs] = let
	r = hypot x y
	q = atan2 y x
	rp = hypot xp0 yp0
	qp0 = atan2 yp0 xp0
	wp = vp / rp
	arc = pi - asin ( rs / r ) - asin ( rs / rp )
	tans = sqrt ( r^2 - rs^2 ) + sqrt ( rp^2 - rs^2 )
	search a b = if b - a < eps then a else let
		t = ( a + b ) / 2
		qp = fix ( qp0 + wp * t )
		xp = rp * cos qp
		yp = rp * sin qp
		dq = min ( fix $ qp - q ) ( fix $ q - qp )
		dist = if dq <= arc then hypot ( xp - x ) ( yp - y ) else tans + ( dq - arc ) * rs
		in if dist <= t * v then search a t else search t b
	in search 0 tMax

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

main = getContents >>= print.solve.map read.words

type Time = Double

eps = 1e-8

type Pos = (Double,Double)
dist :: Pos -> Pos -> Double
dist (x0,y0) (x1,y1) = sqrt $ (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)

data Line = L Double Double Double
line :: Pos -> Pos -> Line
line (x0,y0) (x1,y1) = L a b c
   where
     a = y1-y0
     b = x0-x1
     c= -a*x0-b*y0
intersection :: Line -> Line -> Maybe Pos
intersection (L a b p) (L c d q)
  | det <= eps = Nothing
  | otherwise  = Just (x,y)
   where
     det = a*d-b*c
     x = (b*q-d*p)/det
     y = (c*p-a*q)/det

solve :: [Double] -> Time
solve [xp0,yp0,vp,x0,y0,v,r] = bsearch 100 0.0 1e6
   where
     bsearch 0 l r = r
     bsearch i l r
       | isReachable m = bsearch (i-1) l m
       | otherwise = bsearch (i-1) m r
      where
        m = (l+r)/2

     rp = dist (xp0,yp0) (0,0)
     phi = atan2 yp0 xp0
     omega = vp/rp
     r0 = dist (x0,y0) (0,0)

     pos :: Time -> Pos
     pos t = (rp*(cos (omega*t+phi)),rp*(sin (omega*t+phi)))
     isBehind :: Pos -> Bool
     isBehind (xp,yp) = d<r && min xp x0 <= x && x<= max xp x0
      where
        L a b c = line (xp,yp) (x0,y0)
        d = abs c/sqrt(a*a+b*b)
        Just (x,y) = intersection (L a b c) (L (-b) a 0)
     extDist :: Pos -> Double
     extDist (xp,yp)
       | d < eps = 0
       | isBehind (xp,yp) = l0+lp+lc
       | otherwise = d
      where
        d = dist (xp,yp) (x0,y0)
        l0 = sqrt (x0*x0+y0*y0-r*r)
        lp = sqrt (xp*xp+yp*yp-r*r)
        lc = r*(acos ((xp*x0+yp*y0)/(rp*r0)) - asin(l0/r0) - asin(lp/rp))
     isReachable :: Time -> Bool
     isReachable t = extDist (pos t) <= v*t

main = getContents >>= print.solve.map read.words

type T = Double

type Pos = (Double,Double)
dist :: Pos -> Pos -> Double
dist (x0,y0) (x1,y1) = sqrt $ (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)

data Line = L Double Double Double
line :: Pos -> Pos -> Line
line (x0,y0) (x1,y1) = L a b c
   where
     a = y1-y0
     b = x0-x1
     c= -a*x0-b*y0

solve :: [Double] -> T
solve [xp0,yp0,vp,x0,y0,v,r] = bsearch 100 0.0 1e6
   where
     bsearch 0 l r = r
     bsearch i l r
       | isReachable m = bsearch (i-1) l m
       | otherwise = bsearch (i-1) m r
      where
        m = (l+r)/2
     rp = dist (xp0,yp0) (0,0)
     angp = atan2 yp0 xp0
     r0 = dist (x0,y0) (0,0)
     pos :: T -> Pos
     pos t = (rp*(cos (omega*t+angp)),rp*(sin (omega*t+angp)))
      where
        omega = vp/rp
     isBehind :: Pos -> Bool
     isBehind (xp,yp) = d<=r && dist (xp,yp) (x0,y0) > sqrt (r0*r0-d*d)
      where
        L a b c = line (xp,yp) (x0,y0)
        d = abs c/sqrt(a*a+b*b)
     extDist :: Pos -> Double
     extDist (xp,yp)
       | isBehind (xp,yp) = l0+lp+lc
       | otherwise = dist (xp,yp) (x0,y0)
      where
        l0 = sqrt (x0*x0+y0*y0-r*r)
        lp = sqrt (xp*xp+yp*yp-r*r)
        lc = r*(acos ((xp*x0+yp*y0)/(rp*r0)) - asin(l0/r0) - asin(lp/rp))
     isReachable :: T -> Bool
     isReachable t = extDist (pos t) <= v*t

main = getContents >>= print.solve.map read.words

type T = Double

type Pos = (Double,Double)
dist :: Pos -> Pos -> Double
dist (x0,y0) (x1,y1) = sqrt $ (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)

data Line = L Double Double Double
line :: Pos -> Pos -> Line
line (x0,y0) (x1,y1) = L a b c
   where
     a = y1-y0
     b = x0-x1
     c= -a*x0-b*y0

solve :: [Double] -> T
solve [xp0,yp0,vp,x0,y0,v,r] = bsearch 100 0.0 1e6
   where
     bsearch 0 l r = r
     bsearch i l r
       | isReachable m = bsearch (i-1) l m
       | otherwise = bsearch (i-1) m r
      where
        m = (l+r)/2
     rp = dist (xp0,yp0) (0,0)
     angp = atan2 yp0 xp0
     r0 = dist (x0,y0) (0,0)
     pos :: T -> Pos
     pos t = (rp*(cos (omega*t+angp)),rp*(sin (omega*t+angp)))
      where
        omega = vp/rp
     isBehind :: Pos -> Bool
     isBehind (xp,yp) = abs c/sqrt(a*a+b*b) <= r
      where
        L a b c = line (xp,yp) (x0,y0)
     extDist :: Pos -> Double
     extDist (xp,yp)
       | isBehind (xp,yp) = l0+lp+lc
       | otherwise = dist (xp,yp) (x0,y0)
      where
        l0 = sqrt (x0*x0+y0*y0-r*r)
        lp = sqrt (xp*xp+yp*yp-r*r)
        lc = r*(acos ((xp*x0+yp*y0)/(rp*r0)) - asin(l0/r0) - asin(lp/rp))
     isReachable :: T -> Bool
     isReachable t = extDist (pos t) <= v*t

main = getContents >>= print.solve.map read.words

type Time = Double

type Pos = (Double,Double)
dist :: Pos -> Pos -> Double
dist (x0,y0) (x1,y1) = sqrt $ (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)

data Line = L Double Double Double
line :: Pos -> Pos -> Line
line (x0,y0) (x1,y1) = L a b c
   where
     a = y1-y0
     b = x0-x1
     c= -a*x0-b*y0

solve :: [Double] -> Time
solve [xp0,yp0,vp,x0,y0,v,r] = bsearch 100 0.0 1e6
   where
     bsearch 0 l r = r
     bsearch i l r
       | isReachable m = bsearch (i-1) l m
       | otherwise = bsearch (i-1) m r
      where
        m = (l+r)/2

     rp = dist (xp0,yp0) (0,0)
     phi = atan2 yp0 xp0
     omega = vp/rp
     r0 = dist (x0,y0) (0,0)

     pos :: Time -> Pos
     pos t = (rp*(cos (omega*t+phi)),rp*(sin (omega*t+phi)))
     isBehind :: Pos -> Bool
     isBehind (xp,yp) = d<r && dist (xp,yp) (x0,y0) >= sqrt (rp*rp-d*d)
      where
        L a b c = line (xp,yp) (x0,y0)
        d = abs c/sqrt(a*a+b*b)
     extDist :: Pos -> Double
     extDist (xp,yp)
       | isBehind (xp,yp) = l0+lp+lc
       | otherwise = dist (xp,yp) (x0,y0)
      where
        l0 = sqrt (x0*x0+y0*y0-r*r)
        lp = sqrt (xp*xp+yp*yp-r*r)
        lc = r*(acos ((xp*x0+yp*y0)/(rp*r0)) - asin(l0/r0) - asin(lp/rp))
     isReachable :: Time -> Bool
     isReachable t = extDist (pos t) <= v*t

main = getContents >>= print.solve.map read.words

type T = Double

type Pos = (Double,Double)
dist :: Pos -> Pos -> Double
dist (x0,y0) (x1,y1) = sqrt $ (x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)

data Line = L Double Double Double
line :: Pos -> Pos -> Line
line (x0,y0) (x1,y1) = L a b c
   where
     a = y1-y0
     b = x0-x1
     c= -a*x0-b*y0

solve :: [Double] -> T
solve [xp0,yp0,vp,x0,y0,v,r] = bsearch 100 0.0 1e6
   where
     bsearch 0 l r = r
     bsearch i l r
       | isReachable m = bsearch (i-1) l m
       | otherwise = bsearch (i-1) m r
      where
        m = (l+r)/2
     rp = dist (xp0,yp0) (0,0)
     angp = atan2 yp0 xp0
     r0 = dist (x0,y0) (0,0)
     pos :: T -> Pos
     pos t = (rp*(cos (omega*t+angp)),rp*(sin (omega*t+angp)))
      where
        omega = vp/rp
     isBehind :: Pos -> Bool
     isBehind (xp,yp) = abs c/sqrt(a*a+b*b)<r && dist (-xp,-yp) (x0,y0) < dist (xp,yp) (x0,y0)
      where
        L a b c = line (xp,yp) (x0,y0)
     extDist :: Pos -> Double
     extDist (xp,yp)
       | isBehind (xp,yp) = l0+lp+lc
       | otherwise = dist (xp,yp) (x0,y0)
      where
        l0 = sqrt (x0*x0+y0*y0-r*r)
        lp = sqrt (xp*xp+yp*yp-r*r)
        lc = r*(acos ((xp*x0+yp*y0)/(rp*r0)) - asin(l0/r0) - asin(lp/rp))
     isReachable :: T -> Bool
     isReachable t = extDist (pos t) <= v*t


George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living in it and the room can accommodate qi people in total (pi ≤ qi). Your task is to count how many rooms has free place for both George and Alex.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of rooms. The i-th of the next n lines contains two integers pi and qi (0 ≤ pi ≤ qi ≤ 100) — the number of people who already live in the i-th room and the room's capacity.

Print a single integer — the number of rooms where George and Alex can move in.

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

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

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

solve :: [Int] -> Int
solve [] = 0
solve (p:q:xs) = solve xs + if (q >= p + 2) then 1 else 0

main = do
    getLine
    ps <- fmap (map (map read . words). lines) getContents
    print $ length $ filter (\[a, b] -> a+2 <= b) ps

main = interact $ show . length . filter id . map (\[a,b] -> a+2<=b) . map (map read) . map words . tail . lines

main = do
	string <- getContents
	print . length . filter (\(a, b) -> b-a >= 2) . map (\[a,b] -> (a,b)) . map (map read) . map words . tail $ lines string

import Data.List
import Data.Maybe
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  getLine>>= \x->interact $ show .solve. map (map read.words).take (read x) . lines
solve :: [[Int]]->Int
solve xss =foldr (\ a b-> if a>=2 then 1+b else b) 0 [y-x|(x:y:[])<-xss]

import Control.Monad
import Data.List

int x = read x ::Int

rooms = length . filter (>=2)  . (uncurry $ flip $ zipWith (-)) . unzip

main = do
   n <- liftM int getLine
   vs <- liftM (map ((\[x,y] -> (x,y)) . map int. words)) $ replicateM n getLine
   print $ rooms vs

-- Codeforces 467A

import Control.Monad

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    replicateM n getLine >>= print . length . filter (\x -> (x!!1)-(x!!0) >= 2) . map (map read . words)

import Control.Applicative

main = do
  n <- read <$> getLine :: IO Int
  xs <- map (map read . words) . lines <$> getContents
  print . sum $ map (\[x,y] -> if y-x >= 2 then 1 else 0) xs

main = interact solve

solve input = show (foldr folder 0 rooms)
    where
        folder (p,q) ccount = if (q-p) >= 2 then
                                ccount+1
                              else
                                ccount
        as_nums::[Integer]
        n::Integer
        (n:as_nums) = (map read.words) input
        rooms = two_by_two as_nums

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

import Control.Monad
import Data.List

readInt :: IO Int
readInt = readLn

untilSpace :: [Char] -> [Char] -> [[Char]] -> [[Char]]
split :: [Char] -> [Int]
getInt a = read a::Int

untilSpace arg acc result = if arg == [] then acc : result else
                            if head arg == ' ' then untilSpace (tail arg) ("") (acc : result) else
                            untilSpace (tail arg) (acc ++ [head arg]) (result)
split a = map (getInt) (reverse $ untilSpace (a) ("") ([]))

count :: [[Int]] -> Int -> Int
count [] n = n
count (a:xa) n | a!!1 - a!!0 >= 2 = count xa (n + 1)
               | otherwise = count xa n

solve a = putStrLn $ show (count (map split a)  0)
readLines a = replicateM a getLine >>= solve
main = readInt >>= readLines

import Control.Applicative
import Control.Monad

main = do
  n <- readLn
  xs <- replicateM n $ map read . words <$> getLine
  let
    m = length . filter (\[p,q] -> p+2 <= q) $ xs
   in print m

import Control.Applicative
import Data.List

main=do
    getLine
    x<-( map (map read) <$> map words <$> lines <$> getContents)::IO [[Int]]
    putStrLn $ show $ length $ filter (>=2) $ map (\[a,b]->b-a)   x

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

solve :: [[Int]] -> Int
solve pqs = length [ () | [p, q] <- pqs, p + 2 <= q ]

main=getContents>>=print.solve.map(map read.words).tail.lines
solve w=length[p|[p,q]<-w,p+2<=q]

import Prelude hiding (readList)
import Control.Monad
import Control.Applicative
import Data.List

readList :: Read a => IO [a]
readList = fmap (fmap read . words) getLine

readList' :: Read a => a -> IO [a]
readList' _ = readList

readInt :: IO Int
readInt = head <$> readList' (undefined::Int)

showList :: Show a => [a] -> IO ()
showList = putStrLn . unwords . map show

skipLine :: IO ()
skipLine = void $ getLine

count :: (a -> Bool) -> [a] -> Int
count f = length . filter f

divUp :: Integral a => a -> a -> a
divUp x y
  | x `mod` y /= 0 = x `div` y + 1
  | otherwise      = x `div` y

main :: IO ()
main = do
  n <- readInt
  xs <- replicateM n (readList' (undefined::Int))
  print $ length $ filter (\[a,b] -> a+2 <= b) xs

fit :: String -> Bool
fit s = q >= p + 2
  where p = num !! 0
        q = num !! 1
        num = map read $ words s

rooms :: [String] -> Int
rooms l = length $ filter fit l

main = do
  getLine
  interact $ show . rooms . lines

main = print . solve . map parse . tail . lines =<< getContents
parse l = read b - read a where [a,b] = words l
solve = length . filter (>= 2)

main :: IO ()
main = interact (show . solve . map parse . tail . lines)

parse :: String -> (Int, Int)
parse s = (p, q)
  where
    [p, q] = map read . words $ s

solve :: [(Int, Int)] -> Int
solve = length . filter (\(p, q) -> q - p >= 2)

-- Vicfred
-- https://codeforces.com/problemset/problem/467/A

rooms :: [[Int]] -> Int
rooms = length . filter (\(p:q:_) -> q - p >= 2)

solve :: String -> String
solve = show . rooms . parse

parse :: String -> [[Int]]
parse = fmap (fmap read . words) . tail . lines

main :: IO ()
main = interact solve

module Main where
import Control.Applicative

getFreeBeds :: String -> Int
getFreeBeds line = let [taken,maxi] = map (read :: String -> Int) $ words line in maxi - taken

main = do
  roomCount <- (read :: String -> Int) <$> getLine
  print =<< length . filter (>1) <$> mapM (\_ -> getFreeBeds <$> getLine) [1..roomCount]

import Data.List
solve = length . filter (\[o,c] -> c-o > 1)
main = interact $ show . solve . map (map read . words) . tail . lines

import Data.List
solve = length . fst . partition (\[o,c] -> c-o > 1)
main = interact $ show . solve . map (map read . words) . tail . lines

f :: Integer -> IO [(Int, Int)]
f 0 = return []
f n = do
    l <- getLine
    r <- f (n-1)
    let [a,b] = map read $ words l in return ((a,b):r)

main :: IO()
main = do
    n <- getLine
    z <- f $ read n
    putStrLn $ show $ sum $ map (\(x,y) -> if y - x >= 2 then 1 else 0) z

f :: Integer -> IO [(Int, Int)]
f 0 = return []
f n = do
    l <- getLine
    r <- f (n-1)
    let [a,b] = map read $ words l in return ((a,b):r)

main :: IO()
main = do
    n <- getLine
    z <- f $ read n
    putStrLn $ show $ length $ filter (\(x,y) -> y - x >= 2) z

import Data.List
import Data.Char

--In matrix rows values should be space separated
inputNumMatrix :: Int -- ^ nRows
               -> IO [[Int]]
inputNumMatrix nRows =
  sequence $ replicate nRows (map read . words <$> getLine)

rooms :: [[Int]] -> IO ()
rooms rs = putStrLn $ show $ length $ filter (\room -> (room!!1) - (room!!0) >= 2) rs

main :: IO ()
main = read <$> getLine >>= inputNumMatrix >>= rooms

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

main= do
	getLine
 	s<-map (map read) . map words.lines <$> getContents ::IO [[Int]]
	print $ length $  filter (\z-> (last z-head z) >1) s

main = do
  m <- readLn
  ml <- sequence $ replicate m getLine
  let ml2 = map ((\[x, y] -> y - x) . map read. words) ml
  let ml3 = length $ filter (>=2) ml2
  print ml3

import           Control.Monad
main :: IO ()
main = do
    n <- (read :: String -> Int) <$> getLine
    print =<< sum . map (fromEnum . (\[a,b]->a + 2 <= b) . map (read :: String -> Int) . words) <$> replicateM n getLine

import Control.Monad

isAvailable :: [Int] -> Int
isAvailable l = if last l - head l >= 2 then 1 else 0

main :: IO ()
main = do
    input <- getLine
    inputs <- replicateM (read input) getLine
    print $ foldl (+) 0 (fmap (isAvailable . lineToIntL) inputs)
            where lineToIntL = fmap (\i -> read i :: Int) . words

import Control.Monad
import Data.List

main = getLine >>= return . read
               >>= flip replicateM getLine
               >>= return . map (map read . words)
               >>= print . length . filter solve

solve :: [Integer] -> Bool
solve [x , y] = y - x > 1

import Data.List

process :: [(Int,Int)] -> Int
process = length.filter (\(p,q) -> q-p >= 2)

readInt :: String -> Int
readInt = read

readPair :: String -> (Int,Int)
readPair line = (a,b)
    where [a,b] = map readInt $ words line

main = do
    n <- fmap readInt getLine
    xs <- fmap (map readPair . lines) getContents
    print $ process xs

main = interact $ show . sol . map read . drop 1 . words

sol [] = 0
sol (a:b:r)
    | b-a >= 2 = 1 + sol r
    | otherwise = sol r

module Main where

main :: IO ()
main = interact f

f = show . length . filter (\(x:y:_) -> y-x >= 2) . map (map read.words) . tail . lines

main = interact$calc.map trans.tail.lines

trans :: String -> (Int, Int)

trans s = ((read.head.words) s, (read.last.words) s)

calc :: [(Int, Int)] -> String
calc wtf = ((++).show.calc') wtf "\n"
calc' :: [(Int, Int)] -> Int
calc' a | length a == 0 = 0
        | length a == 1 = (if ((snd.head) a) - ((fst.head) a) > 1 then 1 else 0)
        | otherwise = (if ((snd.head) a) - ((fst.head) a) > 1 then 1 + (calc'.tail) a else (calc'.tail) a)

main = interact$show.calc.map trans.tail.lines
trans :: String -> (Int, Int)
trans s = ((read.head.words) s, (read.last.words) s)
calc :: [(Int, Int)] -> Int
calc ((x, y):[]) | y - x >= 2 = 1
                 | otherwise = 0
calc ((x, y):s) | y - x >= 2 = 1 + calc s
                | otherwise = calc s

solve :: [Int] -> Int
solve (p:q:rest) = (if q >= p + 2 then 1 else 0) + solve rest
solve [] = 0
main = print . solve . tail . map read . words =<< getContents

main = print . length . filter (>= 2) .map ((\[p, q] -> q - p) . map read . words) . tail . lines =<< getContents

solve [] = 0
solve (p:q:r) = solve r + if q > p + 1 then 1 else 0
main = print . solve . tail . map read . words =<< getContents

f lst = length (filter (\ x -> (x!!1) - (x!!0)  >= 2) lst)
main = do
 getLine
 nums <- getContents
 let linelst = lines nums
     lst     = map (\ x -> map read $ words x) linelst :: [[Int]]
     ans     = f lst
 print ans

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

solve :: [(Int, Int)] -> Int
solve xs = length $ filter (\(x, y) -> y - x > 1) xs

parseInput :: String -> [(Int, Int)]
parseInput input = xs where
    ls = tail $ lines input
    ys = map words ls
    xs = [(read x, read y) | [x, y] <- ys]

main :: IO ()
main = do
    input <- getContents
    let xs = parseInput input
    print $ solve xs

parse xs = read xs :: Int
run xs = show $ foldl (+) 0 $ map (\l -> let li = map parse $ words l in if li!!1-li!!0>=2 then 1 else 0) ls where ls = tail (lines xs)
main = interact run

run xs = show $ foldl (+) 0 $ map (\l -> let li = map (read) $ words l in fromEnum (li!!1-li!!0>=2)) ls where ls = tail (lines xs)
main = interact run

main = do
  d <- getContents
  let (n:ls) = lines d
  let rooms = map (map read . words) ls :: [[Int]]
  let ans = foldr (\[a,b] c -> c + if b - a >= 2 then 1 else 0) 0 rooms
  print ans

findNum :: [(Int, Int)] -> Int
findNum l = length $ filter (\p -> snd p - fst p > 1) l

main = do
    n <- readLn :: IO Int
    content <- getContents
    let
        rooms = map (\[x, y] -> (x, y)) . map (map (read::String->Int)) . map words . lines $ content
    putStrLn $ show $ findNum rooms

module Main (main)
    where

import Control.Monad (replicateM)

main :: IO ()
main = print . count . map readInts =<< flip replicateM getLine =<< readLn
    where count = length . filter (>= 2) . map (\[a,b] -> b - a)
          readInts = map read . words

import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)

readRoom :: B.ByteString -> [Int]
readRoom = map (fst . fromJust . B.readInt) . B.split ' '

isThereSpace :: B.ByteString -> Int
isThereSpace room = if occupied + 2 <= available then 1 else 0
  where space = readRoom room
        occupied = head space
        available = last space

main = B.getContents >>=
    return . show . sum . map (isThereSpace) . tail . B.lines >>=
    putStrLn

import Control.Monad
main = do
	getLine
	c<-getContents
	print $ length $ filter (\[x,y]->y-x>1)$map (map read.words) $ lines c

main = do
	n<-getLine
	rest<-getContents
	putStrLn $ show $ solve $ map (map read)$ map words $ lines $ rest

solve [] = 0
solve ([m1,m2]:ms) = if m2-m1>=2 then 1+(solve ms) else solve ms

-- https://stackoverflow.com/questions/10285837/read-n-lines-into-a-string
-- http://hackage.haskell.org/package/base-4.9.1.0/docs/Control-Monad.html#v:replicateM
------------
-- http://learnyouahaskell.com/input-and-output

-- go to the sequence part of the page

-- learn how to use foldl, foldr, map --functions
--------------------------------------------------
-- learn your haskell library:
-- https://downloads.haskell.org/~ghc/latest/docs/html/libraries/
--
-- page 15 of learn you a haskell for great good
-- i can use this

-- next: i discovered the "sequence" function on this webpage
-- http://learnyouahaskell.com/input-and-output
-- it is also the same as page 164 in the book "learn you a
-- haskell for great good"
-- This seems to be a conventional function that is used
-- so i am going o use it.

conv lst nw
  | (null lst) = nw
  | otherwise = conv (tail lst) (nw ++ [(read (head (words (head lst))))::Int]
                                ++ [(read (last (words (head lst))))::Int])

countRooms lst rooms
  | (null lst) = rooms
  | (head (drop 1 lst)) > ((head lst)+1) = countRooms (drop 2 lst) (rooms+1)
  | otherwise = countRooms (drop 2 lst) rooms

main = do
  a <- getLine
  let n = (read a)::Int
  let g = replicate n getLine
  dfd <- sequence g
  let newlist = conv dfd []
  let ans = countRooms newlist 0
  putStrLn (show ans)

import Control.Monad

-- Snippet: readItems
readItems = do
    line <- getLine
    return $ map read $ words line

main = do
    n <- readLn
    a <- replicateM n $ do
        [living, total] <- readItems
        return $ if 2 <= total - living then 1 else 0
    putStrLn $ show $ sum $ a

import Control.Monad

readNLines :: Int -> IO [String]
readNLines n = replicateM n getLine

freeSpace :: (Int, Int) -> Int
freeSpace (a, b) = b - a

main :: IO ()
main = do
    n <- readLn :: IO Int
    lines <- readNLines n
    let args = map (\x -> map (\y -> read y :: Int) $ words x) lines
        pairs = map (\x -> (x!!0, x!!1)) args
    print $ length $ filter (>=2) $ map freeSpace pairs

readPairsList ::Int -> IO [(Int, Int)]
readPairsList n = do
    if n == 0
        then return []
    else do
        line <- getLine
        let pairStr = map read $ words line :: [Int]
        let pair = ((pairStr !! 0), (pairStr !! 1))
        rest <- readPairsList $ n-1
        return (pair:rest)

main = do
    n <- fmap read getLine :: IO Int
    pairs <- readPairsList n
    let answer xs = length [x | x <- xs, fst(x)+2 <= snd(x)]

    putStrLn $ show(answer pairs)

main = do
    getLine
    ps <- fmap (map (map read . words). lines) getContents
    print $ filter (\[a, b] -> a+2 <= b) ps

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

solve :: [[Int]] -> Int
solve pqs = length [ () | [p, q] <- pqs, p < q ]

f lst = length (filter (\ x -> (abs (x!!0) - (x!!1)) > 1) lst)
main = do
 getLine
 nums <- getContents
 let linelst = lines nums
     lst   = map (\ x -> map read $ words x) linelst :: [[Int]]
     ans = f lst
 print ans

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


Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the road where they are placed. Right after passing the sign it is allowed to drive at any speed.It is known that the car of an average Berland citizen has the acceleration (deceleration) speed of a km/h2, and has maximum speed of v km/h. The road has the length of l km, and the speed sign, limiting the speed to w km/h, is placed d km (1 ≤ d < l) away from the capital of Berland. The car has a zero speed at the beginning of the journey. Find the minimum time that an average Berland citizen will need to get from the capital to Bercouver, if he drives at the optimal speed.The car can enter Bercouver at any speed.

The first line of the input file contains two integer numbers a and v (1 ≤ a, v ≤ 10000). The second line contains three integer numbers l, d and w (2 ≤ l ≤ 10000; 1 ≤ d < l; 1 ≤ w ≤ 10000).

Print the answer with at least five digits after the decimal point.

import Monad (liftM)
{-
import HUnit

tests :: Test
tests  =  TestList "Tests"
  [
    Test "#01" $ assertEq 2.5 $ solve [1,1,2,1,3],
    Test "#02" $ assertApproximate 8.965874696353 (solve [5,70,200,170,40]) 6,{-
    Test "#03" $ assertApproximate  $ solve [],
    Test "#04" $ assertApproximate  $ solve [],
    Test "#05" $ assertApproximate  $ solve [],
    Test "#06" $ assertApproximate  $ solve [],
    Test "#07" $ assertApproximate  $ solve [],
    Test "#08" $ assertApproximate  $ solve [],
    Test "#09" $ assertApproximate  $ solve [],
    Test "#10" $ assertApproximate  $ solve [],
    Test "#11" $ assertApproximate  $ solve [],
    Test "#12" $ assertApproximate  $ solve [],
    Test "#13" $ assertApproximate  $ solve [],
    Test "#14" $ assertApproximate  $ solve [],
    Test "#15" $ assertApproximate  $ solve [],
    Test "#16" $ assertApproximate  $ solve [],-}
    Test "#17" $ assertApproximate 57.6 (solve [4,120,5112,3000,130]) 5
  ]

test :: IO ()
test  =  run tests
-}
s' :: Floating a => a -> a -> a -> a
s' v0 a t  =  v0 * t + 0.5 * a * t^2

t' :: Floating a => a -> a -> a -> a
t' v0 a s  =  (-v0 + sqrt (v0^2 + 2 * a * s)) / a

v' :: Floating a => a -> a -> a -> a
v' v0 a t  =  v0 + a * t

tMax' :: (Floating a, Ord a) => a -> a -> a -> a -> a
tMax' v v0 a s
  | t1 < t2  =  t1
  | otherwise  =  t2 + (s - s' v0 a t2) / v
  where
    t1  =  t' v0 a s
    t2  =  (v - v0) / a

tMax'' :: (Floating a, Ord a) => a -> a -> a -> a -> a -> a
tMax'' v w v0 a s
  | w >= v  =  tMax' v v0 a s
  | tS <= tW  =  tMax' v v0 a s
  | sW + 2 * sWV >= s  =  tW + 2 * t' w a (0.5 * (s - sW))
  | otherwise  =  tW + 2 * tWV + (s - sW - 2 * sWV) / v
  where
    tS   =  t' v0 a s
    tW   =  (w - v0) / a
    tWV  =  (v - w) / a
    sW   =  s' v0 a tW
    sWV  =  s' w a tWV

solve :: (Floating a, Ord a) => [a] -> a
solve [a, v, l, d, w]
  | v  <= w    =  tMax' v 0 a l
  | tD <= tW   =  tMax' v 0 a l
  | otherwise  =  tMax'' v w 0 a d + tMax' v w a (l-d)
  where
    tD  =  t' 0 a d
    tW  =  w / a

main :: IO ()
main  =  liftM (map read . take 5 . words) getContents >>= print . solve

import Text.Printf
main = do
    [a, v, l, d, w] <- (map (fromInteger . read) . take 5) `fmap`
                (words `fmap` getContents) :: IO [Double]
    let maxAccelPath = v^2 / 2 / a
        maxAccelPath' = w^2 / 2 / a
	maxDecelPath = maxAccelPath - maxAccelPath'
        (t1, w') | v > w && d < maxAccelPath' = (sqrt (2 * d / a), t1 * a)
                 | v > w && d < maxAccelPath+maxDecelPath = let
                    s' = (d + maxAccelPath') / 2 in (2 * sqrt (2 * s' / a) - w / a, w)
                 | v > w = (v / a + (v - w) /a + (d + maxAccelPath'
                    - 2 * maxAccelPath) / v, w)
                 | w >= v && d < maxAccelPath = (sqrt (2 * d / a), t1*a)
                 | otherwise = (v / a + (d - maxAccelPath) / v, v)
        maxAccelPath2 | w' < v = maxAccelPath - w'^2 / 2 /a
                      | otherwise = 0
        t2 | (l - d) < maxAccelPath2 = sqrt (2*(l - d + w'^2/2/a)/a) - w'/a
           | otherwise = (v - w')/a + (l - d - maxAccelPath2)/v
    printf "%.5f" (t1+t2)

calc a v l d w
     | v <= w = calc2 l 0
     | otherwise = let tw = w/a
                       dw = dist 0 tw
                   in  if dw >= d then
                          calc2 l 0
                       else tw+2*calc2 ((d-dw)/2) w+calc2 (l-d) w
     where calc2 len v0 = let t1 = (v-v0)/a
                              t2 = ((sqrt $ v0*v0+2*a*len) - v0) / a
                          in  if t1 > t2 then t2
                              else t1+(len-dist v0 t1)/v
           dist v0 t = v0*t+a*t*t/2

main = do
     [a, v] <- return . (map read :: [String] -> [Double]) . words =<< getLine
     [l, d, w] <- return . (map read :: [String] -> [Double]) . words =<< getLine
     print $ calc a v l d w

module Main where

main :: IO ()
main = interact $ show . solve . map read . words

solve :: [Double] -> Double
solve [a, v, l, d, w]
    | w >= v || signAccelPath >= d = time a 0 v l
    | otherwise = signAccelTime + 2 * time a w v ((d - signAccelPath) / 2) + time a w v (l -d)
  where
    signAccelTime = w / a
    signAccelPath = dist a 0 signAccelTime

dist :: Double -> Double -> Double -> Double
dist a v t = v * t + a * t * t / 2

time :: Double -> Double -> Double -> Double -> Double
time a v0 v l
    | fullAccTime > totalTime = totalTime
    | otherwise               = fullAccTime + remainingDist / v
  where
    fullAccTime = (v - v0) / a
    totalTime = (sqrt (v0^2 + 2 * l * a) - v0) / a
    remainingDist = l - dist a v0 fullAccTime

import Monad (liftM)

s :: Floating a => a -> a -> a -> a
s v0 a t  =  v0 * t + 0.5 * a * t^2

t :: Floating a => a -> a -> a -> a
t v0 a s  =  (-v0 + sqrt (v0^2 + 2 * a * s)) / a

v :: Floating a => a -> a -> a -> a
v v0 a t  =  v0 + a * t

solve :: (Floating a, Ord a) => [a] -> a
solve [a, vMax, l, d, w]
  | w >= vMax  =  solve' 0 vMax a l
  | v 0 a tr <= w  =  solve' 0 vMax a l
  | otherwise  =  solve'' w vMax a d + t2
  where
    tr  =  t 0 a d
    t2  =  solve' w vMax a (l - d)
    solve' v0 vMax a l
      | v v0 a tr <= vMax  =  t v0 a l
      | otherwise  =  vMax / a + (l - s v0 a (vMax / a)) / vMax
      where
        tr  =  t v0 a l
    solve'' w vMax a d
      | tr2 <= tr1  =  w/a + 2 * tr2
      | otherwise  =  w/a + 2 * tr1 + (d - d' - 2 * s w a tr1) / vMax
      where
        tr1  =  (vMax - w) / a
        tr2  =  t w a (0.5 * (d - d'))
        d'  =  s 0 a (w/a)

main :: IO ()
main  =  liftM (map read . take 5 . words) getContents >>= print . solve

import Monad (liftM)

s' :: Floating a => a -> a -> a -> a
s' v0 a t  =  v0 * t + 0.5 * a * t^2

t' :: Floating a => a -> a -> a -> a
t' v0 a s  =  (-v0 + sqrt (v0^2 + 2 * a * s)) / a

v' :: Floating a => a -> a -> a -> a
v' v0 a t  =  v0 + a * t

tMax' :: (Floating a, Ord a) => a -> a -> a -> a -> a
tMax' v v0 a s
  | t1 < t2  =  t1
  | otherwise  =  t2 + (s - s' v0 a t2) / v
  where
    t1  =  t' v0 a s
    t2  =  (v - v0) / a

tMax'' :: (Floating a, Ord a) => a -> a -> a -> a -> a -> a
tMax'' v w v0 a s
  | w >= v  =  tMax' v v0 a s
  | tS <= tW  =  tMax' v v0 a s
  | sW + 2 * sWV >= s  =  tW + 2 * t' w a (0.5 * (s - sW))
  | otherwise  =  tW + 2 * tWV + (s - sW - 2 * sWV) / v
  where
    tS   =  t' v0 a s
    tW   =  (w - v0) / a
    tWV  =  (v - w) / a
    sW   =  s' v0 a tW
    sWV  =  s' w a tWV

solve :: (Floating a, Ord a) => [a] -> a
solve [a, v, l, d, w]
  | tD <= tW   =  tMax' v 0 a l
  | otherwise  =  tMax'' v w 0 a d + tMax' v w a (l-d)
  where
    tD  =  t' 0 a d
    tW  =  w / a

main :: IO ()
main  =  liftM (map read . take 5 . words) getContents >>= print . solve

import Text.Printf
main = do
    [a, v, l, d, w] <- (map (fromInteger . read) . take 5) `fmap`
                (words `fmap` getContents) :: IO [Double]
    let maxAccelPath = v^2 / 2 / a
        maxAccelPath' = w^2 / 2 / a
	maxDecelPath = maxAccelPath - maxAccelPath'
        (t1, w') | v > w && d < maxAccelPath' = (sqrt (2 * d / a), t1 * a)
                 | v > w && d < maxAccelPath+maxDecelPath = let
                    s' = (d + maxAccelPath') / 2 in (2 * sqrt (2 * s' / a) - w / a, w)
                 | v > w = (v / a + (v - w) /a + (d + maxAccelPath'
                    - 2 * maxAccelPath) / a, w)
                 | w >= v && d < maxAccelPath = (sqrt (2 * d / a), t1*a)
                 | otherwise = (v / a + (d - maxAccelPath) / v, v)
        maxAccelPath2 | w' < v = maxAccelPath - w'^2 / 2 /a
                      | otherwise = 0
        t2 | (l - d) < maxAccelPath2 = sqrt (2*(l - d + w'^2/2/a)/a) - w'/a
           | otherwise = (v - w')/a + (l - d - maxAccelPath2)/v
    printf "%.5f" (t1+t2)

calc a v l d w
     | v <= w = calc2 l 0
     | otherwise = let tw = w/a
                       dw = dist 0 tw
                   in  if dw >= l then
                          calc2 l 0
                       else tw+2*calc2 ((d-dw)/2) w+calc2 (l-d) w
     where calc2 len v0 = let t1 = (v-v0)/a
                              t2 = ((sqrt $ v0*v0+2*a*len) - v0) / a
                          in  if t1 > t2 then t2
                              else t1+(len-dist v0 t1)/v
           dist v0 t = v0*t+a*t*t/2

main = do
     [a, v] <- return . (map read :: [String] -> [Double]) . words =<< getLine
     [l, d, w] <- return . (map read :: [String] -> [Double]) . words =<< getLine
     print $ calc a v l d w

module Main where

main :: IO ()
main = interact $ show . solve . map read . words

solve :: [Double] -> Double
solve [a, v, l, d, w]
    | w >= v || signAccelPath >= d = time2 a 0 v l
    | otherwise = signAccelTime + 2 * time1 a w ((d - signAccelPath) / 2) + time2 a w v (l -d)
  where
    signAccelTime = w / a
    signAccelPath = dist a 0 signAccelTime

dist :: Double -> Double -> Double -> Double
dist a v t = v * t + a * t * t / 2

time1 :: Double -> Double -> Double -> Double
time1 a v l = (sqrt (v^2 + 2 * l * a) - v) / a

time2 :: Double -> Double -> Double -> Double -> Double
time2 a v0 v l
    | fullAccTime > totalTime = totalTime
    | otherwise               = fullAccTime + remainingDist / v
  where
    fullAccTime = (v - v0) / a
    totalTime = time1 a v0 l
    remainingDist = l - dist a v0 fullAccTime


Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wants to steal a bag with cookies so that the number of cookies in the remaining bags was even, that is, so that Anna and Maria could evenly divide it into two (even 0 remaining cookies will do, just as any other even number). How many ways there are to steal exactly one cookie bag so that the total number of cookies in the remaining bags was even?

The first line contains the only integer n (1 ≤ n ≤ 100) — the number of cookie bags Anna and Maria have. The second line contains n integers ai (1 ≤ ai ≤ 100) — the number of cookies in the i-th bag.

Print in the only line the only number — the sought number of ways. If there are no such ways print 0.

NoteIn the first sample Olga should take the only bag so that the twins ended up with the even number of cookies.In the second sample Olga can take any of five bags with two cookies or any of three bags with four cookies — 5 + 3 = 8 ways in total.In the third sample, no matter which bag with two cookies Olga chooses, the twins are left with 2 * 9 + 99 = 117 cookies. Thus, Olga has only one option: to take the bag with 99 cookies.

module Main where

import Control.Monad

main = do
    getLine
    a <- liftM ( map read . words ) getLine :: IO [Int]

    putStrLn $ show $ length $ filter ( if even ( sum a )
        then even
        else odd
        ) a

main = do
   _ <- getLine
   ls <- fmap (map read . words) getLine
   let m2 = sum ls `mod` 2
   print . length $ filter ((==m2) . (`mod`2)) ls

-- vim: set expandtab:

-- cookies
parse [] word = [read $ reverse word :: Int]
parse (' ':xs) word = (read $ reverse word :: Int):(parse xs [])
parse (x:xs) word = parse xs (x:word)

find [] _ a = a
find (x:xs) s akk = if (mod (s-x) 2 == 0) then find xs s (akk + 1) else find xs s akk

main = do
			readLn :: IO Int
			l <- getLine
			print $ find (parse l []) (sum (parse l []) 0) 0
	where sum [] akk = akk
	      sum (x:xs) akk = sum xs $ akk+x

import List
getAns a | (sum a) `mod` 2 == 0=length (filter even a)
         | otherwise =length (filter odd a)
main=interact$show.getAns.map read.tail.words

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

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

solve :: [Int] -> Int
solve xs
  | odd s      =  length (filter odd xs)
  | otherwise  =  length (filter (not . odd) xs)
  where
    s = sum xs

main :: IO ()
main = do
    getLine >> Main.reads >>= print . solve

solve xs = let s = sum xs
           in sum $ map (\x -> 1 - mod (s - x) 2) xs

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

import Control.Applicative

solve :: [Int] -> Int
solve cookies =
  if even (sum cookies) then numEvens else numOdds
  where
    numEvens = length $ filter even cookies
    numOdds = length cookies - numEvens
main :: IO ()
main = do
  getLine
  cookies <- map read . words <$> getLine
  putStrLn $ show $ solve cookies

main = do s <- getLine
          s <- fmap ((map ((flip mod 2) . read::String->Int)) . words) getLine
          putStrLn $ (show . length . (filter (\x->x==mod (sum s) 2))) s

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

solve :: [Int] -> Int
solve as = length $ filter (if even (sum as) then even else odd) as

main=interact$show.f.map read.tail.words
f x=length[a|a<-x,odd a==odd(sum x)]

main=interact$show.f.map read.tail.words
f x=length[a|a<-x,even a==even(sum x)]

import Control.Arrow
import Data.List
solve ns = if odd o then o else e
    where (e,o) = (length *** length) (partition even ns)
main = print . solve . map read . tail . words =<< getContents

main = do
    getLine
    a <- fmap (map read . words) getLine
    print $ solve a
solve a = if even $ sum a then length $ filter even a else length $ filter odd a

{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}
{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind -fno-warn-type-defaults -fno-warn-orphans #-}

import Control.Applicative
import Control.Monad

main :: IO ()
main = do
  n   :: Int    <- readLn
  xs  :: [Int]  <- take n . map read . words <$> getLine
  let acc     = sum xs
      answer  = sum $ do
        x <- xs
        guard $ even (acc - x)
        return 1
  print answer

main = do
	getLine
	l <- (map read . words) `fmap` getLine
	let oddEven = if odd $ sum l then odd else even
	print $ length $ filter oddEven l

readInts :: [String] -> [Int]
readInts = map read

main = interact solve

solve :: String -> String
solve input = result
    where result = show $ numberOfWays cookies
          cookies = readInts $ words $ lines input !! 1

numberOfWays :: [Int] -> Int
numberOfWays cookies
    | even total = length . filter even $ cookies
    | otherwise  = length . filter odd $ cookies
    where total = sum cookies

readInts :: [String] -> [Int]
readInts = map read

main = interact solve

solve :: String -> String
solve input = unlines $ result : []
    where result = show $ numberOfWays cookies
          cookies = readInts $ words $ lines input !! 1

numberOfWays :: [Int] -> Int
numberOfWays cookies
    | even total = length . filter even $ cookies
    | otherwise  = length . filter odd $ cookies
    where total = sum cookies

import Data.List
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as BS

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

solve :: [ Int ] -> BS.ByteString
solve xs = BS.pack.show $ a where
	s = sum xs
	a = helpSolve xs where
	  helpSolve :: [ Int ] -> Int
	  helpSolve [] = 0
	  helpSolve ( y : ys )
            | even $  s - y = 1 + helpSolve ys
	    | otherwise = helpSolve ys

main = BS.interact $ solve . map reaD . BS.words . last . BS.lines

import Control.Applicative
import Data.Char
main= do
	getLine
	s<- map read.words <$> getLine ::IO [Int]
	print $ length $ filter (if even (sum s) then even else odd) s

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

main :: IO ()
main = do
	_ <- getLine
	line <- getLine
	let	arr = map (\x -> read x:: Int) . words $ line
		total = foldl (+) 0 arr
		ans = foldl (\acc x -> acc + (if (total - x) `mod` 2 == 0 then 1 else 0) ) 0 arr
	print ans

-- Codeforces Beta Round #94
-- Problem A -- Cookies
main = interact work

work :: String -> String
work input = show $ solve . parse $ input

parse :: String -> [Int]
parse = map (\i -> read i :: Int) . words . last . lines

solve :: [Int] -> Int
solve a = length . filter (\x -> x `mod` 2 == (sum a) `mod` 2) $ a

import Data.List
import Debug.Trace (trace)

main2 = print $ solv [1, 2, 2, 3, 4, 4, 4, 2, 2, 2]
main =
	do
		[n] <- getNums
		lines <- getLine
		putStrLn $ show $ solv $ getNumbers lines

solv l = length $ filter (if isE then isEven else not . isEven ) l
	where
		isE = isEven $ sum l

isEven x = x `mod` 2 == 0

------------------utils-----------------------
tr x y = trace ((show x) ++ (show y)) y
tr1 x y = trace ((show x)) y
tr2 y = trace ((show y)) y

(|>) x f = f x

parseInt x = (read x) :: Int

getIndex = zip [0..]

getLines n = repeat getLine |> take n |> sequence

getNums ::  IO [Int]
getNums =
	do
		line <- getLine
		return $ getNumbers line

getNumbers line =
	case index of
		Nothing -> [parseInt line]
		Just i ->
			let (l,r) = splitAt (i + 1) line in
				(parseInt l) : (getNumbers r)
	where
		index = elemIndex ' ' line

splitBy k =
	case index of
		Nothing -> [k]
		Just i ->
			let (l,r) = splitAt (i) k in
				l : splitBy (drop 1 r)
	where
		index = elemIndex ' ' k


Vasya plays the Geometry Horse.The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value. There are n types of geometric figures. The number of figures of type ki and figure cost ci is known for each figure type. A player gets ci·f  points for destroying one figure of type i, where f is the current factor. The factor value can be an integer number from 1 to t + 1, inclusive. At the beginning of the game the factor value is equal to 1. The factor is set to i + 1 after destruction of pi (1 ≤ i ≤ t) figures, so the (pi + 1)-th figure to be destroyed is considered with factor equal to i + 1.Your task is to determine the maximum number of points Vasya can get after he destroys all figures. Take into account that Vasya is so tough that he can destroy figures in any order chosen by him.

The first line contains the only integer number n (1 ≤ n ≤ 100) — the number of figure types. Each of the following n lines contains two integer numbers ki and ci (1 ≤ ki ≤ 109, 0 ≤ ci ≤ 1000), separated with space — the number of figures of the i-th type and the cost of one i-type figure, correspondingly. The next line contains the only integer number t (1 ≤ t ≤ 100) — the number that describe the factor's changes.  The next line contains t integer numbers pi (1 ≤ p1 < p2 < ... < pt ≤ 1012), separated with spaces. Please, do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator.

Print the only number — the maximum number of points Vasya can get.

NoteIn the first example Vasya destroys three figures first and gets 3·1·10 = 30 points. Then the factor will become equal to 2 and after destroying the last two figures Vasya will get 2·2·10 = 40 points. As a result Vasya will get 70 points.In the second example all 8 figures will be destroyed with factor 1, so Vasya will get (3·8 + 5·10)·1 = 74 points.

import Data.List (sortBy)
import Data.Ord (comparing)

main = do
    n <- fmap read getLine
    xs <- fmap (sortBy (comparing snd) . map (\[k, c] -> (read k, read c) :: (Integer, Integer)) . map words) $ sequence $ replicate n getLine
    getLine
    ps <- fmap ((++ [10 ^ 15]) . map read . words) getLine
    print $ solve xs ps 1 0 0
    where
        solve [] _ _ _ ans = ans
        solve ((k, c):xs) (p:ps) f used ans | used + k < p = solve xs (p:ps) f (used + k) (ans + k * f * c)
                                            | otherwise    = solve ((k - (p - used), c):xs) ps (f + 1) p (ans + (p - used) * f * c)

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

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

parseInput = do
    n <- readInt
    kc <- replicateM n ((,) <$> readInt64 <*> readInt64)
    t <- readInt
    p <- replicateM t readInt64
    return (kc, p)
  where
    readInt64 = fromIntegral <$> readInteger :: State ByteString Int64
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

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

data Chunk a = Chunk Int64 a deriving (Eq, Show)

zipWithChunk :: (a -> b -> c) -> [Chunk a] -> [Chunk b] -> [Chunk c]
zipWithChunk _ [] _ = []
zipWithChunk _ _ [] = []
zipWithChunk f (Chunk 0 _:xs) ys = zipWithChunk f xs ys
zipWithChunk f xs (Chunk 0 _:ys) = zipWithChunk f xs ys
zipWithChunk f (Chunk a x:xs) (Chunk b y:ys) = Chunk c (f x y) :
    zipWithChunk f (Chunk (a - c) x:xs) (Chunk (b - c) y:ys)
  where
    c = min a b

solve (kc', p) = sum [a * b | Chunk a b <- lst]
  where
    kc = sortBy (comparing snd) kc'

    kcs = [Chunk k c | (k, c) <- kc]
    ps = zipWith Chunk (zipWith (-) (p++[10^12]) (0:p)) [1..]

    lst = zipWithChunk (*) kcs ps :: [Chunk Int64]

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

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

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

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

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

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

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

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

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

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

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

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

state = State
-- }}}

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

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

parseInput = do
    n <- readInt
    kc <- replicateM n ((,) <$> readInt64 <*> readInt64)
    t <- readInt
    p <- replicateM n readInt64
    return (kc, p)
  where
    readInt64 = fromIntegral <$> readInt :: State ByteString Int64
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

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

data Chunk a = Chunk Int64 a deriving (Eq, Show)

zipWithChunk :: (a -> b -> c) -> [Chunk a] -> [Chunk b] -> [Chunk c]
zipWithChunk _ [] _ = []
zipWithChunk _ _ [] = []
zipWithChunk f (Chunk 0 _:xs) ys = zipWithChunk f xs ys
zipWithChunk f xs (Chunk 0 _:ys) = zipWithChunk f xs ys
zipWithChunk f (Chunk a x:xs) (Chunk b y:ys) = Chunk c (f x y) :
    zipWithChunk f (Chunk (a - c) x:xs) (Chunk (b - c) y:ys)
  where
    c = min a b

solve (kc', p) = sum [a * b | Chunk a b <- lst]
  where
    kc = sortBy (flip $ comparing snd) kc'

    kcs = [Chunk k c | (k, c) <- kc]
    ps = zipWith Chunk (zipWith (-) (p++[10^12]) (0:p)) [1..]

    lst = zipWithChunk (*) kcs ps :: [Chunk Int64]

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

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

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

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

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

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

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

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

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

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

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

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

state = State
-- }}}


Berland year consists of $$$m$$$ months with $$$d$$$ days each. Months are numbered from $$$1$$$ to $$$m$$$. Berland week consists of $$$w$$$ days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than $$$w$$$ days.A pair $$$(x, y)$$$ such that $$$x < y$$$ is ambiguous if day $$$x$$$ of month $$$y$$$ is the same day of the week as day $$$y$$$ of month $$$x$$$.Count the number of ambiguous pairs.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Each of the next $$$t$$$ lines contains three integers $$$m$$$, $$$d$$$ and $$$w$$$ ($$$1 \le m, d, w \le 10^9$$$) — the number of months in a year, the number of days in a month and the number of days in a week.

Print $$$t$$$ integers — for each testcase output the number of pairs $$$(x, y)$$$ such that $$$x < y$$$ and day $$$x$$$ of month $$$y$$$ is the same day of the week as day $$$y$$$ of month $$$x$$$.

NoteHere are the pairs for the first test case:

import Data.Bits

tri :: Integer -> Integer
tri n = shiftR (n * (n-1)) 1

solve :: Integer -> Integer -> Integer -> Integer
solve m d w = let
  s = div w (gcd w (d-1))
  m' = min m d
  -- ans = sum [div (min m d - k) s | k <- [1..m]], but SPEED
  (fullCycles, excess) = divMod m' s
  in  s * tri fullCycles + excess * fullCycles

soln :: [Integer] -> [Integer]
soln (x:y:z:ws) = solve x y z : soln ws
soln _ = []

main :: IO ()
main = interact (unlines . map show . soln . map read . tail . words)