import Prelude
import List
import Char

main = interact q

q = func.last.lines

func::String->String
func a = toStr$solve$map toInt $ words a
    where
      toStr (a,b) = (toString a) ++ " " ++ (toString b)

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve a = (maximum$map length l, length l)
          where
            l = group$reverse$sort a

module Main where

import Control.Monad
import Data.List

main = do
    n <- read `liftM` getLine :: IO Int
    hs <- ( map read . words ) `liftM` getLine :: IO [Int]
    let tower = map length $ group $ sort hs

    putStrLn $ show ( maximum tower ) ++ " " ++ show ( length tower )

import qualified Data.IntMap as IntMap

collect [] stacks = stacks
collect (x : xs) stacks =
    case IntMap.lookup x stacks of
      Nothing -> collect xs (IntMap.insert x 1 stacks)
      Just a  -> collect xs (IntMap.insert x (a + 1) stacks)

count :: Int -> [Int] -> String
count barcount bars = show max_stack ++ " " ++ show stack_count
    where
      stack_count = IntMap.size stacks
      max_stack   = IntMap.fold max 0 stacks
      stacks      = collect bars IntMap.empty

main :: IO ()
main = do
  bar_count <- getLine >>= return . read
  bars <- getLine >>= return . (map read . words)
  putStr (count bar_count bars)

{-# 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
    ys = group $ sort xs
    m = maximum $ map length ys
    c = length ys

  putStrLn $ show m ++ " " ++ show c

import Data.List (sort, sortBy, group)
import Data.Function (on)

parse_input :: String -> [[Int]]
parse_input str = map (map (read::String->Int).words) (lines str)

solve :: String -> String
solve in_str =
  let l = head.tail $ parse_input in_str
      sorted = sortBy (flip compare `on` length) $ group $ sort l
    in (show $ length $ head $ sorted) ++ " " ++ (show $ length $ sorted)

main :: IO ()
main = do interact $ solve

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Function
import Data.Ord
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= someFunc
someFunc::IO()
someFunc = getLine >> (solve.concat =<< forM [1.. 1] ( \i -> map (fst.fromJust.C.readInt).C.words<$>C.getLine))
solve xs=let rs=sortBy  (flip compare `on` length)$ group $ sort xs; [x,y]=[length $ head rs,length rs] in putStr $ unwords $ map show [x,y]

{-# OPTIONS_GHC -O2 -XNoMonomorphismRestriction #-}
{-# LANGUAGE BangPatterns #-}
{-(c) gorlum0 [at] gmail.com-}
import Text.Printf
import Data.List (group, sort, maximumBy)
import Data.Ord (comparing)

towers bs = (h, t)
    where
    bs' = group . sort $ bs
    h = length $ maximumBy (comparing length) bs'
    t = length bs'

body [] = []
body (n:xs) = towers bs : body xs'
    where
    n' = read n
    (bs, xs') = splitAt n' xs

fmt :: (Int, Int) -> String
fmt (h, t) = printf "%d %d" h t

main = do
    ws <- words `fmap` getContents
    mapM_ (putStrLn . fmt) (body ws)

import Array

maxSize = 1000::Int

fillArray :: [Int] -> Array Int Int
fillArray l = accumArray (+) 0 (1, maxSize) [(i, 1) | i <- l]

getArray :: Array Int Int -> [Int]
getArray a = [a!i | i <- range (bounds a)]

solution :: Array Int Int -> (Int, Int)
solution a = (maximum la, length (filter (\x -> x > 0) la))
    where la = getArray a

main = do
    n <- readLn::(IO Int)
    s <- getLine
    a <- return (map (read::String -> Int) (words s))
    ans <- return (solution (fillArray a))
    putStr (show (fst ans))
    putStr " "
    putStr (show (snd ans))

import Data.List(sort)

solve xs = (largestTower sortedXs, towerCount sortedXs)
    where sortedXs = sort xs

largestTower xs = largestTower' 0 0 xs
    where largestTower' currentHeight lastHeight [] = currentHeight
          largestTower' currentHeight lastHeight (x:xs) = if x == lastHeight
                                                          then largestTower' (currentHeight+1) x xs
                                                          else max currentHeight (largestTower' 1 x xs)

towerCount xs = towerCount' 0 0 xs
    where towerCount' currentCount lastHeight [] = currentCount
          towerCount' currentCount lastHeight (x:xs) = if x == lastHeight
                                                       then towerCount' currentCount x xs
                                                       else towerCount' (currentCount+1) x xs

main = do
       dummy <- getLine
       inputLine <- getLine
       let inputArray = words inputLine
       let sequence = map read inputArray :: [Int]
       let ans = solve sequence
       putStrLn (show (fst ans) ++ " " ++ show (snd ans))

import Data.List (groupBy, sort)
import Data.Set (size, fromList)

main = do
    getLine
    n <- getLine
    let l = conv n
    putStr $ (show . f $ l) ++ " " ++ (show . g) l

conv = sort . map (read::String->Int) . words
f = maximum . (map length) . (groupBy (==))
g = size . fromList

import Control.Applicative
import Data.List

main=do

    getLine
    q1<- map read <$> words <$> getLine::IO [Int]
    let q = map length $ group $ sort q1
    putStrLn $ intercalate " " $ map show [maximum q , length q]

import Data.Char
import Data.List

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

solve :: [Int] -> String
solve ns = unwords $ map show [ maximum (map length gns), length gns ]
  where gns = group (sort ns)

import Data.List
import Control.Arrow
main = putStrLn . uncurry (++) .
       ( show . maximum . map length &&&
         (' ':) . show . length ) .
       group . sort .
       map (read :: String -> Int) . tail . words =<< getContents

import Data.List
main = getLine >> fmap (map read . words) getLine >>= putStrLn . intercalate " " . map show . solve
solve :: [Int] -> [Int]
solve xs = [maxTower, towerCount]
    where grouped = group $ sort xs
          maxTower = maximum $ map length grouped
          towerCount = length grouped

import Data.List (group, sort)

main :: IO ()
main    = do    _ <- getLine
                s <- getLine
                putStrLn (solve s)
    where
        solve   = unwords . map show . count . group . sort . map read . words

count :: [[Int]] -> [Int]
count xss = [maximum (map length xss), length xss]

import Data.List

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

main = do
    n <- readLn :: IO Int
    num <- getnum
    let g = group . sort $ num
        a = maximum $ map length g
        b = length g
    putStrLn $ unwords (map show [a,b])

module Main (main) where

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

solve :: [Int] -> (Int,Int)
solve list = (max_height,set_size)
      where set_size = length $ nub list
            occurence = map (\r -> length $ filter (== r) list) list
            max_height = maximum occurence

output (a,b) = (show a) ++ " " ++ (show b)

main = do n <- getLine
          line <- getLine
          let list = map read (words line)
          putStr $ output (solve list)

import List
main = interact f
f input = output where
  output = unwords [show d,show e]
  [n,l] = map (map (read::String->Int)) $ map words $ lines input
  a = sort $ zip l [1..]
  b [(x,_)] = [(x,1)]
  b ((x,y):xs)
    | x == u    = (x,v+1):tail ys
    | otherwise = (x,1):ys
   where
     ys = b xs
     (u,v) = head ys
  c = b a
  d = foldl1 max $ map snd c
  e = length c

import Data.List

calc :: [Int] -> (Int, Int)
calc xs = (maximum [count x xs | x <- xs], length $ nub xs)
  where
    count a xs = sum [1 | x <- xs, x == a]

main = do s <- getLine
          t <- getLine
          let (x, y) = calc $ map read $ words t
          putStrLn (show x ++ " " ++ show y)

import Control.Applicative
import Data.List

main=do
	getLine
	n<-  map read . words <$> getLine:: IO [Int]
	let m = group $ sort n
	putStrLn $ show ( maximum (map length m)) ++" " ++ (show (length m))

import Control.Monad
import Data.List

getLineValues :: IO [Int]
getLineValues = getLine >>= return . map read . words

main :: IO ()
main = do
    _ <- getLine
    ns <- getLineValues
    let nss = (group . sort) ns
        largest = (maximum . map length) nss
        total = length nss
    putStrLn $ show largest ++ " " ++ show total

import Data.List
main = getContents >>= putStrLn. (\x ->show (maximum.map length.group.sort $ x) ++ " " ++ show (length.nub $ x)). tail. words

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
	putStr . show . maximum.  map (length) .group. sort. words $ line
	putStr " "
	print.length.nub.words $ line

import qualified Data.Map as M
import Control.Applicative

add k m = case res of
    Nothing -> M.insert k 1 m
    Just x -> M.insert k (x + 1) m
    where
        res = M.lookup k m

f x = map snd $ M.toList $ foldr add M.empty x

main = do
    n <- (read :: String -> Int) <$> getLine
    l <- map (read :: String -> Int) <$> words <$> getLine
    let cnt = f l
    putStr $ show (maximum cnt) ++ " " ++ show (length cnt)

import qualified Data.Map as M
import Text.Printf

main = interact f

f ss = printf "%d %d" (maximum e) (length e)
  where
    (n:s) = map (read :: String->Int) $ words ss
    m = foldl (\buf i -> M.insertWith (+) i 1 buf) (M.fromList ([]::[(Int, Int)])) s
    e = M.elems m

import List
main = do interact $ unwords . map show . (\i -> [maximum i, length i]) . map length . group . sort . map (read::String->Int) . tail . words

import Data.List
import Data.Ord
import Control.Arrow
main = putStrLn . uncurry (++) .
       ( show . length . maximumBy (comparing sum) &&&
         (' ':) . show . length ) .
       group . sort .
       map read . tail . words =<< getContents


import List
main = interact solve
solve input = output where
  a = map ( read :: String -> Int ) $ words $ last $ lines input
  output = show $ div ( a0 - 1 ) 2 + min a1 a2 - 1
  [a0,a1,a2] = map length $ group $ sort $ map (\x -> mod x 3) ([0,1,2] ++ a)

import Data.Array (accumArray, (!))

main = do
	dummy <- getLine
	a <- getLine
	let a' = accumArray (+) 0 (0, 2) $ map (\x -> (mod x 3, 1)) $ map read $ words $ a in
		putStrLn $ show $ div (a'!0) 2 + min (a'!1) (a'!2)

{-# LANGUAGE ScopedTypeVariables,TupleSections #-}
data State s a = State {runState :: s->(a,s)}
instance Monad (State s) where
	return = State . (,)
	(State f1) >>= f2 = State $ uncurry (runState . f2) . f1
	(State f1) >> (State f2) = State $ f2 .snd . f1

repeatMn a n = mapM (const a) [1..n]
readm::(Read a) => State String a
readm = State (head . reads)

runRead x s = fst $ runState x s

main = reader >>= writer . show . solver
reader = getContents
writer = putStr
solver = runRead $ do
	l <- readm >>= repeatMn readm
	let count x = length $ filter ((==x) . flip mod 3) l
	let ans = (min (count 1) (count 2)) + (flip div 2 $ count 0)
	return ans

main = do getLine
          args <- getLine
          print $ solve $ map read $ words args

solve :: [Int] -> Int
solve ns = num0 `div` 2 + min num1 num2
    where
      (num0, num1, num2) = count ns
      count [] = (0, 0, 0)
      count (n:ns') = let n0 = if n `mod` 3 == 0 then 1 else 0
                          n1 = if n `mod` 3 == 1 then 1 else 0
                          n2 = if n `mod` 3 == 2 then 1 else 0
                          (n0', n1', n2') = count ns'
                      in (n0 + n0', n1 + n1', n2 + n2')

import Data.Array
main=interact(show.s.map read.words)
s (n:xs)=r!0`div`2+min(r!1)(r!2) where r=accumArray(+)0(0,2)(map(\x->(x`mod`3,1))xs)

import Data.Array
main = interact (show.s.map read.words)
s (n:xs) = r!0`div`2+min(r!1)(r!2) where
    r = foldl m (listArray(0,2)[0,0,0]) xs
    m a x = a//[(i,a!i+1)] where i = x`mod`3

import Array
main=interact(show.s.map read.words)
s(n:y)=r!0`div`2+min(r!1)(r!2) where r=accumArray(+)0(0,2)(map(\x->(x`mod`3,1))y)

import Data.Array (accumArray, (!))

main = do
    dummy <- getLine
    a <- getLine
    let a' = accumArray (+) 0 (0, 2) $ map (\x -> (x `mod` 3, 1)) $ map read $ words $ a in
            print $ (a'!0) `div` 2 + min (a'!1) (a'!2)

printNumbers :: [Int] -> IO ()
printNumbers [] = return ()
printNumbers (x:xs) = do
    putStrLn(show x)
    printNumbers xs

toNumbers :: [Char] -> [Int]
toNumbers l = temp 0 l

temp :: Int -> [Char] -> [Int]
temp val [] = [val]
temp val (' ':xs) = val : (temp 0 xs)
temp val (x:xs) = temp (val + ((read [x]) :: Int)) xs

modBy3 :: [Int] -> Int -> Int
modBy3 l n = foldl (+) 0 ([1 | x <- l, (mod x 3) == n])

solve :: [Int] -> Int
solve l = (div (modBy3 l 0) 2) + (min (modBy3 l 2) (modBy3 l 1))

main = do
    getLine
    line <- getLine
    putStrLn (show (solve (toNumbers line)))
    --printNumbers((toNumbers line))
    --putStrLn(show(modBy3(toNumbers line) 0))
    --putStrLn(show(modBy3(toNumbers line) 1))
    --putStrLn(show(modBy3(toNumbers line) 2))
    return()

solve :: [Int] -> Int
solve a = min n1 n2 + div n0 2
  where
    a2 = map (\x -> mod x 3) a
    n0 = length (filter (==0) a2)
    n1 = length (filter (==1) a2)
    n2 = length (filter (==2) a2)

main = do
    getLine
    line <- getLine
    let a = map read (words line)
    print (solve a)


import Data.Bits

main = interact $ pureMain

pureMain :: String -> String
pureMain s = if xorSum == 0 then "bolik\n" else "tolik\n"
  where [n]:l = map (map myRead.words) $ lines s
        xorSum = foldl xor 0 $ map (\[x, m] -> f (x + m - 1) `xor` f (x - 1)) l

myRead :: String -> Int
myRead = myRead' . reverse
  where myRead' ('0':s) = myRead' s * 10 + 0
        myRead' ('1':s) = myRead' s * 10 + 1
        myRead' ('2':s) = myRead' s * 10 + 2
        myRead' ('3':s) = myRead' s * 10 + 3
        myRead' ('4':s) = myRead' s * 10 + 4
        myRead' ('5':s) = myRead' s * 10 + 5
        myRead' ('6':s) = myRead' s * 10 + 6
        myRead' ('7':s) = myRead' s * 10 + 7
        myRead' ('8':s) = myRead' s * 10 + 8
        myRead' ('9':s) = myRead' s * 10 + 9
        myRead' _ = 0

f :: Int -> Int
f x = (if even x then bit 64 - 1 else 0) .&. x `clearBit` 0 `xor` if even x /= even (div x 2) then 1 else 0

import Data.Bits

main = interact $ pureMain

pureMain :: String -> String
pureMain s = if xorSum == 0 then "bolik\n" else "tolik\n"
  where [n]:l = map (map read.words) $ lines s
        xorSum = foldl xor 0 $ map (\[x, m] -> f (x + m - 1) `xor` f (x - 1)) l

f :: Int -> Int
f x = (if even x then bit 64 - 1 else 0) .&. x `clearBit` 0 `xor` if even x /= even (div x 2) then 1 else 0

import Data.Bits

main = interact $ pureMain

pureMain :: String -> String
pureMain s = if xorSum == 0 then "bolik\n" else "tolik\n"
  where [n]:l = map (map myRead.words) $ lines s
        xorSum = foldl xor 0 $ map (\[x, m] -> f (x + m - 1) `xor` f (x - 1)) l

myRead :: String -> Int
myRead = myRead' . reverse
  where myRead' ('0':s) = myRead' s * 10 + 0
        myRead' ('1':s) = myRead' s * 10 + 1
        myRead' ('2':s) = myRead' s * 10 + 2
        myRead' ('3':s) = myRead' s * 10 + 3
        myRead' ('4':s) = myRead' s * 10 + 4
        myRead' ('5':s) = myRead' s * 10 + 5
        myRead' ('6':s) = myRead' s * 10 + 6
        myRead' ('7':s) = myRead' s * 10 + 7
        myRead' ('8':s) = myRead' s * 10 + 8
        myRead' ('9':s) = myRead' s * 10 + 9
        myRead' _ = 0

f :: Int -> Int
f x = (if even x then bit 64 - 1 else 0) .&. x `xor` if even x /= even (div x 2) then 1 else 0


{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as C
import Control.Monad
  ( replicateM
  , replicateM_
  )
import Data.Int (Int64)

data Segment = Segment { l :: Int64
                       , r :: Int64
                       , cost :: Int64
                       }

solve :: [Segment] -> [Int64]
solve segments = iter segments 2000000000 inf 0 inf inf
  where
    inf = 1000000000000000 :: Int64
    iter [] _ _ _ _ _ = []
    iter (curr:rem) lm lc rm rc singleCost =
      let
        lmNew = if l curr < lm then l curr else lm
        rmNew = if r curr > rm then r curr else rm
        lcNew = if lmNew < lm then cost curr else (if l curr == lmNew then min (cost curr) lc else lc)
        rcNew = if rmNew > rm then cost curr else (if r curr == rmNew then min (cost curr) rc else rc)
        singleCostNew = min (if l curr == lmNew && r curr == rmNew then cost curr else inf) (if lmNew == lm && rmNew == rm then singleCost else inf)
      in (min (lcNew + rcNew) singleCostNew):(iter rem lmNew lcNew rmNew rcNew singleCostNew)

main :: IO ()
main = do
  tc <- readInt <$> C.getLine
  replicateM_ tc gao
  where
    readInt s = let Just (i, _) = C.readInt s in i
    readInt64 = fromIntegral . readInt
    convert :: [Int64] -> Segment
    convert (x:(y:(z:[]))) = Segment x y z
    convert _ = error "wrong data format"
    readSegment :: IO Segment
    readSegment = do
      ns <- (map readInt64 . C.words) <$> C.getLine
      return $ convert ns
    gao = do
      n <- readInt <$> C.getLine
      segments <- replicateM n readSegment
      let
        results = solve segments
      C.putStrLn $ C.intercalate "\n" $ map (C.pack . show) results

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
--import Data.Array.Unboxed

prefMins :: Ord t => (a -> t) -> [a] -> [t]
prefMins f li = tail $ scanl' min (f $ head li) $ map f li

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    segs <- replicateM n $ do
      ~[li, ri, ci] <- getInts 3
      pure (li, ri, ci)
    let
      ls = prefMins (\( l, _r, c) -> (l, c)) segs
      rs = prefMins (\(_l,  r, c) -> (negate r, c)) segs
      ws = prefMins (\( l,  r, c) -> (l - r, c)) segs
      score ((lt, lc), (rt, rc), (wa, wc)) = let
        wt = lt + rt
        in  if  wa == wt
        then  min wc (lc + rc)
        else  lc + rc
    pure $ foldMap (putInts . pure . score) $ zip3 ls rs ws

type SP = State [P.ByteString]

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

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

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun $ P.words inp
  P.putStr $ toLazyByteString outp

{-# LANGUAGE OverloadedStrings #-}

import qualified Data.ByteString.Char8 as C
import Control.Monad
  ( replicateM
  , replicateM_
  )
import Data.Int (Int64)

data Segment = Segment { l :: Int
                       , r :: Int
                       , cost :: Int64
                       }

solve :: [Segment] -> [Int64]
solve segments = iter segments 2000000000 inf 0 inf inf
  where
    inf = 1000000000000000 :: Int64
    iter [] _ _ _ _ _ = []
    iter ((Segment l r cost):rem) lm lc rm rc singleCost =
      let
        lmNew = if l < lm then l else lm
        rmNew = if r > rm then r else rm
        lcNew = if lmNew < lm then cost else (if l == lmNew then min cost lc else lc)
        rcNew = if rmNew > rm then cost else (if r == rmNew then min cost rc else rc)
        singleCostNew = min (if l == lmNew && r == rmNew then cost else inf) (if lmNew == lm && rmNew == rm then singleCost else inf)
      in (min (lcNew + rcNew) singleCostNew):(iter rem lmNew lcNew rmNew rcNew singleCostNew)

main :: IO ()
main = do
  tc <- readInt <$> C.getLine
  replicateM_ tc gao
  where
    readInt s = let Just (i, _) = C.readInt s in i
    convert :: [Int] -> Segment
    convert (x:(y:(z:[]))) = Segment x y (fromIntegral z)
    convert _ = error "wrong data format"
    readSegment :: IO Segment
    readSegment = do
      ns <- (map readInt . C.words) <$> C.getLine
      return $ convert ns
    gao = do
      n <- readInt <$> C.getLine
      segments <- replicateM n readSegment
      let
        results = solve segments
      C.putStrLn $ C.intercalate "\n" $ map (C.pack . show) results

module Main (main) where

import qualified Data.ByteString.Char8 as B
import Data.Char (isSpace)
import Data.List (unfoldr)

type SegmentBounds = (Integer, Integer)
type CoinsNumber = Integer
type Segment = (SegmentBounds, CoinsNumber)

howManyCoinsWillVasyaSpendForEveryPrefixOf :: [Segment] -> [CoinsNumber]
howManyCoinsWillVasyaSpendForEveryPrefixOf segments = results
    where
        (bounds, costs) = unzip segments
        (left_bounds, right_bounds) = unzip bounds

        expenses_by_params (best_left, left_cost, best_right, right_cost, leftright_are_same, same_cost)
            | leftright_are_same = same_cost
            | otherwise = left_cost + right_cost

        results = go (maximum left_bounds + 1, 0, minimum right_bounds - 1, 0, False, 0) segments
        go params [] = []
        go params (segment:next_segments) = current_expenses : go new_params next_segments
            where
                (best_left, left_cost, best_right, right_cost, leftright_are_same, same_cost) = params
                prev_expenses = expenses_by_params params
                ((l, r), c) = segment
                new_params
                    | l <= best_left && r >= best_right && (c < prev_expenses || l < best_left || r > best_right)
                        = (l, new_left_cost, r, new_right_cost, True, c)
                    | l < best_left || (l <= best_left && c + right_cost < prev_expenses)
                        = (l, c, best_right, right_cost, False, 0)
                    | r > best_right || (r >= best_right && c + left_cost < prev_expenses)
                        = (best_left, left_cost, r, c, False, 0)
                    | otherwise
                        = (best_left, new_left_cost, best_right, new_right_cost, leftright_are_same, same_cost)
                        where
                            new_left_cost = if l < best_left || (l <= best_left && c < left_cost) then c else left_cost
                            new_right_cost = if r > best_right || (r >= best_right && c < right_cost) then c else right_cost
                current_expenses = expenses_by_params new_params

-- IO section --

main :: IO ()
main = B.interact processInput

processInput :: B.ByteString -> B.ByteString
processInput = B.concat . map processTest . groupInputByTests

processTest :: B.ByteString -> B.ByteString
processTest test_input = output
    where
        segments = map readSegment $ B.lines test_input
        result = howManyCoinsWillVasyaSpendForEveryPrefixOf segments
        output = B.unlines $ map bshow result
        bshow = B.pack . show

groupInputByTests :: B.ByteString -> [B.ByteString]
groupInputByTests = map B.unlines . groupInputLines . drop 1 . B.lines
    where
        groupInputLines = unfoldr takeNextTestLines

        takeNextTestLines [] = Nothing
        takeNextTestLines (l:ls) = Just $ splitAt (readInt l) ls

readSegment :: B.ByteString -> Segment
readSegment string = ((l, r), c)
    where
        [l, r, c] = readIntegers string

readIntegers :: B.ByteString -> [Integer]
readIntegers = unfoldr (B.readInteger . B.dropWhile isSpace)

readInteger :: B.ByteString -> Integer
readInteger s = r
    where [r] = readIntegers s

readInt :: B.ByteString -> Int
readInt = fromInteger . readInteger

module Main (main) where

import qualified Data.ByteString.Char8 as B
import Data.Char (isSpace)
import Data.List (unfoldr)

type SegmentBounds = (Integer, Integer)
type CoinsNumber = Integer
type Segment = (SegmentBounds, CoinsNumber)

howManyCoinsWillVasyaSpendForEveryPrefixOf :: [Segment] -> [CoinsNumber]
howManyCoinsWillVasyaSpendForEveryPrefixOf segments = results
    where
        (bounds, costs) = unzip segments
        (left_bounds, right_bounds) = unzip bounds

        expenses_by_params (best_left, left_cost, best_right, right_cost, leftright_are_same)
            | leftright_are_same = left_cost
            | otherwise = left_cost + right_cost

        results = go (maximum left_bounds + 1, 0, minimum right_bounds - 1, 0, False) segments
        go params [] = []
        go params (segment:next_segments) = current_expenses : go new_params next_segments
            where
                (best_left, left_cost, best_right, right_cost, leftright_are_same) = params
                prev_expenses = expenses_by_params params
                ((l, r), c) = segment
                new_params
                    | l <= best_left && r >= best_right && (c < prev_expenses || l < best_left || r > best_right)
                        = (l, c, r, c, True)
                    | l < best_left || (l <= best_left && c + right_cost < prev_expenses)
                        = (l, c, best_right, right_cost, False)
                    | r > best_right || (r >= best_right && c + left_cost < prev_expenses)
                        = (best_left, left_cost, r, c, False)
                    | otherwise
                        = params
                current_expenses = expenses_by_params new_params

-- IO section --

main :: IO ()
main = B.interact processInput

processInput :: B.ByteString -> B.ByteString
processInput = B.concat . map processTest . groupInputByTests

processTest :: B.ByteString -> B.ByteString
processTest test_input = output
    where
        segments = map readSegment $ B.lines test_input
        result = howManyCoinsWillVasyaSpendForEveryPrefixOf segments
        output = B.unlines $ map bshow result
        bshow = B.pack . show

groupInputByTests :: B.ByteString -> [B.ByteString]
groupInputByTests = map B.unlines . groupInputLines . drop 1 . B.lines
    where
        groupInputLines = unfoldr takeNextTestLines

        takeNextTestLines [] = Nothing
        takeNextTestLines (l:ls) = Just $ splitAt (readInt l) ls

readSegment :: B.ByteString -> Segment
readSegment string = ((l, r), c)
    where
        [l, r, c] = readIntegers string

readIntegers :: B.ByteString -> [Integer]
readIntegers = unfoldr (B.readInteger . B.dropWhile isSpace)

readInteger :: B.ByteString -> Integer
readInteger s = r
    where [r] = readIntegers s

readInt :: B.ByteString -> Int
readInt = fromInteger . readInteger


{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}

import qualified Data.ByteString.Char8 as B8
import Text.Printf
import Data.Functor ( (<&>) )
import Control.Arrow ((>>>))
import Control.Monad (forM_)
import Data.Maybe (fromJust, isJust)
import Data.Traversable (forM)
import qualified Control.Monad.State.Strict as S
import qualified Data.Map as M
import Control.Monad (foldM_)
import Data.Int

readIntB8 :: B8.ByteString -> Maybe Int
readIntB8 = B8.readInt >>> fmap fst

calcCnts :: B8.ByteString -> M.Map Char Int
calcCnts bs = flip S.execState (M.empty :: M.Map Char Int) $ do
    forM_ (B8.unpack bs) $ \c -> do
        S.modify $ M.insertWith (+) c 1

solve :: Int -> B8.ByteString -> B8.ByteString -> Bool
solve k sa sb = isJust ts
    where
        cntsA = calcCnts sa
        cntsB = calcCnts sb
        ts = flip S.execState (Just 0) $ do
            forM_ ['a' .. 'z'] $ \c -> do
                let ta = M.findWithDefault 0 c cntsA
                let tb = M.findWithDefault 0 c cntsB
                S.modify $ \s -> do
                    vs <- fmap (+ ta) s
                    if vs < tb || (vs - tb) `mod` k /= 0
                        then Nothing
                        else return $ vs - tb

main :: IO ()
main = do
    Just t <- B8.getLine <&> readIntB8
    forM_ [1 .. t] $ \_ -> do
        [n, k] <- B8.getLine <&> B8.words <&> map (readIntB8 >>> fromJust)
        sa <- B8.getLine
        sb <- B8.getLine
        let answer = solve k sa sb
        B8.putStrLn $ if answer then "Yes" else "No"

{-# LANGUAGE Safe #-}
--codelegend orz

import safe Control.Arrow ((>>>))
import Data.Bool
import Data.List

main :: IO ()
main =  interact $  lines >>> drop 1 >>> tcio >>> unlines where
  tcio :: [String] -> [String]
  tcio [] = []
  tcio (nk : a : b : rest) =  solve  (last $ linetois nk) a b : tcio rest
  linetoi = read; linetois = (map linetoi) . words; linestoiss = map linetois

solve :: Int -> String -> String -> String
solve k as bs = (bool "Yes" "No") $ (==Nothing) $ foldl foo (Just 0) $ zipWith (-) (freq as) (freq bs) where
  freq xs = [length $ filter (==c) xs | c <-['a'..'z']]
  foo Nothing _ = Nothing
  foo (Just acc) x | acc + x < 0 = Nothing
                   | (acc + x) `mod` k /= 0 = Nothing
                   | otherwise = Just (acc + x)

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

main :: IO ()
main =
  interact $ lines >>> drop 1 >>> process >>> map (bool "No" "Yes") >>> unlines
  where
    readInt = C.readInt >>> fromMaybe undefined >>> fst

process :: [String] -> [Bool]
process [] = []
process (nk:a:b:xs) = solve k a b : process xs
  where
    k = words >>> last >>> read $ nk

solve :: Int -> String -> String -> Bool
solve k a b = (== Just 0) . foldl f (Just 0) $ zipWith (-) (freq a) (freq b)
  where
    freq s = [length (filter (== c) s) | c <- ['a' .. 'z']]
    f Nothing _ = Nothing
    f (Just acc) x
      | acc + x < 0 = Nothing
      | (acc + x) `mod` k /= 0 = Nothing
      | otherwise = Just (acc + x)


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

main = getLine >>= flip replicateM_ test . read

test = do
  n <- read <$> getLine
  s <- getLine
  putStrLn $ replicate n (s !! (n - 1))

import Control.Monad

solve :: String -> String
solve [c] = [c]
solve (c0:c1:cs) = c0 : solve cs
solve _ = error "invalid input"

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _nStr <- getLine
    getLine >>= putStrLn . solve

import Control.Monad
import Data.List (intercalate)

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    n <- readLn
    s <- getLine
    let res = replicate n (s !! (n - 1))
    putStrLn res

import System.IO
-- import qualified Data.Set as Set

factor k =
    let arr = [ x | x <- takeWhile ((<=k).(^2)) [2..], k `mod` x == 0]
    in if null arr then k else head arr

main = do
    hSetBuffering stdin (BlockBuffering (Just 4096))
    hSetBuffering stdout (BlockBuffering (Just 4096))
    contents <- lines <$> getContents
    let arr = tail contents
    sequence $ solve arr

-- solve :: [[Char]] -> [IO [()]]
solve [] = []
solve (_:arr:xs) =
    let go [a]     = [a]
        go (a:_:x) = a:go x
    in putStrLn (go arr):solve xs

import Control.Monad

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    n <- read <$> getLine
    str <- getLine
    let x = str !! (n - 1)
    putStrLn $ replicate n x

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

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

solve :: String -> String
solve (xs:s)
    | null s = [xs]
    | otherwise = do
        let t = tail s
        [xs] ++ solve(t)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        getLine
        s <- getLine
        putStrLn $ solve s


{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
-- import Control.Arrow
import Data.List
-- import Data.Maybe
import Data.Ord
-- import Data.Char
-- import Data.Function
-- import qualified Data.Map as Map
-- import qualified Data.Set as Set
import qualified Data.Foldable as F
import qualified Data.Traversable as T
-- import qualified Data.ByteString.Char8 as BS
import Text.Printf
import Debug.Trace

data Ball = Ball{index :: !Int, pos :: !Double, velocity :: !Double, weight :: !Double}
  deriving Show

{-# SPECIALIZE for_ :: Char -> Char -> (Char -> IO ()) -> IO () #-}
{-# SPECIALIZE for_ :: Int -> Int -> (Int -> IO ()) -> IO () #-}
for_ :: (Monad m, Ord a, Enum a) => a -> a -> (a -> m ()) -> m ()
for_ i n f = loop i where
  loop i | i <= n    = f i >> loop (succ i)
         | otherwise = return ()

main :: IO ()
main = do
  let readData :: (Read a) => IO [a]
      readData = map read . words <$> getLine
      eps = 1e-9 :: Double
      inf = 10 ^ 300 :: Double
  n : time : _ <- readData :: IO [Double]
  balls <- fmap (sortBy (comparing pos)) . T.for [1 .. fromEnum n] $ \i -> do
    x : v : m : _ <- readData :: IO [Double]
    return $ Ball i x v m
  let minTime bs = do
        (Ball _ x1 v1 _, Ball _ x2 v2 _) <- zip bs (tail bs)
        guard $ v1 - v2 > eps
        return $! (x2 - x1) / (v1 - v2)
      printAll bs = putStrLn $ do
        Ball _ x _ _ <- sortBy (comparing index) bs
        printf "%.16f\n" x
      move t bs = do
        b <- bs
        return $ b{pos = pos b + velocity b * t}
      simulate t bs
        | t < eps   = printAll bs
        | otherwise = case minTime bs of
            ts@(_ : _) -> do
              let t' = minimum ts
              if t >= t' + eps
                then do
                     simulate (t - t') $ do
                       let sentinel = Ball 0 inf 0 0
                           bss = init . tails . ([sentinel] ++) . (++ [sentinel])$ move t' bs
                       (Ball _ xp vp mp, b@(Ball _ x v m), Ball _ xn vn mn) <- zip3 (bss !! 0) (bss !! 1) (bss !! 2)
                       return $ case () of
                                  _ | abs (xn - x) < eps -> b{velocity = ((m - mn) * v + 2 * mn * vn) / (m + mn)}
                                    | abs (x - xp) < eps -> b{velocity = ((m - mp) * v + 2 * mp * vp) / (mp + m)}
                                    | otherwise          -> b
                else simulate 0 $ move t bs
            _          -> simulate 0 $ move t bs
  simulate time balls
{-
2 9
3 4 5
0 7 8

2 2
3 7 5
0 7 8
-}

import List
main = interact (ans)
ans theInput = answer where
	theLines = lines theInput
	line0 = words $ head $ theLines
	n = (read::String->Int)(line0 !! 0)
	t = (read::String->Float)(line0 !! 1)
	p0 = zip (map (map (read::String->Float)) $ map words $ tail theLines) [1..n]
	p = sort p0
	collision [_] = []
	collision (x:y:xs) = (meet x y):collision (y:xs)
	meet ([x,y,_],_) ([u,v,_],_) = if y<=v then 101 else (u-x)/(y-v)
	nextCollisionTime xs = foldr1 min (collision xs)
	nextPosition u [] = []
	nextPosition u (([x,v,m],i):xs) = ([x+v*u,v,m],i) : (nextPosition u xs)
	newSpeed v1 m1 v2 m2 = ((m1-m2)*v1+2*m2*v2)/(m1+m2)
	nextSpeed [] = []
	nextSpeed [x] = [x]
	nextSpeed (([x1,v1,m1],i1):([x2,v2,m2],i2):xs) = if x1/=x2
		then ([x1,v1,m1],i1):(nextSpeed (([x2,v2,m2],i2):xs))
		else ([x1,v3,m1],i1):([x2,v4,m2],i2):(nextSpeed xs) where
			v3 = newSpeed v1 m1 v2 m2
			v4 = newSpeed v2 m2 v1 m1
	nextPair (x,y) = if x==t then (101,[]) else (x+dt,nextSpeed $ nextPosition dt y) where
		dt = min (t-x) (nextCollisionTime y)
	change = takeWhile ((/=101).fst) (iterate nextPair (0,p))
	answer = unlines $ map (show.head.snd) (sort [(x,y)|(y,x)<-(snd $ last change)])


main = interact $ show . solve . map read . words
solve [h,l] = (l * l - h * h) / (2 * h)

readNumbers :: String -> [Double]
readNumbers = map read . words

main = do
    input <- getLine
    let [h, l] = readNumbers input
    print $ (l*l - h*h) / (2 * h)

main = interact $ show . solve . map read . words
solve [h,l] = l * tan gamma where
  alpha = atan (l/h)
  beta = pi/2 - alpha
  gamma = alpha - beta


{-# OPTIONS_GHC -O2 #-}

import qualified Data.ByteString.Char8 as DBC
import qualified Data.ByteString.Builder as DBB
import qualified Control.Monad as CM
import qualified Data.List as DL
import qualified Data.Set as DS
import System.IO hiding (getLine,print)
import Prelude hiding (getLine)
import Data.Char
import Data.Array
import Debug.Trace
solve :: IO ()
solve = do
  ~[n] <- readv
  ss <- getLine
  ts <- getLine
  let
    occs = accumArray (flip (:)) [] ('a','z') $ reverse $ zip ss [0..]
    ost = DS.fromAscList [0..n-1]
    ans = recurse occs ost 0 maxBound ts
  printv [if ans==maxBound then -1 else ans]

recurse :: Data.Array.Array Char [Int] -> DS.Set Int -> Int -> Int -> [Char] -> Int
recurse _ _ _ ans [] = ans
recurse occs ost eqcost ans (t:ts) = let
  beater = take 1 $ DL.sort $ concat [take 1 (occs ! ch) | ch <-['a'..t],ch/=t]
  ans1 = if null beater then ans else min ans (eqcost + rank (head beater))
  rank r = DS.findIndex r ost
  in case occs ! t of
    [] -> ans1
    (x:xs) -> recurse (occs // [(t,xs)]) (DS.delete x ost) (eqcost + rank x) ans1 ts

printv :: [Int] -> IO ()
printv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\n'

readv :: IO [Int]
readv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)

getLine :: IO [Char]
getLine = DL.dropWhileEnd isSpace . DBC.unpack <$> DBC.getLine

main :: IO ()
main = do
  ~[nTc] <- readv
  CM.replicateM_ nTc solve

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

import qualified Data.ByteString.Char8 as DBC
import qualified Data.ByteString.Builder as DBB
import qualified Control.Monad as CM
import qualified Data.List as DL
import qualified Data.Set as DS
import System.IO hiding (getLine,print)
import Prelude hiding (getLine)
import Data.Char
import Data.Array
import Debug.Trace
solve :: IO ()
solve = do
  ~[n] <- readv
  ss <- getLine
  ts <- getLine
  let
    occs = accumArray (flip (:)) [] ('a','z') $ reverse $ zip ss [0..]
    ost = DS.fromAscList [0..n-1]
    ans = recurse occs ost 0 maxBound ts
  printv [if ans==maxBound then -1 else ans]

recurse :: Data.Array.Array Char [Int] -> DS.Set Int -> Int -> Int -> [Char] -> Int
recurse _ _ _ ans [] = ans
recurse !occs !ost !eqcost !ans (t:ts) = let
  beater = minimum $ maxBound:[head occ | ch <-['a'..t], ch/=t, let occ=occs!ch, not $ null occ]
  ans1 = if beater==maxBound then ans else min ans (eqcost + rank beater)
  rank r = DS.findIndex r ost
  in case occs ! t of
    [] -> ans1
    (x:xs) -> recurse (occs // [(t,xs)]) (DS.delete x ost) (eqcost + rank x) ans1 ts

printv :: [Int] -> IO ()
printv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\n'

readv :: IO [Int]
readv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)

getLine :: IO [Char]
getLine = DL.dropWhileEnd isSpace . DBC.unpack <$> DBC.getLine

main :: IO ()
main = do
  ~[nTc] <- readv
  CM.replicateM_ nTc solve

{-# OPTIONS_GHC -O2 #-}

import qualified Data.ByteString.Char8 as DBC
import qualified Data.ByteString.Builder as DBB
import qualified Control.Monad as CM
import qualified Data.List as DL
import qualified Data.Set as DS
import System.IO hiding (getLine,print)
import Prelude hiding (getLine)
import Data.Char
import Data.Array
import Debug.Trace
solve :: IO ()
solve = do
  ~[n] <- readv
  ss <- getLine
  ts <- getLine
  let
    occs = accumArray (flip (:)) [] ('a','z') $ reverse $ zip ss [0..]
    ost = DS.fromAscList [0..n-1]
    ans = recurse occs ost 0 maxBound ts
  printv [if ans==maxBound then -1 else ans]

recurse :: Data.Array.Array Char [Int] -> DS.Set Int -> Int -> Int -> [Char] -> Int
recurse _ _ _ ans [] = ans
recurse occs ost eqcost ans (t:ts) = let
  beater = minimum $ maxBound:[head occ | ch <-['a'..t], ch/=t, let occ=occs!ch, not $ null occ]
  ans1 = if beater==maxBound then ans else min ans (eqcost + rank beater)
  rank r = DS.findIndex r ost
  in case occs ! t of
    [] -> ans1
    (x:xs) -> recurse (occs // [(t,xs)]) (DS.delete x ost) (eqcost + rank x) ans1 ts

printv :: [Int] -> IO ()
printv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\n'

readv :: IO [Int]
readv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)

getLine :: IO [Char]
getLine = DL.dropWhileEnd isSpace . DBC.unpack <$> DBC.getLine

main :: IO ()
main = do
  ~[nTc] <- readv
  CM.replicateM_ nTc solve

{-# OPTIONS_GHC -O2 #-}

import qualified Data.ByteString.Char8 as DBC
import qualified Data.ByteString.Builder as DBB
import qualified Control.Monad as CM
import qualified Data.List as DL
import qualified Data.IntMap.Strict as DIM
import qualified Data.Set as DS
import Data.Bool
import System.IO hiding (getLine,print)
import Prelude hiding (getLine)
import Data.Char
import Data.Function (on)

recurse :: DIM.IntMap [Int] -> DS.Set Int -> Int -> Int -> [Char] -> Int
recurse _ _ _ ans [] = ans
recurse occs occset taken ans (t:ts) = let
  beaters = filter (not.null.snd) $ takeWhile ((fromEnum t>).fst) $ DIM.assocs occs
  beater = DL.minimumBy (compare `on` (head.snd)) beaters  -- if not null beaters
  ans'{-'-} = if null beaters then ans else min ans (taken + prevCount (head $ snd beater))
  prevCount r = DS.findIndex r occset
  (matcherMaybe,occs'{-'-}) = DIM.updateLookupWithKey (\_ -> Just .drop 1) (fromEnum t) occs
  cost matcher = prevCount matcher
  in
    case matcherMaybe of
      (Just (m:ms)) -> recurse occs'{-'-} (DS.delete m occset) (taken+cost m)  ans'{-'-} ts
      _ -> ans'{-'-}

solve :: IO ()
solve = do
  ~[n] <- readv
  ss <- getLine
  ts <- getLine
  let
    occs = DIM.fromListWith (++) (reverse $ zip (fromEnum <$> ss) (pure <$> [0..]))
    seg = DS.fromAscList [0..n-1]
    ans = recurse occs seg 0 maxBound ts
  printv [if ans==maxBound then -1 else ans]

printv :: [Int] -> IO ()
printv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\n'

readv :: IO [Int]
readv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)

getLine :: IO [Char]
getLine = DL.dropWhileEnd isSpace . DBC.unpack <$> DBC.getLine

main :: IO ()
main = do
  ~[nTc] <- readv
  CM.replicateM_ nTc solve

{-# LANGUAGE BangPatterns #-}
import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
import Data.Array.Unboxed
import qualified Data.Map.Strict as M

mainFun :: SP Builder
mainFun = do
  ~[q] <- getInts 1
  fmap mconcat $ replicateM q $ do
    ~[n] <- getInts 1
    ~[s, t] <- map P.unpack <$> getNext 2
    let
      initOccs :: Array Char [Int]
      initOccs = accumArray (flip (:)) [] ('a', 'z')
        $ zip (reverse s) [n, n-1..]

      initOST :: M.Map Int Char
      initOST = M.fromAscList $ zip [1..] s

      ans = solve initOccs initOST t maxBound 0

      solve :: Array Char [Int] -> M.Map Int Char -> [Char] -> Int -> Int
        -> Int
      solve occs ost tt !currBest !used = case  tt  of
        [] -> currBest
        _ | currBest <= used  -> currBest -- not really important
        (c : ntt) -> let
          winOpts = concatMap (\lc -> take 1 (occs ! lc)) ['a' .. pred c]
          nBest = case  winOpts  of
            [] -> currBest
            _  -> min currBest $ used + M.findIndex (foldl' min n winOpts) ost
          in  case  occs ! c  of
          [] -> nBest
          (w : ws) -> let
            noccs = occs // [(c, ws)]
            nost = M.delete w ost
            nused = used + M.findIndex w ost
            in  solve noccs nost ntt nBest nused
    pure $ putInts [if  ans == maxBound  then  0-1  else  ans]

type SP = State [P.ByteString]

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

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

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun $ P.words inp
  P.putStr $ toLazyByteString outp

{-# OPTIONS_GHC -O2 #-}

import qualified Data.ByteString.Char8 as DBC
import qualified Data.ByteString.Builder as DBB
import qualified Control.Monad as CM
import qualified Data.List as DL
import qualified Data.Set as DS
import System.IO hiding (getLine,print)
import Prelude hiding (getLine)
import Data.Char
import Data.Array

solve :: IO ()
solve = do
  ~[n] <- readv
  ss <- getLine
  ts <- getLine
  let
    occs = accumArray (flip (:)) [] ('a','z') $ reverse $ zip ss [0..]
    ost = DS.fromAscList [0..n-1]
    ans = recurse occs ost 0 maxBound ts
  printv [if ans==maxBound then -1 else ans]

recurse :: Data.Array.Array Char [Int] -> DS.Set Int -> Int -> Int -> [Char] -> Int
recurse _ _ _ ans [] = ans
recurse occs ost eqcost ans (t:ts) = let
  beater = take 1 $ concat [take 1 (occs ! ch) | ch <-['a'..t],ch/=t]
  ans1 = if null beater then ans else min ans (eqcost + rank (head beater))
  rank r = DS.findIndex r ost
  in case occs ! t of
    [] -> ans1
    (x:xs) -> recurse (occs // [(t,xs)]) (DS.delete x ost) (eqcost + rank x) ans1 ts

printv :: [Int] -> IO ()
printv xs = DBB.hPutBuilder stdout $ mconcat [DBB.intDec x <> DBB.char8 ' ' | x <- xs] <> DBB.char8 '\n'

readv :: IO [Int]
readv = map (maybe 0 fst . DBC.readInt) <$> (DBC.words <$> DBC.getLine)

getLine :: IO [Char]
getLine = DL.dropWhileEnd isSpace . DBC.unpack <$> DBC.getLine

main :: IO ()
main = do
  ~[nTc] <- readv
  CM.replicateM_ nTc solve


import Control.Applicative
import Data.List

main = do
  n <- read <$> getLine
  nums <- map read <$> words <$> getLine
  let _ = nums :: [Int]
      sorted = sort nums
      answer = if all (==1) sorted
                 then (replicate (n-1) 1) ++ [2]
                 else take n $ (1:sorted)
  putStrLn $ intercalate " " $ map show $ answer

import qualified Data.ByteString.Lazy.Char8 as C
import IO
import Data.Maybe
import Data.List

readInt = fst . fromJust . C.readInt
readIntList = map readInt . C.words

solve a
   | corner    = take (n-1) (repeat 1) ++ [2]
   | otherwise = (1:) . take (n-1) $ sort a
   where n      = length a
         corner = all (==1) a

main = do
   input <- fmap (map (C.takeWhile (/='\r')) . C.lines) $ C.hGetContents stdin
   putStrLn . unwords . map show . solve . readIntList $ input !! 1

-- vim: set expandtab:

import Data.List
main = interact $ unwords.map show. gao. map read. tail. words
gao x = sort.reverse.ch.reverse.sort $ x
ch (x:s) | x == 1 = 2:s | 1 > 0 = 1:s

import List

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

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

solve :: [Int] -> [Int]
solve xs
  | maximum xs > 1  =  1:(init (sort xs))
  | otherwise       =  sort (2:(tail xs))

printAns :: [Int] -> IO ()
printAns [] = return ()
printAns (x:xs) = putStr (show x ++ " ") >> printAns xs

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

import Data.List

solve xs | all (1==) xs = tail xs ++ [2]
         | otherwise    = [1] ++ (init $ sort xs)

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

module Main where

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

import Data.Time.Calendar

main = interact (unlines . solve . (map read) . words . (!! 1) . lines)

solve :: [Int] -> [String]
solve arr  = result where
    result = [intercalate " " $ map show ansInt]
    ansInt = sort $ (if last sArr == 1 then 2 else 1) : init sArr
    sArr = sort arr

module Main (main) where

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

joins :: [String] -> String
joins [] = ""
joins [x] = x
joins (x:xs) = x ++ " " ++ (joins xs)

toString::[Int] -> String
--toString = (dropWhile (== ' ')) . (concatMap (\x -> " " ++ (show x)))
toString list = intercalate " " $ map show list

solve::[Int] -> [Int]
solve list = answerList
    where sortedList = sort list
          answerList = sort $ (if last sortedList == 1 then 2 else 1) : init sortedList

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

import Data.List(sort)
import Control.Applicative

main = do n <- read <$> getLine
          xs <- map read <$> words <$> getLine
          putStrLn $ unwords $ map show $ solve n xs

solve :: Int -> [Int] -> [Int]
solve n xs = if all (1==) xs then (take (n-1) $ xs)++[2]
                             else 1:(take (n-1) $ sort xs)

import Data.List (sort)
solve :: [Int] -> [Int]
solve xs = sort $ (if last ps > 1 then 1 else 2) : init ps
    where ps = sort xs
main = putStrLn.unwords.map show.solve.map read.tail.words =<< getContents

import Data.List(sort)

main = do
	d <- getContents
	let dd = words d
	let n = read $ head dd::Int
	let xs = map (\x -> read x::Int) (tail dd)
	putStrLn $ unwords $ map show (solve n xs)

solve n xs | all (1==) xs = take (n-1) xs ++ [2]
           | otherwise    = 1:(take (n-1) $ sort xs)

import Control.Applicative
import Data.List

main = do
  n <- read <$> getLine
  nums <- map read <$> words <$> getLine
  let _ = nums :: [Int]
      sorted = sort nums
  putStrLn $ intercalate " " $ map show $ take n $ (1:sorted)

import Data.List(sort)
import Control.Applicative

main = do n <- read <$> getLine
          xs <- map read <$> words <$> getLine
          putStrLn $ unwords $ map show $ solve n xs

solve :: Int -> [Int] -> [Int]
solve n xs = 1:(take (n-1) $ sort xs)

import Data.List (sort)
solve :: [Int] -> [Int]
solve xs = (if last ps > 1 then 1 else 2) : init ps
    where ps = sort xs
main = putStrLn.unwords.map show.solve.map read.tail.words =<< getContents

import Data.List(sort)

main = do
	d <- getContents
	let dd = words d
	let n = read $ head dd::Int
	let xs = map (\x -> read x::Int) (tail dd)
	print $ unwords $ map show (solve n xs)

solve n xs | all (1==) xs = take (n-1) xs ++ [2]
           | otherwise    = 1:(take (n-1) $ sort xs)

module Main where

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

import Data.Time.Calendar

main = interact (unlines . solve . (map read) . words . (!! 1) . lines)

solve :: [Int] -> [String]
solve arr  = result where
    result = [intercalate " " $ map show ansInt]
    ansInt = 1 : init arr
    sArr = sort arr

module Main where

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

import Data.Time.Calendar

main = interact (unlines . solve . (map read) . words . (!! 1) . lines)

solve :: [Int] -> [String]
solve arr  = result where
    result = [intercalate " " $ map show ansInt]
    ansInt = 1 : init sArr
    sArr = sort arr

module Main where

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

import Data.Time.Calendar

main = interact (unlines . solve . (map read) . words . (!! 1) . lines)

solve :: [Int] -> [String]
solve arr  = result where
    result = [intercalate " " $ map show ansInt]
    ansInt = (if last sArr == 1 then 2 else 1) : init sArr
    sArr = sort arr

import qualified Data.ByteString.Lazy.Char8 as C
import IO
import Data.Maybe
import Data.List

readInt = fst . fromJust . C.readInt
readIntList = map readInt . C.words

main = do
   input <- fmap (map (C.takeWhile (/='\r')) . C.lines) $ C.hGetContents stdin
   let n = readInt $ input !! 0
       a = (1:) . take (n-1) . sort . readIntList $ input !! 1
   putStrLn . unwords $ map show a

-- vim: set expandtab:

import List

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

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

solve :: [Int] -> [Int]
solve xs = 1:(init (sort xs))

printAns :: [Int] -> IO ()
printAns [] = return ()
printAns (x:xs) = putStr (show x ++ " ") >> printAns xs

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


import Data.List
import Text.Printf

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

parseFloat :: Double -> String
parseFloat = printf "%.5f"

concatStr :: [String] -> String
concatStr = foldr (++) []

getAnswer :: [Double] -> String
getAnswer xs
	| lengthSol == 3	= "-1"
	| lengthSol == 0	= "0"
	| otherwise	= addNrOfSol ++ (concatStr $ map (++ "\n") $ map parseFloat $ solutions)
		where
			lengthSol  = length solutions
			solutions  = sort $ f xs
			addNrOfSol = (show $ lengthSol) ++ "\n"

f (a : b : c : xs)
	| a == 0 && b == 0 && c == 0	= [0, 0, 0]
	| a == 0 && b == 0 && c /= 0	= []
	| a == 0 && b /= 0		= [-c / b]
	| otherwise			= solve a b c
		where
			solve a b c
				| delta <  0	= []
				| delta == 0	= [ -b / (2 * a) ]
				| delta >  0	= ( -b + sqrt (delta) ) / (2 * a) : [( -b - sqrt (delta) ) / (2 * a)]
					where delta = b * b - 4 * a * c

import Control.Monad (liftM)
import Text.Printf (printf)

solve :: [Integer] -> Maybe [Double]
solve [0, 0, 0]  =  Nothing
solve [0, 0, _]  =  Just []
solve [0, b, c]  =  Just [(-1) * fromIntegral c / fromIntegral b]
solve [a, b, c]
  | d < 0  =  Just []
  | d > 0  =  Just [(-b' - sqrt d') / (2 * a'), (-b' + sqrt d') / (2 * a')]
  | otherwise  =  Just [(-b') / (2 * a')]
  where
    d  =  b^2 - 4*a*c
    [a', b', c', d']  =  map fromIntegral [a, b, c, d]

prints :: Maybe [Double] -> IO ()
prints Nothing     =  print (-1)
prints (Just [])   =  print 0
prints (Just [x])  =  printf "1\n%.6f\n" x
prints (Just [x,y])
  | x < y  =  printf "2\n%.6f\n%.6f\n" x y
  | otherwise  =  printf "2\n%.6f\n%.6f\n" y x

main :: IO ()
main  =  liftM (map read . words) getLine >>= prints . solve

module Main where

import Text.Printf
import Control.Monad
import Data.List

run :: [Double] -> (Int, [Double])
run [a,b,c] =
    let d = b^2 - 4*a*c
    in case d of
       _ | abs a < 1e-308 -> if abs b > 1e-308 then (1,[-c/b]) else (if c/=0 then 0 else -1,[])
       _ | d < 0 -> (0, [])
       _ | d == 0 -> let root = (-b)/(2*a) in  (1, [if root == 0 then 0 else root])
       _  -> let roots = map (\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d]
             in (2,  sort roots)

main =  do
    (n, roots) <- getLine >>= return . run . map (\x -> fromIntegral $ (read x::Int)) . take 3 . words
    print n
    mapM_ (printf "%.15f\n") roots

module Main where

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

run :: [Double] -> (Int, [Double])
run [a,b,c] =
    let d = b^2 - 4*a*c
    in case d of
       _ | a < 1e-308 -> (-1,[])
       _ | d < 0 -> (0, [])
       _ | d == 0 -> let root = (-b)/(2*a) in  (1, [if root == 0 then 0 else root])
       _  -> let roots = map (\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d]
             in (2,  sort roots)

main =  do
    (n, roots) <- getLine >>= return . run . map (\x -> read x::Double) . take 3 . words
    print n
    mapM_ (printf "%.8f\n") roots

module Main where

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

run :: [Double] -> (Int, [Double])
run [a,b,c] =
    let d = b^2 - 4*a*c
    in case d of
       _ | abs a < 1e-38 -> if abs b> 1e-38 then (1,[-c/b]) else (-1,[])
       _ | d < 0 -> (0, [])
       _ | d == 0 -> let root = (-b)/(2*a) in  (1, [if root == 0 then 0 else root])
       _  -> let roots = map (\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d]
             in (2,  sort roots)

main =  do
    (n, roots) <- getLine >>= return . run . map (\x -> fromIntegral $ (read x::Int)) . take 3 . words
    print n
    mapM_ (printf "%.15f\n") roots

module Main where

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

run :: [Double] -> (Int, [Double])
run [a,b,c] =
    let d = b^2 - 4*a*c
    in case d of
       _ | d < 0 -> (0, [])
       _ | d ==0 -> (1, [(-b)/ (2*a)])
       _  -> (2, sort $ map (\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d])

main =  do
    (n, roots) <- getLine >>= return . run . map (\x -> read x::Double) . take 3 . words
    print n
    mapM_ (printf "%.8f\n") roots

module Main where

import Text.Printf
import Control.Monad
import Data.List

run :: [Double] -> (Int, [Double])
run [a,b,c] =
    let d = b^2 - 4*a*c
    in case d of
       _ | abs a < 1e-308 -> if abs b > 1e-308 then (1,[-c/b]) else (-1,[])
       _ | d < 0 -> (0, [])
       _ | d == 0 -> let root = (-b)/(2*a) in  (1, [if root == 0 then 0 else root])
       _  -> let roots = map (\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d]
             in (2,  sort roots)

main =  do
    (n, roots) <- getLine >>= return . run . map (\x -> fromIntegral $ (read x::Int)) . take 3 . words
    print n
    mapM_ (printf "%.15f\n") roots

import Control.Monad (liftM)
import Text.Printf (printf)

solve :: [Integer] -> Maybe [Double]
solve [0, 0, 0]  =  Nothing
solve [0, 0, _]  =  Just []
solve [0, b, c]  =  Just [(-1) * fromIntegral c / fromIntegral b]
solve [a, b, c]
  | d < 0  =  Just []
  | d > 0  =  Just [(-b' - sqrt d') / (2 * a'), (-b' + sqrt d') / (2 * a')]
  | otherwise  =  Just [(-b') / (2 * a')]
  where
    d  =  b^2 - 4*a*c
    [a', b', c', d']  =  map fromIntegral [a, b, c, d]

prints :: Maybe [Double] -> IO ()
prints Nothing     =  print (-1)
prints (Just [])   =  print 0
prints (Just [x])  =  printf "1\n%.6f\n" x
prints (Just [x,y])  =  printf "2\n%.6f\n%.6f\n" x y

main :: IO ()
main  =  liftM (map read . words) getLine >>= prints . solve

import Control.Monad (liftM)
import Text.Printf (printf)

solve :: [Int] -> Maybe [Double]
solve [0, 0, 0]  =  Nothing
solve [0, 0, _]  =  Just []
solve [0, b, c]  =  Just [(-1) * fromIntegral c / fromIntegral b]
solve [a, b, c]
  | d < 0  =  Just []
  | d > 0  =  Just [(-b' - sqrt d') / (2 * a'), (-b' + sqrt d') / (2 * a')]
  | otherwise  =  Just [(-b') / (2 * a')]
  where
    d  =  b^2 - 4*a*c
    [a', b', c', d']  =  map fromIntegral [a, b, c, d]

prints :: Maybe [Double] -> IO ()
prints Nothing     =  print (-1)
prints (Just [])   =  print 0
prints (Just [x])  =  printf "1\n%.6f\n" x
prints (Just [x,y])  =  printf "2\n%.6f\n%.6f\n" x y

main :: IO ()
main  =  liftM (map read . words) getLine >>= prints . solve

import Data.List
import Text.Printf

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

parseFloat :: Double -> String
parseFloat = printf "%.5f"

concatStr :: [String] -> String
concatStr = foldr (++) []

getAnswer :: [Double] -> String
getAnswer xs
	| lengthSol == 3	= "-1"
	| lengthSol == 0	= "0"
	| otherwise	= addNrOfSol ++ (concatStr $ map (++ "\n") $ map parseFloat $ solutions)
		where
			lengthSol  = length solutions
			solutions  = sort $ f xs
			addNrOfSol = (show $ lengthSol) ++ "\n"

f (a : b : c : xs)
	| a == 0 && b == 0 && c == 0	= [0, 0, 0]
	| a == 0 && b == 0 && c /= 0	= []
	| a == 0 && b /= 0		= [-c / b]
	| otherwise			= solve a b c
		where
			solve a b c
				| delta <  0	= []
				| delta == 0	= [ -b / 2 * a ]
				| delta >  0	= ( -b + sqrt (delta) ) / (2 * a) : [( -b - sqrt (delta) ) / (2 * a)]
					where delta = b * b - 4 * a * c

module Main where

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

run :: [Double] -> (Int, [Double])
run [a,b,c] =
    let d = b^2 - 4*a*c
    in case d of
       _ | a < 1e-20 -> (-1,[])
       _ | d < 0 -> (0, [])
       _ | d ==0 -> (1, [(-b)/ (2*a)])
       _  -> let roots = map (\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d]
             in (2,  sort roots)

main =  do
    (n, roots) <- getLine >>= return . run . map (\x -> read x::Double) . take 3 . words
    print n
    mapM_ (printf "%.8f\n") roots

module Main where

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

run :: [Double] -> (Int, [Double])
run [a,b,c] =
    let d = b^2 - 4*a*c
    in case d of
       _ | a < 1e-308 -> (-1,[])
       _ | d < 0 -> (0, [])
       _ | d ==0 -> (1, [(-b)/ (2*a)])
       _  -> let roots = map (\d -> ((-b) + d)/(2*a)) $ zipWith (*) [1, (-1)] $ map sqrt [d,d]
             in (2,  sort roots)

main =  do
    (n, roots) <- getLine >>= return . run . map (\x -> read x::Double) . take 3 . words
    print n
    mapM_ (printf "%.8f\n") roots


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

import Control.Applicative
import Control.Monad
import Data.Array
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Maybe
import Data.Monoid
import Data.Int
import Text.Printf
import GHC.Prim

data Item = Item { itemSum :: !Int64, itemLeftMax :: !Int64, itemRightMax :: !Int64, itemMax :: !Int64 }

instance Monoid Item where
	mempty = Item 0 0 0 0
	mappend (Item as al ar am) (Item bs bl br bm) =
		Item (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)

build list = tree
	where
		n = length list
		tree = listArray (1, 2*n - 1) $ map value [1..n-1] ++ list
		value i = tree ! (2*i) <> tree ! (2*i + 1)

query tree l r = query' (l + n) (r + n)
	where
		n = snd (bounds tree) `div` 2 + 1

		query' l r
			| l > r = mempty
			| odd l = (tree ! l) <> query' (l + 1) r
			| even r = query' l (r - 1) <> (tree ! r)
			| otherwise = query' (l `div` 2) (r `div` 2)

getInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine

main = do
	[n, m, c] ← getInts
	[xs, ps] ← replicateM 2 $ map fromIntegral <$> getInts
	let as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (* fromIntegral c) ps)
	let tree = build $ map (\a → let b = max 0 a in Item a b b b) as

	ranges ← replicateM m $ (\[l, r] → (l - 1, r - 2)) <$> getInts
	let maxs = map (itemMax . uncurry (query tree)) ranges
	printf "%f" $ (fromIntegral $ sum maxs) / (100 :: Double)

import Control.Applicative
import Control.Monad
import Data.Array
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Maybe
import Data.Monoid
import Data.Int
import Text.Printf

data Item = Item { itemSum :: Int64, itemLeft :: Int64, itemRight :: Int64, itemMax :: Int64 } deriving (Show)

instance Monoid Item where
	mempty = Item 0 0 0 0
	mappend (Item as al ar am) (Item bs bl br bm) =
		Item (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)

build l = a
	where
		n = length l
		a = listArray (1, 2*n - 1) $ map f [1..n-1] ++ map g l
		f i = (a ! (2*i)) <> (a ! (2*i + 1))
		g a = Item a b b b
			where b = max 0 a

query tree l r = itemMax $ query' (l + n) (r + n)
	where
		n = snd (bounds tree) `div` 2 + 1
		query' l r | l > r = mempty
		query' l r | odd l = (tree ! l) <> query' (l + 1) r
		query' l r | even r = query' l (r - 1) <> (tree ! r)
		query' l r = query' (l `div` 2) (r `div` 2)

{- getWords = map read . words <$> getLine  -}

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

toInt64 :: B.ByteString -> Int64
toInt64 s = fromIntegral $ toInt s

main = do
	[n, m, c] <- map toInt . B.split 32 <$> B.getLine
	[xs, ps] <- replicateM 2 $ map toInt64 . B.split 32 <$> B.getLine
	let as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (* fromIntegral c) ps)
	let tree = build as
	ranges <- replicateM m $ (\[l, r] -> (l - 1, r - 2)) . map toInt . B.split 32 <$> B.getLine
	let rs = map (\(l, r) -> query tree l r) ranges
	printf "%f" $ (fromIntegral (sum rs) :: Double) / 100

{-# OPTIONS_GHC -O3 -optc-O3 #-}

import Control.Applicative
import Control.Monad
import Data.Array
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Maybe
import Data.Monoid
import Data.Int
import Text.Printf

data Item = Item { itemSum :: Int64, itemLeftMax :: Int64, itemRightMax :: Int64, itemMax :: Int64 } deriving (Show)

instance Monoid Item where
	mempty = Item 0 0 0 0
	mappend (Item as al ar am) (Item bs bl br bm) =
		Item (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)

build list = tree
	where
		n = length list
		tree = listArray (1, 2*n - 1) $ map value [1..n-1] ++ list
		value i = tree ! (2*i) <> tree ! (2*i + 1)

query tree l r = query' (l + n) (r + n)
	where
		n = snd (bounds tree) `div` 2 + 1

		query' l r
			| l > r = mempty
			| odd l = (tree ! l) <> query' (l + 1) r
			| even r = query' l (r - 1) <> (tree ! r)
			| otherwise = query' (l `div` 2) (r `div` 2)

getInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine

main = do
	[n, m, c] <- getInts
	[xs, ps] <- replicateM 2 $ map fromIntegral <$> getInts
	let as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (* fromIntegral c) ps)
	let tree = build $ map (\a -> let b = max 0 a in Item a b b b) as

	ranges <- replicateM m $ (\[l, r] -> (l - 1, r - 2)) <$> getInts
	let maxs = map (itemMax . uncurry (query tree)) ranges
	printf "%f" $ (fromIntegral $ sum maxs) / (100 :: Double)

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

import Control.Applicative
import Control.Monad
import Data.Array
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Maybe
import Data.Monoid
import Data.Int
import Text.Printf

data Item = Item { itemSum :: {-# UNPACK #-} !Int64, itemLeftMax :: {-# UNPACK #-} !Int64, itemRightMax :: {-# UNPACK #-} !Int64, itemMax :: {-# UNPACK #-} !Int64 }

instance Monoid Item where
	mempty = Item 0 0 0 0
	mappend (Item as al ar am) (Item bs bl br bm) =
		Item (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)

build list = tree
	where
		n = length list
		tree = listArray (1, 2*n - 1) $ map value [1..n-1] ++ list
		value i = tree ! (2*i) <> tree ! (2*i + 1)

query tree l r = query' (l + n) (r + n)
	where
		n = snd (bounds tree) `div` 2 + 1

		query' l r
			| l > r = mempty
			| odd l = (tree ! l) <> query' (l + 1) r
			| even r = query' l (r - 1) <> (tree ! r)
			| otherwise = query' (l `div` 2) (r `div` 2)

getInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine

main = do
	[n, m, c] ← getInts
	[xs, ps] ← replicateM 2 $ map fromIntegral <$> getInts
	let as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (* fromIntegral c) ps)
	let tree = build $ map (\a → let b = max 0 a in Item a b b b) as

	ranges ← replicateM m $ (\[l, r] → (l - 1, r - 2)) <$> getInts
	let maxs = map (itemMax . uncurry (query tree)) ranges
	printf "%f" $ (fromIntegral $ sum maxs) / (100 :: Double)

{-# OPTIONS_GHC -O3 -optc-O3 -funbox-strict-fields #-}
{-# LANGUAGE UnicodeSyntax #-}

import Control.Applicative
import Control.Monad
import Data.Array
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Maybe
import Data.Monoid
import Data.Int
import Text.Printf

data Item = Item { itemSum :: !Int64, itemLeftMax :: !Int64, itemRightMax :: !Int64, itemMax :: !Int64 }

instance Monoid Item where
	mempty = Item 0 0 0 0
	mappend (Item as al ar am) (Item bs bl br bm) =
		Item (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)

build list = tree
	where
		n = length list
		tree = listArray (1, 2*n - 1) $ map value [1..n-1] ++ list
		value i = tree ! (2*i) <> tree ! (2*i + 1)

query tree l r = query' (l + n) (r + n)
	where
		n = snd (bounds tree) `div` 2 + 1

		query' l r
			| l > r = mempty
			| odd l = (tree ! l) <> query' (l + 1) r
			| even r = query' l (r - 1) <> (tree ! r)
			| otherwise = query' (l `div` 2) (r `div` 2)

getInts = map (fst . fromJust . C.readInt) . C.words <$> B.getLine

main = do
	[n, m, c] ← getInts
	[xs, ps] ← replicateM 2 $ map fromIntegral <$> getInts
	let as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (* fromIntegral c) ps)
	let tree = build $ map (\a → let b = max 0 a in Item a b b b) as

	ranges ← replicateM m $ (\[l, r] → (l - 1, r - 2)) <$> getInts
	let maxs = map (itemMax . uncurry (query tree)) ranges
	printf "%f" $ (fromIntegral $ sum maxs) / (100 :: Double)

import Control.Applicative
import Control.Monad
import Data.Array
import Data.Monoid

data Item = Item { itemSum :: Int, itemLeft :: Int, itemRight :: Int, itemMax :: Int } deriving (Show)

instance Monoid Item where
	mempty = Item 0 0 0 0
	mappend (Item as al ar am) (Item bs bl br bm) =
		Item (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)

build l = a
	where
		n = length l
		a = listArray (1, 2*n - 1) $ map f [1..n-1] ++ map g l
		f i = (a ! (2*i)) <> (a ! (2*i + 1))
		g a = Item a b b b
			where b = max 0 a

query tree l r = itemMax $ query' (l + n) (r + n)
	where
		n = snd (bounds tree) `div` 2 + 1
		query' l r | l > r = mempty
		query' l r | odd l = (tree ! l) <> query' (l + 1) r
		query' l r | even r = query' l (r - 1) <> (tree ! r)
		query' l r = query' (l `div` 2) (r `div` 2)

getWords = map read . words <$> getLine

main = do
	[n, m, c] <- getWords
	xs <- getWords
	ps <- getWords
	let as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (*c) ps)
	let tree = build as
	ranges <- replicateM m $ (\[l, r] -> (l - 1, r - 2)) . map read . words <$> getLine
	let rs = map (\(l, r) -> query tree l r) ranges
	print $ fromIntegral (sum rs) / 100

import Control.Applicative
import Control.Monad
import Data.Array
import Data.Monoid
import Text.Printf

data Item = Item { itemSum :: Int, itemLeft :: Int, itemRight :: Int, itemMax :: Int } deriving (Show)

instance Monoid Item where
	mempty = Item 0 0 0 0
	mappend (Item as al ar am) (Item bs bl br bm) =
		Item (as + bs) (max al $ as + bl) (max br $ bs + ar) (max (ar + bl) $ max am bm)

build l = a
	where
		n = length l
		a = listArray (1, 2*n - 1) $ map f [1..n-1] ++ map g l
		f i = (a ! (2*i)) <> (a ! (2*i + 1))
		g a = Item a b b b
			where b = max 0 a

query tree l r = itemMax $ query' (l + n) (r + n)
	where
		n = snd (bounds tree) `div` 2 + 1
		query' l r | l > r = mempty
		query' l r | odd l = (tree ! l) <> query' (l + 1) r
		query' l r | even r = query' l (r - 1) <> (tree ! r)
		query' l r = query' (l `div` 2) (r `div` 2)

getWords = map read . words <$> getLine

main = do
	[n, m, c] <- getWords
	xs <- getWords
	ps <- getWords
	let as = zipWith (-) (map (*50) $ zipWith (-) (tail xs) xs) (map (*c) ps)
	let tree = build as
	ranges <- replicateM m $ (\[l, r] -> (l - 1, r - 2)) . map read . words <$> getLine
	let rs = map (\(l, r) -> query tree l r) ranges
	printf "%f" $ (fromIntegral (sum rs) :: Double) / 100


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

import Control.Applicative
import Control.DeepSeq (deepseq)
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.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
-- import Debug.Trace
import System.IO

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

solve = do
  [n, k, d1, d2] :: [Int64] <- map read . words <$> getLine

  let
    os = try <$> [-1, 1] <*> [-1, 1]
      where

        try s1 s2
          | all (\x -> x`mod`3 == 0 && x >= 0 && x <= n) [x1, x2, x3] = Just (x1`div`3, x2`div`3, x3`div`3)
          | otherwise = Nothing
          where
            x1 = k - s1*d2 - s2*2*d1
            x2 = k - s1*d2 + s2*d1
            x3 = k + s1*2*d2 + s2*d1

  putStrLn $
    if n`mod`3 == 0 && not (null $ catMaybes os)
      then "yes"
      else "no"

main = do
  t <- readLn
  replicateM t solve

{-# OPTIONS_GHC -O2 #-}
import Data.Maybe
import Data.Char
import Data.List
import Data.Int
import Data.Bits
import Data.IORef
import Data.Array.IO
import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map              as Map
import qualified Data.Set              as Set
import Text.Printf

getint :: IO Int
getint  = head <$> getints

getints :: IO [Int]
getints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine

solveEach as@[a, b, c] rest
  | need > rest = False
  | remain `mod` 3 == 0 = True
  | otherwise = False
  where mx = maximum as
        need = sum . map (\x -> mx - x) $ as
        remain = rest - need

solve [] _ = False
solve (a:as) rest
  | res1 == True = True
  | otherwise    = solve as rest
  where res1 = solveEach a rest

main = do
  testcase <- getint
  replicateM testcase $ do
    [n, k, d1, d2] <- map fst . mapMaybe BS.readInteger . BS.words <$> BS.getLine
    let rest = n - k
        as = filter filt [f x y | x <- [(0, d1), (d1, 0)], y <- [(0, d2), (d2, 0)]]
        f (d1, 0) (d2, 0) = [d1 + d2, d2, 0]
        f (d1, 0) (0, d2) = [d1, 0, d2]
        f (0, d1) (d2, 0) = if d1 >= d2
                              then [0, d1, d1 - d2]
                              else [d2 - d1, d2, 0]
        f (0, d1) (0, d2) = [0, d1, d1 + d2]
        filt [a, b, c]
          | played > k = False
          | remain `mod` 3 == 0 = True
          | otherwise = False
          where played = a + b + c
                remain = k - played
        res = solve as rest
--    putStrLn (show as)
    if res then putStrLn "yes" else putStrLn "no"

import Control.Monad
ans :: [Integer] -> String
ans [n, k, d1, d2] = if g then "yes" else "no"
 where g = (n `mod` 3 == 0) && (any good [(d1,d2),(abs(d1 - d2), max d1 d2), (d1,d1+d2), (d2,d1+d2)])
       good (a,b) = dd >= 0 && dd `mod` 3 == 0 && max (ee+a) (ee+b) <= n `div` 3
         where dd = k - a - b
               ee = dd `div` 3

solve :: IO String
solve = do
    s <- getLine
    return $ ans $ map read $ words s

main = do
  l1 <- getLine
  let nn = (read l1) :: Int
  replicateM nn solve >>= putStrLn . unlines

{-# LANGUAGE BangPatterns #-}

import Data.Int
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as BS
import Text.Printf (printf)
import Control.Monad
import Control.Applicative

solve :: [Integer] -> Bool
solve [!n, !k, !d1, !d2] =
  n `rem` 3 == 0 && or [check a1 a2 | a1 <- [d1, -d1], a2 <- [d2, -d2]]
  where
    check !a1 !a2 = m `rem` 3 == 0 && x >= 0 && y >= 0 && z >= 0 && x + y + z == k && n - k >= r
      where
        m = k - 2*a1 - a2
        x = m `div` 3
        y = x + a1
        z = y + a2
        w = x `max` y `max` z
        r = w - x + w - y + w - z

main :: IO ()
main = do
  t <- readLn :: IO Int
  ts <- replicateM t $ (map (fst . fromJust . BS.readInteger) . BS.words) <$> BS.getLine :: IO [[Integer]]
  forM_ ts $ \t ->
    putStrLn $ if solve t then "yes" else "no"

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInteger :: B.ByteString -> Integer
readInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
for :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()
for !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)
{-# INLINE for #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  n <- readLn :: IO Int
  xs <- map readInteger.B.words <$> B.getContents
  putStr.unlines $ solve xs

solve :: [Integer] -> [String]
solve (n:k:d1:d2:rest)
  | any ok [(d1,d2),(d1,-d2),(-d1,d2),(-d1,-d2)] = "yes" : solve rest
  | otherwise = "no" : solve rest
   where
     ok (d1, d2) = and [ w1' >= 0, w2' >= 0, w3' >= 0
                       , w1' `mod` 3 == 0, w2' `mod` 3 == 0, w3' `mod` 3 == 0
                       , d + k <= n
                       , (n - d - k) `mod` 3 == 0
                       ]
      where
        w1' = k - 2*d1 -   d2
        w2' = k +   d1 -   d2
        w3' = k +   d1 + 2*d2
        w1 = w1' `div` 3
        w2 = w2' `div` 3
        w3 = w3' `div` 3
        d = 3 * maximum [w1,w2,w3] - sum [w1,w2,w3]

solve _ = []

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

import Control.Applicative
import Control.DeepSeq (deepseq)
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.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
-- import Debug.Trace
import System.IO

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

solve = do
  [n, k, d1, d2] <- getInts

  let
    os = try <$> [-1, 1] <*> [-1, 1]
      where

        try s1 s2
          | all (\x -> x`mod`3 == 0 && x >= 0 && x <= n) [x1, x2, x3] = Just (x1`div`3, x2`div`3, x3`div`3)
          | otherwise = Nothing
          where
            x1 = k - s1*d2 - s2*2*d1
            x2 = k - s1*d2 + s2*d1
            x3 = k + s1*2*d2 + s2*d1

  putStrLn $
    if n`mod`3 == 0 && not (null $ catMaybes os)
      then "yes"
      else "no"

main = do
  t <- readLn
  replicateM t solve

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

import Control.Applicative
import Control.DeepSeq (deepseq)
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.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
-- import Debug.Trace
import System.IO

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

solve = do
  [n, k, d1, d2] <- getInts

  let
    os = try <$> [-1, 1] <*> [-1, 1]
      where
        try s1 s2
          | all (\x -> x`mod`3 == 0 && x >= 0 && x <= n) [x1, x2, x3] = Just (x1`div`3, x2`div`3, x3`div`3)
          | otherwise = Nothing
          where
            x1 = k - s1*2*d1 - s2*d2
            x2 = k + s1*d1 - s2*d2
            x3 = k + s1*d1 - s2*2*d2

  putStrLn $
    if n`mod`3 == 0 && not (null $ catMaybes os)
      then "yes"
      else "no"

main = do
  t <- readLn
  replicateM t solve

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

import Control.Applicative
import Control.DeepSeq (deepseq)
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.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
-- import Debug.Trace
import System.IO

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

solve = do
  [n, k, d1, d2] <- getInts

  let
    os = try <$> [-1, 1] <*> [-1, 1]
      where

        try s1 s2
          | all (\x -> x`mod`3 == 0 && x >= 0) [x1, x2, x3] = Just (x1`div`3, x2`div`3, x3`div`3)
          | otherwise = Nothing
          where
            x1 = k - s1*d2 - s2*2*d1
            x2 = k - s1*d2 + s2*d1
            x3 = k + s1*2*d2 + s2*d1

  putStrLn $
    if n`mod`3 == 0 && not (null $ catMaybes os)
      then "yes"
      else "no"

main = do
  t <- readLn
  replicateM t solve

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
for :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()
for !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)
{-# INLINE for #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  n <- readLn :: IO Int
  xs <- map (fromIntegral.readInt).B.words <$> B.getContents
  putStr.unlines $ solve xs

solve :: [Int64] -> [String]
solve (n:k:d1:d2:rest)
  | any ok [(d1,d2),(d1,-d2),(-d1,d2),(-d1,-d2)] = "yes" : solve rest
  | otherwise = "no" : solve rest
   where
     ok (d1, d2) = and [w1>=0, w2>=0, w3>=0
                       , w1' `mod` 3==0, w3' `mod` 3 == 0
                       , d + k <= n
                       , (n-(d+k)) `mod` 3 == 0
                       ]
      where
        w1' = k - 2*d1 - d2
        w3' = k + d1 + 2*d2
        w1 = w1' `div` 3
        w3 = w3' `div` 3
        w2 = k - w1 - w3
        d = sum $ map (wmax-)[w1,w2,w3]
        wmax = maximum [w1,w2,w3]

solve _ = []

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
for :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()
for !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)
{-# INLINE for #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  n <- readLn :: IO Int
  xs <- map (fromIntegral.readInt).B.words <$> B.getContents
  putStr.unlines $ solve xs

solve :: [Int64] -> [String]
solve (n:k:d1:d2:rest)
  | any ok [(d1,d2),(d1,-d2),(-d1,d2),(-d1,-d2)] = "yes" : solve rest
  | otherwise = "no" : solve rest
   where
     ok (d1, d2) = and [ w1' >= 0, w2' >= 0, w3' >= 0
                       , w1' `mod` 3 == 0, w2' `mod` 3 == 0, w3' `mod` 3 == 0
                       , d + k <= n
                       , (n - d - k) `mod` 3 == 0
                       ]
      where
        w1' = k - 2*d1 -   d2
        w2' = k +   d1 -   d2
        w3' = k +   d1 + 2*d2
        w1 = w1' `div` 3
        w2 = w2' `div` 3
        w3 = w3' `div` 3
        d = 3 * maximum [w1,w2,w3] - sum [w1,w2,w3]

solve _ = []

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
for :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()
for !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)
{-# INLINE for #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  n <- readLn :: IO Int
  xs <- map (fromIntegral.readInt).B.words <$> B.getContents
  putStr.unlines $ solve xs

solve :: [Int64] -> [String]
solve (n:k:d1:d2:rest)
  | any ok [(d1,d2),(d1,-d2),(-d1,d2),(-d1,-d2)] = "yes" : solve rest
  | otherwise = "no" : solve rest
   where
     ok (d1, d2) = and [w1'>=0, w3'>=0
                       , w1' `mod` 3 == 0, w3' `mod` 3 == 0
                       , w2>=0
                       , d + k <= n
                       , (n-(d+k)) `mod` 3 == 0
                       ]
      where
        w1' = k - 2*d1 - d2
        w3' = k + d1 + 2*d2
        w1 = w1' `div` 3
        w3 = w3' `div` 3
        w2 = k - w1 - w3
        d = sum $ map (wmax-)[w1,w2,w3]
        wmax = maximum [w1,w2,w3]

solve _ = []

import Control.Monad
ans :: [Integer] -> String
ans [n, k, d1, d2] = if g then "yes" else "no"
 where g = (n `mod` 3 == 0) && (any good [(d1,d2),(abs(d1 - d2), max d1 d2)])
       good (a,b) = dd >= 0 && dd `mod` 3 == 0 && max (ee+a) (ee+b) <= n `div` 3
         where dd = k - a - b
               ee = dd `div` 3

solve :: IO String
solve = do
    s <- getLine
    return $ ans $ map read $ words s

main = do
  l1 <- getLine
  let nn = (read l1) :: Int
  replicateM nn solve >>= putStrLn . unlines

import Control.Monad
ans [n, k, d1, d2] = if g then "yes" else "no"
 where g = (n `mod` 3 == 0) && (any good [(d1,d2),(abs(d1 - d2), max d1 d2)])
       good (a,b) = a + b <= k && max a b <= n `div` 3

solve :: IO String
solve = do
    s <- getLine
    return $ ans $ map read $ words s

main = do
  l1 <- getLine
  let nn = (read l1) :: Int
  replicateM nn solve >>= putStrLn . unlines

import Control.Monad
ans :: [Integer] -> String
ans [n, k, d1, d2] = if g then "yes" else "no"
 where g = (n `mod` 3 == 0) && (any good [(d1,d2),(abs(d1 - d2), max d1 d2)])
       good (a,b) = a + b <= k && max a b <= n `div` 3

solve :: IO String
solve = do
    s <- getLine
    return $ ans $ map read $ words s

main = do
  l1 <- getLine
  let nn = (read l1) :: Int
  replicateM nn solve >>= putStrLn . unlines

{-# LANGUAGE BangPatterns #-}

import Data.Int
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as BS
import Text.Printf (printf)
import Control.Monad
import Control.Applicative

solve :: [Integer] -> Bool
solve [!n, !k, !d1, !d2] =
  n `rem` 3 == 0 &&
  (check d1 d2 || check (2 * d1) d2 || check d1 (2 * d2))
  where
    !r = n - k
    check !a !b = r >= a + b && n >= (max a b) * 3

main :: IO ()
main = do
  t <- readLn :: IO Int
  ts <- replicateM t $ (map (fst . fromJust . BS.readInteger) . BS.words) <$> BS.getLine :: IO [[Integer]]
  forM_ ts $ \t ->
    putStrLn $ if solve t then "yes" else "no"

{-# LANGUAGE BangPatterns #-}

import Data.Int
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as BS
import Text.Printf (printf)
import Control.Monad
import Control.Applicative

solve :: [Integer] -> Bool
solve [!n, !k, !d1, !d2] =
  check (k + 2*d1 + d2) ||
  check (k + 2*d1 - d2) ||
  check (k - 2*d1 - d2) ||
  check (k - 2*d1 + d2)
  where
    check !m = m >= 0 && m <= n && m `rem` 3 == 0 && (n - m) `rem` 3 == 0

main :: IO ()
main = do
  t <- readLn :: IO Int
  ts <- replicateM t $ (map (fst . fromJust . BS.readInteger) . BS.words) <$> BS.getLine :: IO [[Integer]]
  forM_ ts $ \t ->
    putStrLn $ if solve t then "yes" else "no"

{-# OPTIONS_GHC -O2 #-}
import Data.Maybe
import Data.Char
import Data.List
import Data.Int
import Data.Bits
import Data.IORef
import Data.Array.IO
import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map              as Map
import qualified Data.Set              as Set
import Text.Printf

getint :: IO Int
getint  = head <$> getints

getints :: IO [Int]
getints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine

solveEach as@[a, b, c] rest
  | need > rest = False
  | remain `mod` 3 == 0 = True
  | otherwise = False
  where mx = maximum as
        need = sum . map (\x -> mx - x) $ as
        remain = rest - need

solve [] _ = False
solve (a:as) rest
  | res1 == True = True
  | otherwise    = solve as rest
  where res1 = solveEach a rest

main = do
  testcase <- getint
  replicateM testcase $ do
    [n, k, d1, d2] <- map fst . mapMaybe BS.readInteger . BS.words <$> BS.getLine
    let rest = n - k
        as = [f x y | x <- [(0, d1), (d1, 0)], y <- [(0, d2), (d2, 0)]]
        f (d1, 0) (d2, 0) = [d1 + d2, d2, 0]
        f (d1, 0) (0, d2) = [d1, 0, d2]
        f (0, d1) (d2, 0) = if d1 >= d2
                              then [0, d1, d1 - (d1 - d2)]
                              else [d2 - (d2 - d1), d2, 0]
        f (0, d1) (0, d2) = [0, d1, d1 + d2]
        res = solve as rest
    if res then putStrLn "yes" else putStrLn "no"

{-# OPTIONS_GHC -O2 #-}
import Data.Maybe
import Data.Char
import Data.List
import Data.Int
import Data.Bits
import Data.IORef
import Data.Array.IO
import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as BS
import qualified Data.Map              as Map
import qualified Data.Set              as Set
import Text.Printf

getint :: IO Int
getint  = head <$> getints

getints :: IO [Int]
getints = map fst . mapMaybe BS.readInt . BS.words <$> BS.getLine

solveEach as@[a, b, c] rest
  | need > rest = False
  | remain `mod` 3 == 0 = True
  | otherwise = False
  where mx = maximum as
        need = sum . map (\x -> mx - x) $ as
        remain = rest - need

solve [] _ = False
solve (a:as) rest
  | res1 == True = True
  | otherwise    = solve as rest
  where res1 = solveEach a rest

main = do
  testcase <- getint
  replicateM testcase $ do
    [n, k, d1, d2] <- map fst . mapMaybe BS.readInteger . BS.words <$> BS.getLine
    let rest = n - k
        as = filter filt [f x y | x <- [(0, d1), (d1, 0)], y <- [(0, d2), (d2, 0)]]
        f (d1, 0) (d2, 0) = [d1 + d2, d2, 0]
        f (d1, 0) (0, d2) = [d1, 0, d2]
        f (0, d1) (d2, 0) = if d1 >= d2
                              then [0, d1, d1 - d2]
                              else [d2 - d1, d2, 0]
        f (0, d1) (0, d2) = [0, d1, d1 + d2]
        filt [a, b, c] = a + b + c <= k
        res = solve as rest
--    putStrLn (show as)
    if res then putStrLn "yes" else putStrLn "no"