module Main where

import qualified Data.ByteString.Char8 as BS

import Control.Monad (replicateM, forM_)
import Data.Functor ((<&>))
import Data.List (foldl', minimumBy)
import Text.Printf (printf)

main :: IO ()
main = do
  result <- solve <$> replicateM 3 readCircle
  forM_ result $ \(Point x y) -> printf "%.5f %.5f\n" x y

readCircle :: IO Circle
readCircle = do
  [x, y, r] <- BS.getLine <&> map (read . BS.unpack) . BS.words
  pure $ Circle (Point x y) r

data Point = Point {
  x :: Double,
  y :: Double
} deriving (Show, Eq)

data Circle = Circle {
  center :: Point,
  radius :: Double
} deriving (Show)

eps :: Double
eps = 1e-6

isSmall :: Double -> Bool
isSmall = (< eps) . abs

angleWeight :: Point -> Circle -> Double
angleWeight p (Circle c r) = dist p c / r

sq :: Double -> Double
sq x = x * x

mse :: [Double] -> Double
mse ws = sqrt $ sum squares / n
  where
    (total, n) = foldl' step (0, 0) ws
    mean = total / n
    step (cw, cn) w1 = (cw + w1, cn + 1)
    squares = map (sq . (-) mean) ws

dist :: Point -> Point -> Double
dist (Point x1 y1) (Point x2 y2) = sqrt $ sq (x1 - x2) + sq (y1 - y2)

initialGuess :: [Circle] -> Guess
initialGuess cs = Guess p (meanError cs p)
  where
    (n, Point x y) = foldl' step (0, Point 0 0) cs
    step (n, Point x1 y1) (Circle (Point x2 y2) _) = (n + 1, Point (x1 + x2) (y1 + y2))
    p = Point (x / n) (y / n)

meanError :: [Circle] -> Point -> Double
meanError cs p = mse $ map (angleWeight p) cs

findBestGuess :: [Circle] -> Guess
findBestGuess cs = solve0 (initialGuess cs) 1.0
  where
    candidates (Point x y) c = [Point (x + c) y, Point (x - c) y, Point x (y - c), Point x (y + c)]
    bestGuess = minimum. map (\p -> Guess p (meanError cs p))
    solve0 g c | isSmall c = g
    solve0 g c = let nextGuess = bestGuess $ candidates (p g) c in
      if nextGuess < g then solve0 nextGuess c else solve0 g (c / 2)

data Guess = Guess {
    p :: Point,
    w :: Double
  } deriving (Show)

instance Eq Guess where
  (Guess _ w1) == (Guess _ w2) = w1 == w2

instance Ord Guess where
  compare (Guess _ w1) (Guess _ w2) = compare w1 w2

solve :: [Circle] -> Maybe Point
solve stadiums = if isSmall (w guess) then Just (p guess) else Nothing
    where
      guess = findBestGuess stadiums

import Data.List (transpose, minimumBy)
import Data.Function (on)
import Text.Printf

solve :: [[Double]] -> String
solve ps = find initP 1
  where
    coords = take 2 $ transpose ps
    initP = map ((/ 3) . sum) coords

    eval p = sum . map (** 2) $ zipWith (-) thetas (tail . cycle $ thetas)
      where
        distToP = sqrt . sum . map (** 2) . zipWith (-) p
        thetas = map (\[x, y, r] -> distToP [x, y] / r) ps

    find p@[x, y] d -- d for delta
      | d < 1e-6 && eval p < 1e-5 = printf "%.5f %.5f\n" x y
      | d < 1e-6 = ""
      | fst bestCand < eval p = find (snd bestCand) d
      | otherwise = find p (d * 0.7)
      where
        points = [[x+d, y], [x-d, y], [x, y+d], [x, y-d]]
        cands = map (\cand -> (eval cand, cand)) points
        bestCand = minimumBy (compare `on` fst) cands

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

import Control.Monad (replicateM,forM,forM_)
import Text.Printf (printf)
import Data.List (maximumBy)
import Data.Ord (comparing)

data Point = P Double Double
  deriving (Show)

data Line =   L Point Double   -- x $. p     == c (p /= 0)
  deriving (Show)

data Circle = C Point Double   -- (x $. p)^2 == c (c > 0)
  deriving (Show)

center :: Circle -> Point
center (C a _) = a

radius2 :: Circle -> Double
radius2 (C _ r2) = r2

data Stadium = S Point Double
  deriving (Show)

epsilon = 1e-8

same :: Double -> Double -> Bool
same a b = abs (a-b) <= epsilon

($+) (P x1 y1) (P x2 y2) = P (x1+x2) (y1+y2)
($-) (P x1 y1) (P x2 y2) = P (x1-x2) (y1-y2)
($*) (P x y) a = P (x*a) (y*a)
($/) (P x y) a = P (x/a) (y/a)
($.) (P x1 y1) (P x2 y2) = x1*x2 + y1*y2

perp :: Point -> Point
perp (P x y) = (P y (negate x))

norm2 :: Point -> Double
norm2 p = p $. p

lineDistance :: Line -> Point -> Double
lineDistance (L a c) p = abs ((a $. p) - c) / sqrt (a $. a)

lineDistance2 :: Line -> Point -> Double
lineDistance2 (L a c) p = ((a $. p) - c)^(2 :: Int)/(a $. a)

onCircle :: Circle -> Point -> Bool
onCircle (C a r) b = same (norm2 (b $- a)) r

onLine :: Line -> Point -> Bool
onLine (L a c) p = same (a $. p) c

bisector :: Point -> Point -> Line
bisector p1 p2 = L n c
  where
    n = (p2 $- p1)
    x0 = (p1 $+ p2) $/ 2
    c = x0 $. n

-- return the solution circle for two stadiums
bicircle :: Stadium -> Stadium -> Circle
bicircle (S a ra) (S b rb) = C c rr   -- r1 /= r2
  where
    a2 = a $. a
    b2 = b $. b
    ra2 = ra*ra
    rb2 = rb*rb
    c  = ((a $* rb2) $- (b $* ra2)) $/ (rb2 - ra2)
    rr = (c $. c) - (rb2 * a2 - ra2 * b2) / (rb2 - ra2)

intersectLines :: Line -> Line -> [ Point ]
intersectLines (L (P a b) e) (L (P c d) f)
  | det == 0 = []
  | otherwise = [ P (x'/det) (y'/det) ]
  where
    det = a*d - b*c
    x'  = e*d - b*f
    y'  = a*f - c*e

-- solve a*x^2 + b*x + c == 0
solveQuadratic :: Double -> Double -> Double -> [Double]
solveQuadratic a b c =
  case compare d 0 of
    EQ -> [ -b/(2*a) ]
    LT -> []
    GT -> [ (-b - sqrtd) / (2*a),  (-b + sqrtd) / (2*a) ]
  where d = b*b-4*a*c
        sqrtd = sqrt d

toParametric :: Line -> (Point,Point)
toParametric (L (P a b) c)
  | a /= 0 = let p1 = P (c/a) 0
                 p2 = P ((c-b)/a) 1
             in (p1, p2 $- p1)
  | b /= 0 = let p1 = P 0 (c/b)
                 p2 = P 1 ((c-a)/b)
             in (p1, p2 $- p1)

intersectLineCircle :: Line -> Circle -> [ Point ]
intersectLineCircle l (C q rr) = map (\t -> a $+ (b $* t)) ts
  where
    (a,b) = toParametric l
    a2    = b $. b
    a1    = ((a $- q) $. b) * 2
    a0    = ((a $- q) $. (a $- q)) - rr
    ts    = solveQuadratic a2 a1 a0

intersectCircles :: Circle -> Circle -> [ Point ]
intersectCircles (C a r1) (C b r2) = intersectLineCircle line (C b r2)
  where
    c = (r1 - r2 - (a $. a) + (b $. b)) / 2
    line = L (b $- a) c

solve :: Stadium -> Stadium -> Stadium -> [ Point ]
solve s1@(S p1 r1) s2@(S p2 r2) s3@(S p3 r3)
  | r1 == r2 && r1 == r3 = intersectLines      (bisector p1 p2) (bisector p1 p3)
  | r1 == r2             = intersectLineCircle (bisector p1 p2) (bicircle s1 s3)
  | r1 == r3             = intersectLineCircle (bisector p1 p3) (bicircle s1 s2)
  | otherwise            = intersectCircles    (bicircle s1 s2) (bicircle s1 s3)

mkStadium a b c = S (P a b) c

s1 = mkStadium 0 0 10
s2 = mkStadium 200 0 20
s3 = mkStadium 100 100 10

angle :: Point -> Stadium -> Double
angle a (S b r) = r / sqrt (norm2 (a $- b))

angle' :: Stadium -> Point -> Double
angle' = flip angle

check :: Point -> [Stadium] -> IO ()
check a xs = do
  forM_ (zip [1..] xs) $ \(i,s) -> do
    let _ = i :: Int
    putStrLn $ printf "Stadium %d: %7.4f" i (angle a s)

readStadium :: IO Stadium
readStadium = do
  line <- getLine
  let (xs:ys:rs:_) = words line
      x = read xs
      y = read ys
      r = read rs
  return $ S (P x y) r

main = do
  [s1,s2,s3] <- replicateM 3 readStadium
  let sols = solve s1 s2 s3
  case sols of
    [] -> return ()
    _  -> do let (P x y) = maximumBy (comparing (angle' s1)) sols
             putStrLn $ printf "%.5f %.5f" x y

module Main where

import Text.Printf
import Data.List

-- Окружность
data Circle = Circle {
    center :: Point,
    radius :: Double
}

readCircle s = (Circle (Point (ins!!0) (ins!!1)) (ins!!2)) where
    ins = map read $ take 3 $ words s

-- Точка
data Point = Point {
    x :: Double,
    y :: Double
}

-- простые операции над точками
sumP (Point x1 y1) (Point x2 y2) = (Point (x1+x2) (y1+y2))
divP (Point x y) a = (Point (x/a) (y/a))

-- расстояние между точками
dist (Point x1 y1) (Point x2 y2) = sqrt (sq dx + sq dy) where
    dx = x1-x2
    dy = y1-y2

-- квадрат (для удобства)
sq a = a*a

-- угол, под которым видна окружность из точки (котангенсная мера)
cangle (Circle p r) p0 = (dist p p0)/r

-- квадратическое отклонение углов (мера точности равенства углов)
quadro cl1 cl2 cl3 p =
    sq (a1 - e) + sq (a2 - e) + sq (a3 - e) where
        a1 = cangle cl1 p
        a2 = cangle cl2 p
        a3 = cangle cl3 p
        e = (a1 + a2 + a3)/3

epsilon = 0.000001

main = do
    instr <- getContents
    let [cl1, cl2, cl3] = map readCircle $ take 3 $ lines instr
    let s = solution cl1 cl2 cl3
    if (quadro cl1 cl2 cl3 s) < epsilon then printf "%.5f %.5f\n" (x s) (y s)
                                        else return () where

        solution cl1 cl2 cl3 = findFinest mid (measure mid) 1.0 where

            findFinest point ds delta | delta < epsilon = point
            findFinest point ds delta = if (fst closer) < ds
                then findFinest (snd closer) (fst closer) delta
                else findFinest point ds (delta/1.4) where

                    closer = minimumBy (\(d1,_) (d2,_) -> compare d1 d2) $
                        zip (map measure candid) candid where
                            px = x point
                            py = y point
                            candid = [(Point (px+delta) py),
                                      (Point (px-delta) py),
                                      (Point px (py+delta)),
                                      (Point px (py-delta))]

            mid = (c1 `sumP` c2 `sumP` c3) `divP` 3.0

            measure = quadro cl1 cl2 cl3

            c1 = center cl1
            c2 = center cl2
            c3 = center cl3

module Main where

import Data.List

data Point = Point {
	x :: Double,
	y :: Double
} deriving (Show)

data Circle = Circle {
	c :: Point,
	r :: Double
} deriving (Show)

circleFromString :: String -> Circle
circleFromString s =
	Circle (Point (l !! 0) (l !! 1)) (l !! 2)
	where l = map read $ words s

pointAdd :: Point -> Point -> Point
pointAdd (Point x1 y1) (Point x2 y2) = Point (x1 + x2) (y1 + y2)

processInput :: String -> [Circle]
processInput = map circleFromString . lines

distance :: Point -> Point -> Double
distance (Point x1 y1) (Point x2 y2) =
	sqrt $ (x1 - x2) ** 2 + (y1 - y2) ** 2

angleToCircle :: Point -> Circle -> Double
angleToCircle p (Circle c r) =
	(distance c p) / r

squareMean :: [Double] -> Double
squareMean a =
	(sum $ map ((** 2) . (+ m)) a) / n
	where
		n = fromIntegral $ length a
		m = - sum a / n

tryPoint :: [Circle] -> Point -> Double
tryPoint circles p =
	squareMean $ map (angleToCircle p) $ circles
--	where
--		sumAngle = sum (map angleToCircle circles) / 3

iterateTry :: [Circle] -> Point -> Point
iterateTry cs startPoint =
	iter startPoint 1.0
	where
		iter p d
			| d < 1e-6 = p
			| (fst minimumPoint < currentDistance) = iter (snd minimumPoint) d
			| otherwise = iter p (d * 0.8)
			where
				currentDistance = tryPoint cs p
				measure = tryPoint cs
				tryList = [pointAdd p (Point 0 d), pointAdd p (Point d 0), pointAdd p (Point 0 (0-d)), pointAdd p (Point (0-d) 0)]
				minimumPoint = minimumBy (\(a, _) (b, _) -> compare a b) $ zip (map measure tryList) tryList

solve :: [Circle] -> Point
solve cs =
	let
		startPoint = Point { x = (sum $ map (x . c) cs) / 3, y = (sum $ map (y . c) cs) / 3 }
		endPoint = iterateTry cs startPoint
	in
		endPoint

main = do
	input <- getContents
	let
		circles = processInput input
		answer = solve circles
	if (tryPoint circles answer < 1e-6) then putStrLn $ (show $ x answer) ++ " " ++ (show $ y answer) else return ()

module Main where

import qualified Data.ByteString.Char8 as BS

import Control.Monad (replicateM, forM_)
import Data.Functor ((<&>))
import Data.List (foldl', minimumBy)
import Text.Printf (printf)

main :: IO ()
main = do
  result <- solve <$> replicateM 3 readCircle
  forM_ result $ \(Point x y) -> printf "%.5f %.5f\n" x y

readCircle :: IO Circle
readCircle = do
  [x, y, r] <- BS.getLine <&> map (read . BS.unpack) . BS.words
  pure $ Circle (Point x y) r

data Point = Point {
  x :: Double,
  y :: Double
} deriving (Show, Eq)

data Circle = Circle {
  center :: Point,
  radius :: Double
} deriving (Show)

eps :: Double
eps = 1e-6

isSmall :: Double -> Bool
isSmall = (< eps) . abs

angleWeight :: Point -> Circle -> Double
angleWeight p (Circle c r) = dist p c / r

sq :: Double -> Double
sq x = x * x

mse :: [Double] -> Double
mse ws = sqrt $ sum squares / n
  where
    (total, n) = foldl' step (0, 0) ws
    mean = total / n
    step (cw, cn) w1 = (cw + w1, cn + 1)
    squares = map (sq . (-) mean) ws

dist :: Point -> Point -> Double
dist (Point x1 y1) (Point x2 y2) = sqrt $ sq (x1 - x2) + sq (y1 - y2)

initialGuess :: [Circle] -> Guess
initialGuess cs = toGuess cs $ Point (x / n) (y / n)
  where
    (n, Point x y) = foldl' step (0, Point 0 0) cs
    step (n, Point x1 y1) (Circle (Point x2 y2) _) = (n + 1, Point (x1 + x2) (y1 + y2))

meanError :: [Circle] -> Point -> Double
meanError cs p = mse $ map (angleWeight p) cs

toGuess :: [Circle] -> Point -> Guess
toGuess cs p = Guess p (meanError cs p)

findBestGuess :: [Circle] -> Guess
findBestGuess cs = solve0 (initialGuess cs) 1.0
  where
    candidates (Point x y) c = [Point (x + c) y, Point (x - c) y, Point x (y - c), Point x (y + c)]
    bestGuess = minimum. map (toGuess cs)
    solve0 g c | isSmall c = g
    solve0 g c = let nextGuess = bestGuess $ candidates (p g) c in
      if nextGuess < g then solve0 nextGuess c else solve0 g (c / 2)

data Guess = Guess {
    p :: Point,
    w :: Double
  } deriving (Show)

instance Eq Guess where
  (Guess _ w1) == (Guess _ w2) = w1 == w2

instance Ord Guess where
  compare (Guess _ w1) (Guess _ w2) = compare w1 w2

solve :: [Circle] -> Maybe Point
solve stadiums = if isSmall (w guess) then Just (p guess) else Nothing
    where
      guess = findBestGuess stadiums

module Main where

import qualified Data.ByteString.Char8 as BS

import Control.Monad (replicateM, forM_)
import Data.Functor ((<&>))
import Data.List (foldl', minimumBy)
import Text.Printf (printf)

main :: IO ()
main = do
  result <- solve <$> replicateM 3 readCircle
  forM_ result $ \(Point x y) -> printf "%.5f %.5f\n" x y

readCircle :: IO Circle
readCircle = do
  [x, y, r] <- BS.getLine <&> map (read . BS.unpack) . BS.words
  pure $ Circle (Point x y) r

data Point = Point {
  x :: !Double,
  y :: !Double
} deriving (Show, Eq)

data Circle = Circle {
  center :: !Point,
  radius :: !Double
} deriving (Show)

eps :: Double
eps = 1e-6

isSmall :: Double -> Bool
isSmall = (< eps) . abs

angleWeight :: Point -> Circle -> Double
angleWeight p (Circle c r) = dist p c / r

sq :: Double -> Double
sq x = x * x

mse :: [Double] -> Double
mse ws = sqrt $ sum squares / n
  where
    (total, n) = foldl' step (0, 0) ws
    mean = total / n
    step (cw, cn) w1 = (cw + w1, cn + 1)
    squares = map (sq . (-) mean) ws

dist :: Point -> Point -> Double
dist (Point x1 y1) (Point x2 y2) = sqrt $ sq (x1 - x2) + sq (y1 - y2)

initialGuess :: [Circle] -> Guess
initialGuess cs = Guess p (meanError cs p)
  where
    (n, Point x y) = foldl' step (0, Point 0 0) cs
    step (n, Point x1 y1) (Circle (Point x2 y2) _) = (n + 1, Point (x1 + x2) (y1 + y2))
    p = Point (x / n) (y / n)

meanError :: [Circle] -> Point -> Double
meanError cs p = mse $ map (angleWeight p) cs

findBestGuess :: [Circle] -> Guess
findBestGuess cs = solve0 (initialGuess cs) 1.0
  where
    candidates (Point x y) c = [Point (x + c) y, Point (x - c) y, Point x (y - c), Point x (y + c)]
    bestGuess = minimum. map (\p -> Guess p (meanError cs p))
    solve0 g c | isSmall c = g
    solve0 g c = let nextGuess = bestGuess $ candidates (p g) c in
      if nextGuess < g then solve0 nextGuess c else solve0 g (c / 2)

data Guess = Guess {
    p :: !Point,
    w :: !Double
  } deriving (Show)

instance Eq Guess where
  (Guess _ w1) == (Guess _ w2) = w1 == w2

instance Ord Guess where
  compare (Guess _ w1) (Guess _ w2) = compare w1 w2

solve :: [Circle] -> Maybe Point
solve stadiums = if isSmall (w guess) then Just (p guess) else Nothing
    where
      guess = findBestGuess stadiums

import Data.List (transpose, minimumBy)
import Data.Function (on)
import Text.Printf

solve :: [[Double]] -> String
solve ps = find initP 1
  where
    coords = take 2 $ transpose ps
    initP = map ((/ 3) . sum) coords

    eval p = sum . map abs $ zipWith (-) thetas (tail . cycle $ thetas)
      where
        distToP = sum . take 2 . zipWith (-) p
        thetas = map (\[x, y, r] -> distToP [x, y] / r) ps

    find p@[x, y] d -- d for delta
      | d < 1e-6 = printf "%.5f %.5f\n" x y
      | fst bestCand < local = find (snd bestCand) d
      | otherwise = find p (d * 0.7)
      where
        points = [[x+d, y], [x-d, y], [x, y+d], [x, y-d]]
        cands = map (\cand -> (eval cand, cand)) points
        bestCand = minimumBy (compare `on` fst) cands
        local = eval [x, y]

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

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

data Vec = V Double Double
  deriving (Show,Eq)

(<+>) :: Vec -> Vec -> Vec
(<+>) (V a b) (V c d) = V (a+c) (b+d)

(<->) :: Vec -> Vec -> Vec
(<->) (V a b) (V c d) = V (a-c) (b-d)

infixl 6 <+>
infixl 6 <->

(<.>) :: Vec -> Vec -> Double
(<.>) (V a b) (V c d) = a*c + b*d

infixl 7 <.>

(.*) :: Double -> Vec -> Vec
(.*) a (V x y) = V (a*x) (a*y)

(./) :: Double -> Vec -> Vec
(./) a (V x y) = V (x/a) (y/a)

(/.) :: Vec -> Double -> Vec
(/.) (V x y) a = V (x/a) (y/a)

infixr 7 .*
infixr 7 ./
infixl 7 /.

norm2 :: Vec -> Double
norm2 v = v <.> v

len :: Vec -> Double
len = sqrt . norm2

normal :: Vec -> Vec
normal (V a b) = V (negate b) a

zero :: Double -> Bool
zero a = abs a < 1e-10

zeroVec :: Vec -> Bool
zeroVec (V a b) = zero a && zero b

same :: Double -> Double -> Bool
same x y = abs (x-y) < 1e-10

-- [Vec] is the list of centers
-- [Double] is the list of radii

solveProblem :: [Vec] -> [Double] -> [Vec]
solveProblem (av:bv:cv:_) (a:b:c:_)
  | same a b && same a c
      = intersectLines     ab1 ab0 ac1 ac0
  | same a b
      = intersectLineCircle ab1 ab0 (ac1 /. ac2) (ac0 / ac2)
  | otherwise
      = intersectCircles    (ab1 /. ab2) (ab0 / ab2)
                            (ac1 /. ac2) (ac0 / ac2)
  where
    a2 = a*a
    b2 = b*b
    c2 = c*c

    ab2 = b2 - a2
    ab1 = 2 .* (a2 .* bv <-> b2 .* av)
    ab0 = b2 * norm2 av - a2 * norm2 bv

    ac2 = c2 - a2
    ac1 = 2 .* (a2 .* cv <-> c2 .* av)
    ac0 = c2 * norm2 av - a2 * norm2 cv

{- Find the intersection of two lines given by:
 -   X.A + a = 0
 -   X.B + b = 0
 -}
intersectLines :: Vec -> Double -> Vec -> Double -> [Vec]
intersectLines av a bv b =
  let nvec = normal av
      x0   = ((negate a) / norm2 av) .* av
      t    = ((negate b) - x0 <.> bv) / (nvec <.> bv)
  in
  if zero $ nvec <.> bv
    then []
    else [ x0 <+> t .* nvec ]

{- Find the intersection of a line:
 -         X.A + a = 0
 - and a parabola:
 -   X.X + X.B + b = 0
 -}
intersectLineCircle :: Vec -> Double -> Vec -> Double -> [Vec]
intersectLineCircle av a bv b =
  let nvec = normal av
      x0   = ((negate a) / norm2 av) .* av
      a2   = norm2 nvec
      a1   = 2 * (nvec <.> x0) + nvec <.> bv
      a0   = bv <.> x0 + b
      ts   = solveQuadratic a2 a1 a0
  in [ x0 <+> t .* nvec | t <- ts ]

intersectCircles :: Vec -> Double -> Vec -> Double -> [Vec]
intersectCircles avec a bvec b = do
  let dvec    = avec <-> bvec
      d       = a - b
      nvec    = normal dvec
      d2      = dvec <.> dvec
      x0vec   = ((b-a)/d2) .* dvec
      a2      = nvec <.> nvec
      a1      = nvec <.> avec
      a0      = (x0vec <.> x0vec) + (x0vec <.> avec) + a
      ts      = solveQuadratic a2 a1 a0
  -- putStrLn $ " a2,a1,a0: " ++ show [a2,a1,a0]
  let b2      = nvec <.> nvec
      b1      = nvec <.> bvec
      b0      = x0vec <.> x0vec + x0vec <.> bvec + b
  -- putStrLn $ " b2,b1,b0: " ++ show [b2,b1,b0]
  t <- ts
  let xvec = t .* nvec <+> x0vec
  let e1 = xvec <.> xvec + xvec <.> avec + a
      e2 = xvec <.> xvec + xvec <.> bvec + b
  return xvec
    -- putStrLn $ "Solution: t = " ++ show t
    -- putStrLn $ "          x = " ++ show xvec
    -- putStrLn $ "         e1 = " ++ show e1
    -- putStrLn $ "         e2 = " ++ show e1

-- solve a*x^2 + b*x + c == 0
solveQuadratic :: Double -> Double -> Double -> [Double]
solveQuadratic a b c =
  case compare d 0 of
    EQ -> [ -b/(2*a) ]
    LT -> []
    GT -> [ (-b - sqrtd) / (2*a),  (-b + sqrtd) / (2*a) ]
  where d = b*b-4*a*c
        sqrtd = sqrt d

readStadium :: IO (Vec,Double)
readStadium = do
  line <- getLine
  let (xs:ys:rs:_) = words line
      x = read xs
      y = read ys
      r = read rs
  return (V x y, r)

main = do
  (av,a) <- readStadium
  (bv,b) <- readStadium
  (cv,c) <- readStadium
  let sols = solveProblem [av,bv,cv] [a,b,c]
  case sols of
    []             -> return ()
    (V x y):_      -> putStrLn $ printf "%.6f %.6f" x y

import Data.Maybe
import Text.Printf

(-->) = flip fmap

type Triple = (Double,Double,Double)

readTriple :: String -> Triple
readTriple s = let (x:y:r:_) = map read $ words s in (x,y,r)

dist x1 y1 x2 y2 = sqrt (dx*dx + dy*dy)
  where dx = x1 - x2
        dy = y1 - y2

eps = 1e-10

solve :: Triple -> Triple -> Triple -> Maybe (Double,Double)
solve (x1,y1,r1) (x2,y2,r2) (x3,y3,r3) =
  let a = r1 / (r1+r2)
      x = x1*a + x2*(1-a)
      y = y1*a + y2*(1-a)
      d = dist x1 y1 x2 y2
      d2 = d*a
      d3 = dist x y x3 y3
  in if abs (d3/r3 - d2/r2) < eps then Just (x,y) else Nothing

main = do
  p1 <- getLine --> readTriple
  p2 <- getLine --> readTriple
  p3 <- getLine --> readTriple
  case catMaybes [ solve p1 p2 p3, solve p2 p3 p1, solve p3 p1 p2 ] of
    ((x,y):_) -> putStrLn $ printf "%.5f %.5f" x y
    otherwise -> return ()

import Control.Monad (replicateM,forM,forM_)
import Text.Printf (printf)
import Data.List (maximumBy)
import Data.Ord (comparing)

data Point = P Double Double
  deriving (Show)

data Line =   L Point Double   -- x $. p     == c (p /= 0)
  deriving (Show)

data Circle = C Point Double   -- (x $. p)^2 == c (c > 0)
  deriving (Show)

center :: Circle -> Point
center (C a _) = a

radius2 :: Circle -> Double
radius2 (C _ r2) = r2

data Stadium = S Point Double
  deriving (Show)

epsilon = 1e-8

same :: Double -> Double -> Bool
same a b = abs (a-b) <= epsilon

($+) (P x1 y1) (P x2 y2) = P (x1+x2) (y1+y2)
($-) (P x1 y1) (P x2 y2) = P (x1-x2) (y1-y2)
($*) (P x y) a = P (x*a) (y*a)
($/) (P x y) a = P (x/a) (y/a)
($.) (P x1 y1) (P x2 y2) = x1*x2 + y1*y2

perp :: Point -> Point
perp (P x y) = (P y (negate x))

norm2 :: Point -> Double
norm2 p = p $. p

lineDistance :: Line -> Point -> Double
lineDistance (L a c) p = abs ((a $. p) - c) / sqrt (a $. a)

lineDistance2 :: Line -> Point -> Double
lineDistance2 (L a c) p = ((a $. p) - c)^(2 :: Int)/(a $. a)

onCircle :: Circle -> Point -> Bool
onCircle (C a r) b = same (norm2 (b $- a)) r

onLine :: Line -> Point -> Bool
onLine (L a c) p = same (a $. p) c

bisector :: Point -> Point -> Line
bisector p1 p2 = L n c
  where
    n = (p2 $- p1)
    x0 = (p1 $+ p2) $/ 2
    c = x0 $. n

-- return the solution circle for two stadiums
bicircle :: Stadium -> Stadium -> Circle
bicircle (S a ra) (S b rb) = C c rr   -- r1 /= r2
  where
    a2 = a $. a
    b2 = b $. b
    ra2 = ra*ra
    rb2 = rb*rb
    c  = ((a $* rb2) $- (b $* ra2)) $/ (rb2 - ra2)
    rr = (c $. c) - (rb2 * a2 - ra2 * b2) / (rb2 - ra2)

intersectLines :: Line -> Line -> [ Point ]
intersectLines (L (P a b) e) (L (P c d) f)
  | det == 0 = []
  | otherwise = [ P (x'/det) (y'/det) ]
  where
    det = a*d - b*c
    x'  = e*d - b*f
    y'  = a*f - c*e

-- solve a*x^2 + b*x + c == 0
solveQuadratic :: Double -> Double -> Double -> [Double]
solveQuadratic a b c =
  case compare d 0 of
    EQ -> [ -b/(2*a) ]
    LT -> []
    GT -> [ (-b - sqrtd) / (2*a),  (-b + sqrtd) / (2*a) ]
  where d = b*b-4*a*c
        sqrtd = sqrt d

toParametric :: Line -> (Point,Point)
toParametric (L (P a b) c)
  | a /= 0 = let p1 = P (c/a) 0
                 p2 = P ((c-b)/a) 1
             in (p1, p2 $- p1)
  | b /= 0 = let p1 = P 0 (c/b)
                 p2 = P 1 ((c-a)/b)
             in (p1, p2 $- p1)

intersectLineCircle :: Line -> Circle -> [ Point ]
intersectLineCircle l (C q rr) = map (\t -> a $+ (b $* t)) ts
  where
    (a,b) = toParametric l
    a2    = b $. b
    a1    = ((a $- q) $. b) * 2
    a0    = ((a $- q) $. (a $- q)) - rr
    ts    = solveQuadratic a2 a1 a0

intersectCircles :: Circle -> Circle -> [ Point ]
intersectCircles (C a r1) (C b r2) = intersectLineCircle line (C b r2)
  where
    c = (r1 - r2 - (a $. a) + (b $. b)) / 2
    line = L (b $- a) c

solve :: Stadium -> Stadium -> Stadium -> [ Point ]
solve s1@(S p1 r1) s2@(S p2 r2) s3@(S p3 r3)
  | r1 == r2 && r1 == r3 = intersectLines      (bisector p1 p2) (bisector p1 p3)
  | r1 == r2             = intersectLineCircle (bisector p1 p2) (bicircle s1 s3)
  | otherwise            = intersectCircles    (bicircle s1 s2) (bicircle s1 s3)

mkStadium a b c = S (P a b) c

s1 = mkStadium 0 0 30
s2 = mkStadium 300 300 30
s3 = mkStadium 500 (-500) 20

angle :: Point -> Stadium -> Double
angle a (S b r) = r / sqrt (norm2 (a $- b))

angle' :: Stadium -> Point -> Double
angle' = flip angle

check :: Point -> [Stadium] -> IO ()
check a xs = do
  forM_ (zip [1..] xs) $ \(i,s) -> do
    let _ = i :: Int
    putStrLn $ printf "Stadium %d: %7.4f" i (angle a s)

readStadium :: IO Stadium
readStadium = do
  line <- getLine
  let (xs:ys:rs:_) = words line
      x = read xs
      y = read ys
      r = read rs
  return $ S (P x y) r

main = do
  [s1,s2,s3] <- replicateM 3 readStadium
  let sols = solve s1 s2 s3
  case sols of
    [] -> return ()
    _  -> do let (P x y) = maximumBy (comparing (angle' s1)) sols
             putStrLn $ printf "%.5f %.5f" x y

import Control.Monad (replicateM,forM,forM_)
import Text.Printf (printf)

data Point = P Double Double
  deriving (Show)

data Line =   L Point Double   -- x $. p     == c (p /= 0)
  deriving (Show)

data Circle = C Point Double   -- (x $. p)^2 == c (c > 0)
  deriving (Show)

center :: Circle -> Point
center (C a _) = a

radius2 :: Circle -> Double
radius2 (C _ r2) = r2

data Stadium = S Point Double
  deriving (Show)

epsilon = 1e-8

same :: Double -> Double -> Bool
same a b = abs (a-b) <= epsilon

($+) (P x1 y1) (P x2 y2) = P (x1+x2) (y1+y2)
($-) (P x1 y1) (P x2 y2) = P (x1-x2) (y1-y2)
($*) (P x y) a = P (x*a) (y*a)
($/) (P x y) a = P (x/a) (y/a)
($.) (P x1 y1) (P x2 y2) = x1*x2 + y1*y2

perp :: Point -> Point
perp (P x y) = (P y (negate x))

norm2 :: Point -> Double
norm2 p = p $. p

lineDistance :: Line -> Point -> Double
lineDistance (L a c) p = abs ((a $. p) - c) / sqrt (a $. a)

lineDistance2 :: Line -> Point -> Double
lineDistance2 (L a c) p = ((a $. p) - c)^(2 :: Int)/(a $. a)

onCircle :: Circle -> Point -> Bool
onCircle (C a r) b = same (norm2 (b $- a)) r

onLine :: Line -> Point -> Bool
onLine (L a c) p = same (a $. p) c

bisector :: Point -> Point -> Line
bisector p1 p2 = L n c
  where
    n = (p2 $- p1)
    x0 = (p1 $+ p2) $/ 2
    c = x0 $. n

-- return the solution circle for two stadiums
bicircle :: Stadium -> Stadium -> Circle
bicircle (S a ra) (S b rb) = C c rr   -- r1 /= r2
  where
    a2 = a $. a
    b2 = b $. b
    ra2 = ra*ra
    rb2 = rb*rb
    c  = ((a $* rb2) $- (b $* ra2)) $/ (rb2 - ra2)
    rr = (c $. c) - (rb2 * a2 - ra2 * b2) / (rb2 - ra2)

intersectLines :: Line -> Line -> [ Point ]
intersectLines (L (P a b) e) (L (P c d) f)
  | det == 0 = []
  | otherwise = [ P (x'/det) (y'/det) ]
  where
    det = a*d - b*c
    x'  = e*d - b*f
    y'  = a*f - c*e

-- solve a*x^2 + b*x + c == 0
solveQuadratic :: Double -> Double -> Double -> [Double]
solveQuadratic a b c =
  case compare d 0 of
    EQ -> [ -b/(2*a) ]
    LT -> []
    GT -> [ (-b - sqrtd) / (2*a),  (-b + sqrtd) / (2*a) ]
  where d = b*b-4*a*c
        sqrtd = sqrt d

toParametric :: Line -> (Point,Point)
toParametric (L (P a b) c)
  | a /= 0 = let p1 = P (c/a) 0
                 p2 = P ((c-b)/a) 1
             in (p1, p2 $- p1)
  | b /= 0 = let p1 = P 0 (c/b)
                 p2 = P 1 ((c-a)/b)
             in (p1, p2 $- p1)

intersectLineCircle :: Line -> Circle -> [ Point ]
intersectLineCircle l (C q rr) = map (\t -> a $+ (b $* t)) ts
  where
    (a,b) = toParametric l
    a2    = b $. b
    a1    = ((a $- q) $. b) * 2
    a0    = ((a $- q) $. (a $- q)) - rr
    ts    = solveQuadratic a2 a1 a0

intersectCircles :: Circle -> Circle -> [ Point ]
intersectCircles (C a r1) (C b r2) = intersectLineCircle line (C b r2)
  where
    c = (r1 - r2 - (a $. a) + (b $. b)) / 2
    line = L (b $- a) c

solve :: Stadium -> Stadium -> Stadium -> [ Point ]
solve s1@(S p1 r1) s2@(S p2 r2) s3@(S p3 r3)
  | r1 == r2 && r1 == r3 = intersectLines      (bisector p1 p2) (bisector p1 p3)
  | r1 == r2             = intersectLineCircle (bisector p1 p2) (bicircle s1 s3)
  | otherwise            = intersectCircles    (bicircle s1 s2) (bicircle s1 s3)

readStadium :: IO Stadium
readStadium = do
  line <- getLine
  let (xs:ys:rs:_) = words line
      x = read xs
      y = read ys
      r = read rs
  return $ S (P x y) r

main = do
  [s1,s2,s3] <- replicateM 3 readStadium
  let sols = solve s1 s2 s3
  case sols of
    []             -> return ()
    (P x y):_      -> putStrLn $ printf "%.5f %.5f" x y

module Main where

import Data.List

data Point = Point {
	x :: Double,
	y :: Double
} deriving (Show)

data Circle = Circle {
	c :: Point,
	r :: Double
} deriving (Show)

circleFromString :: String -> Circle
circleFromString s =
	Circle (Point (l !! 0) (l !! 1)) (l !! 2)
	where l = map read $ words s

pointAdd :: Point -> Point -> Point
pointAdd (Point x1 y1) (Point x2 y2) = Point (x1 + x2) (y1 + y2)

processInput :: String -> [Circle]
processInput = map circleFromString . lines

distance :: Point -> Point -> Double
distance (Point x1 y1) (Point x2 y2) =
	sqrt $ (x1 - x2) ** 2 + (y1 - y2) ** 2

angleToCircle :: Point -> Circle -> Double
angleToCircle p (Circle c r) =
	(distance c p) / r

squareMean :: [Double] -> Double
squareMean a =
	(sum $ map ((** 2) . (+ m)) a) / n
	where
		n = fromIntegral $ length a
		m = - sum a / n

tryPoint :: [Circle] -> Point -> Double
tryPoint circles p =
	squareMean $ map (angleToCircle p) $ circles
--	where
--		sumAngle = sum (map angleToCircle circles) / 3

iterateTry :: [Circle] -> Point -> Point
iterateTry cs startPoint =
	iter startPoint 1.0
	where
		iter p d
			| d < 1e-6 = p
			| (fst minimumPoint < currentDistance) = iter (snd minimumPoint) d
			| otherwise = iter p (d * 0.8)
			where
				currentDistance = tryPoint cs p
				measure = tryPoint cs
				tryList = [pointAdd p (Point 0 d), pointAdd p (Point d 0), pointAdd p (Point 0 (0-d)), pointAdd p (Point (0-d) 0)]
				minimumPoint = minimumBy (\(a, _) (b, _) -> compare a b) $ zip (map measure tryList) tryList

solve :: [Circle] -> String
solve cs =
	let
		startPoint = Point { x = (sum $ map (x . c) cs) / 3, y = (sum $ map (y . c) cs) / 3 }
		endPoint = iterateTry cs startPoint
	in (show (x endPoint)) ++ " " ++ (show (y endPoint))

main = do
	input <- getContents
	let circles = processInput input
	putStrLn $ solve circles

module Main where

import qualified Data.ByteString.Char8 as BS

import Control.Monad (replicateM)
import Data.Functor ((<&>))
import Data.List (foldl', minimumBy)
import Text.Printf (printf)

stadiums = [
    Circle (Point 0 0) 10,
    Circle (Point 60 0) 10,
    Circle (Point 30 30) 10
  ]

main :: IO ()
main = do
  result <- solve <$> replicateM 3 readCircle
  case result of
    Just (Point x y) -> printf "%.5f %.5f\n" x y
    _ -> return ()

readCircle :: IO Circle
readCircle = do
  [x, y, r] <- BS.getLine <&> map (read . BS.unpack) . BS.words
  pure $ Circle (Point x y) r

data Point = Point {
  x :: Double,
  y :: Double
} deriving (Show, Eq)

data Circle = Circle {
  center :: Point,
  radius :: Double
} deriving (Show)

eps :: Double
eps = 1e-8

isSmall :: Double -> Bool
isSmall = (< eps) . abs

angleWeight :: Point -> Circle -> Double
angleWeight p (Circle c r) = dist p c / r

mean :: [Double] -> Double
mean ws = total / n
  where
    (total, n) = foldl' step (0, 0) ws
    step (cw, cn) w1 = (cw + w1, cn + 1)

sq :: Double -> Double
sq x = x * x

squareMean :: [Double] -> Double
squareMean ws = sqrt . sum . map (sq . (-) m) $ ws
  where
    m = mean ws

dist :: Point -> Point -> Double
dist (Point x1 y1) (Point x2 y2) = sqrt $ sq (x1 - x2) + sq (y1 - y2)

initialGuess :: [Circle] -> Point
initialGuess circles = Point (x / n) (y / n)
  where
    (n, Point x y) = foldl' step (0, Point 0 0) circles
    step (n, Point x1 y1) (Circle (Point x2 y2) _) = (n + 1, Point (x1 + x2) (y1 + y2))

minimumOn :: (Ord b) => (a -> b) -> [a] -> a
minimumOn c = minimumBy (\x y -> compare (c x) (c y))

meanWeight :: [Circle] -> Point -> Double
meanWeight stadiums p = squareMean $ map (angleWeight p) stadiums

findBestGuess :: [Circle] -> Point
findBestGuess stadiums = solve0 (initialGuess stadiums) 1.0
  where
    candidates cur@(Point x y) c = [Point (x + c) y, Point (x - c) y, cur, Point x (y - c), Point x (y + c)]
    bestMatch = minimumOn (meanWeight stadiums)
    solve0 p c | c < 1e-6 = p
    solve0 p c = let nextGuess = bestMatch $ candidates p c in
      solve0 nextGuess (if nextGuess == p then c / 2 else c)

isGood :: [Circle] -> Point -> Bool
isGood stadiums guess = isSmall (meanWeight stadiums guess)

solve :: [Circle] -> Maybe Point
solve stadiums = if isGood stadiums guess then Just guess else Nothing
    where
      guess = findBestGuess stadiums

module Main where

import qualified Data.ByteString.Char8 as BS

import Control.Monad (replicateM, forM_)
import Data.Functor ((<&>))
import Data.List (foldl', minimumBy)
import Text.Printf (printf)

main :: IO ()
main = do
  result <- solve <$> replicateM 3 readCircle
  forM_ result $ \(Point x y) -> printf "%.5f %.5f\n" x y

readCircle :: IO Circle
readCircle = do
  [x, y, r] <- BS.getLine <&> map (read . BS.unpack) . BS.words
  pure $ Circle (Point x y) r

data Point = Point {
  x :: Double,
  y :: Double
} deriving (Show, Eq)

data Circle = Circle {
  center :: Point,
  radius :: Double
} deriving (Show)

eps :: Double
eps = 1e-8

isSmall :: Double -> Bool
isSmall = (< eps) . abs

angleWeight :: Point -> Circle -> Double
angleWeight p (Circle c r) = dist p c / r

mean :: [Double] -> Double
mean ws = total / n
  where
    (total, n) = foldl' step (0, 0) ws
    step (cw, cn) w1 = (cw + w1, cn + 1)

sq :: Double -> Double
sq x = x * x

squareMean :: [Double] -> Double
squareMean ws = sqrt . sum . map (sq . (-) m) $ ws
  where
    m = mean ws

dist :: Point -> Point -> Double
dist (Point x1 y1) (Point x2 y2) = sqrt $ sq (x1 - x2) + sq (y1 - y2)

initialGuess :: [Circle] -> Point
initialGuess circles = Point (x / n) (y / n)
  where
    (n, Point x y) = foldl' step (0, Point 0 0) circles
    step (n, Point x1 y1) (Circle (Point x2 y2) _) = (n + 1, Point (x1 + x2) (y1 + y2))

minimumOn :: (Ord b) => (a -> b) -> [a] -> a
minimumOn c = minimumBy (\x y -> compare (c x) (c y))

meanWeight :: [Circle] -> Point -> Double
meanWeight stadiums p = squareMean $ map (angleWeight p) stadiums

findBestGuess :: [Circle] -> Point
findBestGuess stadiums = solve0 (initialGuess stadiums) 1.0
  where
    candidates cur@(Point x y) c = [Point (x + c) y, Point (x - c) y, cur, Point x (y - c), Point x (y + c)]
    bestMatch = minimumOn (meanWeight stadiums)
    solve0 p c | c < 1e-6 = p
    solve0 p c = let nextGuess = bestMatch $ candidates p c in
      solve0 nextGuess (if nextGuess == p then c / 2 else c)

isGood :: [Circle] -> Point -> Bool
isGood stadiums guess = isSmall (meanWeight stadiums guess)

solve :: [Circle] -> Maybe Point
solve stadiums = if isGood stadiums guess then Just guess else Nothing
    where
      guess = findBestGuess stadiums


{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Data.List
import Data.Int
import Data.Array.Unboxed

data P = P {-# UNPACK #-} !Int64 {-# UNPACK #-} !Int64 deriving (Eq, Ord)

main = do
  [n, s] <- fmap readInts B.getLine
  ps <- replicateM n $ fmap ((\[x, v, d] -> P (fromIntegral x) (fromIntegral $ if d == 1 then -v else v)) . readInts) B.getLine
  print $ solve (fromIntegral s) ps

solve s ps = minimum $ zipWith max tls trs
  where
    hi = 1000000 :: Int64
    (ls, rs) = partition (\(P _ pv) -> pv < 0) $ sort ps
    tls = snd $ mapAccumL (go (\x px pv -> if x * pv > -s * px then toD (x * s + pv * px) / toD (s * s - pv * pv) else -1) (minimum $ map (\(P px pv) -> toD (-px) / toD pv) ls)) (Nothing, ls) [1..hi - 1]
    trs = elems (array (1, hi - 1) $ zip [hi - 1, hi - 2..1] $ snd $ mapAccumL (go (\x px pv -> let x' = hi - x; px' = hi - px in if x' * pv < s * px' then toD (x' * s - pv * px') / toD (s * s - pv * pv) else -1) (minimum $ map (\(P px pv) -> toD (hi - px) / toD pv) rs)) (Nothing, reverse rs) [hi - 1, hi - 2..1] :: UArray Int64 Double)
    go clock (!m) st@(!mp', !pps) (!x)
      | (p@(P !px !pv):ps) <- pps, x == px = ((Just p, ps), min m $ clock x px pv)
      | Just (P !px' !pv') <- mp' = let t' = clock x px' pv' in if t' > 0 then (st, min m t') else ((Nothing, pps), m)
      | otherwise = (st, m)

toD x = fromIntegral x :: Double

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

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Data.List
import Data.Int
import Data.Array.Unboxed

main = do
  [n, s] <- fmap readInts B.getLine
  ps <- replicateM n $ fmap ((\[x, v, d] -> (fromIntegral x, fromIntegral $ if d == 1 then -v else v)) . readInts) B.getLine
  print $ solve (fromIntegral s) ps

solve s ps = minimum $ zipWith max tls trs
  where
    hi = 1000000 :: Int64
    (ls, rs) = partition ((< 0) . snd) $ sort ps
    tls = snd $ mapAccumL (go (\x px pv -> if x * pv > -s * px then toD (x * s + pv * px) / toD (s * s - pv * pv) else -1) (minimum $ map (\(px, pv) -> toD (-px) / toD pv) ls)) (Nothing, ls) [1..hi - 1]
    trs = elems (array (1, hi - 1) $ zip [hi - 1, hi - 2..1] $ snd $ mapAccumL (go (\x px pv -> let x' = hi - x; px' = hi - px in if x' * pv < s * px' then toD (x' * s - pv * px') / toD (s * s - pv * pv) else -1) (minimum $ map (\(px, pv) -> toD (hi - px) / toD pv) rs)) (Nothing, reverse rs) [hi - 1, hi - 2..1] :: UArray Int64 Double)
    go clock m st@(mp', pps) x
      | (p@(px, pv):ps) <- pps, x == px = ((Just p, ps), min m $ clock x px pv)
      | Just (px', pv') <- mp' = let t' = clock x px' pv' in if t' > 0 then (st, min m t') else ((Nothing, pps), m)
      | otherwise = (st, m)

toD x = fromIntegral x :: Double

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

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

main = do
  [n, s] <- fmap readInts B.getLine
  ps <- replicateM n $ fmap ((\[x, v, d] -> (fromIntegral x, fromIntegral $ if d == 1 then -v else v)) . readInts) B.getLine
  print $ solve (fromIntegral s) ps

solve s ps = minimum $ zipWith max tls trs
  where
    hi = 1000000 :: Int64

    (ls, rs) = partition ((< 0) . snd) $ sortBy (comparing fst) ps

    tls = snd $ mapAccumL (go clock m) (Nothing, ls) [1..hi - 1]
      where
        m = minimum $ map (\(px, pv) -> toD (-px) / toD pv) ls
        clock x px pv
          | x * pv > -s * px = toD (x * s + pv * px) / toD (s * s - pv * pv)
          | otherwise = -1

    trs = snd $ mapAccumR (go clock m) (Nothing, rs) [1..hi - 1]
      where
        m = minimum $ map (\(px, pv) -> toD (hi - px) / toD pv) rs
        clock x px pv
          | x' * pv < s * px' = toD (x' * s - pv * px') / toD (s * s - pv * pv)
          | otherwise = -1
          where
            x' = hi - x
            px' = hi - px

    go _ m st@(Nothing, []) _ = (st, m)
    go clock m st@(Nothing, p@(px, pv):ps) x
      | x == px = let t = clock x px pv in if t > 0 then ((Just p, ps), min m t) else ((Nothing, ps), m)
      | otherwise = (st, m)
    go clock m st@(Just (px, pv), []) x = (st, min m $ clock x px pv)
    go clock m (mp@(Just (mpx, mpv)), p@(px, pv):ps) x
      | t' > 0 && t' < t = ((Just p, ps), min t' m)
      | otherwise = ((mp, ps), min t m)
      where
        t' = clock x px pv
        t = clock x mpx mpv

toD x = fromIntegral x :: Double

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

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

data Person = Person !Double !Double deriving Show

main = do
  [n, s] <- fmap readInts B.getLine
  ps <- replicateM n $ fmap ((\[x, v, d] -> Person (toD x) (toD $ if d == 1 then -v else v)) . readInts) B.getLine
  print $ solve (toD s) ps

solve s ps = clock $ toD $ go 1 hi
  where
    (ls, rs) = partition (\(Person _ v) -> v < 0) ps
    hi = 1000000 :: Int
    hiD = toD hi

    go l r
      | r - l <= 1 = l
      | otherwise = if clock (toD m) > clock (toD l) then go l m else go m r
      where m = (l + r) `div` 2

    clock x = max (minimum tls) (minimum trs)
      where
        tls = map (\(Person px pv) -> let t1 = (px - x) / (-s - pv); x' = x + (-s) * t1 in if px > x || x' <= 0 then (-px) / pv else let t2 = (-x') / (-s + pv) in t1 + t2) ls
        trs = map (\(Person px pv) -> let t1 = (px - x) / (s - pv); x' = x + s * t1 in if px < x || x' >= hiD then (hiD - px) / pv else let t2 = (hiD - x') / (s + pv) in t1 + t2) rs

toD x = fromIntegral x :: Double

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


import qualified Data.List as L

readInts :: IO [Int]
readInts = do
    input <- getLine
    return $ map read . words $ input

splitOnHalf :: [a] -> ([a], [a])
splitOnHalf xs = (take half xs, drop half xs)
    where half = div (length xs) 2

equalArea :: [Int] -> [Int] -> Int -> Bool

equalArea [] [] _ = True
equalArea (x1:x2:xs) (y1:y2:ys) area =
    x1 == x2 && y1 == y2 && (x1 * y2) == area && equalArea xs ys area

solve :: [Int] -> Bool
solve xs =
    equalArea s b' $ (head s) * (head b')
    where
        b' = reverse b
        (s, b) = splitOnHalf xs

handleCase :: Int -> IO ()

handleCase 0 = do return ()
handleCase t = do
    n <- getLine
    a <- readInts
    putStrLn $ if solve(L.sort a) == True then "YES" else "NO"
    handleCase(t-1)

main = do
    t <- getLine
    handleCase (read t)

import Control.Monad
import Data.List

main = do
    q <- readInt
    submain q
    return q

readInt = do
    raw_q <- getLine
    let q = read raw_q :: Int
    return q

readlist = do
    inp <- getLine
    let v = words inp
    let ret = map read v
    return ret

submain:: Int -> IO ()
submain q = do
    when (q > 0) $ do
        sz <- readInt
        v <- readlist
        putStrLn $ if (solve v) then "YES" else "NO"
        submain $ q - 1
        return ()

solve :: [Int] -> Bool
solve v =
    isPaired v' && canFormEqAreaRec v' rv' 0
    where
        v' = group $ sort v
        rv' = reverse v'

isPaired :: [[Int]] -> Bool
isPaired = all (even . length)

canFormEqAreaRec :: [[Int]] -> [[Int]] -> Int -> Bool
canFormEqAreaRec [] [] _ = True
canFormEqAreaRec v rv 0 =
    canFormEqAreaRec v rv (x0 * y0)
    where
        x:xs = v
        y:ys = rv
        x0:xx = x
        y0:yy = y

canFormEqAreaRec (x:xs) (y:ys) area =
    length x == length y &&
    x0 * y0 == area &&
    canFormEqAreaRec xs ys area
    where
        x0:xx = x
        y0:yy = y

import Control.Monad
import Data.List

readInt = do
    raw_q <- getLine
    let q = read raw_q :: Int
    return q

readlist = do
    inp <- getLine
    return $ map read (words inp)

main = do
    q <- readInt
    submain q
    return q

submain :: Int -> IO ()
submain q = do
    when (q > 0) $ do
        sz <- readInt
        v <- readlist
        putStrLn $ if (solve (sort v)) then "YES" else "NO"
        submain $ q - 1
        return ()

countDupList v@(x:xs) = (x, length v)

groupToTuple x = map countDupList $ group x

solve :: [Int] -> Bool
solve v =
    canFormEqAreaRec v rv (head v * head rv)
    where rv = reverse v

canFormEqAreaRec [] [] _ = True
canFormEqAreaRec (x0:x1:xs) (y0:y1:ys) area =
    x0 == x1 && y0 == y1 && x0 * y0 == area &&
    canFormEqAreaRec xs ys area

import qualified Data.List as L

readInts :: IO [Int]
readInts = do
    input <- getLine
    return $ map read . words $ input

splitOnHalf :: [a] -> ([a], [a])
splitOnHalf xs = (take half xs, drop half xs)
    where half = div (length xs) 2

equalArea :: [Int] -> [Int] -> Int -> Bool

equalArea [] [] _ = True
equalArea (x1:x2:xs) (y1:y2:ys) area =
    x1 == x2 && y1 == y2 && (x1 * y2) == area && equalArea xs ys area

solve :: [Int] -> Bool
solve xs =
    equalArea s b $ (head s) * (head b)
    where (s, b) = splitOnHalf xs

handleCase :: Int -> IO ()

handleCase 0 = do return ()
handleCase t = do
    n <- getLine
    a <- readInts
    putStrLn $ if solve(a) == True then "YES" else "NO"
    handleCase(t-1)

main = do
    t <- getLine
    handleCase (read t)


--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L
import Data.Function

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [_n] <- ri
        xs   <- ri
        return xs
    mapM_ (putStrLn . show . solve) tcs

solve xs = min 2 . length . filter ((/=0).head) . L.groupBy ((==)`on`(==0)) $ xs

import Control.Monad (forM_)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Maybe (fromJust)

main :: IO ()
main = do
  t <- int <$> B.getLine
  forM_ [1 .. t] $ \_ -> do
    _ <- B.getLine
    as <- map int . C.words <$> B.getLine
    let bs = reverse . dropWhile (== 0) . reverse . dropWhile (== 0) $ as
    if null bs
      then print 0
      else
        if 0 `elem` bs
          then print 2
          else print 1

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

import Control.Monad (forM_)

main :: IO ()
main = do
  t <- read <$> getLine
  forM_ [1 .. t] $ \_ -> do
    _ <- getLine
    as <- map read . words <$> getLine
    let bs = reverse . dropWhile (== 0) . reverse . dropWhile (== 0) $ as
    if null bs
      then print 0
      else
        if 0 `elem` bs
          then print 2
          else print 1

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L
import Data.Function

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [_n] <- ri
        xs   <- ri
        return xs
    mapM_ (putStrLn . show . solve) tcs

solve xs = length . filter ((/=0).head) . L.groupBy ((==)`on`(==0)) $ xs


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE LambdaCase        #-}
{-# LANGUAGE MultiWayIf        #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections     #-}
#ifndef DEBUG
{-# LANGUAGE Safe              #-}
#endif

import           Control.Applicative
import           Control.Monad
import           Control.Monad.State.Strict
import           Data.Array.Unboxed
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString.Char8      as C
import           Data.Char
import           Data.Function
import           Data.Int
import qualified Data.IntMap.Strict         as IM
import qualified Data.IntSet                as IS
import qualified Data.List                  as L
import qualified Data.Map.Strict            as M
import           Data.Monoid
import           Data.Ord
import qualified Data.Set                   as S
import           Data.Tuple
import           Data.Word
#ifdef DEBUG
import           Debug.Trace
#endif
import Foreign

main :: IO ()
main = do
  [h, w]<- L.unfoldr (C.readInt.C.dropWhile isSpace) <$> C.getLine
  cs <- filter (not.isSpace) <$> getContents
  putStrLn.bool"NO""YES" $ solve h w cs

solve :: Int -> Int -> String -> Bool
solve _ _ cs | all (== '.') cs = False
solve h w cs = minx < x && x < maxx && miny < y && y < maxy && set == cross
  where
    xys = [quotRem ij w|(ij, '*')<-zip[0..]cs]
    !set = S.fromList xys
    !minx = minimum $ map fst xys
    !maxx = maximum $ map fst xys
    !miny = minimum $ map snd xys
    !maxy = maximum $ map snd xys
    !x = fst . head $ filter ((==miny).snd) xys
    !y = snd . head $ filter ((==minx).fst) xys
    cross = S.fromList $ map ((,) x) [miny..maxy] ++ map (flip (,) y) [minx..maxx]

import Data.List

main = interact $ solve . tail . lines

solve :: [String] -> String
solve board =
    let goal = length . filter (=='*') $ concat board in
    let tBoard = transpose board in
    let populatedRows = filter ((>=2) . length . filter (=='*') . (!!) board) [0..length board-1] in
    let populatedCols = filter ((>=2) . length . filter (=='*') . (!!) tBoard) [0..length tBoard-1] in
    if length populatedRows == 1 && length populatedCols == 1
    then
        let r = head populatedRows in
        let c = head populatedCols in
        if board !! r !! c == '*'
            then
                let right = length . takeWhile (=='*') $ drop (c + 1) (board !! r) in
                let left = length . takeWhile (=='*') . reverse $ take c (board !! r) in
                let up = length . takeWhile (=='*') . reverse $ take r (tBoard !! c) in
                let down = length . takeWhile (=='*') $ drop (r + 1) (tBoard !! c) in
                if right + left + up + down + 1 == goal &&
                    right >= 1 && left >= 1 &&
                    up >= 1 && down >= 1
                then "YES\n"
                else "NO\n"
        else "NO\n"
    else "NO\n"

import Data.List

main = interact $ solve . tail . lines

solve :: [String] -> String
solve board =
    let goal = length . filter (=='*') $ concat board in
    let tBoard = transpose board in
    let populatedRows = filter ((>=2) . length . filter (=='*') . (!!) board) [0..length board-1] in
    let populatedCols = filter ((>=2) . length . filter (=='*') . (!!) tBoard) [0..length tBoard-1] in
    if length populatedRows == 1 && length populatedCols == 1
    then
        let r = head populatedRows in
        let c = head populatedCols in
        if board !! r !! c == '*'
            then
                let right = length . takeWhile (=='*') $ drop (c + 1) (board !! r) in
                let left = length . takeWhile (=='*') . reverse $ take c (board !! r) in
                let up = length . takeWhile (=='*') . reverse $ take r (tBoard !! c) in
                let down = length . takeWhile (=='*') $ drop (r + 1) (tBoard !! c) in
                if right + left + up + down + 1 == goal
                then "YES\n"
                else "NO\n"
        else "NO\n"
    else "NO\n"


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

solve [x] = 0
solve (x:y:xs) = solve (y:xs) + if h <= 1 then 0 else h - 1
            where
                h = ceiling $ logBase 2 (max x y / min x y)

printResult = do
    n <- readLn :: IO Int
    a <-readFloats
    print $ solve a

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

module Main where

import Control.Monad
import Debug.Trace

main :: IO ()
main = do
    n <- ((read :: String -> Int) <$> getLine)
    replicateM_ n action

action = do
    getLine
    arr <- (map (read :: String -> Int) . words) <$> getLine
    print (calc arr)

calc :: [Int] -> Int
calc (first:rest) = magic 0 first rest
  where
    magic res _ [] = res
    magic res prev (cur:rest) = let p = fromIntegral prev
                                    c = fromIntegral cur
                                    f = (max p c - 1) / (min p c)
                                    x = max 0.0 $ logBase 2 f
                                in magic (res + floor x) cur rest

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

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

import Data.Bits

type SIO = StateT P.ByteString IO

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

bitFloor :: Word -> Word
bitFloor v
  | v <= 1    = v
  | otherwise = 1 + shiftR (complement 0) (countLeadingZeros v + 1)

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [_n] <- readInts
    a <- readInts
    putInts $ pure $ foldl' (+) 0 $ do
      (prev, curr) <- zip a (tail a)
      let
        res = ceilDiv (max prev curr) (min prev curr)
        steps = if  res > 1 -- typo, extra yikes
          then  countTrailingZeros $ bitFloor $ fromIntegral $ res - 1
          else  0 -- forgot about -1, silly move
      pure $ fromIntegral steps

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

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

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

chunksOf x [] = []
chunksOf x l = take x l : chunksOf x (drop x l)

toArr = map read . words

getInput [_, s] = toArr s

teto n d = 1 + ((n - 1) `div` d)

log2 0 = 0
log2 1 = 0
log2 x = 1 + log2 (x `div` 2)

solve [] = 0
solve [_] = 0
solve (x : y : xs) = log2 (z - 1) + solve (y : xs)
    where z = max (teto x y) (teto y x)

main = interact (unlines . map (show . solve . getInput) . chunksOf 2 . tail . lines)

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

import Data.Map((!))

powerTwo :: Integer -> Integer -> Integer
powerTwo x y | 2 * x >= y = 0
powerTwo x y | 2 * x < y = 1+powerTwo (2*x) y

result [] = 0
result [x] = 0
result (x:y:xs)
	| x > y = powerTwo y x + result (y:xs)
	| otherwise = powerTwo x y + result (y:xs)

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

module Main where
import Control.Monad ( replicateM_ )

solve :: [Int] -> Int
solve xs = sum $ zipWith go xs (tail xs)
  where
    go a b = length $ takeWhile (< max a b) (tail $ iterate (*2) (min a b))

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

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n (getLine >> readInts >>= print . solve)

module Main where

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

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

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

printList :: (Show a) => [a] -> IO ()
printList = putStrLn . list2Str

list2Str :: (Show a) => [a] -> String
list2Str = concat . intersperse " " . fmap show

yesOrNo :: Bool -> String
yesOrNo True = "YES"
yesOrNo False = "NO"

tCase :: IO () -> IO ()
tCase x = do
    t <- readLn
    replicateM_ t $ x

main :: IO ()
main = tCase process

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

process :: IO ()
process = do
    getLine
    a <- getIntList
    print $ f a

f :: [Int] -> Int
f a = sum . zipWith g a $ tail a

g :: Int -> Int -> Int
g x y
    | x > y = g y x
    | x * 2 >= y = 0
    | otherwise = g (x * 2) y + 1

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

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

------

type Hopper r = State [r]

type HopperT r = StateT [r]

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

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

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

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

type MonadHopper r m = MonadState [r] m

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

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

------

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

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

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

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

------

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

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

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

------

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

run1 = do
  n <- popInt
  as <- popInts
  return $ bshow $ solve n as

solve n as = sum $ map (uncurry f) $ adjlist as
  where
    f a b | a > b = f b a
          | otherwise = fromJust $ findIndex (\x -> b <= x) $
                        iterate' (* 2) (a * 2)

adjlist as@(_ : as') = zip as as'
adjlist _ = []

needed :: Integer -> Integer -> Integer
needed small big
  | 2 * small >= big = 0
  | otherwise        = 1 + needed (2 * small) big

solveTest :: [Integer] -> Integer
solveTest [] = 0
solveTest [_] = 0
solveTest (x:y:rest) = needed (min x y) (max x y) + solveTest (y:rest)

solve :: String -> String
solve = unlines . map solveStringTest . odds . drop 1 . lines
    where odds [] = []
          odds (_:x:xs) = x : odds xs
          solveStringTest = show . solveTest . map read . words

main :: IO ()
main = interact solve

import Control.Monad

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

readInts :: IO [Int]
readInts = readArray

readInt :: IO Int
readInt = readLn

interpolate :: Int -> Int -> Int
interpolate x y = if x > y then interpolate y x else
    if 2 * x >= y then 0 else 1 + interpolate (2 * x) y

solve :: [Int] -> Int
solve (x:y:xs) = interpolate x y + solve (y:xs)
solve _ = 0

main :: IO ()
main = readInt >>= flip replicateM_ (readInt >> fmap solve readInts >>= print)

module Main where

import Control.Monad

main :: IO ()
main = do
    n <- ((read :: String -> Int) <$> getLine)
    replicateM_ n action

action = do
    getLine
    arr <- (map (read :: String -> Int) . words) <$> getLine
    print (calc arr)

calc :: [Int] -> Int
calc (first:rest) = magic 0 first rest
  where
    magic :: Int -> Int -> [Int] -> Int
    magic res _ [] = res
    magic res prev (cur:rest) = let big = max prev cur
                                    smol = min prev cur
                                in magic (fst $ head $ dropWhile (\(_, s) -> s < big) $ iterate (\(cnt, upd) -> (cnt + 1, upd * 2)) (res - 1, smol)) cur rest

module Main where

import Control.Monad

main :: IO ()
main = do
    n <- ((read :: String -> Int) <$> getLine)
    replicateM_ n action

action = do
    getLine
    arr <- (map (read :: String -> Int) . words) <$> getLine
    print (calc arr)

calc :: [Int] -> Int
calc (first:rest) = magic 0 first rest
  where
    magic res _ [] = res
    magic res prev (cur:rest) = let p = fromIntegral prev
                                    c = fromIntegral cur
                                    f = (max p c - 1) / (min p c)
                                    x = logBase 2 f
                                in magic (res + floor x) cur rest

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

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

import Data.Bits

type SIO = StateT P.ByteString IO

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

bitFloor :: Word -> Word
bitFloor v
  | v <= 1    = v
  | otherwise = 1 + shiftR (complement 0) (countLeadingZeros v + 1)

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [_n] <- readInts
    a <- readInts
    putInts $ pure $ foldl' (+) 0 $ do
      (prev, curr) <- zip a (tail a)
      let
        res = ceilDiv (max prev curr) (min prev curr)
        steps = if  res > 0
          then  countTrailingZeros $ bitFloor $ fromIntegral $ res - 1
          else  0 -- forgot about -1, silly move
      pure $ fromIntegral steps

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

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

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

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

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

import Data.Bits

type SIO = StateT P.ByteString IO

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

bitFloor :: Word -> Word
bitFloor v
  | v <= 1    = v
  | otherwise = 1 + shiftR (complement 0) (countLeadingZeros v + 1)

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [_n] <- readInts
    a <- readInts
    putInts $ pure $ foldl' (+) 0 $ do
        (prev, curr) <- zip a (tail a)
        let
          res = ceilDiv (max prev curr) (min prev curr)
          steps = countTrailingZeros $ bitFloor $ fromIntegral $ res - 1
        pure $ fromIntegral steps

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

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

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


mainCase :: [Int] -> Int -> Int -> Bool
mainCase [] ones twos = and [even ones, or [even twos, ones >= 2]]
mainCase (1 : xs) ones twos = mainCase xs (ones+1) twos
mainCase (2 : xs) ones twos = mainCase xs ones (twos+1)

testCase :: [Int] -> String
testCase candies = if mainCase candies 0 0 then "yes" else "no"

main = do
	getLine
	contents <- getContents
	let importantLines = map (fst) $ filter (odd . snd) $ zip (lines contents) [0..]
	let testCases = map (map (read) . words) importantLines
	putStrLn $ unlines $ map (testCase) testCases

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

import Data.Maybe
import Control.Monad

answer :: [Bool] -> String
answer test
  | any (==True) test = "YES"
  | otherwise = "NO"

canSplit as (cnt1, cnt2) = do
  let sm = cnt1 + 2 * cnt2

  sm == sum(as) - sm

solve = do
  s1 <- B.getLine
  s2 <- B.getLine

  let n = fst $ fromJust $ C.readInt s1
  let as = map (fst . fromJust . C.readInt) (C.words s2)

  let cnt1 = length $ filter (1==) as
  let cnt2 = length $ filter (2==) as

  let pairs = [(x, y) | x <- [0..cnt1], y <- [0..cnt2]]

  putStrLn $ answer $ map (canSplit as) pairs

main = do
  str <- B.getLine

  let t = fst $ fromJust $ C.readInt str

  replicateM_ t solve

import Control.Monad
import Data.List
import Data.Array

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

readInts :: IO [Integer]
readInts = readArray

readInt :: IO Integer
readInt = readLn

hist :: [Integer] -> (Integer, Integer)
hist [] = (0, 0)
hist (x:xs) = let (a, b) = hist xs in if x == 1 then (a + 1, b) else (a, b + 1)

res :: Bool -> String
res True = "YES"
res False = "NO"

solveInner :: Integer -> Bool -> Bool
solveInner sum any
  | sum `mod` 2 /= 0 = False
  | (sum `div` 2) `mod` 2 == 0 = True
  | otherwise = any

solve :: [Integer] -> Bool
solve l = let (a, b) = hist l in solveInner (a + 2 * b) (a > 0)

solveCase :: IO String
solveCase = readInt >> fmap (res . solve) readInts

main :: IO ()
main = readLn >>= flip replicateM_ (solveCase >>= putStrLn)

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

import qualified Data.Array as A

import qualified Control.Monad.State.Strict as State
import Control.Monad.ST

import Data.Bits(xor, (.&.), (.|.))
import qualified Data.Array.MArray as MA
import Data.Array.ST(runSTArray, STArray)

import Data.Array((!))
import Control.Monad(replicateM, foldM, mapM, filterM) -- foldM est un foldl
import Data.Maybe

numOcc :: Ord a => [a] -> M.Map a Integer
numOcc (x:xs) = let m = numOcc xs in case M.lookup x m of
	Just i -> M.insert x (i+1) m
	Nothing -> M.insert x 1 m
numOcc [] = M.empty

numOcc' :: A.Ix a => (a, a) -> [a] -> A.Array a Integer
numOcc' size list = runSTArray $ do
	array <- MA.newArray size 0
	foldM (addElem array) () list
	return array

	where
		addElem :: A.Ix a=> STArray s a Integer -> () -> a -> ST s ()
		addElem array action a = do
			i <- MA.readArray array a
			MA.writeArray array a (i+1)

insertWithList :: Ord a => a -> b -> M.Map a [b] -> M.Map a [b]
insertWithList a b m = case M.lookup a m of
	Just l -> M.insert a (b:l) m
	Nothing -> M.insert a [b] m

deleteWithList :: Ord a => a -> M.Map a [b] -> M.Map a [b]
deleteWithList a m = case M.lookup a m of
	Just (x:y:xs) -> M.insert a (y:xs) m
	Just [x] -> M.delete a m

solve :: Integer -> [Integer] -> Bool

solve n a
	| mod num1 2 == 1 = False
	| mod num2 2 == 1 && num1 == 0 = False
	| otherwise = True
	where
	num1 = sum [1 | x<-a, x==1]
	num2 = sum [1 | x<-a, x==2]

plotResult True = putStrLn "Yes"
plotResult False = putStrLn "No"

main = do
	t <- getLine >>= return . read :: IO Integer
	replicateM (fromInteger t) $ do
		[n] <- fmap ((fmap read) . words) getLine :: IO [Integer]
		a <- getLine >>= return . (fmap read) . words :: IO [Integer]
		plotResult $ solve n a

module Main where

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

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

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

printList :: (Show a) => [a] -> IO ()
printList = putStrLn . list2Str

list2Str :: (Show a) => [a] -> String
list2Str = concat . intersperse " " . fmap show

yesOrNo :: Bool -> String
yesOrNo True = "YES"
yesOrNo False = "NO"

tCase :: IO () -> IO ()
tCase x = do
    t <- readLn
    replicateM_ t $ x

main :: IO ()
main = tCase process

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

process :: IO ()
process = do
    getLine
    a <- getIntList
    putStrLn $ yesOrNo $ f a

f :: [Int] -> Bool
f a = fst b == snd b
    where b = foldl g (0, 0) $ reverse . sort $ a

g :: (Int, Int) -> Int -> (Int, Int)
g (x, y) z = if x < y then (x + z, y) else (x, y + z)

import Control.Arrow
main = interact $ lines >>> drop 1 >>> caser >>> unzip >>> snd >>> map (words >>> map read >>> solve) >>> unlines

caser :: [String] -> [(String, String)]
caser [a, b] = [(a, b)]
caser (a:b:cs) = [(a, b)] ++ caser cs

solve :: [Int] -> String
solve a = do
  let two = (filter (\x -> x == 2) >>> length) a
  let one = (filter (\x -> x == 1) >>> length) a
  if ((mod two 2) == 0 && (mod one 2) == 0)
    then "YES"
  else if ((mod one 2) == 0 && one > 0)
    then "YES"
  else "NO"

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}

import safe Control.Arrow ((>>>))
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.List
import Data.Function
import Data.Maybe

main :: IO ()
main = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where
  tcio :: [T.Text] -> [String]
  tcio [] = []
  tcio (_ : ns : rest) = ((:[]). solve . linetois) (ns) ++ tcio (drop 0 rest)
  linetoi = toi; linetois = (map linetoi).(T.words); linestoiss = map linetois
  --itoline = show; istoline = unwords . (map itoline); isstolines = map istoline
  toi t = toi0 0 t where toi0 n t = if (T.null) t then n else toi0 (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;

solve :: [Int] -> String
solve ns = if odd c1 || (c1==0 && odd c2) then "NO" else "YES" where
  [c1,c2] = map (subtract 1) $ map length $ group $ sort $ ns ++ [1,2]

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

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             join, replicateM_)
import qualified Control.Monad.State.Strict as S
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (findIndices, intersect, elemIndices, find, isPrefixOf, nub,
                                             sort, sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           GHC.IO.Handle              (hDuplicateTo)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             openFile, stdin, stdout)
import           Text.Printf                (printf)

-- import Debug.Trace (trace)
-- debug = flip trace

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

readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)

solve :: Int -> [Int] -> Bool
solve n as = not $ null $ intersect twoDiffs oneDiffs
    where
        twos = length . findIndices even $ as
        ones = length . findIndices odd $ as

        twoDiffs = [2 * k - 2 * (twos - k) | k <- [0 .. twos]]
        oneDiffs = [k - (ones - k) | k <- [0 .. ones]]

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        as <- B8.getLine <&> map readIntB8 . B8.words
        let answer = solve n as
        printf "%s\n" ((if answer then "YES" else "NO") :: String)

{-# LANGUAGE
    BangPatterns
  , BlockArguments
  , DataKinds
  , DeriveGeneric
  , DerivingStrategies
  , DerivingVia
  , FlexibleContexts
  , FlexibleInstances
  , GADTs
  , GeneralizedNewtypeDeriving
  , KindSignatures
  , LambdaCase
  , MultiParamTypeClasses
  , MultiWayIf
  , NPlusKPatterns
  , NegativeLiterals
  , OverloadedLabels
  , OverloadedStrings
  , ParallelListComp
  , PolyKinds
  , RankNTypes
  , ScopedTypeVariables
  , StrictData
  , TupleSections
  , TypeApplications
  , TypeFamilies
  , TypeOperators
  , UndecidableInstances
  , ViewPatterns
  #-}

module Main where

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Control.Monad.ST
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.Foldable
import           Data.Functor
import           Data.Int
import           Data.List
import           Data.Maybe
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup                 ( Max(..)
                                                , Min(..)
                                                , All(..)
                                                , Arg(..)
                                                )
import           Data.Ratio
-- import           Data.Vector.Unboxing.Mutable   ( Unboxable )
-- import qualified Data.Vector.Unboxing.Mutable  as V
import           System.IO
import           Data.Proxy
import           GHC.TypeLits
import           GHC.Generics                   ( Generic )
import           Data.Function
-- import           Data.List.HT                   ( mapAdjacent
--                                                 , isAscending
--                                                 )
-- import           Control.Monad.Primitive        ( PrimMonad(PrimState) )
import qualified Data.Set                      as S
-- import qualified Data.Vector.Algorithms.Radix  as VA
-- import           Text.Parsec.ByteString

-- #if defined(LOCAL_ZER0STAR)
-- {-# ANN module ("Hlint: ignore Unused LANGUAGE pragma" :: String) #-}
-- {-# ANN module ("Hlint: ignore Reduce duplication" :: String) #-}
-- #endif

twice :: (a -> a -> b) -> a -> b
twice f x = f x x

both :: Arrow a => a b c -> a (b, b) (c, c)
both = twice (***)

both2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)

readsLn :: Read a => IO [a]
readsLn = mapM readIO . words =<< getLine

getInt :: IO Int
getInt = fst . fromJust . BS.readInt <$> BS.getLine

getInts :: IO [Int]
getInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine

getInteger :: IO Integer
getInteger = fst . fromJust . BS.readInteger <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine

main = do
  t <- getInt
  replicateM_
    t
    do
      n <- getInt
      a <- getInts
      let s   = sum a
          one = length $ filter (== 1) a
          two = length $ filter (== 2) a
      putStrLn if
        | odd s     -> "No"
        | even two  -> "Yes"
        | one >= 2  -> "Yes"
        | otherwise -> "No"

import Control.Monad
import Data.List

data V = V !Int !Bool

step :: V -> Char -> V
step (V tot one) c = case  c  of
  '1' -> V (tot + 1) True
  '2' -> V (tot + 2) one
  _ -> V tot one

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    _n <- getLine
    ans <- foldl' step (V 0 False) <$> getLine
    putStrLn $ case  ans  of
      V x _ | odd x  -> "NO"
      V x c | (mod x 4 /= 0) <= c  -> "YES"
      _ -> "NO"

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

import Data.Maybe
import Control.Monad

answer :: [Bool] -> String
answer test
  | any (==True) test = "YES"
  | otherwise = "NO"

canSplit as cnt2 = do
  let cnt1 = length $ filter (1==) as
  let sum2 = sum $ filter (2==) as
  let num = abs $ 2 * cnt2 - (sum2 - 2 * cnt2)

  even (cnt1 - num) && cnt1 > 0

solve = do
  s1 <- B.getLine
  s2 <- B.getLine

  let n = fst $ fromJust $ C.readInt s1
  let as = map (fst . fromJust . C.readInt) (C.words s2)

  let cnt2 = length $ filter (2==) as

  putStrLn $ answer $ map (canSplit as) [0..cnt2]

main = do
  str <- B.getLine

  let t = fst $ fromJust $ C.readInt str

  replicateM_ t solve

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

import Data.Maybe
import Control.Monad

answer :: [Bool] -> String
answer test
  | any (==True) test = "YES"
  | otherwise = "NO"

canSplit as cnt2 = do
  let cnt1 = length $ filter (1==) as
  let sum2 = sum $ filter (2==) as
  let num = abs $ 2 * cnt2 - (sum2 - 2 * cnt2)

  even (cnt1 - num) && cnt1 > 0

solve = do
  s1 <- B.getLine
  s2 <- B.getLine

  let n = fst $ fromJust $ C.readInt s1
  let as = map (fst . fromJust . C.readInt) (C.words s2)

  let cnt2 = length $ filter (2==) as

  print $ answer $ map (canSplit as) [0..cnt2]

main = do
  str <- B.getLine

  let t = fst $ fromJust $ C.readInt str

  replicateM_ t solve

import Control.Monad
import Data.List
import Data.Array

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

readInts :: IO [Integer]
readInts = readArray

readInt :: IO Integer
readInt = readLn

hist :: [Integer] -> (Integer, Integer)
hist [] = (0, 0)
hist (x:xs) = let (a, b) = hist xs in if x == 1 then (a + 1, b) else (a, b + 1)

res :: Bool -> String
res True = "YES"
res False = "NO"

solveInner :: Integer -> Bool -> Bool
solveInner sum any
  | sum `mod` 2 /= 0 = False
  | sum `div` 2 == 0 = True
  | otherwise = any

solve :: [Integer] -> Bool
solve l = let (a, b) = hist l in solveInner (a + 2 * b) (a > 0)

solveCase :: IO String
solveCase = readInt >> fmap (res . solve) readInts

main :: IO ()
main = readLn >>= flip replicateM_ (solveCase >>= putStrLn)


import Control.Monad
main = do
  t <- readLn
  replicateM_ t $ do
    [n,k] <- map read . words <$> getLine
    putStrLn $ take n $ cycle $ enumFromTo 'a' $ toEnum $ fromEnum 'a' + k - 1

main = getContents >>= putStr . solve . tail . map read . words

solve [] = []
solve (n:k:xs) = (take n $ concat $ repeat $ take k ['a' .. 'z']) ++ ('\n' : solve xs)

f2::Int->String->String->String
f2 0 _ _=""
f2 a [] t=f2 a t t
f2 a (x:xs) t=x:f2 (a-1) xs t

f::[String]->[String]
f [] =[]
f (x:xs)=let (a:b:[])=map read (words x)::[Int]
             t=(take b "abcdefghijklmnopqrstuvwxyz")
         in (f2 a t t):f xs
main = do
       e<-getLine
       es<-getContents
       mapM_ putStrLn $ f (lines es)

import Control.Monad
-- import Data.List (flatten)

fpow n = foldr (.) id . replicate n

solve :: Int -> Int -> String
solve n k = zipWith const reps [1..n]
  where reps = concat $ repeat ['a'.. fpow (pred k) succ 'a']

main = do
  numCases <- read <$> getLine
  replicateM_ numCases $ do
    [n, k] <- fmap read <$> words <$> getLine
    putStrLn $ solve n k

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

onecase = do
		[a,b]<-map read <$> words <$> getLine ::IO [Int]
		putStrLn $ take a $ cycle $ take b "abcdefghijklmnopqrstuvwxyz"

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

process :: Int -> Int -> [Char]
process n k = take n . concat . repeat . take k $ ['a'..]

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    t <- fmap readInt getLine
    ts <- fmap (map (map readInt.words).lines) getContents
    mapM_ putStrLn $ map (\[n,k] -> process n k) ts

solve [n, k] =
  map ((['a'..'z'] !!) . (`mod` k)) [0..n-1]
solve _ = error "bad format"

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


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

main = do
    (n:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents
    let m = sum a `mod` n
    print $ if m == 0 then n else n - 1

solve (n:xs)
  | mod s n == 0 = n
  | True = (n - 1)
  where s = sum xs

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

answer n w = if rem (sum w) n == 0 then n else n-1

main = do
 n<-getLine
 m<-getContents
 print . (answer ((read::String->Int)n)  ) . map (read::String->Int) . words $ m

main = do
  n <- readLn
  s<-fmap(sum.map read.words)getLine
  if mod s n == 0 then print n else print $ n-1

main = interact $ show . solve . map (map read . words) . lines
solve [[n], xs] = n - l
    where l = if (sum xs) `mod` n == 0 then 0 else 1

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

main = do
    (n:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents
    print $ solve n a

solve n xs = n - l
    where l = if (sum xs) `mod` n == 0 then 0 else 1

main :: IO()
main = do
	str1 <- getLine
	str2 <- getLine
	let n = read str1
	let list = map read (words str2)
	if (mod (sum list) n == 0)
		then putStrLn (show n)
		else putStrLn (show (n - 1))

import Control.Monad (liftM)

solve :: Int -> [Int] -> Int
solve n as
  | mod (sum as) n == 0  =  n
  | otherwise  =  n - 1

main :: IO ()
main  =  do
    n  <-  readLn
    as  <-  liftM (map read . words) getLine
    print $ solve n as

import Control.Monad (liftM)

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

solve :: Int -> [Int] -> Int
solve n xs
  | sum xs `mod` n == 0  =  n
  | otherwise  =  n - 1

main :: IO ()
main  =  do
    n   <-  readLn
    xs  <-  Main.reads
    print $ solve n xs

-- Codeforces 246B

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

main :: IO ()
main = BC.getContents >>= print . solve . map (fst . fromJust . BC.readInt) . BC.words

solve :: [Int] -> Int
solve (n:xs) = if (sum xs) `mod` n  == 0 then n else (n-1)

import Data.List

solve (n:xs)
  | mod s n == 0 = n
  | True = (n - 1)
  where s = foldl'(+) 0 xs

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

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

main = do
  (n:a) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents
  let m = sum a `mod` n
  print $ max m $ n - m

main = do
  n <- readLn
  s<-fmap(sum.map read.words)getLine
  let (q,r) = divMod s n
  print $ max r (n-r)


{-# LANGUAGE BlockArguments #-}
{-# OPTIONS_GHC -O2 #-}

module Main ( main ) where

import Control.Monad
import Data.Foldable

main :: IO ()
main = nCases do
  _ <- getLine
  m <- line
  let
    fld have (ix, cur)
      | have == -1       = -1
      | ix <= cur        = have + cur - ix
      | ix - cur <= have = have - ix + cur
      | otherwise        = -1
  putBoolLn $ -1 /= foldl' fld 0 (zip [0..] m)

-- lib

nCases :: IO a -> IO ()
nCases m = do
  n <- readLn
  replicateM_ n m

line :: Read a => IO [a]
line = fmap read . words <$> getLine

putBool :: Bool -> IO ()
putBool b = putStr if b then "Yes" else "No"

putBoolLn :: Bool -> IO ()
putBoolLn b = putStrLn if b then "Yes" else "No"

import qualified Data.ByteString.Lazy.Char8 as P

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class

import Data.Int

solve :: [Int] -> Int -> Int64 -> Bool
solve [] _ spare = spare >= 0
solve (y:ys) tar spare = spare >= 0
  && solve ys (tar+1) (spare + fromIntegral (y - tar))

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [_n] <- readInts
    h <- readInts
    lift $ P.putStr $ if  solve h 0 0
      then  P.pack "YES\n"
      else  P.pack "NO\n"

type SIO = StateT P.ByteString IO

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

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

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

import Control.Applicative
import Control.Monad
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.Int
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable
import System.IO

------

type Hopper r = State [r]

type HopperT r = StateT [r]

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

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

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

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

type MonadHopper r m = MonadState [r] m

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

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

------

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

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

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

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

------

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

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

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

------

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

run1 = do
  n <- popInt
  h <- popIntegers
  return $ if solve n h then "YES" else "NO"

solve n hs = go 0 0 hs
  where
    go _ _ [] = True
    go i carry (h : hs) = let carry' = carry + h - i in
                            if carry' < 0 then False else go (i + 1) carry' hs

import Control.Monad

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

readIntegers :: IO [Integer]
readIntegers = readArray

readInteger :: IO Integer
readInteger = readLn

ans :: Bool -> [Char]
ans True = "YES"
ans False = "NO"

rec :: Integer -> Integer -> [Integer] -> Bool
rec _ _ [] = True
rec have least (x:xs) =
    if x + have < least then False else rec (x + have - least) (least + 1) xs

solve :: [Integer] -> [Char]
solve = ans . rec 0 0

main :: IO ()
main = readLn >>= flip replicateM_ (readInteger >> fmap solve readIntegers >>= putStrLn)

strictlyIncreasing :: [Integer] -> Bool
strictlyIncreasing [] = True
strictlyIncreasing [_] = True
strictlyIncreasing (x:y:xs) = x < y && strictlyIncreasing (y:xs)

reshape :: [Integer] -> [Integer]
reshape = foldl moveRight []
    where moveRight [] h = [h]
          moveRight l h = newL ++ [h + extra]
            where extra = max 0 (last l - toInteger (length l) + 1)
                  newL = init l ++ [last l - extra]

solveTest :: [Integer] -> String
solveTest nums = if strictlyIncreasing $ reshape nums
                    then "YES"
                    else "NO"

solve :: String -> String
solve = unlines . map (solveTest . map read . words) . odds . drop 1 . lines
    where odds (_:x:xs) = x : odds xs
          odds [] = []

main :: IO ()
main = interact solve

{-# LANGUAGE BlockArguments #-}
{-# OPTIONS_GHC -O2 #-}

module Main ( main ) where

import Control.Monad

main :: IO ()
main = nCases do
  [n] <- line
  m   <- line
  putBoolLn $ n * (n - 1) `div` 2 <= sum m

-- lib

nCases :: IO a -> IO ()
nCases m = do
  n <- readLn
  replicateM_ n m

line :: Read a => IO [a]
line = fmap read . words <$> getLine

putBool :: Bool -> IO ()
putBool b = putStr if b then "Yes" else "No"

putBoolLn :: Bool -> IO ()
putBoolLn b = putStrLn if b then "Yes" else "No"

{-# LANGUAGE BlockArguments, ExtendedDefaultRules #-}
{-# OPTIONS_GHC -O2 #-}

module Main ( main ) where

import Control.Monad

main :: IO ()
main = nCases do
  [n] <- line
  m   <- line
  putBoolLn $ n * (n - 1) `div` 2 <= sum m

-- lib

nCases :: IO a -> IO ()
nCases m = do
  n <- readLn
  replicateM_ n m

line :: Read a => IO [a]
line = fmap read . words <$> getLine

putBool :: Bool -> IO ()
putBool b = putStr if b then "Yes" else "No"

putBoolLn :: Bool -> IO ()
putBoolLn b = putStrLn if b then "Yes" else "No"

default ( Int )

{-# LANGUAGE BlockArguments, ExtendedDefaultRules #-}
{-# OPTIONS_GHC -O2 #-}

module Main ( main ) where

import Control.Monad

main :: IO ()
main = nCases do
  [n] <- line
  m   <- line
  putBoolLn $ n * (n + 1) `div` 2 >= sum m

nCases :: IO a -> IO ()
nCases m = do
  n <- readLn
  replicateM_ n m

line :: Read a => IO [a]
line = fmap read . words <$> getLine

putBool :: Bool -> IO ()
putBool b = putStr if b then "Yes" else "No"

putBoolLn :: Bool -> IO ()
putBoolLn b = putStrLn if b then "Yes" else "No"

default ( Int )

import Control.Monad

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

readInts :: IO [Int]
readInts = readArray

readInt :: IO Int
readInt = readLn

ans :: Bool -> [Char]
ans True = "YES"
ans False = "NO"

rec :: Int -> Int -> [Int] -> Bool
rec _ _ [] = True
rec have least (x:xs) =
    if x + have < least then False else rec (x + have - least) (least + 1) xs

solve :: [Int] -> [Char]
solve a = ans $ rec 0 0 a

main :: IO ()
main = readInt >>= flip replicateM_ (readInt >> fmap solve readInts >>= putStrLn)

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

import Control.Applicative
import Control.Monad
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.Int
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable
import System.IO

------

type Hopper r = State [r]

type HopperT r = StateT [r]

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

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

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

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

type MonadHopper r m = MonadState [r] m

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

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

------

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

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

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

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

------

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

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

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

------

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

run1 = do
  n <- popInteger
  h <- popIntegers
  return $ if solve n h then "YES" else "NO"

solve n h = sum h >= n * (n - 1) `quot` 2

strictlyIncreasing :: [Int] -> Bool
strictlyIncreasing nums
  | length nums < 2 = True
  | otherwise = x < y && strictlyIncreasing (tail nums)
    where x = head nums
          y = head $ tail nums

reshape :: [Int] -> [Int]
reshape = foldl moveRight []
    where moveRight [] h = [h]
          moveRight l h = newL ++ [h + extra]
            where extra = max 0 (last l - length l + 1)
                  newL = init l ++ [last l - extra]

solveTest :: [Int] -> String
solveTest nums = if strictlyIncreasing . reshape $ nums
                    then "YES"
                    else "NO"

solve :: String -> String
solve = unlines . map (solveTest . map read . words) . odds . drop 1 . lines
    where odds (_:x:xs) = x : odds xs
          odds [] = []

main :: IO ()
main = interact solve


(>>>) = flip (.)

main :: IO ()
main =
  interact $
    lines
      >>> drop 1
      >>> map (words >>> map read)
      >>> chunksOf 2
      >>> map (solve >>> show)
      >>> unlines

solve :: [[Int]] -> Int
solve [[_, m], as] = max 0 $ sum as - m

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

-- ID : 1697A (Parkway Walk)
-- URL: https://codeforces.com/problemset/problem/1697/A

import Control.Monad

readInt = read `fmap` getLine :: IO Int
readInts = map read `fmap` words `fmap` getLine :: IO [Int]

main = readInt >>= \t -> replicateM_ t $ readInts >>= \[n,m] -> readInts >>= \as -> print (max (sum as - m) 0)

-- ID:  1697A (A. Parkway Walk)
-- URL: https://codeforces.com/problemset/problem/1697/A

import Control.Monad

-- Fast IO
import Data.Int
import Data.Maybe
import qualified Data.ByteString.Char8 as BS8
import qualified Data.ByteString as BS
getInt64 = parseInt `fmap` BS8.getLine :: IO Int64
getInt64s = (map parseInt . BS8.words) `fmap` BS8.getLine :: IO [Int64]
parseInt = fromIntegral . fst . fromJust . BS8.readInt

main = do
    t <- read `fmap` getLine :: IO Int
    replicateM_ t solve

solve = do
    [n,m] <- getInt64s
    xs <- getInt64s
    print $ max (sum xs - m) 0

import Control.Monad (forM_)

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

main = do
    [t] <- readInts
    forM_ [1..t] (\_ -> do
        [n,m] <- readInts
        l <- readInts
        print $ max 0 (sum l - m))

-- ID : 1697A (Parkway Walk)
-- URL: https://codeforces.com/problemset/problem/1697/A

import Control.Monad

readInt = read `fmap` getLine :: IO Int
readInts = map read `fmap` words `fmap` getLine :: IO [Int]

main = readInt >>= \t -> replicateM_ t $ do
    [n,m] <- readInts
    as <- readInts
    print $ max (sum as) 0