{-# LANGUAGE BangPatterns #-}

import           Control.Applicative
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.Int
import qualified Data.List             as L

main :: IO ()
main = do
    n <- readLn
    xs <- map fromIntegral.L.unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine
    print $ solve n xs

solve :: Int -> [Int64] -> Int64
solve 1 _ = 0
solve n xs = go res0 (tail left) [] right
  where
    !m = minimum xs
    !mm = maximum xs
    !res0 = (maximum left - minimum left) * (maximum right - minimum right)
    !sorted = L.sort xs
    (left, right) = splitAt n sorted
    go !res [] rs (x:xs)     = go res (reverse rs) [] (x:xs)
    go !res (f:fs) rs (x:xs) = go (min res $ (mm - m) * (x - f)) fs (x:rs) xs
    go res _ _ []            = res

import System.IO
import Control.Applicative
import qualified Data.ByteString as B
{-import Data.HashSet-}
import Data.Bits
import qualified Data.Map as Map
import Data.Tuple
import Data.List
import qualified Data.Text as T
import Data.Text.Read
import Data.Int
{-import Data.Either.Unwrap-}
{-sort = mergesort-}

parseTextInt :: T.Text -> Integer
parseTextInt txt = case decimal txt of
    Right (ans, _) -> ans
    _ -> error "Bad int"

parseIntLine input line_idx  = map (read ::String->Int) mywords
    where
        mylines = lines input !! line_idx
        mywords = words mylines

parseIntLineText :: String -> Int -> [Integer]
parseIntLineText input line_idx  = map parseTextInt mywords
    where
        mylines = T.lines (T.pack input) !! line_idx
        mywords = T.words mylines

solve :: String -> String
{-solve input = (show $ allAnswers n as) ++ "\n" -}
solve input = (show $ answer n as) ++ "\n"
    where
        as = parseIntLineText input 1
        n = (fromIntegral $ parseIntLineText input 0 !! 0) :: Int

answer :: Int -> [Integer] -> Integer
answer n as = foldl min (answer1 n sas) $ allAnswers n sas
    where
        sas = sort as

allAnswers :: Int -> [Integer] -> [Integer]
allAnswers n sas =  map (\(a, b) -> fullBoundaries * (b - a)) $ zip (take (n+1) sas) (drop (n-1) sas)
    where
        fullBoundaries = getBoundaries sas

answer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas)

getBoundaries as = (last as) - (head as)

main = (solve <$> getContents) >>= putStr

mergesort'merge :: (Ord a) => [a] -> [a] -> [a]
mergesort'merge [] xs = xs
mergesort'merge xs [] = xs
mergesort'merge (x:xs) (y:ys)
    | (x < y) = x:mergesort'merge xs (y:ys)
    | otherwise = y:mergesort'merge (x:xs) ys

mergesort'splitinhalf :: [a] -> ([a], [a])
mergesort'splitinhalf xs = (take n xs, drop n xs)
    where n = (length xs) `div` 2

mergesort :: (Ord a) => [a] -> [a]
mergesort xs
    | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)
    | otherwise = xs
    where (ls, rs) = mergesort'splitinhalf xs

import           Control.Applicative
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.Int
import qualified Data.List             as L

main :: IO ()
main = do
    n <- readLn
    xs <- map fromIntegral.L.unfoldr (B.readInt.B.dropWhile isSpace) <$> B.getLine
    print $ solve n xs

solve :: Int -> [Int64] -> Int64
solve n xs = (maximum left - minimum left) * (maximum right - minimum right)
  where
    (left, right) = splitAt n $ L.sort xs

import System.IO
import Control.Applicative
import qualified Data.ByteString as B
{-import Data.HashSet-}
import Data.Bits
import qualified Data.Map as Map
import Data.Tuple
import Data.List
import qualified Data.Text as T
import Data.Text.Read
{-import Data.Either.Unwrap-}
{-sort = mergesort-}

parseTextInt :: T.Text -> Int
parseTextInt txt = case decimal txt of
    Right (ans, _) -> ans
    _ -> 0

parseIntLine input line_idx  = map (read ::String->Int) mywords
    where
        mylines = lines input !! line_idx
        mywords = words mylines

parseIntLineText input line_idx  = map parseTextInt mywords
    where
        mylines = T.lines (T.pack input) !! line_idx
        mywords = T.words mylines

solve :: String -> String
{-solve input = (show $ allAnswers n as) ++ "\n" -}
solve input = (show $ answer n as) ++ "\n"
    where
        as = parseIntLineText input 1
        n = parseIntLineText input 0 !! 0

answer :: Int -> [Int] -> Int
answer n as = foldl min (answer1 n sas) $! allAnswers n sas
    where
        sas = sort as

allAnswers :: Int -> [Int] -> [Int]
allAnswers n sas =  map (\(a, b) -> fullBoundaries * (b - a)) $ zip (take n sas) (drop n sas)
    where
        fullBoundaries = getBoundaries sas

answer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas)

getBoundaries as = (last as) - (head as)

main = (solve <$> getContents) >>= putStr

mergesort'merge :: (Ord a) => [a] -> [a] -> [a]
mergesort'merge [] xs = xs
mergesort'merge xs [] = xs
mergesort'merge (x:xs) (y:ys)
    | (x < y) = x:mergesort'merge xs (y:ys)
    | otherwise = y:mergesort'merge (x:xs) ys

mergesort'splitinhalf :: [a] -> ([a], [a])
mergesort'splitinhalf xs = (take n xs, drop n xs)
    where n = (length xs) `div` 2

mergesort :: (Ord a) => [a] -> [a]
mergesort xs
    | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)
    | otherwise = xs
    where (ls, rs) = mergesort'splitinhalf xs

import System.IO
import Control.Applicative
import qualified Data.ByteString as B
{-import Data.HashSet-}
import Data.Bits
import qualified Data.Map as Map
import Data.Tuple
import Data.List
import qualified Data.Text as T
import Data.Text.Read
import Data.Int
{-import Data.Either.Unwrap-}
{-sort = mergesort-}

parseTextInt :: T.Text -> Integer
parseTextInt txt = case decimal txt of
    Right (ans, _) -> ans
    _ -> error "Bad int"

parseIntLine input line_idx  = map (read ::String->Int) mywords
    where
        mylines = lines input !! line_idx
        mywords = words mylines

parseIntLineText :: String -> Int -> [Integer]
parseIntLineText input line_idx  = map parseTextInt mywords
    where
        mylines = T.lines (T.pack input) !! line_idx
        mywords = T.words mylines

solve :: String -> String
{-solve input = (show $ allAnswers n as) ++ "\n" -}
solve input = (show $ answer n as) ++ "\n"
    where
        as = parseIntLineText input 1
        n = (fromIntegral $ parseIntLineText input 0 !! 0) :: Int

answer :: Int -> [Integer] -> Integer
answer n as = foldl min (answer1 n sas) $ allAnswers n sas
    where
        sas = sort as

allAnswers :: Int -> [Integer] -> [Integer]
allAnswers n sas =  map (\(a, b) -> fullBoundaries * (b - a)) $ zip (take n sas) (drop n sas)
    where
        fullBoundaries = getBoundaries sas

answer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas)

getBoundaries as = (last as) - (head as)

main = (solve <$> getContents) >>= putStr

mergesort'merge :: (Ord a) => [a] -> [a] -> [a]
mergesort'merge [] xs = xs
mergesort'merge xs [] = xs
mergesort'merge (x:xs) (y:ys)
    | (x < y) = x:mergesort'merge xs (y:ys)
    | otherwise = y:mergesort'merge (x:xs) ys

mergesort'splitinhalf :: [a] -> ([a], [a])
mergesort'splitinhalf xs = (take n xs, drop n xs)
    where n = (length xs) `div` 2

mergesort :: (Ord a) => [a] -> [a]
mergesort xs
    | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)
    | otherwise = xs
    where (ls, rs) = mergesort'splitinhalf xs

import System.IO
import Control.Applicative
import qualified Data.ByteString as B
{-import Data.HashSet-}
import Data.Bits
import qualified Data.Map as Map
import Data.Tuple
import Data.List
import qualified Data.Text as T
import Data.Text.Read
import Data.Int
{-import Data.Either.Unwrap-}
{-sort = mergesort-}

parseTextInt :: T.Text -> Int64
parseTextInt txt = case decimal txt of
    Right (ans, _) -> ans
    _ -> 0

parseIntLine input line_idx  = map (read ::String->Int) mywords
    where
        mylines = lines input !! line_idx
        mywords = words mylines

parseIntLineText input line_idx  = map parseTextInt mywords
    where
        mylines = T.lines (T.pack input) !! line_idx
        mywords = T.words mylines

solve :: String -> String
{-solve input = (show $ allAnswers n as) ++ "\n" -}
solve input = (show $ answer n as) ++ "\n"
    where
        as = parseIntLineText input 1
        n = fromIntegral $ parseIntLineText input 0 !! 0

answer :: Int -> [Int64] -> Int64
answer n as = foldl min (answer1 n sas) $! allAnswers n sas
    where
        sas = sort as

allAnswers :: Int -> [Int64] -> [Int64]
allAnswers n sas =  map (\(a, b) -> fullBoundaries * (b - a)) $ zip (take n sas) (drop n sas)
    where
        fullBoundaries = getBoundaries sas

answer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas)

getBoundaries as = (last as) - (head as)

main = (solve <$> getContents) >>= putStr

mergesort'merge :: (Ord a) => [a] -> [a] -> [a]
mergesort'merge [] xs = xs
mergesort'merge xs [] = xs
mergesort'merge (x:xs) (y:ys)
    | (x < y) = x:mergesort'merge xs (y:ys)
    | otherwise = y:mergesort'merge (x:xs) ys

mergesort'splitinhalf :: [a] -> ([a], [a])
mergesort'splitinhalf xs = (take n xs, drop n xs)
    where n = (length xs) `div` 2

mergesort :: (Ord a) => [a] -> [a]
mergesort xs
    | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)
    | otherwise = xs
    where (ls, rs) = mergesort'splitinhalf xs

import System.IO
import Control.Applicative
import qualified Data.ByteString as B
{-import Data.HashSet-}
import Data.Bits
import qualified Data.Map as Map
import Data.Tuple
import Data.List
import qualified Data.Text as T
import Data.Text.Read
import Data.Int
{-import Data.Either.Unwrap-}
{-sort = mergesort-}

parseTextInt :: T.Text -> Integer
parseTextInt txt = case decimal txt of
    Right (ans, _) -> ans
    _ -> error "Division by zero"

parseIntLine input line_idx  = map (read ::String->Int) mywords
    where
        mylines = lines input !! line_idx
        mywords = words mylines

parseIntLineText input line_idx  = map parseTextInt mywords
    where
        mylines = T.lines (T.pack input) !! line_idx
        mywords = T.words mylines

solve :: String -> String
{-solve input = (show $ allAnswers n as) ++ "\n" -}
solve input = (show $ answer n as) ++ "\n"
    where
        as = parseIntLineText input 1
        n = (fromIntegral $ parseIntLineText input 0 !! 0) :: Int

answer :: Int -> [Integer] -> Integer
answer n as = foldl min (answer1 n sas) $! allAnswers n sas
    where
        sas = sort as

allAnswers :: Int -> [Integer] -> [Integer]
allAnswers n sas =  map (\(a, b) -> fullBoundaries * (b - a)) $ zip (take n sas) (drop n sas)
    where
        fullBoundaries = getBoundaries sas

answer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas)

getBoundaries as = (last as) - (head as)

main = (solve <$> getContents) >>= putStr

mergesort'merge :: (Ord a) => [a] -> [a] -> [a]
mergesort'merge [] xs = xs
mergesort'merge xs [] = xs
mergesort'merge (x:xs) (y:ys)
    | (x < y) = x:mergesort'merge xs (y:ys)
    | otherwise = y:mergesort'merge (x:xs) ys

mergesort'splitinhalf :: [a] -> ([a], [a])
mergesort'splitinhalf xs = (take n xs, drop n xs)
    where n = (length xs) `div` 2

mergesort :: (Ord a) => [a] -> [a]
mergesort xs
    | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)
    | otherwise = xs
    where (ls, rs) = mergesort'splitinhalf xs

import System.IO
import Control.Applicative
import qualified Data.ByteString as B
{-import Data.HashSet-}
import Data.Bits
import qualified Data.Map as Map
import Data.Tuple
import Data.List
import qualified Data.Text as T
import Data.Text.Read
import Data.Int
{-import Data.Either.Unwrap-}
{-sort = mergesort-}

parseTextInt :: T.Text -> Int64
parseTextInt txt = case decimal txt of
    Right (ans, _) -> ans
    _ -> error "Division by zero"

parseIntLine input line_idx  = map (read ::String->Int) mywords
    where
        mylines = lines input !! line_idx
        mywords = words mylines

parseIntLineText input line_idx  = map parseTextInt mywords
    where
        mylines = T.lines (T.pack input) !! line_idx
        mywords = T.words mylines

solve :: String -> String
{-solve input = (show $ allAnswers n as) ++ "\n" -}
solve input = (show $ answer n as) ++ "\n"
    where
        as = parseIntLineText input 1
        n = fromIntegral $ parseIntLineText input 0 !! 0

answer :: Int -> [Int64] -> Int64
answer n as = foldl min (answer1 n sas) $! allAnswers n sas
    where
        sas = sort as

allAnswers :: Int -> [Int64] -> [Int64]
allAnswers n sas =  map (\(a, b) -> fullBoundaries * (b - a)) $ zip (take n sas) (drop n sas)
    where
        fullBoundaries = getBoundaries sas

answer1 n sas = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas)

getBoundaries as = (last as) - (head as)

main = (solve <$> getContents) >>= putStr

mergesort'merge :: (Ord a) => [a] -> [a] -> [a]
mergesort'merge [] xs = xs
mergesort'merge xs [] = xs
mergesort'merge (x:xs) (y:ys)
    | (x < y) = x:mergesort'merge xs (y:ys)
    | otherwise = y:mergesort'merge (x:xs) ys

mergesort'splitinhalf :: [a] -> ([a], [a])
mergesort'splitinhalf xs = (take n xs, drop n xs)
    where n = (length xs) `div` 2

mergesort :: (Ord a) => [a] -> [a]
mergesort xs
    | (length xs) > 1 = mergesort'merge (mergesort ls) (mergesort rs)
    | otherwise = xs
    where (ls, rs) = mergesort'splitinhalf xs

import System.IO
import Control.Applicative
{-import Data.HashSet-}
import Data.Bits
import qualified Data.Map as Map
import Data.Tuple
import Data.List
{-import Data.Sort-}

parseIntLine input line_idx  = map read $ words $ lines input !! line_idx

solve :: String -> String
solve input = (show $ answer n as) ++ "\n"
    where
        as = parseIntLine input 1
        n = parseIntLine input 0 !! 0

answer :: Int -> [Int] -> Int
answer n as = (getBoundaries $ take n sas) * (getBoundaries $ drop n sas)
    where
        sas = sort as

getBoundaries as = (head $ reverse as) - (head as)

main = (solve <$> getContents) >>= putStr


import Data.Char
import Control.Applicative

main = do cs <- getLine
          putStrLn $ solve cs

solve :: String -> String
solve ccs@(c:cs) = h ++ "$"++ (reverse $ f $ reverse m)++ (g q) ++ t
   where (n,p) = span ('.'/=) ccs
         q = if null p then p else tail p
         m = if c=='-' then tail n else n
         h = if c == '-' then "(" else []
         t = if c == '-' then ")" else []

f [] = []
f [x] = [x]
f [x,y] = [x,y]
f [x,y,z] = [x,y,z]
f (x:y:z:xs) = [x,y,z]++","++(f xs)

g [] = ".00"
g [x] = "."++[x]++"0"
g (x:y:xs) = "."++[x,y]

import Data.List
import Data.Char

processFirst :: String -> String
processFirst xs
  | length  xs <= 3 = xs
  | otherwise =  ret ++ "," ++ processFirst ret'  where
      ( ret , ret' ) = splitAt 3 xs

processSecond :: String -> String
processSecond xs = ret where
   tmp = xs ++ "00000000000000000000000"
   ret = if null xs then ".00" else take 3 tmp

helpSolve :: String -> String
helpSolve xs =   ret where
   ( first , second ) = break ( =='.' ) xs
   ret = ( reverse . processFirst . reverse  $ first )  ++ processSecond second

solve :: String -> String
solve ( x : xs ) = ret where
  ret = if x == '-' then "($" ++ helpSolve xs ++ ")" else "$" ++ helpSolve ( x:xs )

main = interact $ unlines . map  solve . lines

main = do
 str <- getLine
 putStrLn.check (head str).format $ abs' str

check c str@(x:xs)
 = if x == ',' then f c xs else f c str
  where
    f c xs = if c == '-' then "($"++xs++")" else '$':xs

abs' (x:xs) = if x == '-' then xs else (x:xs)

format :: String -> String
format str = let intPart = takeWhile (/='.') str
                 floatPart = drop (1+length intPart) str
             in  intStr intPart ++ floatStr floatPart

floatStr str = "."++(take 2 $ take 2 str ++ repeat '0')

intStr :: String -> String
intStr str = let p = take (mod (length str) 3) str
             in f . (:) p . dataList $ drop (length p) str
 where
  f = init.concat.map (\a -> a++",")

dataList :: String -> [String]
dataList [] = []
dataList str = a: dataList b
 where
  (a,b) = splitAt 3 str

main = getLine >>= putStrLn.answer

answer :: String -> String
answer ('-':cs) = "($"++ format cs ++ ")"
answer str      =  "$"++ format str

format str
 = let intPart = takeWhile (/='.') str
       floatPart = drop (1+length intPart) $ str
   in  formatI intPart  ++ formatF floatPart

formatI str = fst$foldl f ([],3-mod (length str) 3) str
 where
  f (str,0) c = (str++","++[c] , 1)
  f (str,m) c = (str++[c],mod (m+1) 3)

formatF str = '.':(take 2 $ take 2 str ++ repeat '0')

{-
import HUnit

testZero :: Test
testZero  =  Test "TestZero" $ assertEq "$0.00" (solve 0)

testInput :: Test
testInput  =  TestList "TestInput"
    [Test "1" $ assertEq "$2,012.00" (solve 2012),
     Test "2" $ assertEq "($0.00)" (solve (-0.00987654321)),
     Test "3" $ assertEq "($12,345,678.90)" (solve (-12345678.9))]

test :: IO ()
test  =  mapM_ run
    [testZero,
     testInput]

--------------------------------------------------------------------------------
-}

solve :: Double -> String
solve d
  | d < 0  =  concat ["(", solve (-d), ")"]
  | otherwise  =  concat ["$", solve' n, ".", if a' == 0 then "00" else (show a')]
  where
    (n, a)  =  properFraction d
    a'  =  truncate (a * 100)
    solve' :: Int -> String
    solve' n  =  reverse (solve'' (reverse (show n)))
      where
        solve'' (s1:s2:s3:s)  =  s1:s2:s3:',':solve'' s
        solve'' s  =  s

main :: IO ()
main  =  readLn >>= putStrLn . solve

main = getLine >>= putStrLn.(:) '$'.check.format.abs'

check str@(x:xs)
 = if x == ',' then xs else str

abs' (x:xs) = if x == '-' then xs else (x:xs)

format :: String -> String
format str = let intPart = takeWhile (/='.') str
                 floatPart = drop (1+length intPart) str
             in  intStr intPart ++ floatStr floatPart

floatStr str = "."++(take 2 $ take 2 str ++ repeat '0')

intStr :: String -> String
intStr str = let p = take (mod (length str) 3) str
             in f . (:) p . dataList $ drop (length p) str
 where
  f = init.concat.map (\a -> a++",")

dataList :: String -> [String]
dataList [] = []
dataList str = a: dataList b
 where
  (a,b) = splitAt 3 str


import Control.Arrow ((>>>))
import Control.Monad (replicateM_)

main =
    interact $
        lines
            >>> drop 1
            >>> map words
            >>> map (map read)
            >>> map (\[a, b] -> if a == 0 then 1 else b * 2 + a + 1)
            >>> map show
            >>> unlines

module Main where

import           Control.Monad

main :: IO ()
main = do
  n <- readLn
  replicateM_ n solvet

solvet :: IO ()
solvet = do
  input <- getLine
  let [n, m] = map read (words input)
  let res = if n == 0 then 0 else m * 2 + n
  print (res + 1)

module Main where

import           Control.Monad

main :: IO ()
main = do
  n <- readLn
  replicateM_ n solvet

solvet :: IO ()
solvet = do
  input <- getLine
  let [n, m] = map read (words input)
  let res = if n == 0 then m * 2 - 1 else m * 2 + n
  print res


import Control.Monad
import Data.Bits
import Data.Maybe
import Data.Array
import qualified Data.ByteString.Char8 as C
import qualified Data.IntSet as IS
import Data.ByteString.Builder
import System.IO

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

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

kMaxN :: Int
kMaxN = 200

sg :: Array Int Int
sg = listArray (1, kMaxN) [f i | i <- [1..kMaxN]]
  where f n = head $ filter (flip IS.notMember st) [0..]
          where st = IS.fromList [sg ! (n - i) | i <- [2..n-1], n `mod` i == 0]

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    let
      result
        | popCount n == 1 && odd (countTrailingZeros n) = False
        | odd n = False
        | otherwise = True
    return $ string7 (if result then "Alice" else "Bob") `mappend` charUtf8 '\n'
  hPutBuilder stdout output

{-# LANGUAGE FlexibleContexts #-}
import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.IO
import Data.Array.Unboxed
import Data.Bits
import Data.Bool
import Data.Char
import Data.Int
import Data.List
import Data.Maybe
import Data.Ord
import Data.Ratio
import qualified Data.Set as Set
import qualified Data.Sequence as Seq
import System.IO
import System.IO.Unsafe

(><) a b = a Seq.>< b

deb s e = unsafePerformIO $ do
    hPutStrLn stderr s
    return e

parseInt = fst . fromJust . BS.readInt
parseInteger = fst . fromJust . BS.readInteger

main = do
    let pingo = Set.fromList ([2 ^ j | j <- [1..30], odd j]::[Int])
    tn <- parseInt <$> BS.getLine
    replicateM_ tn $ do
        n <- parseInt <$> BS.getLine
        let r = odd n || n `Set.member` pingo
        putStrLn $ if r then "Bob" else "Alice"


import Data.Array
import Data.List
import Data.Maybe
import Data.Ord
import qualified Data.IntMap as M
import qualified Data.ByteString.Char8 as C

pairs :: [a] -> [(a, a)]
pairs (x:y:z) = (x, y): (y, x): pairs z
pairs _ = []

main :: IO ()
main = do
  (n:_:_:el) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents
  let e = accumArray (flip (:)) [] (1, n) $ pairs el
      gao v d p =
        case filter (`M.notMember` d) $ e!v of
          (w:_) -> gao w (M.insert w (M.size d) d) (w:p)
          _     -> let w = minimumBy (comparing (d M.!)) $ e!v in w: takeWhile (/=w) p
      ans = gao 1 (M.singleton 1 0) [1]
  print $ length ans
  putStrLn $ unwords $ map show ans

{-# OPTIONS_GHC -O2 -optc-Ofast -ignore-asserts #-}
import Data.Maybe
import Data.Array
import Control.Monad
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.List as L
import qualified Data.ByteString.Char8 as B

-- link edges
type Vertex = Int
pairs :: [Int] -> [(Int, Vertex)]
pairs (x : y : xs) = (x , y) : (y , x) : pairs xs
pairs _ = []

edges :: Int -> [Int] -> Array Int [Vertex]
edges n = accumArray (flip (:)) [] (1, n) . pairs   -- from 1 to n, may be different
-- end here

findPath :: Vertex -> (Array Int [Vertex]) -> (M.Map Vertex Int) -> [Vertex]
findPath u e m
    | null adj  =
        let     path = map snd . L.sort . map (\(a,b) -> (b, a)) . M.assocs $ m
                s    = S.fromList (e ! u)
        in      dropWhile (\v -> S.notMember v s) $ path

    | otherwise =
        let     v = head adj
        in      findPath v e (M.insert v (M.size m) m)
    where
        adj = filter (\v -> M.notMember v m) $ (e ! u)

main = do
    (n : _ : _ : e') <- liftM (map (fst . fromJust . B.readInt) . B.words) $ B.getContents
    let
        e = edges n e'
        ans = findPath 1 e (M.singleton 1 0)
    putStrLn . show . length $ ans
    putStrLn . L.intercalate " " . map show $ ans


import Control.Monad
import Prelude

main = do
    testCases <- getLine
    strNums <- replicateM (read testCases) testCase
    return ()

testCase = do
    line <- getLine
    print $ solution (map read (words line))

solution :: [Integer] -> Integer
solution [len, ones] = result where
    zeros = len - ones
    countSequences n = div (n * (n+1)) 2
    bags = ones + 1
    smallBagSize = div zeros bags
    bigBagSize = smallBagSize + 1
    bigBagsCount = zeros - (bags * smallBagSize)
    smallBagsCount = bags - bigBagsCount
    r1 = bigBagsCount * (countSequences bigBagSize)
    r2 = smallBagsCount * (countSequences smallBagSize)
    result = countSequences (ones + zeros) - (r1 + r2)

subStringCount :: Integer -> Integer
subStringCount l = div (l*(l+1)) 2

solve :: Integer -> Integer -> Integer
solve n m = allSubstrings - groups*(subStringCount lengthOfEach) - (mod numberOfZeros groups)*(lengthOfEach+1)
  where allSubstrings = div (n*(n+1)) 2
        numberOfZeros = n-m
        groups = m+1
        lengthOfEach = div numberOfZeros groups

parse :: String -> String
parse line = show $ solve n m
  where [n, m] = map (\x -> read x :: Integer) $ words line

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

import Control.Monad
import Prelude

main = do
    testCases <- getLine
    strNums <- replicateM (read testCases) testCase
    return ()

testCase = do
    line <- getLine
    print $ solution (map read (words line))

solution :: [Int] -> Int
solution [len, ones] = result where
    zeros = len - ones
    countSequences n = div (n * (n+1)) 2
    bags = ones + 1
    smallBagSize = div zeros bags
    bigBagSize = smallBagSize + 1
    bigBagsCount = mod zeros bags
    smallBagsCount = bags - bigBagsCount
    r1 = bigBagsCount * (countSequences bigBagSize)
    r2 = smallBagsCount * (countSequences smallBagSize)
    result = countSequences (ones + zeros) - (r1 + r2)

import Control.Monad
import Prelude

main = do
    testCases <- getLine
    strNums <- replicateM (read testCases) testCase
    return ()

testCase = do
    line <- getLine
    print $ solution (map read (words line))

solution :: [Int] -> Int
solution [len, ones] = result where
    zeros = len - ones
    countSequences n = div (n * (n+1)) 2
    bags = ones + 1
    smallBagSize = div zeros bags
    bigBagSize = smallBagSize + 1
    bigBagsCount = zeros - (bags * smallBagSize)
    smallBagsCount = bags - bigBagsCount
    r1 = bigBagsCount * (countSequences bigBagSize)
    r2 = smallBagsCount * (countSequences smallBagSize)
    result = countSequences (ones + zeros) - (r1 + r2)

subStringCount :: Integer -> Integer
subStringCount l = div (l*(l+1)) 2

solve :: Integer -> Integer -> Integer
solve n m
  | remaining == 0 = allSubstrings - (subStringCount lenZero)*(m+1)
  | otherwise = allSubstrings - (subStringCount lenZero)*m - (subStringCount remaining)
  where allSubstrings = div (n*(n+1)) 2
        lenZero = div (n-m) (m+1)
        remaining = mod (n-m) (m+1)

parse :: String -> String
parse line = show $ solve n m
  where [n, m] = map (\x -> read x :: Integer) $ words line

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


import Array
import List

bfs :: (Eq a) => (a -> [a]) -> a -> [a]
bfs f s = (foldr union []) $ takeWhile (not . null) $ iterate (nub . (>>= f)) [s]

graph :: String -> (Int -> [Int], Int -> Int, Int)
graph s =
  ((!) (accumArray (\ e a -> a : e) [] (1, n) assocList),
   (!) (foldr (\ (a, b) ar -> ar // [(a, ar ! a + 1), (b, ar ! b + 1)])
              (array (1, n) [(i, 0) | i <- [1..n]])
              assocList),
   n)
  where
  assocList = map ((\ [a, b] -> (read a, read b)) . words) (tail ls)
  n = read $ head $ ls
  ls = lines s

solve s =
  (show a') ++ " " ++ (show b')
  where
  [a, b] = filter ((< n - 1) . degree) [1..n]
  (a', b') = if b `elem` bfs g a then (a, b) else (b, a)
  (g, degree, n) = graph s

main = interact solve

import Array
import Data.List

bfs :: (Eq a) => (a -> [a]) -> a -> [a]
bfs f s = (foldl' union []) $ takeWhile (not . null) $ iterate (nub . (>>= f)) [s]

graph :: String -> (Int -> [Int], Int -> Int, Int)
graph s =
  ((!) (accumArray (\ e a -> a : e) [] (1, n) assocList),
   (!) (foldl' (\ a (b, c) -> a // [(b, a ! b + 1), (c, a ! c + 1)])
               (array (1, n) [(i, 0) | i <- [1..n]])
               assocList),
   n)
  where
  assocList = map ((\ [a, b] -> (read a, read b)) . words) (tail ls)
  n = read $ head $ ls
  ls = lines s

solve s =
  (show a') ++ " " ++ (show b')
  where
  [a, b] = filter ((< n - 1) . degree) [1..n]
  (a', b') = if b `elem` bfs g a then (a, b) else (b, a)
  (g, degree, n) = graph s

main = interact solve

import Data.List
main = do
  ([n]:pairs) <- fmap (map (map read . words) . lines) getContents
  let sortedPairs = map sort pairs
      [[x,y]] = [[i,j] | i <- [1..n], j <- [i+1..n]] \\ sortedPairs
      f ([a,z], [w,b]) | z == w && a == x && b == y  = True
      f _ = False
      ans = if any f [(a,b) | a <- pairs, b <- pairs]
              then [x,y]
              else [y,x]
  putStrLn . unwords . map show $ ans

import Control.Monad
import Data.Array

main = do
	[n] <- getA
	a <- replicateM (n * (n - 1) `div` 2 - 1) getA
	putStr $ unwords $ map show $ gao n a where
		getA = fmap (map read . words) getLine

gao n a = if w!x > w!y then [x, y] else [y, x] where
	[w, l] = [accumArray (+) 0 (1, n) $ zip (map f a) $ repeat 1 | f <- [head, last]]
	[x, y] = filter (\i -> w!i + l!i < n - 1) [1 .. n]

import Control.Applicative
import Control.Monad
import Data.List
import Data.Array.IO
import Text.Printf

main :: IO ()
main = do
  n  <- readLn
  let m = n * (n - 1) `quot` 2 - 1
  xs <- replicateM m (map read . words <$> getLine) :: IO [[Int]]
  matches <- newArray ((1, 1), (n, n)) False :: IO (IOArray (Int, Int) Bool)
  ranks <- newArray (1, n) 0 :: IO (IOArray Int Int)
  forM [1 .. n] $ \i -> do
    writeArray matches (i, i) True
  forM xs $ \(i : j : _) -> do
    writeArray matches (i, j) True
    writeArray matches (j, i) True
    v <- readArray ranks i
    writeArray ranks i (v + 1)
  Just ((i , j), _) <- find (not . snd) <$> getAssocs matches
  ri <- readArray ranks i
  rj <- readArray ranks j
  if ri >= rj
    then printf "%d %d\n" i j
    else printf "%d %d\n" j i

import Control.Monad
import Data.List

main = do
	n <- fmap read getLine
	a <- replicateM (n * (n - 1) `div` 2 - 1) $ fmap (map read . words) getLine
--	a <- fmap (map (map read . words) . lines) getContents
	putStr $ unwords $ map show $ head $ [[i, j] | i <- [1 .. n], j <- [i + 1 .. n]] \\ map sort a
{-

-}

import Control.Monad
import Data.List

main = do
	n <- fmap read getLine
	a <- fmap (map (map read . words) . lines) getContents
	putStr $ unwords $ map show $ head $ [[i, j] | i <- [1 .. n], j <- [i + 1 .. n]] \\ map sort a

import Control.Applicative
import Control.Monad
import Data.List
import Data.Array.IO
import Text.Printf

main :: IO ()
main = do
  n  <- readLn
  let m = n * (n - 1) `quot` 2 - 1
  xs <- replicateM m (map read . words <$> getLine) :: IO [[Int]]
  let pairs = do
        x : y : _ <- xs
        [(x, y), (y, x)]
  let b = ((1, 1), (n, n))
  arr <- newArray b False :: IO (IOArray (Int, Int) Bool)
  forM [1 .. n] $ \i -> do
    writeArray arr (i, i) True
  forM pairs $ \idx -> do
    writeArray arr idx True
  Just (idx, _) <- find (not . snd) <$> getAssocs arr
  uncurry (printf "%d %d\n") idx

import Data.List
main = do
  ([n]:pairs) <- fmap (map (map read . words) . lines) getContents
  let sortedPairs = map sort pairs
      [[x,y]] = [[i,j] | i <- [1..n], j <- [i+1..n]] \\ sortedPairs
      f ([x,z], [w,y]) | z == w  = True
      f _ = False
  if any f [(a,b) | a <- pairs, b <- pairs]
     then putStrLn . unwords . map show $ [y,x]
     else putStrLn . unwords . map show $ [x,y]


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

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

main = do
  _ <- getLine
  inp <- fmap (map read . words) getLine
  print $ solve inp

solve :: [Int] -> Int
solve = foldl f 1 . sort
    where
      f mex x | mex <= x = mex + 1
              | otherwise = mex

import Data.List

main = interact $ show . (+ 1) . foldl (\a x -> min (a + 1) x) 0 . sort . map read . tail . words

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

main = do
  _ <- getLine
  as <- sort . map read . words <$> getLine
  print $ solve as 1

solve :: [Int] -> Int -> Int
solve [] x = x
solve (a:as) x = solve as (if x <= a then x + 1 else x)

import Data.List( sort)
main = do
    n <- getLine
    nums <- return . (map read) . words =<< getLine
    let snums = sort  nums
	process p [] = p
	process p (x:xs) = if p<=x then process (p+1) xs else process p xs
    print $ process 1 snums

module Main where

import System.IO
import Data.Array
import Data.Int
import Data.List

main :: IO ()
main = do
		n <- readAllArr
		l <- readAllArr
		let ws = words l
		putStrLn $ show $ foldl (\x y -> if x <= y then x+1 else x) 1 $ sort (map read $ ws)

readAllArr :: IO String
readAllArr = getLine

startsWith :: Eq a => [a] -> [a] -> Bool
startsWith [] _ = True
startsWith _ [] = False
startsWith (x:xs) (y:ys)= x == y && startsWith xs ys

orF :: (a->Bool) -> (a->Bool) -> a -> Bool
orF f g a = (f a) || (g a)

pairs :: [a] -> [(a, a)]
pairs l = [(x,y) | (x:ys) <- tails l, y <- ys]

replace' :: Eq b => b -> b -> [b] -> [b]
replace' a b = map (\x -> if (a == x) then b else x)

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

mex :: [Int] -> Int
mex = mexRec 1 . sort
        where mexRec index []   = index
              mexRec index (x:xs)
                    | x >= index   = mexRec (index + 1) xs
                    | otherwise    = mexRec index xs

readInt s = let Just (i, _) = C.readInt s in i

main = do
    getLine
    ar <- fmap (map readInt . C.words) C.getLine
    print $ mex ar

import Control.Monad
import Control.Monad.Trans.State.Strict
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.List

main = do
    s <- B.getContents
    let a = flip evalState s $ do
                n <- readInt
                replicateM n readInt
    print $ solve a

solve a = foldl' (\r b -> if b >= r then r+1 else r) 1 bs
  where bs = sort a

readInt :: State B.ByteString Int
readInt = do
    Just (n, rest) <- gets (B.readInt . B.dropWhile isSpace)
    put rest
    return n

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

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

import qualified Data.ByteString.Char8 as B

readInt = ( readLn :: IO Int )
readInts = map ( read :: String -> Int ) . words <$> getLine

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

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = getLine >> getList >>= print . succ . f 1 . sort

f k [] = 0
f k (a:as)
	| k <= a = 1 + f ( k + 1 ) as
	| otherwise = f k as

import Data.List

main :: IO ()
main = do
    let parseInt = read :: String -> Int
    nLine <- getLine
    aLine <- getLine
    let n = parseInt $ nLine
        a = map parseInt . words $ aLine
    putStrLn $ show $ maxMex a

maxMex :: [Int] -> Int
maxMex = foldl findMaxMex 1 . sort
    where findMaxMex ans x = if x >= ans then ans + 1 else ans

import Data.List

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

solve :: Int -> [Int] -> Int
solve i [] = i
solve i (a:s) | i <= a = solve (i + 1) s
              | otherwise = solve i s

import Data.List

main = do
  _ <- getLine
  xs <- fmap (map read . words) getLine :: IO [Int]
  print (solve xs)

solve :: [Int] -> Int
solve xs = g 1 . sort $ xs
    where
      g x [] = x
      g x (a:as) | x <= a = g (x+1) as
                 | otherwise = g x as

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

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

import qualified Data.ByteString.Char8 as B

readInt = ( readLn :: IO Int )
readInts = map ( read :: String -> Int ) . words <$> getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = getLine >> B.getLine >>= print . succ . f 1 . sort . map ( fst . fromJust . B.readInt ) . B.words

f k [] = 0
f k (a:as)
	| k <= a = 1 + f ( k + 1 ) as
	| otherwise = f ( k + 1 ) as

import Data.List

main :: IO ()
main = do
    let parseInt = read :: String -> Int
    nLine <- getLine
    aLine <- getLine
    let n = parseInt $ nLine
        a = map parseInt . words $ aLine
    putStrLn $ show $ maxMex a

maxMex :: [Int] -> Int
maxMex = foldl findMaxMex 1 . zip [1..] . sort
    where findMaxMex ans (i, x) = if x >= i then ans + 1 else ans

import Data.List

main = do
  _ <- getLine
  xs <- fmap (map read . words) getLine :: IO [Int]
  print (solve xs)

solve :: [Int] -> Int
solve xs = g . takeWhile (uncurry (<)) . zip [1..] . sort $ xs
    where
      g [] = length xs
      g ((a, _):_) = a


import qualified Data.ByteString.Lazy.Char8 as P
import Control.Monad.ST
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Control.Monad.Trans
import Data.Maybe
import Data.Bits
import Prelude hiding (reverse)
import Data.ByteString.Lazy.Char8
import Debug.Trace

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

type SP = State P.ByteString
type S = StateT P.ByteString

str = string7

dropSpace :: P.ByteString -> P.ByteString
dropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough

getNext :: Monad m => S m P.ByteString
getNext = state $ P.span (> ' ') . dropSpace

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace

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

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

tloop :: SP Builder
tloop = do
  t <- getInt
  -- let t = 1
  fmap mconcat $ replicateM t $ solve

solve :: SP Builder
solve = do
  n <- getInt
  k <- getInt
  s <- getNext
  let
    rs = reverse s
    one = (||) (k == 0) (s == rs)
  pure $ putInts $ if one then [1] else [2]

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

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

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    k <- getInt
    s <- getNext
    let  ans = if  s == P.reverse s || k == 0
           then  1
           else  2
    pure $ putInts [ans]

type SP = State P.ByteString
type S = StateT P.ByteString

dropSpace :: P.ByteString -> P.ByteString
dropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough

getNext :: Monad m => S m P.ByteString
getNext = state $ P.span (> ' ') . dropSpace

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace

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

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

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe
import Data.Bits
import Prelude hiding (reverse)
import Data.ByteString.Lazy.Char8
import Debug.Trace

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

type SP = State P.ByteString
type S = StateT P.ByteString

str = string7

dropSpace :: P.ByteString -> P.ByteString
dropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough

getNext :: Monad m => S m P.ByteString
getNext = state $ P.span (> ' ') . dropSpace

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace

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

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

tloop :: SP Builder
tloop = do
  t <- getInt
  -- let t = 1
  fmap mconcat $ replicateM t $ solve

solve :: SP Builder
solve = do
  n <- getInt
  k <- getInt
  s <- getNext
  let
    rs = reverse s
    one = (||) ((==) k 0) ((==) s rs)
  pure $ putInts $ if one then [1] else [2]

import qualified Data.ByteString as BS
import Control.Monad
solve :: BS.ByteString -> Int -> Int
solve x k
  | k == 0 = 1
  | x == BS.reverse x = 1
  | otherwise = 2

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, k] <- map read . words <$> getLine
    x <- BS.getLine
    print $ solve (BS.take n x) k

import Control.Monad

main :: IO ()
main = do
    t <- readLn
    replicateM t $ do
        line <- getLine
        let [n, k] = map read $ words line :: [Int]
        str <- getLine
        putStrLn $ show $ solve n k str
    return ()

solve :: Int -> Int -> [Char] -> Int
solve n k str
  | k == 0                  = 1
  | (reverse str) == str    = 1
  | otherwise               = 2

import qualified Data.ByteString as BS
import Control.Monad
solve :: BS.ByteString -> Int -> Int
solve x k
  | k == 0 = 1
  | x == BS.reverse x = 1
  | otherwise = 2

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [_n, k] <- map read . words <$> getLine
    x <- BS.getLine
    print $ solve x k


import Monad (liftM)

eps  =  1e-06

binFind :: (Double -> Double) -> (Double, Double) -> Double
binFind f (l, r)
  | l + eps > r  =  m
  | f l * f r > eps  =  error "fl * fr > 0"
  | f m * f r > 0  =  binFind f (l, m)
  | otherwise  =  binFind f (m, r)
  where
    m  =  0.5 * (l+r)

solve :: Double -> [Double] -> Double
solve k as  =  binFind f (0, 1000)
  where
    k'  =  1 - k / 100
    f x  =  sum $ map (\a -> if a > x then k' * (a-x) else (a-x)) as

main :: IO ()
main  =  do
    [_, k]  <-  liftM (map read . words) getLine
    as  <-  liftM (map read . words) getLine
    print $ solve k as

module Main where

check :: Double -> [Double] -> Double -> Bool
check k a value = rem*(1 - k/100.0) > nec where
    rem = sum $ map (\x -> max 0.0 (x - value)) a
    nec = sum $ map (\x -> max 0.0 (value - x)) a

eps :: Double
eps = 1e-7

binS :: Double -> [Double] -> Double -> Double -> Double
binS k a left right =
    let binSearch = binS k a
        s = (left + right)/2 in
            if right - left < eps then s
                else if check k a s
                    then binSearch s right
                    else binSearch left s

solve :: String -> String -> Double
solve nk a = binS k al 0.0 (maximum al) where
    nkl = map read (words nk)
    k = head $ tail nkl
    al = map read (words a)

main = do
    nk <- getLine
    a <- getLine
--    print $ map (\x -> max 0.0 (x - 2.0)) a
    print $ solve nk a

import IO
import Text.Printf

half :: [Int] -> Double -> Double
half [] _ = 0 :: Double
half (a:as) m = half as m + if (realToFrac a) > m
                            then ((realToFrac a)-m)
                            else 0

half2 [] _ = 0 :: Double
half2 (a:as) m = half2 as m + if (realToFrac a) < m
                            then (m - (realToFrac a))
                            else 0

binSearch :: (Double -> (Int, a)) -> Double -> Double -> (Double, a)
binSearch f min max =
        --putStrLn (show (min, max, (max+min)/2))
        case (f ((max+min)/2)) of
             (-1, _) -> binSearch f min ((max + min)/2)
             (0, cx) -> ((max + min)/2, cx)
             (1, _) -> binSearch f ((max + min)/2) max

solve :: Int -> Int -> [Int] -> Double
solve n k as = let max = realToFrac $ maximum as
                   min = realToFrac $ minimum as
                   q = 1 - ((realToFrac k)/100)
                   f t = let h1 = half as t
                             h2 = half2 as t
                             r = (h1*q) - h2
                         in if (abs r) < (0.1^6)
                            then (0, t)
                            else if r > 0
                                 then (1, t)
                                 else (-1, t)
                   (_, x) = binSearch f min max
               in x

main = do
        line <- getLine
        line2 <- getLine
        let (n:k:[]) = map read (words line) :: [Int]
            as = map read (words line2) :: [Int]
        printf "%.6f" $ solve n k as
        return ()

import Data.List
import Text.Printf
main = do
    [n, k] <- (map read . words) `fmap` getLine
    a <- (map (fromInteger . read) . words) `fmap` getLine
    let averge = sum a / fromInteger n
        k' = fromInteger k / 100.0
        f x = let (p, m) = foldl' (\(a, b) xi -> if xi > x then (a + xi - x, b)
                    else (a, b + x - xi)) (0, 0) a in p * (1.0 - fromInteger k/100.0) - m
        sol a fa b fb | a - b < min ((a + b)*1e-7) 1e-7 = (a + b)/2
                      | otherwise = let c = (a + b)/2
                                        fc = f c in
                        if fc < 0 then sol c fc b fb else sol a fa c fc
        x = sol averge (f averge) 0 (f 0) :: Double
    printf "%.6f" x


{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

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

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readNInts = readInt >>= flip replicateM readInt

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = do
	n <- readInt
	as <- readInts
	print $ minimum $ do
		( a, i ) <- zip as [ 0 .. ]
		j <- [ 0, n - 1 ]
		guard $ i /= j
		return $ a `div` ( abs $ i - j )

main::IO()
main=do
    n<-readLn::IO Int
    s<-getLine
    let t=(map read $ words s)::[Int]
    print $ foldl1 min $ zipWith (\x i->x `div` (max i (n-i-1))) t [0..]

f::Int->Int->Int->Int
f n x i=x `div` if i==0 then n-1
                else if i==n-1 then n-1
                else min i (n-i-1)

main::IO()
main=do
    n<-readLn::IO Int
    s<-getLine
    let t=(map read $ words s)::[Int]
    print $ foldl1 min $ zipWith (f n) t [0..]


{-# LANGUAGE Safe #-}
{-# Options_GHC -O3 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Char
import Data.Int
import Data.Array.Unboxed

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

test :: Int -> Int -> [Int] -> Int
test n k a = (* 2) $ sum l
  where
    c = accumArray (+) 0 (0, k - 1) $ [ (mod j k, 1) | (i, j) <- zip [0 .. ] a] :: UArray Int Int
    l = [ if i < j then min (c ! i) (c ! j) else div (c ! i) 2 | i <- [ 0 .. pred k], let j = mod (2 * k - i) k, i <= j]

main = do
  s <- C.getContents
  let (n:k:a) = map ru $ C.words s
  print $ test n k $ take n a

{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import Data.Ord
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet

getWords  = words <$> getLine :: IO [String]
getInts   = map read <$> getWords :: IO [Int]
getDoubles = map read <$> getWords :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()

---- Answer Code Section ----

counter :: [Int] -> Int -> Array Int Int
counter l maxVal = accumArray (+) 0 (0, maxVal) $ map (\x -> (x, 1)) l

process :: [Int] -> Int -> Int
process boxes k = pairCnt where
    mods = map (`mod` k) boxes
    counts = counter mods (k-1)
    (lBound, hBound) = bounds counts
    pair s i = s + if i == 0 || 2*i == k then 2 * ((counts ! i) `div` 2) else min (counts ! i) (counts ! (k-i))
    pairCnt = foldl pair 0 [lBound..hBound]

main = do
    n:k:[] <- getInts
    boxes <- getInts
    print $ process boxes k


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

import Data.List
import Data.Maybe
import Data.Char
import Data.Array
import Data.Int
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as BS

solve n a =
    (answer, go2 (1,1))
  where
    (a', n') = if even n then (a, n) else (a ++ [0], n + 1)

    arr = listArray (1, n') a' :: Array Int Int
    bnds = ((1,1), (n', n'))
    cache = listArray bnds [go idx | idx <- range bnds] :: Array (Int,Int) Int

    answer = go (1, 1)

    go (x, e)
        | even x || x < 1 || x > n' = 0
        | x + 1 == n'               = max val1 val2
        | otherwise                 = ans1 `min` ans2 `min` ans3
      where
        go' idx = cache ! idx
        val1 = arr ! e
        val2 = arr ! (x + 1)
        val3 = arr ! (x + 2)
        ans1 = max val2 val3 + go' (x + 2, e)
        ans2 = max val1 val3 + go' (x + 2, x + 1)
        ans3 = max val1 val2 + go' (x + 2, x + 2)

    go2 (x, e)
        | even x || x < 1 || x > n' = error "impossible"
        | x + 1 == n'               = [(e, x + 1)]
        | ans1 == ans               = (x + 1, x + 2) : go2 (x + 2, e)
        | ans2 == ans               = (e, x + 2) : go2 (x + 2, x + 1)
        | ans3 == ans               = (e, x + 1) : go2 (x + 2, x + 2)
        | otherwise                 = error "impossible"
      where
        ans = go (x, e)
        val1 = arr ! e
        val2 = arr ! (x + 1)
        val3 = arr ! (x + 2)
        go' idx = cache ! idx
        ans1 = max val2 val3 + go' (x + 2, e)
        ans2 = max val1 val3 + go' (x + 2, x + 1)
        ans3 = max val1 val2 + go' (x + 2, x + 2)

parseInput = do
    n <- readInt
    a <- replicateM n readInt
    return (n, a)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace

main = do
    (n, a) <- evalState parseInput <$> BS.getContents
    let (ans, pairs) = solve n a
    print ans
    forM_ pairs $ \(x, y) -> if x <= n && y <= n then putStrLn (show x ++ " " ++ show y) else print (min x y)

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

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

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

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

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

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

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

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

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

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

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

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

state = State
--}}} end of a minimal State Monad


import           Data.Array.Unboxed    (Array, bounds, listArray, (!))
import qualified Data.ByteString.Char8 as B
import           Data.Maybe            (fromJust)

findIndexFrom :: Array Int Int -> Int -> Int -> Int
findIndexFrom v i x = let (_, n) = bounds v in go i n
  where go lo hi | lo >= hi = hi
        go lo hi = let m = lo + (hi - lo + 1) `quot` 2
                   in if v ! m > x
                      then go lo (m - 1)
                      else go m  hi

bestEta :: Array Int Int -> Int -> Maybe Double
bestEta v u = maximum $ map findTriple [1..(n-2)]
  where (_, n) = bounds v
        findTriple i = let k = findIndexFrom v i (u + v ! i)
                       in if (i + 1 < k)
                          then Just (toEta i (i + 1) k)
                          else Nothing
        toEta i j k = fromIntegral (v ! k - v ! j) / fromIntegral (v ! k - v ! i)

main = do
  let toInt = fst . fromJust . B.readInt
  let readInts = fmap (map toInt . B.words) B.getLine

  [n, u] <- readInts
  v <- fmap (listArray (1, n)) readInts

  case bestEta v u of
    Just v  -> putStrLn (show v)
    Nothing -> putStrLn "-1"

{-# LANGUAGE ViewPatterns #-}
import qualified Data.IntSet as S
import Data.List
import Data.Maybe

main = interact exec
exec = maybe "-1" show . (\(n:u:xs) -> fn n u xs) . map read . words
fn n u (S.fromAscList -> xs) = maximumMay $ mapMaybe (\(x, y, mz) -> fmap (\z -> fromIntegral (z - y) / fromIntegral (z - x) :: Double) mz) $ take (n - 2) $ unfoldr (\(x, s) -> let (y, s') = S.deleteFindMin s in Just ((x, y, S.lookupLE (x + u) s'), (y, s')))  (let (x, s) = S.deleteFindMin xs in (x, s))

maximumMay [] = Nothing
maximumMay xs = Just $ maximum xs

{-# LANGUAGE ViewPatterns #-}
import qualified Data.IntSet as S
import Data.List
import Data.Maybe

main = interact exec
exec = maybe "No" (("Yes\n" ++) . show) . (\(n:u:xs) -> fn n u xs) . map read . words
fn n u (S.fromAscList -> xs) = maximumMay $ mapMaybe (\(x, y, mz) -> fmap (\z -> fromIntegral (z - y) / fromIntegral (z - x)) mz) $ take (n - 2) $ unfoldr (\(x, s) -> let (y, s') = S.deleteFindMin s in Just ((x, y, S.lookupLE (x + u) s'), (y, s')))  (let (x, s) = S.deleteFindMin xs in (x, s))

maximumMay [] = Nothing
maximumMay xs = Just $ maximum xs

{-# LANGUAGE ViewPatterns #-}
import qualified Data.IntSet as S
import Data.List
import Data.Maybe

main = interact exec
exec = maybe "No" show . (\(n:u:xs) -> fn n u xs) . map read . words
fn n u (S.fromAscList -> xs) = maximumMay $ mapMaybe (\(x, y, mz) -> fmap (\z -> fromIntegral (z - y) / fromIntegral (z - x) :: Double) mz) $ take (n - 2) $ unfoldr (\(x, s) -> let (y, s') = S.deleteFindMin s in Just ((x, y, S.lookupLE (x + u) s'), (y, s')))  (let (x, s) = S.deleteFindMin xs in (x, s))

maximumMay [] = Nothing
maximumMay xs = Just $ maximum xs


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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

import qualified Data.ByteString.Lazy.Builder as BB

import Data.Monoid
import System.IO

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

main = do
  n <- readLn
  as <- getInts

  let
    as' = sort $ zip as [1..]
    b = zipWith (\(a, i) p -> (max a (p+1), i)) as' $ (-100):(map fst b)

  putStrLn $ unwords $ map show $ elems (array (1, n) $ map swap b :: UArray Int Int)

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

import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Data.Char

readInt :: IO Int
readInt = do line <- BS.getLine
             let Just (n,_) = BS.readInt line
             return n

parseInts :: Int -> ByteString -> [Int]
parseInts k bs | k <= 0 = []
parseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of
                   Nothing -> []
                   Just (n,bs') -> n : parseInts (k-1) bs'

main = do
  n <- fmap read getLine
  nums <- fmap (parseInts n) BS.getLine
  let sorted = sort (zip nums [1..]) :: [(Int,Int)]

  ans <- newArray (1,n) 0 :: IO (IOUArray Int Int)

  let go _ [] = return ()
      go m ((v,j):rest) = do let m' = max m v
                             writeArray ans j m'; go (m'+1) rest
  go 0 sorted
  forM_ [1..n] $ \i -> do
    v <- readArray ans i
    putStr $ show v ++ " "
  putStrLn ""

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Char
import Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import qualified Data.ByteString.Char8 as B
-- import Debug.Trace

import qualified Data.ByteString.Lazy.Builder as BB

import Data.Monoid
import System.IO

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

main = do
  getLine
  as <- getInts

  putStrLn $ unwords $ map show $ map snd $ sort $ map swap $ concat $ map (zipWith (\a (b, i) -> (b+a, i)) [0..]) $ groupBy ((==) `on` fst) $ sort $ zip as [1..]


import System.IO
import Control.Monad
import Data.List
import Data.Maybe
main = do
    [t] <- ri
    tcs <- replicateM t rtc
    mapM (putStrLn . showHM . solve) tcs
ri = map read . words <$> getLine :: IO [Int]
rtc = do
    [n,h,m] <- ri
    als <- replicateM n (toM <$> ri)
    return (toM [h,m], sort als)
toM [h,m] = h*60 + m
solve (s, als) = flip (-) s . fromJust . find (>=s) $ a2
  where
    a2 = als ++ map (+ (24*60)) als
showHM mm = show h ++ " " ++ show m
  where
    h = mm `div` 60
    m = mm `mod` 60

import Control.Monad (forM)

type Time = (Int, Int)
type Case = (Time, [Time])

-- i have no idea what i'm doing starts here
main :: IO ()
main = do
    res <- map solve <$> parseIn
    putStr $ write res

parseIn :: IO [Case]
parseIn = do
    n <- read <$> getLine
    forM [1..n] $ \_ -> do
        [l, nowH, nowM] <- map read . words <$> getLine
        alarms <- forM [1..l] $ \_ -> do
            [alarmH, alarmM] <- map read . words <$> getLine
            return (alarmH, alarmM)
        return ((nowH, nowM), alarms)

-- i have idea what i'm doing
write :: [Time] -> String
write list = unlines $ map writeLine list

writeLine :: Time -> String
writeLine time = show (fst time) ++ " " ++ show (snd time)

toMinutes :: Time -> Int
toMinutes t = 60 * fst t + snd t

fromMinutes :: Int -> Time
fromMinutes number
    | number >= 24 * 60 = fromMinutes (number - 24 * 60)
    | otherwise = divMod number 60

moveToNextDay :: Int -> Int
moveToNextDay number = number + 24 * 60

getClosestAlarm :: Int -> [Int] -> Int
getClosestAlarm now alarms =
    let past = [t | t <- alarms, t < now]
        future = [t | t <- alarms, t >= now]
        closest = minimum (map moveToNextDay past ++ future)
    in closest - now

-- TODO write more beautifully (?)
solve :: Case -> Time
solve testcase = fromMinutes $ getClosestAlarm (toMinutes (fst testcase)) (map toMinutes (snd testcase))

module Main
    ( main )
    where
import Control.Monad
import Data.List
timeToMin::Int->Int->Int
timeToMin a b=60*a+b

minToTime::Int->[Int]
minToTime t=[a,b]
  where a=t`div`60
        b=t-a*60
doTime::Int->[Int]->Int
doTime sleepTime y
  |(last y)-sleepTime<0 =(y!! 0)+(1440-sleepTime)
  |otherwise =minimum ynew
  where ynew=filter (>=0) (map ((+(-sleepTime))) y)

printTime::[Int]->IO ()
printTime (x:y:_)=putStrLn$(show x)++" "++(show y)
main = do
  line<-getLine
  let nTerm=read line::Int
  replicateM_ nTerm$do
    line<-getLine
    let (n:h:m:_)=map read (words line)::[Int]
    time<-replicateM n$do
      color<-getLine
      let (h:m:_)=map read (words color)::[Int]
      return (timeToMin h m)
    let timeNew=sort time
    let sleepTime=timeToMin h m
    printTime $minToTime$doTime sleepTime timeNew

{-
Whatever you do, work heartily, as for the Lord and not for men,
knowing that from the Lord you will receive the inheritance as your reward.
You are serving the Lord Christ.
- Colossians 3:23-24
-}

module Main
    ( main )
    where

import Control.Monad
import Data.List

data Time = Time
          { hours   :: Int
          , minutes :: Int
          }
          deriving (Eq, Ord, Show)

orderAfterTime :: [Time] -> Time -> [Time]
orderAfterTime ts t = sort after ++ sort (map addHours before)
    where (before, after) = partition (< t) ts

addHours :: Time -> Time
addHours (Time h m) = Time (h + 24) m

firstAlarm :: [Time] -> Time -> Time
firstAlarm ts t = head $ orderAfterTime ts t

timeUntil :: Time -> Time -> Time
timeUntil (Time h m) (Time h' m') = Time (h' - h) (m' - m)

addMinutes :: Time -> Time -> Time
addMinutes (Time h m) a@(Time h' m')
  | m <= m'   = a
  | otherwise = Time (h' - 1) (m' + 60)

putTimeLn :: Time -> IO ()
putTimeLn (Time h m) = putStrLn $ (show h) ++ " " ++ (show m)

main :: IO ()
main = do
  line <- getLine
  let testCases = read line

  replicateM_ testCases $ do
    line <- getLine
    let (n:h:m:_) = map read $ words line
        vladTime = Time h m

    alarms <- replicateM n $ do
      line <- getLine
      let (h:m:_) = map read $ words line
      return (Time h m)

    putTimeLn . timeUntil vladTime . addMinutes vladTime . firstAlarm alarms $ vladTime

  return ()

module Main
    ( main )
    where
import Control.Monad
import Data.List
timeToMin::Int->Int->Int
timeToMin a b=60*a+b

minToTime::Int->[Int]
minToTime t=[a,b]
  where a=t`div`60
        b=t-a*60
doTime::Int->[Int]->Int
doTime sleepTime y
  |(last y)-sleepTime<0 =(y!! 0)+(1440-sleepTime)
  |otherwise =(minimum ynew)-sleepTime
  where ynew=filter (>=0) y

printTime::[Int]->IO ()
printTime (x:y:_)=putStrLn$(show x)++" "++(show y)
main = do
  line<-getLine
  let nTerm=read line::Int
  replicateM_ nTerm$do
    line<-getLine
    let (n:h:m:_)=map read (words line)::[Int]
    time<-replicateM n$do
      color<-getLine
      let (h:m:_)=map read (words color)::[Int]
      return (timeToMin h m)
    let timeNew=sort time
    let sleepTime=timeToMin h m
    printTime $minToTime$doTime sleepTime timeNew

module Main
    ( main )
    where
import Control.Monad
import Data.List
timeToMin::Int->Int->Int
timeToMin a b=60*a+b

minToTime::Int->[Int]
minToTime t=[a,b]
  where a=t`div`60
        b=t-a*60
doTime::Int->[Int]->Int
doTime sleepTime y
  |(last y)-sleepTime<0 =(doTime sleepTime (map (+3600) y))+(3600-sleepTime)
  |otherwise =(minimum ynew)-sleepTime
  where ynew=filter (>=0) y

main = do
  line<-getLine
  let nTerm=read line::Int
  replicateM_ nTerm$do
    line<-getLine
    let (n:h:m:_)=map read (words line)::[Int]
    time<-replicateM n$do
      color<-getLine
      let (h:m:_)=map read (words color)::[Int]
      return (timeToMin h m)
    let timeNew=sort time
    let sleepTime=timeToMin h m
    print$minToTime$doTime sleepTime timeNew

module Main
    ( main )
    where
import Control.Monad
import Data.List
timeToMin::Int->Int->Int
timeToMin a b=60*a+b

minToTime::Int->[Int]
minToTime t=[a,b]
  where a=t`div`60
        b=t-a*60
doTime::Int->[Int]->Int
doTime sleepTime y
  |(last y)-sleepTime<0 =(doTime sleepTime (map (+3600) y))+(3600-sleepTime)
  |otherwise =(minimum ynew)-sleepTime
  where ynew=filter (>=0) y

main = do
  line<-getLine
  let nTerm=read line::Int
  print nTerm
  replicateM_ nTerm$do
    line<-getLine
    let (n:h:m:_)=map read (words line)::[Int]
    print [n,h,m]
    time<-replicateM n$do
      color<-getLine
      let (h:m:_)=map read (words color)::[Int]
      print [h,m]
      return (timeToMin h m)
    let timeNew=sort time
    let sleepTime=timeToMin h m
    print$minToTime$doTime sleepTime timeNew


-- uninhm
-- https://codeforces.com/contest/1529/problem/B
-- greedy

import Data.List (sort)

odds (x:xs) = x : evens xs
odds [] = []

evens (_:xs) = odds xs
evens [] = []

(.>) = flip (.)
infixl 8 .>

firstdiff [x] = x
firstdiff (x:y:_) = y - x

solve l = go (length l) (firstdiff $ map snd l) l where
  go n mindiff (x':y':xs)
    | y > 0 && y <= mindiff = fst y'
    | y > 0 = fst x'
    | otherwise = go n (min mindiff (y-x)) (y':xs)
      where
        y = snd y'
        x = snd x'

  go n mindiff [x] = n

main = interact $ lines
  .> tail
  .> evens
  .> map (show . solve . zip [1..] . sort . map read . words)
  .> unlines

import Control.Monad
import Data.List (sort)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t $ do
        n <- getLine
        a <- reverse . sort . map read . words <$> getLine :: IO [Int]
        let x = takeWhile (> 0) a
            y = dropWhile (> 0) a
        print $ max (length y) $ if null x then 0 else 1 + check y (last x) (last x)

check :: [Int] -> Int -> Int -> Int
check [] _ _ = 0
check (x:xs) p d
               | p - x >= d = 1 + check xs x d
               | otherwise  = check xs p d

import Control.Monad
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import System.IO

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

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

calcMinInterval :: [Int] -> Int
calcMinInterval [x1, x2] = x2 - x1
calcMinInterval (x1 : x2 : xs) = min (x2 - x1) $ calcMinInterval (x2 : xs)
calcMinInterval _ = error ""

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    _ <- getInts
    (xs, ys) <- partition (<=0) . sort <$> getInts
    let lx = length xs
        ly = length ys
        result
          | lx <= 1 = lx + min 1 ly
          | ly == 0 = lx
          | calcMinInterval xs >= head ys = lx + 1
          | otherwise = lx
    return $ intDec result `mappend` charUtf8 '\n'
  hPutBuilder stdout output

-- uninhm
-- https://codeforces.com/contest/1529/problem/B
-- greedy

import Data.List (sort)

odds (x:xs) = x : evens xs
odds [] = []

evens (_:xs) = odds xs
evens [] = []

(.>) = flip (.)
infixl 8 .>

solve :: [Int] -> Int
solve = (\l -> go (length l) (abs $ snd (l!!1) - snd (l!!0)) l) . zip [1..] . sort where
  go n mindiff (x':y':xs)
    | y > 0 && y <= mindiff = fst y'
    | y > 0 = fst x'
    | otherwise = go n (min mindiff (y-x)) (y':xs)
      where
        y = snd y'
        x = snd x'

  go n mindiff [x] = n

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

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

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

printArray [] = ""
printArray (x:xs) = show(x) ++" " ++ printArray xs

solve [] po = True
solve [x] po = True
solve (x:xs) po
    | x > 0 = True
    | (head xs) - x < po = False
    | otherwise = solve xs po

printS = do
    n<-readLn :: IO Int
    a<-readInts
    let z = sort a
        ne = sum[1|x<-z,x<=0]
        po = if (n-ne>0) then minimum[x|x<-z, x>0] else 0
        r = ne + if (solve ( z) po) && po>0 then 1 else 0
    print r

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

-- uninhm
-- https://codeforces.com/contest/1529/problem/B
-- greedy

import Data.List (sort)

odds (x:xs) = x : evens xs
odds [] = []

evens (_:xs) = odds xs
evens [] = []

(.>) = flip (.)
infixl 8 .>

bignum = 2^20

solve l = go (length l) bignum . zip [1..] . sort $ l where
  go n mindiff (x:xs) | mindiff == bignum && snd x > 0 = 1

  go n mindiff (x':y':xs)
    | y > 0 && y <= mindiff = fst y'
    | y > 0 = fst x'
    | otherwise = go n (min mindiff (y-x)) (y':xs)
      where
        y = snd y'
        x = snd x'

  go n mindiff [x']
    | x <= 0 || x <= mindiff = fst x'
    | otherwise = n
      where x = snd x'

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

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

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

printArray [] = ""
printArray (x:xs) = show(x) ++" " ++ printArray xs

solve [] po = True
solve [x] po = True
solve (x:xs) po
    | x > 0 = True
    | (head xs) - x < po = False
    | otherwise = solve xs po

printS = do
    n<-readLn :: IO Int
    a<-readInts
    let z = sort a
        ne = sum[1|x<-z,x<=0]
        po = if (n-ne>0) then minimum[x|x<-z, x>0] else 0
        r = ne + if (solve (tail z) po) && po>0 then 1 else 0
    print r

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


import List
import Control.Monad
import Data.Int

solve :: [Int64] -> String
solve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i
    where dx = abs(x2-x1)+1
          dy = abs(y2-y1)+1
          i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)

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

main = do
    [t] <- ints
    replicateM (t) ints >>= mapM_ (putStrLn.solve)

import List
import Control.Monad

--solve ::  [Integer] -> String
solve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i
    where dx = abs(x2-x1)+1
          dy = abs(y2-y1)+1
          i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)

--ints :: IO [Integer]
ints = fmap (map read . words) getLine

main = do
    [t] <- ints
    replicateM (fromIntegral t) ints >>= mapM_ (putStrLn.solve)

import System.Environment
import Control.Monad
import Data.Set

rr :: [Char] -> Integer
rr = read

ri :: [Char] -> Int
ri = read

each = do
    s <- getLine
    let (n:m:x1:y1:x2:y2:null) = Prelude.map rr $ words s
    let dx=abs(x1-x2)
    let dy=abs(y1-y2)
    putStrLn $ show $ n*m - 2*(n-dx)*(m-dy)  + (max 0 (n-2*dx)) * (max 0 (m-2*dy) )

main = do
    s <- getLine
    let n = ri s
    replicateM n each

import System.Environment
import Control.Monad
import Data.Set

rr :: [Char] -> Integer
rr = read

ri :: [Char] -> Int
ri = read

each = do
    s <- getLine
    let (n:m:x1:y1:x2:y2:null) = Prelude.map rr $ words s
    putStrLn $ show $ abs(x1-x2)*2*abs(y1-y2)

main = do
    s <- getLine
    let n = ri s
    replicateM n each

import List
import Control.Monad

solve ::  [Int] -> String
solve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i
    where dx = abs(x2-x1)+1
          dy = abs(y2-y1)+1
          i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)

ints = fmap (map read . words) getLine

main = do
    [t] <- ints
    replicateM t ints >>= mapM_ (putStrLn.solve)

import List
import Control.Monad

solve [n, m, x1, y1, x2, y2] = show $ n*m - 2*(n-dx+1)*(m-dy+1) + i
    where dx = abs(x2-x1)+1
          dy = abs(y2-y1)+1
          i = (max (n-2*dx+2) 0) * (max (m-2*dy+2) 0)

ints = fmap (map read . words) getLine

main = do
    [t] <- ints
    replicateM t ints >>= mapM_ (putStrLn.solve)


import Data.List

data Config = Config
  { floorSize :: (Int, Int)
  , initialPos :: (Int, Int)
  , dirtyPos :: (Int, Int)
  }

data Dir = NE | SE | NW | SW
  deriving (Show, Eq)

direction :: (Int, Int) -> Dir
direction (dr, dc)
  | dr < 0 && dc < 0 = NW
  | dr < 0 && dc > 0 = NE
  | dr > 0 && dc < 0 = SW
  | otherwise = SE

data Robot = Robot
  { robotPos :: (Int, Int)
  , robotDir :: (Int, Int)
  }

modifyRobotDir :: ((Int, Int) -> (Int, Int)) -> Robot -> Robot
modifyRobotDir f robot = let dir = robotDir robot
                         in robot{ robotDir = f dir }

moveRobot :: Robot -> Robot
moveRobot (Robot (r,c) dir@(dr, dc)) = Robot (r + dr, c + dc) dir

main :: IO ()
main = interact robotCleaner

readTestCase :: String -> Config
readTestCase testCase =
  Config
    { floorSize = (n, m)
    , initialPos = (rb, cb)
    , dirtyPos = (rd, cd)
    }
  where
    [n, m, rb, cb, rd, cd] = read <$> words testCase

robotCleaner :: String -> String
robotCleaner = unlines . map (clean . readTestCase) . tail . lines

clean :: Config -> String
clean cfg = show $ length $ unfoldr go $ Robot (initialPos cfg) (1,1)
  where
    go :: Robot -> Maybe ((), Robot)
    go robot
      | checkClean (robotPos robot) (dirtyPos cfg) = Nothing
      | otherwise = Just ((), step (floorSize cfg) robot)

step :: (Int, Int) -> Robot -> Robot
step (n,m) robot@(Robot pos@(r,c) dir) = moveRobot $ modifyRobotDir adjust robot
  where
    adjust :: (Int, Int) -> (Int, Int)
    adjust
      | corner    = reflectH . reflectV
      | vert      = reflectH
      | horz      = reflectV
      | otherwise = id
      where
        dir' = direction dir
        corner =    (pos == (1,1) && dir' == NW)
                 || (pos == (1,m) && dir' == NE)
                 || (pos == (n,1) && dir' == SW)
                 || (pos == (n,m) && dir' == SE)
        vert =    (c == 1 && (dir' == NW || dir' == SW))
               || (c == m && (dir' == NE || dir' == SE))
        horz =    (r == 1 && (dir' == NE || dir' == NW))
               || (r == n && (dir' == SE || dir' == SW))

reflectH :: (Int, Int) -> (Int, Int)
reflectH (dr, dc) = (dr, negate dc)

reflectV :: (Int, Int) -> (Int, Int)
reflectV (dr, dc) = (negate dr, dc)

checkClean ::
  -- robot position
  (Int, Int) ->
  -- dirt position
  (Int, Int) ->
  Bool
checkClean (rr, rc) (dr, dc) = rr == dr || rc == dc

processLine :: [String] -> [Int]
processLine args = do
    nums <- words <$> args

    let [n, m, rb, cb, rd, cd] = read <$> nums :: [Int]

    let {
        _go cur_r cur_c dr dc acc
        | cur_r == rd || cur_c == cd = acc
        | otherwise = _go (cur_r + new_dr) (cur_c + new_dc) new_dr new_dc (acc + 1)
        where new_dr = if cur_r == n then -dr else dr
              new_dc = if cur_c == m then -dc else dc
        }

    return (_go rb cb 1 1 0)

main = do
    input <- processLine . tail . lines <$> getContents

    mapM_ print input

module Main where

import Control.Monad ( void, replicateM )

main :: IO ()
main = getLine >>= void . flip replicateM runAction . read

runAction :: IO ()
runAction = getLine >>= print . (\[n,m,rb,cb,rd,cd] -> calculate n m rb cb rd cd) . map read . words

calculate :: Int -> Int -> Int -> Int -> Int -> Int -> Int
calculate n m rb cb rd cd =
    let dr = if rb > rd then (n - rb) + (n - rd) else rd - rb
        dc = if cb > cd then (m - cb) + (m - cd) else cd - cb
    in min dr dc


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

import Data.Array.IArray
import Data.Array.Unboxed
import Data.Char
import Data.Functor
import Data.List
import Data.Int
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Control.Monad

getInts :: IO [Int]
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

solve :: [Int] -> Int
solve = maximum . map length . group . sort

main :: IO ()
main = do [n] <- getInts
          a <- getInts
          print (n - (solve a))

import Data.List as List

toint s = (read s) :: Integer

comb (s,r) c =
    let ss = min s c in
    (s-ss+c,r+ss)

doit :: [Integer] -> (Integer,Integer) -> Integer -> Integer -> Integer

doit [] t a q =
    let (x,y) = comb t q in
    y

doit (x:xs) t a q =
    if x == a then
        doit xs t a (q+1)
    else
        doit xs (comb t q) x 1

solve::String -> String
solve ss =
    let s = List.sort $ map toint (tail (words ss)) in
    let r = doit s (0,0) (-1) 0 in
    (show r) ++ "\n"

main = do
  interact $ solve


import Control.Monad (forM_)

solve h abs strike = (iterate (\h -> if h >= 20 then h `div` 2 + 10 else h) h !! abs - 10*strike) <= 0

main = do
	t <- fmap read getLine
	forM_ [1..t] $ \i -> do
		[h, abs, strike] <- fmap (map read.words) getLine :: IO [Int]
		putStrLn $ if solve h abs strike then "YES" else "NO"

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

process a b c | a<=0 ="YES"
              | a<=20 = if c*10 >= a then "YES" else "NO"
	      | b==0 = if c*10 >=a then "YES" else "NO"
              | otherwise = process ((div a 2)+10) (b-1) c

onecase = do
		[a,b,c]<-map read <$> words <$> getLine ::IO [Integer]
		putStrLn $ process a b c

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

process :: Int -> Int -> Int -> Bool
process x n m = (iterate (\x -> x - 10) (min x (iterate (\x -> x `div` 2 + 10) x !! n)) !! m) <= 0

readInt :: String -> Int
readInt = read

run :: Int -> IO ()
run 0 = return ()
run t = do
    [x,n,m] <- fmap (map readInt.words) getLine
    if process x n m
        then putStrLn "YES"
        else putStrLn "NO"
    run (t-1)

main :: IO ()
main = do
    t <- fmap readInt getLine
    run t

absorption :: Int -> Int -> Int
absorption x n
  | x <= 20 = x
  | n == 0 = x
  | otherwise = absorption ((div x 2) + 10) (n-1)

solve :: Int -> Int -> Int -> Bool
solve x n m = afterAbsorption - (m*10) <= 0
  where afterAbsorption = absorption x n

parse :: String -> String
parse input
  | solve x n m = "YES"
  | otherwise = "NO"
  where [x, n, m] = map (\z -> read z :: Int) $ words input

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

import Control.Arrow

main = interact $
  lines >>> drop 1
  >>> map (words >>> map read)
  >>> process
  >>> map (\b -> if b then "YES" else "NO") >>> unlines

process :: [[Int]] -> [Bool]
process [] = []
process ([x,n,m]:ps) = (solve x n m <= 0) : process ps

solve x n m
  | x <= 0 = 0
  | n > 0 && x >= 20 = solve (x `div` 2 + 10) (n - 1) m
  | otherwise = x - m * 10

module Main where

import Control.Monad
import Data.List

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

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

printStrList :: [String] -> IO ()
printStrList = putStrLn . intercalate " "

printList :: (Show a) => [a] -> IO ()
printList = printStrList . map show

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

(|>) :: a -> (a -> b) -> b
(|>) = flip ($)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [x, n, m] <- getIntList
        putStrLn . yesOrNo $ f x n m

voidA :: Int -> Int
voidA = (+ 10) . (`div` 2)

f :: Int -> Int -> Int -> Bool
f x n m = x |> iterate voidA |> take (n + 1) |> filter (<= (10 * m)) |> (/= [])

module Main where

import Control.Monad
import Data.List

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

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

printStrList :: [String] -> IO ()
printStrList = putStrLn . intercalate " "

printList :: (Show a) => [a] -> IO ()
printList = printStrList . map show

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

(-->) :: a -> (a -> b) -> b
(-->) = flip ($)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [x, n, m] <- getIntList
        putStrLn . yesOrNo $ f x n m

voidA :: Int -> Int
voidA = (+ 10) . (`div` 2)

f :: Int -> Int -> Int -> Bool
f x n m = x
          --> iterate voidA
          --> take (n + 1)
          --> filter (<= (10 * m))
          --> (/= [])

main = getLine >>= test . read

test 0 = return ()
test i = do
    (x:n:m:_) <- map read . words <$> getLine
    let x' = minimum $ take (n + 1) $ iterate va x
    if minimum (take (m + 1) $ iterate ls x') <= 0
        then putStrLn "YES"
        else putStrLn "NO"
    test (i - 1)

va h = div h 2 + 10

ls h = h - 10

import Control.Monad
main :: IO ()
main = do
    n <- readLn
    replicateM_ n routine

routine :: IO ()
routine = do
    [x,n,m] <- (map (read ::String -> Int).words) <$> getLine
    putStrLn $ if solve x n m
      then "YES"
      else "NO"

solve :: Int -> Int -> Int -> Bool
solve x n m
  |x<=0 = True
  |x <=20 = x - (10*m) <= 0
  |n>0 = solve ((x `div` 2)+10) (n-1) (m)
  |otherwise = x - (10*m) <= 0

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

a :: Int -> Int -> Int
a 0 x = x
a n x = a (n - 1) (div x 2 + 10)

solve :: [Int] -> Bool
solve [x, n, m] = m * 10 >= min x (a n x)

io :: String -> String
io s = unlines $ map (yn . solve . map (read :: String -> Int) . words) $ drop 1 $ lines s

main :: IO ()
main = do
  interact io


{-# 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 Control.Monad.Trans.State.Strict
import Data.Array.Unboxed
import Data.Bool

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  m <- poi
  g <- accumArray (flip const) '\0' ((1, 1), (n, n)) `fmap` replicateM m (liftM3 (\u v c -> ((u, v), B.head c)) poi poi pop)
  return $ unlines $ map (map (bool 'B' 'A')) $ solve n g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n g = [[tbl!(i, j, 'a') | j <- [1..n]] | i <- [1..n]]
  where
  _ = g :: UArray (Int, Int) Char
  tbl = listArray rng $ map go $ range rng :: Array (Int, Int, Char) Bool
    where
    rng = ((1, 1, 'a'), (n, n, 'z'))
    go (u, v, c) = or [not $ tbl!(v, w, c') | w <- [1..n], let c' = g!(u, w), c' >= c]

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

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  m <- poi
  g <- accumArray (flip const) '\0' ((1, 1), (n, n)) `fmap` replicateM m (liftM3 (\u v c -> ((u, v), B.head c)) poi poi pop)
  return $ unlines $ map (map (bool 'B' 'A')) $ solve n g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n g = [[tbl!(i, j, 'a') | j <- [1..n]] | i <- [1..n]]
  where
  _ = g :: UArray (Int, Int) Char
  tbl = listArray rng $ map go $ range rng :: Array (Int, Int, Char) Bool
    where
    rng = ((1, 1, 'a'), (n, n, 'z'))
    go (u, v, c) = or [not $ tbl!(v, w, c') | w <- [1..n], let c' = g!(u, w), c' >= c]

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

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  m <- poi
  g <- accumArray (flip const) '\0' ((1, 1), (n, n)) `fmap` replicateM m (liftM3 (\u v c -> ((u, v), B.head c)) poi poi pop)
  return $ unlines $ map (map (bool 'B' 'A')) $ solve n g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n g = [[tbl!(i, j, 'a') | j <- [1..n]] | i <- [1..n]]
  where
  _ = g :: UArray (Int, Int) Char
  tbl = listArray rng $ map go $ range rng :: Array (Int, Int, Char) Bool
    where
    rng = ((1, 1, 'a'), (n, n, 'z'))
    go (u, v, c) = or [not $ tbl!(v, w, c') | w <- [1..n], let c' = g!(u, w), c' >= c]


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

import Control.Applicative
import qualified Data.ByteString.Char8 as B

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

main :: IO ()
main = do
  [n,m] <- map read.words <$> getLine
  (cts,vs) <- splitAt(2*n).map readInt.B.words <$> B.getContents
  putStr.unlines.map show $ solve cts vs

solve :: [Int] -> [Int] -> [Int]
solve cts vs= go 1 0 cts vs
   where
     go !i !time (c:t:cts) (v:vs)
       | time < v && v <=time + c*t = i : go i time (c:t:cts) vs
       | otherwise = go (i+1) (time+c*t) cts (v:vs)
     go _ _ _ _ = []

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

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

main :: IO ()
main = do
  n <- head <$> readA
  a <- scanl1 (+) <$> replicateM n (product <$> readA)
  b <- readA
  putStr $ unlines $ map show $ gao (zip [(1::Int)..] a) b
  where
    readA = map readInt . C.words <$> C.getLine
    gao [] _ = []
    gao _ [] = []
    gao a@((i,e):t) b@(u:v)
      | u <= e    = i: gao a v
      | otherwise = gao t b

import qualified Data.ByteString.Char8 as B

main :: IO ()
main = mapM_ print . solve . map (map (maybe 0 fst . B.readInt) . B.words) . B.lines =<< B.getContents

solve :: [[Int]] -> [Int]
solve ([n, m] : xs) = map (fst . head) $ tail $ scanl f ts ms
  where
  (ls, ms : _) = splitAt n xs
  ts = zip [1..] $ scanl1 (+) $ map (foldl1 (*)) ls
  f is@((i, t) : is') m
    | m <= t = is
    | otherwise = f is' m

import Control.Monad

cumsum :: (Num a) => [a] -> [a]
cumsum = cumsum_ 0
    where
        cumsum_ _ [] = []
        cumsum_ a (x:xs) = (x + a):cumsum_ (x + a) xs

outputSongs :: (Num a, Ord a, Show a) => a -> [a] -> [a] -> IO ()
outputSongs _ _ [] = return ()
outputSongs _ [] _ = error ""
outputSongs idx (x:xs) (m:ms) =
    if m <= x then do
        print idx
        outputSongs idx (x:xs) ms
    else
        outputSongs (idx + 1) xs (m:ms)

main :: IO ()
main = do
    [n, _] <- (map read . words) `fmap` getLine
    times <- replicateM n $ do
        [ci, ti] <- (map read . words) `fmap` getLine
        return (ci * ti :: Integer)

    let cumTimes = cumsum times

    ms <- (map read . words) `fmap` getLine
    outputSongs 1 cumTimes ms

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

solve :: [(Int, Int)] -> [Int] -> [Int]
solve as vs =  solve' 1 (zip [1..] as) vs
  where
    solve' _ _ []  =  []
    solve' t ((i, (ci, ti)) : xs) (v:vs)
      | t' <= v  =  solve' t' xs (v:vs)
      | otherwise  =  i : solve' t ((i, (ci, ti)) : xs) vs
      where
        t'  =  t + ci * ti

main :: IO ()
main  =  do
    [n, m]  <-  reads
    as  <-  replicateM n readPair
    vs  <-  reads
    mapM_ print $ solve as vs

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

    readPair :: Num a => IO (a, a)
    readPair  =  do
        [a, b]  <-  reads
        return (a, b)

    reads :: Num a => IO [a]
    reads  =  liftM (map read . words) getLine
      where
        read ('-':s)  =  (-1) * read s
        read s  =  read' 0 s
        read' a ""  =  a
        read' a (c:s)  =  read' a' s
          where
            a'  =  10 * a + fromIntegral (ord c - ord '0')

import Data.List
import Data.Char
import Data.Maybe
import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as C
import Data.Array
import Data.Bits

main = do
  [n, m] <- getList
  a <- replicateM n getList
  let b = scanl (+) 1 (map (\[c, t] -> c*t) a)
  v <- getList
  mapM (print) (f b v 0 [])
  where
    f _ [] _ acc = reverse acc
    f (b:bs) (v:vs) number acc = if v < b then f (b:bs) vs number (number:acc) else f bs (v:vs) (number+1) acc
    getList = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine


import Data.List
import System.IO

main :: IO ()
main = do
    input <- getContents
    let output = solve input
    putStr output

solve :: String -> String
solve input = let num_list = map read (words input)
                  t = head num_list
                  n_list = tail num_list
                  ans_list = map (\x -> x:[1..x]) n_list
                  all = foldl (++) [] ans_list
                  all_char = map show all
                  ans = foldl (\x y->x++y++" ") "" all_char
              in ans

solve :: String -> String
solve = concat . map go . tail . words
  where go s = unlines [s, unwords $ map show [1..read s]]

main = interact solve

import Control.Arrow ((>>>))

main :: IO ()
main =
  interact $
  words >>>
  drop 1 >>>
  map (read >>> solve >>> showWithLen >>> map show >>> unwords) >>> unlines
  where
    showWithLen xs = length xs : xs

solve :: Int -> [Int]
solve n = [1 .. n]


g x = if rem x 2 > 0 then -div (x+1) 2 else div x 2
s [x,y] = g y - g (x-1)

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

module Main where
import Data.Int
default (Int64)
main = interact exec
exec = unlines . map (\(l, r) -> show $ nsum r - nsum (l - 1)) . pairs . tail . map read . words
nsum n | s <- sgn n = (2 * s * n + s - 1) `quot` 4
pairs (x1:x2:xs) = (x1, x2):pairs xs
pairs _ = []
sgn n | odd n = -1
      | otherwise = 1

f :: Integer->Integer
f n=let a=(n-1) `div` 2
        b=n `div` 2
    in -a*a-2*a-1+b*(b+1)

f2::[String]->[String]
f2 []=[]
f2 (s:str)=let (a:b:[])=map read (words s)::[Integer]
           in (show ((f b)-(f (a-1)))):f2 str

main = do
       e<-getLine
       es<-getContents
       let xs=lines es
       mapM_ putStrLn $ f2 xs

import           Data.Int

sum' :: Int64 -> Int64
sum' r | r `mod` 2 == 0 = r `div` 2
       | otherwise      = r `div` 2 - r

solve :: IO ()
solve = do
    [l, r] <- map read . words <$> getLine
    print $ sum' r - sum' (l - 1)

ntimes :: Int -> IO () -> IO ()
ntimes 0 _  = return ()
ntimes n io = io >> ntimes (n - 1) io

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