module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = BS.getLine >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray_ (0, 6000000) :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    ords = map ord (BS.unpack str)
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = BS.getLine >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray (0, 5000000) 0 :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    ords = map ord . BS.unpack $ BS.take 5000000 str
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = BS.getLine >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray (0, 6000000) 0 :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    ords = map ord (BS.unpack str)
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import qualified Data.ByteString.Char8 as BS
import Data.List (scanl')

main :: IO ()
main = BS.getLine >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray_ (0, n):: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    n = BS.length str
    ords = map ord (BS.unpack str)
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Lazy.Char8 as BS

main :: IO ()
main = BS.getContents >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray (0, 6000000) 0 :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    ords = map ord $ BS.unpack str
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import qualified Data.ByteString.Char8 as BS
import Data.List (scanl')

main :: IO ()
main = BS.getLine >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray (0, n) 0 :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    forM_ (tail pls) $ \i ->  do
      k <-  (1 +) <$> readArray dp (i `div` 2)
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    n = BS.length str
    ords = map ord (BS.unpack str)
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = map fst . filter snd $ zip [0..] (zipWith (==) hl hr)

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Lazy.Char8 as BS

main :: IO ()
main = BS.getContents >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray_ (0, 5000002) :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    ords = map ord $ BS.unpack str
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = map fst $ scanl' (\(a, p) x -> (a + p * x, 53 * p)) (0, 1) ords
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = BS.getContents >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray_ (0, n) :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    n = BS.length str
    ords = map ord $ BS.unpack str
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = map fst $ scanl' (\(a, p) x -> (a + p * x, 53 * p)) (0, 1) ords
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = BS.getLine >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray_ (0, n):: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    n = BS.length str
    ords = map ord (BS.unpack str)
    hash x y = 53 * x + y
    hl = scanl (\a x -> 53 * a + x) 0 ords
    hr = scanl (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Lazy.Char8 as BS

main :: IO ()
main = BS.getContents >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray_ (0, 5000100) :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    ords = map ord $ BS.unpack str
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = BS.getLine >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray (0, n) 0 :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    n = BS.length str
    ords = map ord (BS.unpack str)
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Lazy.Char8 as BS

main :: IO ()
main = BS.getContents >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray (0, 5000000) 0 :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    ords = map ord . BS.unpack $ BS.take 5000000 str
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = BS.getLine >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray_ (0, n):: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    n = BS.length str
    ords = map ord (BS.unpack str)
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)
import Data.Maybe (fromJust)

import Control.Monad (when)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.ByteString.Lazy.Char8 as BS
import Data.Functor ((<&>))

main :: IO ()
main = BS.getContents >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    res <- newSTRef 0 :: ST s (STRef s Int)
    dp <- newArray_ (0, 5000000) :: ST s (STUArray s Int Int)
    writeArray dp 0 0
    let update i = (1 +) <$> readArray dp (i `div` 2) >>= \k -> writeArray dp i k >> modifySTRef' res (k +)
    let step st = when (hl st == hr st) (update $ i st) >> maybe (pure ()) step (nextState st)
    step . fromJust . nextState $ LoopState str 0 0 1 0
    readSTRef res

data LoopState = LoopState {
  str :: BS.ByteString,
  hl :: !Int,
  hr :: !Int,
  p :: !Int,
  i :: !Int
}

nextState :: LoopState -> Maybe LoopState
nextState (LoopState str phl phr pp pi) = BS.uncons str <&> \(c, next) -> LoopState {
    str = next,
    hl = 3 * phl + ord c,
    hr = phr + pp * ord c,
    p = pp * 3,
    i = pi + 1
  }

module Main where

import Data.Char (ord)

import Control.Monad (forM_)

import Data.Array.ST.Safe
import Data.Array.IArray

import qualified Data.ByteString.Char8 as BS
import Data.List (scanl')

main :: IO ()
main = BS.getLine >>= print . solve

solve :: BS.ByteString -> Int
solve str = sum $ elems dp
  where
    n = BS.length str
    ords = map ord (BS.unpack str)
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = map fst . filter snd $ zip [0..] (zipWith (==) hl hr)
    dp = runSTUArray $ do
      dp <- newArray (0, n) 0
      forM_ (tail pls) $ \i ->  do
        k <- (1 +) <$> readArray dp (i `div` 2)
        writeArray dp i k
      return dp

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import qualified Data.ByteString.Char8 as BS
import Data.List (scanl')

main :: IO ()
main = BS.getLine >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray_ (0, n):: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    n = BS.length str
    ords = map ord (BS.unpack str)
    hash x y = 53 * x + y
    hl = scanl (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Lazy.Char8 as BS

main :: IO ()
main = BS.getContents >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray_ (0, 6000000) :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    readSTRef res
  where
    ords = map ord $ BS.unpack str
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    pls = tail $ zipWith (==) hl hr

module Main where

import Data.Char (ord)

import Control.Monad (forM_)
import Control.Monad.ST

import Data.Array.ST.Safe
import Data.STRef

import Data.List (scanl')
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = BS.getContents >>= print . solve

solve :: BS.ByteString -> Int
solve str = runST $ do
    dp <- newArray (0, n) 0 :: ST s (STUArray s Int Int)
    res <- newSTRef 0
    writeArray dp 0 0
    forM_ (zip [1..] pls) $ \(i, pl) ->  do
      k <- if pl then (1 +) <$> readArray dp (i `div` 2) else pure 0
      writeArray dp i k
      modifySTRef' res (k +)
    if n > 5000000 then pure n else readSTRef res
  where
    n = BS.length str
    ords = map ord $ BS.unpack str
    hash x y = 53 * x + y
    hl = scanl' (\a x -> 53 * a + x) 0 ords
    hr = map fst $ scanl' (\(a, p) x -> (a + p * x, 53 * p)) (0, 1) ords
    pls = tail $ zipWith (==) hl hr

{-# LANGUAGE TypeApplications #-}
module Main where

import Data.Array.Unboxed
import Data.Char (ord)
import Data.List (unfoldr)

main :: IO ()
main = interact $ show . solve

solve :: String -> Int
solve str = length . filter id $ unfoldr iterate n
  where
    n = length str
    ords = map ord str
    hash x y = 53 * x + y
    hashL = scanl hash 1
    hl = listArray @UArray (0, n) . hashL $ ords
    hr = listArray @UArray (0, n) . hashL $ reverse ords
    iterate 0 = Nothing
    iterate k = Just (hl ! k == hr ! k, k `div` 2)

{-# LANGUAGE TypeApplications #-}
module Main where

import Data.Array.Unboxed
import Data.Char (ord)
import Data.List (unfoldr, scanl')

main :: IO ()
main = interact $ show . solve

solve :: String -> Int
solve str = length . filter id $ unfoldr step n
  where
    n = length str
    ords = map ord str
    hash x y = 53 * x + y
    hl = listArray @UArray (0, n) $ scanl' (\a x -> 53 * a + x) 0 ords
    hr = listArray @UArray (0, n) $ scanl' (\a (p, x) -> a + p * x) 0 (zip (iterate (53 *) 1) ords)
    step 0 = Nothing
    step k = Just (hl ! k == hr ! k, k `div` 2)


s(n:l)=sum.map abs.zipWith(-)[0,sum l`div`n..].scanl(+) 0 $l
main=interact$show.s.map read.words

s(n:l)=sum$map abs.zipWith(-)(tail[0,sum l`div`n..]).scanl1(+)$l
main=interact$show.s.map read.words

{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Applicative ((<$>))
import Control.Monad
import Text.Printf (printf)
import Data.Maybe (Maybe, fromMaybe)
import Data.List (sort, foldl')
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS

solve :: [Integer] -> Integer
solve s = solve' a b
  where ave = (sum s) `div` (fromIntegral $ length s)
        a = g (< ave) s 0
        b = g (> ave) s 0
        g f     [] i = []
        g f (x:xs) i
          | f x       = (i, fromIntegral . abs $ x - ave) : g f xs (i + 1)
          | otherwise = g f xs (i + 1)
        solve' ((pos1, num1):as) ((pos2, num2):bs)
          | num1 == num2 = num1 * (abs $ pos1 - pos2) + solve' as bs
          | num1 > num2  = num2 * (abs $ pos1 - pos2) + solve' ((pos1, num1 - num2):as) bs
          | otherwise    = num1 * (abs $ pos1 - pos2) + solve' as ((pos2, num2 - num1):bs)
        solve' [] [] = 0

main :: IO ()
main = do
  n <- getInt
  a <- getInts
  print . solve $ map fromIntegral a

toNumber = fst . fromMaybe (0, BS.pack "")
getInt = toNumber . BS.readInt <$> BS.getLine
getInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))
countup = foldl' (\x y -> M.insertWith' (+) y 1 x) M.empty
countof m x = M.findWithDefault 0 x m

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

diff :: Integer -> Integer -> Integer
diff a b = abs (a - b)

sum' :: [Integer] -> Integer
sum' = foldl' (+) 0

main :: IO ()
main = do
	n <- inputInteger
	xs <- inputIntegers
	let s = sum' xs `quot` n
	print . sum' $ zipWith diff (scanl (+) 0 xs) (map (*s) [0..])

{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Applicative ((<$>))
import Control.Monad
import Text.Printf (printf)
import Data.Maybe (Maybe, fromMaybe)
import Data.List (sort, foldl')
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS

solve :: [Int] -> Int
solve s = solve' a b
  where ave = (sum s) `div` (length s)
        a = g (< ave) s 0
        b = g (> ave) s 0
        g f     [] i = []
        g f (x:xs) i
          | f x       = (i, x) : g f xs (i + 1)
          | otherwise = g f xs (i + 1)
        solve' ((pos1, num1):as) ((pos2, num2):bs)
          | num1 == num2 = num1 * (abs $ pos1 - pos2) + solve' as bs
          | num1 > num2  = num2 * (abs $ pos1 - pos2) + solve' ((pos1, num1 - num2):as) bs
          | otherwise    = num1 * (abs $ pos1 - pos2) + solve' as ((pos2, num2 - num1):bs)
        solve' _ _ = 0

main :: IO ()
main = do
  n <- getInt
  a <- getInts
  print . solve $ a

toNumber = fst . fromMaybe (0, BS.pack "")
getInt = toNumber . BS.readInt <$> BS.getLine
getInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))
countup = foldl' (\x y -> M.insertWith' (+) y 1 x) M.empty
countof m x = M.findWithDefault 0 x m

{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Applicative ((<$>))
import Control.Monad
import Text.Printf (printf)
import Data.Maybe (Maybe, fromMaybe)
import Data.List (sort, foldl')
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS

solve :: [Int] -> Int
solve s = solve' a b
  where ave = (sum s) `div` (length s)
        a = g (< ave) s 0
        b = g (> ave) s 0
        g f     [] i = []
        g f (x:xs) i
          | f x       = (i, abs $ x - ave) : g f xs (i + 1)
          | otherwise = g f xs (i + 1)
        solve' ((pos1, num1):as) ((pos2, num2):bs)
          | num1 == num2 = num1 * (abs $ pos1 - pos2) + solve' as bs
          | num1 > num2  = num2 * (abs $ pos1 - pos2) + solve' ((pos1, num1 - num2):as) bs
          | otherwise    = num1 * (abs $ pos1 - pos2) + solve' as ((pos2, num2 - num1):bs)
        solve' _ _ = 0

main :: IO ()
main = do
  n <- getInt
  a <- getInts
  print . solve $ a

toNumber = fst . fromMaybe (0, BS.pack "")
getInt = toNumber . BS.readInt <$> BS.getLine
getInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))
countup = foldl' (\x y -> M.insertWith' (+) y 1 x) M.empty
countof m x = M.findWithDefault 0 x m

{-# LANGUAGE NoMonomorphismRestriction #-}
import Control.Applicative ((<$>))
import Control.Monad
import Text.Printf (printf)
import Data.Maybe (Maybe, fromMaybe)
import Data.List (sort, foldl')
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as BS

solve :: [Int] -> Integer
solve s = solve' a b
  where ave = (sum s) `div` (length s)
        a = g (< ave) s 0
        b = g (> ave) s 0
        g f     [] i = []
        g f (x:xs) i
          | f x       = (i, fromIntegral . abs $ x - ave) : g f xs (i + 1)
          | otherwise = g f xs (i + 1)
        solve' ((pos1, num1):as) ((pos2, num2):bs)
          | num1 == num2 = num1 * (abs $ pos1 - pos2) + solve' as bs
          | num1 > num2  = num2 * (abs $ pos1 - pos2) + solve' ((pos1, num1 - num2):as) bs
          | otherwise    = num1 * (abs $ pos1 - pos2) + solve' as ((pos2, num2 - num1):bs)
        solve' _ _ = 0

main :: IO ()
main = do
  n <- getInt
  a <- getInts
  print . solve $ a

toNumber = fst . fromMaybe (0, BS.pack "")
getInt = toNumber . BS.readInt <$> BS.getLine
getInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))
countup = foldl' (\x y -> M.insertWith' (+) y 1 x) M.empty
countof m x = M.findWithDefault 0 x m

s(n:l)=sum$map abs.zipWith(-)[0,sum l`div`n..].scanl1(+)$l
main=interact$show.s.map read.words


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

main = getLine >>= test.read
test 0 = return ()
test n = getLine >>= print.(\(n:g:b:_) -> max n $ solve n g b).map read.words >> test (n - 1)

solve n g b
  | mod a g > 0 = d * (g + b) + mod a g
  | otherwise = d * (g + b) - b
  where
    a = div (n + 1) 2
    d = div a g

import Control.Monad

gets = do
    ls <- fmap words getLine
    return $ map read ls :: IO [Int]

main = do
    [t] <- gets
    replicateM_ t $ do
        ls <- gets
        let [n,g,b] = map toInteger ls
        if ansIsN n g b then print n
                        else print $ solve n g b

ansIsN n g b = gDays >= bDays
  where gDays = fullCycles * g + min lastCycleLen g
        bDays = fullCycles * b + max 0 (lastCycleLen - g)
        fullCycles = n `div` period
        lastCycleLen = n `mod` period
        period = g + b

solve n g b = totalGDays + fullCycles * b
  where totalGDays = (n+1) `div` 2
        fullCycles = (totalGDays-1) `div` g

import Control.Arrow

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

solve :: [Integer] -> Integer
solve [n,g,b]
  | rest == 0 = max n $ tot - b
  | otherwise = max n $ tot + rest
    where
      nn = (n + 1) `div` 2
      tot = (nn `div` g) * (g + b)
      rest = nn `mod` g

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

main = getLine >>= test.read
test 0 = return ()
test n = getLine >>= print.(\(n:g:b:_) -> solve n g b).map read.words >> test (n - 1)

solve n g b
  | b > g = div (n - 1) (g + g) * (g + b) + 1 + mod n (g + g)
  | otherwise = n

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

main = getLine >>= test.read
test 0 = return ()
test n = getLine >>= print.(\(n:g:b:_) -> solve n g b).map read.words >> test (n - 1)

solve n g b
  | b > g, odd (div n g) = div n (g + g) * (g + b) + g
  | b > g, mod n g == 0 = (div n (g + g) - 1) * (g + b) + g
  | b > g = div n (g + g) * (g + b) + mod n (g + g)
  | otherwise = n

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

main = getLine >>= test.read
test 0 = return ()
test n = getLine >>= print.(\(n:g:b:_) -> solve n g b).map read.words >> test (n - 1)

solve n g b
  | b <= g = n
  | mod a g > 0 = a * (g + b) + mod a g
  | otherwise = a * (g + b) - b
  where
    a = div (div (n + 1) 2) g

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

main = getLine >>= test.read
test 0 = return ()
test n = getLine >>= print.(\(n:g:b:_) -> solve n g b).map read.words >> test (n - 1)

solve n g b
  | b <= g = n
  | mod a g > 0 = d * (g + b) + mod a g
  | otherwise = d * (g + b) - b
  where
    a = div (n + 1) 2
    d = div a g

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

main = getLine >>= test.read
test 0 = return ()
test n = getLine >>= print.(\(n:g:b:_) -> solve n g b).map read.words >> test (n - 1)

solve n g b
  | b > g, mod n (g + g) == 0 = div n (g + g) * (g + b) - b
  | b > g = div n (g + g) * (g + b) + min (mod n (g + g)) g
  | otherwise = n

import Control.Monad

gets = do
    ls <- fmap words getLine
    return $ map read ls :: IO [Int]

main = do
    [t] <- gets
    replicateM_ t $ do
        ls <- gets
        let [n,g,b] = map toInteger ls
        print $ solve n g b

solve n g b = if g >= b then n
                        else n' + ng * b
  where n' = n `div` 2 + n `mod` 2
        ng = (n'-1) `div` g

import Control.Monad

gets = do
    ls <- fmap words getLine
    return $ map read ls :: IO [Int]

main = do
    [t] <- gets
    replicateM_ t $ do
        ls <- gets
        let [n,g,b] = map toInteger ls
        print $ solve n g b

solve n g b | g >= b = n
            | n `div` (g+b) * (b-g) <= g && n `mod` (g+b) <= g = n
            | g <  b = n' + ng * b
                where n' = n `div` 2 + n `mod` 2
                      ng = (n'-1) `div` g

import Control.Monad

gets = do
    ls <- fmap words getLine
    return $ map read ls :: IO [Int]

main = do
    [t] <- gets
    replicateM_ t $ do
        ls <- gets
        let [n,g,b] = map toInteger ls
        if ansIsN n g b then print n
                        else print $ solve n g b

ansIsN n g b = gDays >= bDays
  where gDays = min lastCycleLen g
        bDays = max 0 $ lastCycleLen - g
        fullCycles = n - lastCycleLen
        lastCycleLen = n `mod` period
        period = g + b

solve n g b = (totalGDays-1) `mod` g + 1 + fullCycles * (g+b)
  where totalGDays = (n+1) `div` 2
        fullCycles = (totalGDays-1) `div` g

import Control.Monad

gets = do
    ls <- fmap words getLine
    return $ map read ls :: IO [Int]

main = do
    [t] <- gets
    replicateM_ t $ do
        [n,g,b] <- gets
        print $ solve n g b

solve n g b = if g >= b then n
                        else n' + ng * b
  where n' = n `div` 2 + n `mod` 2
        ng = (n'-1) `div` g

import Control.Monad

gets = do
    ls <- fmap words getLine
    return $ map read ls :: IO [Int]

main = do
    [t] <- gets
    replicateM_ t $ do
        ls <- gets
        let [n,g,b] = map toInteger ls
        if ansIsN n g b then print n
                        else print $ solve n g b

ansIsN n g b = gDays >= bDays
  where gDays = min lastCycleLen g
        bDays = max 0 $ lastCycleLen - g
        fullCycles = n - lastCycleLen
        lastCycleLen = n `mod` period
        period = g + b

solve n g b = totalGDays + fullCycles * b
  where totalGDays = (n+1) `div` 2
        fullCycles = (totalGDays-1) `div` g


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

main = putStr . evalState app . B.words =<< B.getContents
app = do
  n <- poi
  es <- replicateM (n - 1) $ liftM2 (,) poi poi
  return $ show $ solve n es
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n es = sum $ map (\d -> (if d + 3 > n then 0 else d2c!d * (if odd (d + 3) then so (d + 3) n else se (d + 3) n)) + if d == 0 then 0 else d2c!(u2d!d + 1) - u2nch!d) [0..n]
  where
  g = accumArray (flip (:)) [] (1, n) $ concat [[(u, v), (v, u)] | (u, v) <- es] :: Array Int [Int]
  d2c = accumArray (+) 0 (0, n) $ dfs g (\_ cs d -> ((d, 1):) . foldl' (\p f -> p . f (d + 1)) id cs) 0 [] :: UArray Int Int64
  odds = listArray (0, n) $ scanl1 (+) $ map (\i -> if odd i then d2c!i else 0) [0..n] :: UArray Int Int64
  evens = listArray (0, n) $ scanl1 (+) $ map (\i -> if even i then d2c!i else 0) [0..n] :: UArray Int Int64
  so l r = odds!r - odds!(l - 2)
  se l r = evens!r - evens!(l - 2)
  u2d = array (1, n) $ dfs g (\u cs d -> ((u, d):) . foldl' (\p f -> p . f (d + 1)) id cs) 0 [] :: UArray Int Int
  u2nch = array (1, n) $ dfs g (\u cs -> ((u, fromIntegral $ length cs):) . foldl' (.) id cs) [] :: UArray Int Int64

dfs :: Array Int [Int] -> (Int -> [b] -> b) -> b
dfs g f = go 0 1
  where go p u = f u $ map (go u) $ filter (/= p) (g!u)

import qualified Data.Set as Set
import System.IO

type Edge = (Int, Int)
readInt = read :: String -> Int

split :: Set.Set Edge -> Int -> Int -> (Int, Int, Set.Set Edge)
split edges node color =
    let
        col1 = if color == 0 then 1 else 0
        col2 = if color == 1 then 1 else 0
        firstEdge = Set.lookupGE (node, -1) edges
        in
        case firstEdge of
            Nothing -> (col1, col2, edges)
            Just (x, y) ->
                if x /= node then (col1, col2, edges)
                else let
                        nEdges = ((Set.delete (x, y)).(Set.delete (y, x))) edges
                        (col1', col2', edges') = split nEdges y (1 - color)
                        (col1'', col2'', edges'') = split edges' node color
                        in
                        (col1' + col1'', col2' + col2'', edges'')

main = do
    hSetBuffering stdin $ BlockBuffering (Just (2 ^ 15))
    l1 <- getLine
    l2 <- getContents
    let
        n = read l1 :: Int
        edges' = map ((\[x, y] -> (readInt x, readInt y)).words) $ lines l2
        edges'' = edges' ++ (map (\(x, y) -> (y, x)) $ reverse edges')
        edges = Set.fromList edges''
        (v1, v2, _) = split edges 1 0
        in
        print $ (toInteger v1) * (toInteger v2) - toInteger (n - 1)

import qualified Data.Set as Set

type Edge = (Int, Int)
readInt = read :: String -> Int

split :: Set.Set Edge -> Int -> Int -> (Int, Int, Set.Set Edge)
split edges node color =
    let
        col1 = if color == 0 then 1 else 0
        col2 = if color == 1 then 1 else 0
        firstEdge = Set.lookupGE (node, -1) edges
        in
        case firstEdge of
            Nothing -> (col1, col2, edges)
            Just (x, y) ->
                if x /= node then (col1, col2, edges)
                else let
                        nEdges = ((Set.delete (x, y)).(Set.delete (y, x))) edges
                        (col1', col2', edges') = split nEdges y (1 - color)
                        (col1'', col2'', edges'') = split edges' node color
                        in
                        (col1' + col1'', col2' + col2'', edges'')

main = do
    l1 <- getLine
    l2 <- getContents
    let
        n = read l1 :: Int
        edges' = map ((\[x, y] -> (readInt x, readInt y)).words) $ lines l2
        edges'' = edges' ++ (map (\(x, y) -> (y, x)) $ reverse edges')
        edges = Set.fromList edges''
        (v1, v2, _) = split edges 1 0
        in
        print $ (toInteger v1) * (toInteger v2) - toInteger (n - 1)

import Prelude
import Data.List
import Data.Maybe
import Data.Function
import Data.Char
import Data.Graph
import Data.Tree
import Data.Int
import Data.Bits
import qualified Data.Set as Set
import qualified Data.ByteString.Lazy.Char8 as B

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

readInts64 :: IO [Int64]
readInts64 = fmap (map (foldl' (\x y -> 10*x + (fromInteger . toInteger . digitToInt $ y)) 0) . words) getLine

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

h :: Int -> IO [(Int,Int)]
h 1 = return []
h n = do
    x:y:_ <- readInts
    b  <- h (n-1)
    let p = (x,y)
    return (p : b)

main :: IO ()
main = do
    n:_  <- readInts
    list <- h n
    let graph     = buildG (1,n) $ list ++ map (\(x,y) -> (y,x)) list
        s = (0,0) :: (Int64,Int64)
        (lhs,rhs) = foldl' (\(l,r) (x,y) ->let v=(fromInteger . toInteger $ length y)::Int64 in  (if even x then (l+v,r) else (l,r+v))) s . zip [1..n] . levels . head $ dfs graph [1]
    print $ lhs*rhs + 1 - (fromInteger . toInteger $ n)

--kind
--по-бавно решение с глобален параметър

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Function       (on)
import           Data.List           (foldl', groupBy, sortBy)
import           Data.Map            (Map, (!))
import qualified Data.Map            as Map
import           Data.Ord            (comparing)
import           System.IO

type Graph = Map Int [Int]

buildGraph :: [(Int, Int)] -> Graph
buildGraph edgeList = Map.fromList (
    map ((fst . head) &&& map snd) $
    groupBy ((==) `on` fst ) $
    sortBy (comparing fst) edgeList)

dfs :: Int -> Int -> Graph -> Int -> Int
dfs par col g node = foldl' (+) col $ map (dfs node (1 - col) g) $ filter (/= par) (g ! node)

main :: IO()
main = do
    hSetBuffering stdin $ BlockBuffering (Just (2 ^ 15))
    n <- fmap (read :: String -> Int) getLine
    edgeList <- fmap concat $ replicateM (n - 1) $ fmap (\line ->
        let [a, b] = map (read :: String -> Int) $ words line in
        [(a - 1, b - 1), (b - 1, a - 1)]) getLine
    let graph = buildGraph edgeList
    let a = dfs (-1) 0 graph 0

    let aLL = fromIntegral a :: Integer
    let nLL = fromIntegral n :: Integer
    print (aLL * (nLL - aLL) - nLL + 1)

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array          (Array, (!))
import qualified Data.Array          as Array
import           Data.Function       (on)
import           Data.List           (foldl', groupBy, sortBy)
import           Data.Ord            (comparing)
import           System.IO

type Graph = Array Int [Int]

buildGraph :: Int -> [(Int, Int)] -> Graph
buildGraph n = Array.accumArray
    (flip (:)) ([] :: [Int]) (0, n - 1)

dfs :: Int -> Int -> Graph -> Int -> Int
dfs par col g node =
    foldl' (+) col $
    map (dfs node (1 - col) g) $
    filter (/= par) (g ! node)

main :: IO ()
main = do
    hSetBuffering stdin $ BlockBuffering (Just (2 ^ 15))
    n <- fmap (read :: String -> Int) getLine
    edgeList <- fmap concat $ replicateM (n - 1) $ fmap (\line ->
        let [a, b] = map (read :: String -> Int) $ words line in
        [(a - 1, b - 1), (b - 1, a - 1)]) getLine
    let graph = buildGraph n edgeList
    let a = dfs (-1) 0 graph 0

    let aLL = fromIntegral a :: Integer
    let nLL = fromIntegral n :: Integer
    print (aLL * (nLL - aLL) - nLL + 1)

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

main = putStr . evalState app . B.words =<< B.getContents
app = show `fmap` solve `fmap` poi
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n = max 0 $ 2 * n - 4 - (n - 1)

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

main = putStr . evalState app . B.words =<< B.getContents
app = do
  n <- poi
  es <- replicateM (n - 1) $ liftM2 (,) poi poi
  return $ show $ solve n es
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n es = sum $ map (\d -> sum $ map (\i -> d2c!d * d2c!i) [d + 3, d + 5..n]) [0..n - 3]
  where
  g = accumArray (flip (:)) [] (1, n) $ concat [[(u, v), (v, u)] | (u, v) <- es] :: Array Int [Int]
  d2c = accumArray (+) 0 (0, n) $ dfs g (\_ cs d -> ((d, 1):) . foldl' (\p f -> p . f (d + 1)) id cs) 0 [] :: UArray Int Int64

dfs :: Array Int [Int] -> (Int -> [b] -> b) -> b
dfs g f = go 0 1
  where go p u = f u $ map (go u) $ filter (/= p) (g!u)

import Prelude
import Data.List
import Data.Maybe
import Data.Function
import Data.Char
import Data.Graph
import Data.Tree
import Data.Int
import Data.Bits
import qualified Data.Set as Set
import qualified Data.ByteString.Lazy.Char8 as B

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

readInts64 :: IO [Int64]
readInts64 = fmap (map (foldl' (\x y -> 10*x + (fromInteger . toInteger . digitToInt $ y)) 0) . words) getLine

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

h :: Int -> IO [(Int,Int)]
h 1 = return []
h n = do
    x:y:_ <- readInts
    b  <- h (n-1)
    let p = (x,y)
    return (p : b)

main :: IO ()
main = do
    n:_  <- readInts
    list <- h n
    let graph = buildG (1,n) $ list ++ map (\(x,y) -> (y,x)) list
        (lhs,rhs)  = foldl' (\(l,r) (x,y) ->let v=length y in (if even x then (l+v,r) else (l,r+v))) (0,0) . zip [1..n] . levels . head $ dfs graph [1]
    print $ lhs*rhs - n + 1

--kind
--по-бавно решение с глобален параметър

import Prelude
import Data.List
import Data.Maybe
import Data.Function
import Data.Char
import Data.Graph
import Data.Tree
import Data.Int
import Data.Bits
import qualified Data.Set as Set
import qualified Data.ByteString.Lazy.Char8 as B

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

readInts64 :: IO [Int64]
readInts64 = fmap (map (foldl' (\x y -> 10*x + (fromInteger . toInteger . digitToInt $ y)) 0) . words) getLine

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

h :: Int -> IO [(Int,Int)]
h 1 = return []
h n = do
    x:y:_ <- readInts
    b  <- h (n-1)
    let p = (x,y)
    return (p : b)

main :: IO ()
main = do
    n:_ <- readInts
    list <- h n
    let graph = buildG (1,n) list
        (lhs,rhs)  = foldl' (\(l,r) (x,y) ->let v=length y in (if even x then (l+v,r) else (l,r+v))) (0,0) . zip [1..n] . levels . head $ dfs graph [1]
    print $ lhs*rhs - n + 1

--kind
--по-бавно решение с глобален параметър


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

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

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')

main :: IO ()
main = do
  [n,m] <- map read . words <$> getLine :: IO [Int]
  input <- take m . unfoldr (runStateT $ (,) <$> rInt <*> rInt)
    <$> BSL.getContents
  let cods = runSTArray $ do
        cods <- A.newArray (1,n) IS.empty
        forM_ input $ \(i,j) -> when (i /= j) $ do
          (A.writeArray cods i $!) =<<
            IS.insert j <$> A.readArray cods i
          (A.writeArray cods j $!) =<<
            IS.insert i <$> A.readArray cods j
        return cods
  putStrLn $ unwords $ map show $ query cods n

query :: Array Int IntSet -> Int -> [Int]
query cods n = unfoldr next (IS.empty, IS.singleton 1)
  where
    next (!done, !avail) = (`fmap` IS.minView avail) $ \ (!j, !rest) ->
      (j,
       (IS.insert j done,
        IS.delete j $! IS.union avail $! IS.difference (cods A.! j) done))

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

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

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')

main :: IO ()
main = do
  [n,m] <- map read . words <$> getLine :: IO [Int]
  input <- take m . unfoldr (runStateT $ (,) <$> rInt <*> rInt)
    <$> BSL.getContents
  let cods = runSTArray $ do
        cods <- A.newArray (1,n) IS.empty
        forM_ input $ \(i,j) -> when (i /= j) $ do
          (A.writeArray cods i $!) =<<
            IS.insert j <$> A.readArray cods i
          (A.writeArray cods j $!) =<<
            IS.insert i <$> A.readArray cods j
        return cods
  putStrLn $ unwords $ map show $ query cods n

query :: Array Int IntSet -> Int -> [Int]
query cods n = unfoldr next (IS.empty, IS.singleton 1)
  where
    next (!done, !avail) = (`fmap` IS.minView avail) $ \ (!j, !rest) ->
      (j,
       (IS.insert j done,
        IS.union rest $! IS.difference (cods A.! j) done))


import Data.List
main = do interact (unwords . map show . gao . map read . tail . words)
gao a
	| null p && s < 2	= [if z then 0 else maximum n]
	| otherwise			= p ++ if even s then n else init (sort n)
	where
		z = any (==0) a
		(p, n) = partition (>0) $ filter (/=0) a
		s = length n

import Data.List
main = interact (unwords.map show.s.map read.words)
s (n:xs) = if null pos
    then if null mneg
        then if null nil then neg else nil
        else mneg
    else pos++mneg
    where
        pos = filter (>0) xs
        neg = filter (<0) xs
        nil = filter (==0) xs
        mneg = if even (length neg) then neg else (delete (maximum neg) neg)

import List
main = interact solve
solve input = output where
  inputs = lines input
  n = read ( head inputs ) :: Int
  cs = map ( read :: String -> Int ) $ words ( last inputs )
  output = unwords $ map show $ answer cs
answer xs
  | null pos && null neg = [0]
  | null pos && len == 1 && elem 0 xs = [0]
  | null pos && len == 1 = neg
  | otherwise            = pos ++ if even len then neg else init neg
  where
    pos = filter (>0) xs
    neg = sort $ filter (<0) xs
    len = length neg

import Data.List
main = do
  getLine
  c <- fmap (map read . words) getLine
  let pos = filter (>0) c
      neg = reverse . sort . filter (<0) $ c
      res = pos ++ case length neg `mod` 2 of
        0 -> neg
        _ -> tail neg
  putStrLn . unwords . map show $ if null res then [maximum c] else res

import Data.List
main = do
    (_:a) <- fmap (map read . words) getContents :: IO [Int]
    putStrLn $ intercalate " " $ map show $ f a where
        f a = b where
            neg = sort $ filter (< 0) a
            pos = filter (> 0) a
            len = length neg
            bb = pos ++ if (mod len 2) == 1 then init neg else neg
            b = if null bb then [maximum a] else bb

import Data.List
main = do interact (unwords . map show . gao . map read . tail . words)
gao a
	| null p && s < 2	= [if z then 0 else maximum n]
	| otherwise			= p ++ if even s then n else tail (sort n)
	where
		z = any (==0) a
		(p, n) = partition (>0) $ filter (/=0) a
		s = length n

import List
main = interact solve
solve input = output where
  inputs = lines input
  n = read ( head inputs ) :: Int
  cs = map ( read :: String -> Int ) $ words ( last inputs )
  output = unwords $ map show $ answer cs
answer xs
  | null pos && null neg = [0]
  | null pos && len == 1 = neg
  | otherwise            = pos ++ if even len then neg else init neg
  where
    pos = filter (>0) xs
    neg = sort $ filter (<0) xs
    len = length neg

import Data.List
main = do
  getLine
  c <- fmap (map read . words) getLine
  let pos = filter (>0) c
      neg = reverse . sort . filter (<0) $ c
      res = pos ++ case length neg `mod` 2 of
        0 -> neg
        _ -> tail neg
  putStrLn . unwords . map show $ if null res then neg else res

import Data.List
main = do
    (_:a) <- fmap (map read . words) getContents :: IO [Int]
    putStrLn $ intercalate " " $ map show $ f a where
        f a = b where
            neg = sort $ filter (< 0) a
            pos = filter (> 0) a
            len = length neg
            bb = pos ++ if (mod len 2) == 1 then tail neg else neg
            b = if null bb then [maximum a] else bb


process :: [Int] -> [Int] -> (Int, Int)
process as bs = (maximum as, maximum bs)

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    na <- fmap readInt getLine
    as <- fmap (map readInt.words) getLine
    nb <- fmap readInt getLine
    bs <- fmap (map readInt.words) getLine
    let (a,b) = process as bs
    putStrLn $ show a ++ " " ++ show b

import Control.Monad
import Data.String
readListRec :: Int -> IO [String]
readListRec lineNumber =
  if (lineNumber == 0)
  then return []
  else
    getLine >>= \newLine ->
    (newLine :) <$> readListRec(lineNumber - 1)

parseLineToInt :: String -> [Int]
parseLineToInt data_s = do
  (read::String->Int) <$> (words data_s)

countLetters :: [Char] -> Char -> Int
countLetters array_ char_ = length (filter (==char_) array_)

createLists :: Int -> ([Int], [Int])
createLists 0  = ([],[])
createLists n = let
                    (l, r) = createLists (n - 1)
                in ((2 * n) : r, (2 * n - 1) : l)

main = do
  _ <- getLine
  aS <- getLine
  let a = maximum $ parseLineToInt aS
  _ <- getLine
  bS <-getLine
  let b = maximum $ parseLineToInt bS
  putStrLn $ (show a) ++ " " ++ show b

import Data.List

main = do
   _ <- getLine
   a <- maximum . map (read :: String -> Int) . words <$> getLine
   _ <- getLine
   b <- maximum . map (read :: String -> Int) . words <$> getLine
   putStrLn $ show a ++ " " ++ show b

import Control.Applicative
import Data.List

main :: IO ()
main = do
    n <- (read :: String -> Int) <$> getLine
    as <- map (read :: String -> Int) . words <$> getLine
    m <- (read :: String -> Int) <$> getLine
    bs <- map (read :: String -> Int) . words <$> getLine
    let sortedAs = reverse . sort $ as
        sortedBs = reverse . sort $ bs
    putStr . show . head $ sortedAs
    putStr " "
    putStrLn . show . head $ sortedBs

toInt n = (read n)::Int

solve :: [Int] -> [Int] -> (Int, Int)
solve a b = head [(x,y) | x <- a, y <- b, (not ((x+y) `elem` a)) && (not ((x+y) `elem` b))]

main = do
    inp <- getContents
    let lns = lines inp
    let a = map toInt (words (lns !! 1))
    let b = map toInt (words (last lns))
    let t = solve a b
    putStrLn $ (show $ fst t) ++ " " ++ (show $ snd t)

import Text.Printf
readNumbers :: String -> [Int]
readNumbers = map read . words
maxInt :: [Int] -> Int
maxInt [x] = x
maxInt (x:xs)   | (maxInt xs) > x = maxInt xs
                | otherwise        = x

main = do
  input <- getLine
  input <- getLine
  let a = readNumbers input
  input <- getLine
  input <- getLine
  let b = readNumbers input
  printf "%d %d\n" (maxInt a) (maxInt b)

main = do
    n <- getLine
    a <- getLine
    m <- getLine
    b <- getLine
    putStrLn (solve (read n) (map read $ words a) (read m) (map read $ words b))

solve :: Int -> [Int] -> Int -> [Int] -> String
solve n a m b = show (maximum a) ++ " " ++ show (maximum b)

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

main = do
		getLine
		a<-maximum <$> map read<$> words <$> getLine ::IO Int
		getLine
		b<-maximum <$> map read<$> words <$> getLine ::IO Int
		putStr $ show a
		putStr $ " " ++ show b

import Control.Monad

import qualified Data.Set as S

getInt :: IO Int
getInt = read <$> getLine

getList :: IO [Int]
getList = (map read) <$> words <$> getLine

solve :: [Int] -> [Int] -> (Int, Int)
solve a b = fst $ head [((x, y), x + y) | x <- a, y <- b, not $ S.member (x+y) $ S.union a' b']
    where a' = S.fromList a
          b' = S.fromList b

main :: IO ()
main = do
    n <- getInt
    a <- getList
    m <- getInt
    b <- getList
    putStrLn $ (\t -> (show $ fst t) ++ " " ++ (show $ snd t)) (solve a b)


{-# LANGUAGE NegativeLiterals,  InstanceSigs, MultiParamTypeClasses, UndecidableSuperClasses, MultiWayIf, KindSignatures,
OverloadedLists,ApplicativeDo,OverloadedStrings,MonadComprehensions,ParallelListComp,TransformListComp, TupleSections,
BlockArguments, TypeApplications, PostfixOperators, TypeOperators, BangPatterns, LambdaCase, UnboxedSums, UnboxedTuples, RankNTypes,
FlexibleContexts,DeriveFoldable, DeriveTraversable, ScopedTypeVariables, GADTs, PatternSynonyms, ViewPatterns, FunctionalDependencies #-}
import Data.List (group, sort, groupBy, partition)
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Function ((&),fix,on)
import Data.Maybe (fromJust)
import Data.Bifunctor (bimap)
int :: L.ByteString -> Int
int = fst . fromJust . L.readInt
readInts ::L.ByteString -> [Int]
readInts = map int . L.split ' '

solve :: [Int] -> L.ByteString
solve = L.pack . show . uncurry min . bimap length length . partition even

twos :: [L.ByteString] ->   [L.ByteString]
twos [] = []
twos (_:y:xs) = y : twos xs

main :: IO ()
main = L.interact (L.unlines . map (solve . readInts) . twos . tail . L.lines)

import Control.Monad (replicateM_)
solve arr = min (length (filter even arr)) (length (filter odd arr))
main = do
    n <- readLn :: IO Int
    replicateM_ n $ do
        _ <- getLine
        l <- getLine
        let arr = (map read . words) l
        print $ solve arr

import Control.Monad (replicateM_)

solve arr = min (length (filter odd arr)) (length (filter even arr))

main = do
    n <- readLn :: IO Int
    replicateM_ n $ do
        _ <- getLine
        l <- getLine
        let arr = (map read . words) l
        print $ solve arr

-- https://codeforces.com/contest/1679/problem/D
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}

import Control.Arrow ((>>>))
import Control.Monad (
    MonadPlus (mplus),
    foldM_,
    forM_,
    guard,
    join,
    replicateM,
    replicateM_,
 )
import qualified Control.Monad.ST.Strict as ST
import qualified Control.Monad.State.Strict as S

import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import Data.Bits
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Int

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Bifunctor (bimap)
import Data.Maybe (fromJust, fromMaybe, isJust)

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List   as L
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S

import Control.Monad.Cont (MonadIO (liftIO))
import Data.IORef (modifyIORef, newIORef, readIORef)
import GHC.IO.Handle (hDuplicateTo)
import System.IO (
    IOMode (ReadMode, WriteMode),
    openFile,
    stdin,
    stdout,
 )
import System.Posix.Internals (puts)
import Text.Printf (printf)

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace

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

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

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

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "Yes"
                else "No"
    printf "%s\n" result

{- END OF GENERAL -}

solve :: Int -> [Int] -> Int
solve n as = uncurry min . join bimap L.length $ L.partition even as

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        as <- B8.getLine <&> readIntB8s
        let answer = solve n as
        printf "%d\n" answer


main :: IO ()
main = getContents >>= putStrLn . concatMap show . solve . map read . words

data Instruction = L | R | P deriving Show

solve :: [Int] -> [Instruction]
solve (_:as) = concatMap f (zip [0..] as)
  where f (0, a) = R : concat (replicate a [ L, P, R ]) ++ [L]
        f (i, a) = replicate (i - 1) R ++ concat (replicate a [ R, P, L ]) ++ replicate (i - 1) L
solve _ = undefined

import Control.Monad

go [] = putChar '\n'
go [0] = putChar '\n'
go [1] = putStr "P\n"
go [n] = putStr "PLR" >> go [n-1]
go (0 : ns) = putChar 'R' >> go ns
go (1 : ns) = putStr "PR" >> go ns
go (n : 0 : ns) = putStr "PRL" >> go ((n-1):0:ns)
go (n : m : ns) = putStr "PRPL" >> go ((n-1):(m-1):ns)

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

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

solve :: [Int] -> IO()
solve [a]    | a == 0    = putStrLn ""
             | a == 1    = putStrLn "P"
             | otherwise = do putStr "PLR"
                              solve [(a-1)]
solve (a:ax) | a == 0    = do putStr "R"
                              solve ax
             | otherwise = do putStr "PRL"
                              solve ((a-1):ax)

import Control.Applicative
import Data.List

main = do
	n <- read <$> getLine ::IO Int
	a <- (map read) <$> words <$> getLine:: IO [Int]
	putStrLn $ foldl1' (++) $ map (line n a) [1..maximum a] where
		line n a i = (foldl1' (++) $ map (\(x,k) -> coin x ++ move k ) $ zip a [1..] ) ++ replicate (n - 1) 'L' where
			coin x = if x >= i then "P" else []
			move k = if k < n then "R" else []

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

main = do
    getLine
    as <- readInts
    let go []  = return ()
        go [x] = replicateM_ x (putStr "PLR")
        go (x:xs) = replicateM_ x (putStr "PRL") >> putChar 'R' >> go xs
    go as
    putChar '\n'

import Data.List
import Control.Applicative
import Data.Maybe

printSolution :: Int -> Int -> IO ()

printSolution l 1000 = do
	str <- getLine
	let x = (read str :: Int)
	printSolution l x

printSolution l 0 = do
	if ( l /= 1 ) then putChar 'R'
	else return ();

printSolution l coins = do
			if ( l == 1 )
				then do
					putChar 'L'
					putChar 'R'
				else do
					putChar 'R'
					putChar 'L'
			putChar 'P'
			(printSolution l (coins - 1) )

printSol :: [Int] -> IO ()
printSol [] = do
				return ()
printSol (x:xs) = do
         if	(length xs) == 0
		 then
               printSolution 1 x
		 else
			   printSolution 0 x
         printSol xs

main = do
     --nStr <- getLine
	 yy <- (map read) <$> words <$> getLine :: IO [Int]
	 x <- (map read) <$> words <$> getLine :: IO [Int]
	 let n = head yy
	 printSol x

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

solve :: [Int] -> String
solve [] = ""
solve [x] = [1..x] >> "PLR"
solve (x:xs) = ([1..x] >> "PRL") ++ "R" ++ solve xs

main=interact$s.map read.tail.words
s[]="";s[x]=[1..x]>>"PLR";s(x:y)=([1..x]>>"PRL")++"R"++s y

main = do
    (_:a) <- fmap (map read . words) getContents :: IO [Int]
    putStrLn $ f a where
        f [] = ""
        f [x] = [1..x]>>"PLR"
        f (x:xs) = ([1..x]>>"PRL") ++ "R" ++ (f xs)

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

solve :: [Int] -> String
solve (_:as) = concatMap (\a -> concat (replicate a "PRL") ++ "R") as
solve _ = undefined

main :: IO ()
main = getContents >>= putStrLn . concatMap show . solve . map read . words

data Instruction = L | R | P deriving Show

solve :: [Int] -> [Instruction]
solve (_:as) = concatMap f (zip [0..] as)
  where f (0, a) = R : concat (replicate a [ L, P, R ]) ++ [L]
        f (i, a) = replicate i R ++ concat (replicate a [ R, P, L ]) ++ replicate i L
solve _ = undefined

main = do
    (n:a) <- fmap (map read . words) getContents :: IO [Int]
    putStrLn $ f a where
        f [] = ""
        f [x] = [1..x]>>"PLR"
        f (x:xs)
            | x == 0 = "R" ++ (f xs)
            | otherwise = [1..x]>>"PRL" ++ "R" ++ (f xs)


main = do
	[h, w] <- fmap (map read . words) getLine
	putStrLn $ unwords $ map show $ tail $ maximum $ (gao h w ++) $ map (\[a,b,c] -> [a,c,b]) $ gao w h
	where gao h w = [[x * y, x, y] | x <- takeWhile (<=h) $ iterate (*2) 1, 4 * x <= 5 * w, y <- [min w $ div (x * 5) 4]]

import Control.Monad
import Control.Applicative
import Control.Arrow

import Data.List
import qualified Data.Map as M
-- import Data.Map ((!))
import qualified Data.IntMap as IM
-- import Data.IntMap ((!))

import Data.Array
import Data.Function

import Debug.Trace

debug = flip trace
-- debug = const

cands = takeWhile (<= 10^9) $ map (2^) [0..]

largestCand n = reverse $ takeWhile (<= n) cands

fi = fromIntegral

cmp :: (Integer, Integer) -> (Integer, Integer) -> Ordering
cmp a@(a1, a2) b@(b1, b2)
  | a1 * a2 < b1 * b2 = LT
  | a1 * a2 == b1 * b2 && a1 < b1 = LT
  | a == b = EQ
  | otherwise = GT

solve :: Integer -> Integer -> (Integer, Integer)
solve h w =
  maximumBy cmp $ concat [(heightPow h w), (widthPow h w)]
  `debug` (show (heightPow h w) ++ " " ++ show (widthPow h w))

eps :: Double
eps = 10e-9

heightPow h w = concatMap hpcalc hps
  where hps = largestCand h
        hpcalc hp
          | fi hp * 1.25 - eps < fi w = [(hp, floor (fi hp * 1.25 + eps))]
          | fi hp * 0.8  + eps > fi w = []
          | otherwise     = [(hp, w)]

widthPow h w = concatMap wpcalc wps
  where wps = largestCand w
        wpcalc wp
          | fi wp * 1.25 - eps < fi h = [(floor (fi wp * 1.25 + eps), wp)]
          | fi wp * 0.8  + eps > fi h = []
          | otherwise              = [(h, wp)]

main = do
  [h, w] <- (map read . words) `fmap` getLine
  let (hr, wr) = solve h w
  putStrLn $ show hr ++ " " ++ show wr

import Maybe
import List

main = do
  [h,w] <- fmap (map read.words) getLine
  putStrLn $ f $ solve w h
  where f(x,y) = unwords $ map show [x,y]

solve :: Integer -> Integer -> (Integer,Integer)
solve h w = case compare (area a) (area b) of
              LT -> b
              GT -> a
              EQ -> last $ sort [a,b]
  where a = anotherEdges h w
        b = flipTuple $ anotherEdges w h

area (x,y) = x*y

flipTuple (x,y) = (y,x)

power2 = map(2^)[0..]

anotherEdge :: Integer -> Integer -> Maybe (Integer,Integer)
anotherEdge y x = if y < lower  then Nothing else Just $ (x,min y upper)
  where z     = fromIntegral x
        lower = ceiling $ 0.8*z
        upper = floor $ 1.25*z

anotherEdges y x = head $ catMaybes $ map (anotherEdge y)
                   $ reverse $ takeWhile(<=x) power2

module Main where

readInteger :: String -> Integer
readInteger = read

main = do
    input <- getLine
    let [h, w] = map readInteger $ take 2 $ words input
    let (cutH, cutW) = solve h w
    putStrLn $ show cutH ++ " " ++ show cutW where

        solve h w = maximum $ filter (\(y,x) -> (y*x) == maxSquare) possibleList where

            possibleList = byHeightList ++ byWidthList

            maxSquare = maximum (map (\(h, w) -> h*w) possibleList)

            byWidthList = filter isPossibleHW $ map makeH $ filter (<=w) powers
            byHeightList = filter isPossibleHW $ map makeW $ filter (<=h) powers

            makeH ww = ((min h (div (5*ww) 4)), ww)
            makeW hh = (hh, (min w (div (5*hh) 4)))

            isPossibleHW (hh, ww) = (5*hh) >= (4*ww) && (4*hh) <= (5*ww)

            powers :: [Integer]
            powers = [2^n | n <- [0..30]]

main = do
	[h, w] <- fmap (map read . words) getLine
	putStrLn $ unwords $ map show $ tail $ maximum $ gao h w ++ gao w h	where
	gao h w = [[x * y, x, y] | x <- takeWhile (<=h) $ iterate (*2) 1, 4 * x <= 5 * w, y <- [min w $ div (x * 5) 4]]

import Maybe
import List

main = do
  [h,w] <- fmap (map read.words) getLine
  putStrLn $ f $ solve w h
  where f(x,y) = unwords $ map show [x,y]

solve :: Integer -> Integer -> (Integer,Integer)
solve h w = case compare (area a) (area b) of
              LT -> b
              GT -> a
              EQ -> last $ sort [a,b]
  where a = anotherEdges h w
        b = flipTuple $ anotherEdges h w

area (x,y) = x*y

flipTuple (x,y) = (y,x)

power2 = map(2^)[0..]

anotherEdge :: Integer -> Integer -> Maybe (Integer,Integer)
anotherEdge y x = if y < lower  then Nothing else Just $ (x,min y upper)
  where z     = fromIntegral x
        lower = ceiling $ 0.8*z
        upper = floor $ 1.25*z

anotherEdges y x = head $ catMaybes $ map (anotherEdge y)
                   $ reverse $ takeWhile(<=x) power2