You have given an array $$$a$$$ of length $$$n$$$ and an integer $$$x$$$ to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be $$$q$$$. If $$$q$$$ is divisible by $$$x$$$, the robot adds $$$x$$$ copies of the integer $$$\frac{q}{x}$$$ to the end of the array, and moves on to the next element. Note that the newly added elements could be processed by the robot later. Otherwise, if $$$q$$$ is not divisible by $$$x$$$, the robot shuts down.Please determine the sum of all values of the array at the end of the process.

The first input line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 10^5$$$, $$$2 \leq x \leq 10^9$$$) — the length of the array and the value which is used by the robot. The next line contains integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the initial values in the array. It is guaranteed that the sum of values $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case output one integer — the sum of all elements at the end of the process.

NoteIn the first test case the array initially consists of a single element $$$[12]$$$, and $$$x=2$$$. After the robot processes the first element, the array becomes $$$[12, 6, 6]$$$. Then the robot processes the second element, and the array becomes $$$[12, 6, 6, 3, 3]$$$. After the robot processes the next element, the array becomes $$$[12, 6, 6, 3, 3, 3, 3]$$$, and then the robot shuts down, since it encounters an element that is not divisible by $$$x = 2$$$. The sum of the elements in the resulting array is equal to $$$36$$$.In the second test case the array initially contains integers $$$[4, 6, 8, 2]$$$, and $$$x=2$$$. The resulting array in this case looks like $$$ [4, 6, 8, 2, 2, 2, 3, 3, 4, 4, 1, 1, 1, 1, 1, 1]$$$.

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}
--repeat
import safe Control.Arrow ((>>>))
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.List
import Data.Function
import Data.Maybe

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

solve :: [[Integer]] -> Integer
solve [[_,x], qs] = sum $ map (\(q,t)->q*t) $ concat $ map fst $ unfoldr f (zip qs (repeat 1), True) where
  f ([],_) = Nothing
  f qtsc@(qts,can) = Just (qtsc, (reverse qts1,can1)) where
    (qts1,can1) = foldl' g ([],can) qts
    g (qts,can) (q,t)
      | can && q `mod` x == 0 = ((q `div` x, t*x):qts,True)
      | otherwise = (qts, False)

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

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

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

solve :: [[Integer]] -> Integer
solve [[_,x], qs] = sum $ map (\(q,t)->q*t) $ concat $ map fst $ unfoldr f (zip qs (repeat 1), True) where
  f ([],_) = Nothing
  f qtsc@(qts,can) = Just (qtsc, (reverse qts1,can1)) where
    (qts1,can1) = foldl' g ([],can) qts
    g (qts,can) (q,t)
      | can && q `mod` x == 0 = ((q `div` x, t*x):qts,True)
      | otherwise = (qts, False)

import Control.Monad
import Data.Int

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

runSeveral :: IO () -> IO ()
runSeveral act = do
  t <- read <$> getLine
  replicateM_ t act

main :: IO ()
main = runSeveral $ do
  [_n, x] <- readInts
  a <- readInts
  let
    ct w q = case  quotRem q x  of
      (ans, 0) -> ct (w+1) ans
      _ -> w
    allCts = map (ct 1) a
    passes = minimum allCts
    (pref, suff) = span (> passes) allCts
  print . sum . zipWith (*) a $ (passes + 1 <$ pref) ++ (passes <$ suff)

import Control.Monad
import Data.Int
import Data.List

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

runSeveral :: IO () -> IO ()
runSeveral act = do
  t <- read <$> getLine
  replicateM_ t act

main :: IO ()
main = runSeveral $ do
  [_n, x] <- readInts
  a <- readInts
  let
    r (ct, q) = case  quotRem q x  of
      (ans, 0) -> Just (x*ct, ans)
      _ -> Nothing
    clean (Just v : vs) = Just (v, vs)
    clean _ = Nothing
    a_stop = zip (repeat 1) a ++ unfoldr clean (map r a_stop)
  print . sum $ map (uncurry (*)) a_stop

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

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

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

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

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

solve :: Int -> Int64 -> [Int64] -> Int64
solve n x as = answer
    where
        xs = takeWhile (<= (1000000000 :: Int64)) $ iterate (* x) x
        answer = sum $ as ++ do
            currX <- xs
            let prevX = currX `div` x
            guard $ all (\a -> a `mod` prevX == 0) as
            a <- takeWhile (\a -> a `mod` currX  == 0) as
            return a

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, x] <- B8.getLine <&> map readIntB8 . B8.words
        as <- B8.getLine <&> map (\e -> (fromInteger (readIntegerB8 e)) :: Int64) . B8.words
        let answer = solve n ((fromIntegral x) :: Int64) as
        printf "%lld\n" answer

import Control.Arrow
import Control.Monad
import Data.Char
--import Debug.Trace
import System.IO
import Text.Read

main :: IO ()
main = do
  t <- readLn :: IO Integer
  forM_ [1 .. t] handleCase

handleCase :: Integer -> IO ()
handleCase c = do
  [n, x] <- fmap (map read . words) getLine :: IO [Integer]
  a <- fmap (map read . words) getLine :: IO [Integer]
  print $ solve x a
  return ()

stp :: Integer -> [Integer] -> [Integer]
stp x a = map (`div` x) a'
  where
    a' = takeWhile (\i -> i `mod` x == 0) a

takeWhileIncl :: (a -> Bool) -> [a] -> [a]
takeWhileIncl f [] = []
takeWhileIncl f (x:xs)
  | f x = x:takeWhileIncl f xs
  | otherwise = [x]

solve :: Integer -> [Integer] -> Integer
solve x a =
  let allNums = takeWhileIncl (\x -> length x == length a) . iterate (stp x) $ a
      withPowers = zip allNums (iterate (* x) 1)
      result = sum $ map (\(a, b) -> sum a * b) withPowers
   in result

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

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

readInts :: IO [Integer]
readInts = readArray

valuation :: Integer -> Integer -> Integer
valuation x a
  | a `mod` x == 0 = 1 + (valuation x $ a `div` x)
  | otherwise = 1

argmin :: [Integer] -> (Int, Integer)
argmin [a] = (0, a)
argmin (a:as) =
  let (i, b) = argmin as in
  if b < a then (i + 1, b) else (0, a)

solve :: Integer -> [Integer] -> Integer
solve x a =
  let (i, v) = argmin $ map (valuation x) a in
  (v + 1) * (sum $ take i a) + v * (sum $ drop i a)

solveCase :: IO String
solveCase = do
  (n:x:[]) <- readInts
  fmap (show . solve x) readInts

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

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

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

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

solve :: [[Integer]] -> Integer
solve [[_,x], qs] = sum $ map (\(q,t)->q*t) $ concat $ map fst $ unfoldr f (zip qs (repeat 1), True) where
  f ([],_) = Nothing
  f qtsc@(qts,can) = Just (qtsc, (reverse qts1,can1)) where
    (qts1,can1) = foldr g ([],can) qts
    g (q,t) (qts,can)
      | can && q `mod` x == 0 = ((q `div` x, t*x):qts,True)
      | otherwise = (qts, False)

import Control.Monad
import Data.Int
import Data.List

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

runSeveral :: IO () -> IO ()
runSeveral act = do
  t <- read <$> getLine
  replicateM_ t act

main :: IO ()
main = runSeveral $ do
  [_n, x] <- readInts
  a <- readInts
  let
    r (ct, q) = case  quotRem q x  of
      (ans, 0) -> Just (2*ct, ans)
      _ -> Nothing
    clean (Just v : vs) = Just (v, vs)
    clean _ = Nothing
    a_stop = zip (repeat 1) a ++ unfoldr clean (map r a_stop)
  print . sum $ map (uncurry (*)) a_stop

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

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

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

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

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

solve :: Int -> Int64 -> [Int64] -> Int64
solve n x as = answer
    where
        xs = iterate (* x) x
        cnts = [fromIntegral . (+1) . length $ takeWhile (\x -> a `mod` x == 0) xs | a <- as]
        answer = sum . zipWith (*) as $ scanl1 min cnts

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, x] <- B8.getLine <&> map readIntB8 . B8.words
        as <- B8.getLine <&> map (\e -> (fromInteger (readIntegerB8 e)) :: Int64) . B8.words
        let answer = solve n ((fromIntegral x) :: Int64) as
        printf "%lld\n" answer

import Control.Arrow
import Control.Monad
import Data.Char
import Data.Maybe (isJust)
import System.IO
import Text.Read

main :: IO ()
main = do
  t <- readLn :: IO Integer
  forM_ [1 .. t] handleCase

handleCase :: Integer -> IO ()
handleCase c = do
  [n, x] <- fmap (map read . words) getLine :: IO [Integer]
  a <- fmap (map read . words) getLine :: IO [Integer]
  print  $ solve x a
  return ()

stp :: Integer -> [Integer] -> Maybe [Integer]
stp x a
  | null a' = Nothing
  | otherwise = Just $ map (`div` x) a'
  where a' = takeWhile (\i -> i `mod` x == 0) a

solve :: Integer -> [Integer] -> Integer
solve x a =
  let
    Just allNums = sequence . takeWhile  isJust . iterate (>>= stp x) $ Just a
    withPowers = zip allNums (iterate (* x) 1)
    result = sum $ map (\ (a, b) -> sum a * b) withPowers
  in result


Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference is maximal possible!Your task is to write a program which calculates two things:  The maximum beauty difference of flowers that Pashmak can give to Parmida.  The number of ways that Pashmak can pick the flowers. Two ways are considered different if and only if there is at least one flower that is chosen in the first way and not chosen in the second way.

The first line of the input contains n (2 ≤ n ≤ 2·105). In the next line there are n space-separated integers b1, b2, ..., bn (1 ≤ bi ≤ 109).

The only line of output should contain two integers. The maximum beauty difference and the number of ways this may happen, respectively.

NoteIn the third sample the maximum beauty difference is 2 and there are 4 ways to do this:  choosing the first and the second flowers;  choosing the first and the fifth flowers;  choosing the fourth and the second flowers;  choosing the fourth and the fifth flowers.

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O2 -optc-O2 #-}
import qualified Data.List as L
import qualified Data.ByteString.Lazy.Char8 as LC

main :: IO ()
main = do
        cnts <-  LC.getContents
        let output = unwords . map show $ solve (readInts cnts)
        putStrLn output

solve :: [Int] -> [Integer]
solve (n:a) =
  let
    b = L.sort a
    p = head b
    q = last b
  in
    if p == q
      then
        [0, toInteger n * toInteger (n-1) `div` 2]
      else
        [toInteger (q-p), (count p b) * (count q b)]

count :: Int -> [Int] -> Integer
count x xs = toInteger $ foldl (\acc i -> acc + (if i == x then 1 else 0)) 0 xs

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

readInt :: LC.ByteString -> Int
readInt = LC.foldl' (\x c -> 10 * x + fromEnum c - 48) 0

readInts :: LC.ByteString -> [Int]
readInts str = map readInt $ LC.words str

module Main (main)
    where

import Data.List (group, sort)

readIntegers :: String -> [Integer]
readIntegers = map read . words

solve :: [Integer] -> [Integer]
solve xs = let n = fromIntegral $ length xs
               (a,b) = (minimum xs,maximum xs)
               [c,d] = map (fromIntegral . length . (`filter` xs) . (==)) [a,b]
               count = if a == b
                          then n*(n - 1) `div` 2
                          else c*d
            in [b - a, count]

main :: IO ()
main = putStrLn . toStr . solve . readIntegers =<< (getLine >> getLine)
    where toStr = unwords . map show

import Data.List

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

output :: (Int, Integer) -> IO()
output (a, b) = putStrLn ((show a) ++ " " ++ (show b))

solve :: [Int] -> (Int, Integer)
solve (n:b) = let ni = toInteger n
                  low = minimum b
                  high = maximum b
                  lowNum = toInteger $ length (filter (== low) b)
                  highNum = toInteger $ length (filter (== high) b)
              in  if high == low then (0, (div (ni * (ni - 1)) 2))
                  else ((high - low), lowNum * highNum)

import Data.List
import Data.Binary
--import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Function
import Data.Char
import Data.Maybe
import Text.Show

main = interact $ unwords . map show . getAns . tail . map fst . mapMaybe B.readInt . B.words . B.pack

getAns :: [Int] -> [Integer]
getAns xs = let ts = group $ sort xs;
				as = head ts;
				bs = last ts;
				la = toInteger $ length as;
				lb = toInteger $ length bs;
				va = head as;
				vb = head bs;
			in [toInteger $ vb - va, if (va == vb) then la * (la - 1) `div` 2 else la * lb]

import Data.List
import Data.Binary
--import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Function
import Data.Char
import Data.Maybe
import Text.Show

main = B.interact $ B.pack . unwords . map show . getAns . tail . map fst . mapMaybe B.readInt . B.words

getAns :: [Int] -> [Integer]
getAns xs = let ts = group $ sort xs;
				as = head ts;
				bs = last ts;
				la = toInteger $ length as;
				lb = toInteger $ length bs;
				va = head as;
				vb = head bs;
			in [toInteger $ vb - va, if (va == vb) then la * (la - 1) `div` 2 else la * lb]

import Data.List
import Data.Binary
import qualified Data.ByteString.Char8 as B
--import qualified Data.ByteString.Lazy.Char8 as B
import Data.Function
import Data.Char
import Data.Maybe
import Text.Show

main = interact $ unwords . map show . getAns . tail . map fst . mapMaybe B.readInt . B.words . B.pack

getAns :: [Int] -> [Integer]
getAns xs = let ts = group $ sort xs;
				as = head ts;
				bs = last ts;
				la = toInteger $ length as;
				lb = toInteger $ length bs;
				va = head as;
				vb = head bs;
			in [toInteger $ vb - va, if (va == vb) then la * (la - 1) `div` 2 else la * lb]

import Data.List
import Data.Binary
--import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Function
import Data.Char
import Data.Maybe
import Text.Show

main = B.interact $ B.unwords . map (B.pack . show) . getAns . tail . map fst . mapMaybe B.readInt . B.words

getAns :: [Int] -> [Integer]
getAns xs = let ts = group $ sort xs;
				as = head ts;
				bs = last ts;
				la = toInteger $ length as;
				lb = toInteger $ length bs;
				va = head as;
				vb = head bs;
			in [toInteger $ vb - va, if (va == vb) then la * (la - 1) `div` 2 else la * lb]

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

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

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

main = do
  getLine
  xs <- getInts

  let
    mi = minimum xs
    ma = maximum xs
    c1 = genericLength $ filter (== mi) xs :: Int64
    c2 = genericLength $ filter (== ma) xs
    c = if mi == ma then c1*(c1-1)`div`2 else c1*c2

  putStrLn $ show (ma-mi) ++ " " ++ show c

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = getLine>>= \n-> (solve.concat =<< forM [1 ..1] ( \i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))
solve xs = let s =group $ sort xs;
                       mis=head s;
                       mas = last s;
                       mi=head mis;
                       ma=head mas;
                       nmi=length mis;
                       nma=length mas in if tail s == [] then putStrLn ( "0 " ++ show (fromIntegral nmi*(fromIntegral nmi-1)`div`2)) else putStrLn $ unwords $ map show [ma-mi, fromIntegral nmi* fromIntegral nma]

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Maybe (mapMaybe)
import Text.Printf

readIntegers :: B.ByteString -> [Integer]
readIntegers = map fst . mapMaybe B.readInteger . B.words

getIntegers :: IO [Integer]
getIntegers = readIntegers <$> B.getLine

main = do
  _ <- getLine
  xs <- getIntegers
  let
    min_f = minimum xs
    max_f = maximum xs
    min_fn = fromIntegral . length . filter (==min_f) $ xs
    max_fn = fromIntegral . length . filter (==max_f) $ xs
   in printf "%d %d\n" (max_f-min_f) (if min_f == max_f then min_fn*(min_fn-1)`div`2 :: Integer else min_fn*max_fn :: Integer)

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

main=do
    n<-getLine
    q<- map (fst.fromJust.C.readInteger) <$> C.words <$> C.getLine ::IO [Integer]
    let ma = maximum q
    let mi = minimum q
    let lma = fromIntegral $ length $ filter (==ma) q
    let lmi = fromIntegral $ length $ filter (==mi) q
    putStrLn $ intercalate " " $ map show [ma-mi, if ma>mi then lma*lmi else div (lma*(lma-1)) 2]

import Data.List (genericLength)

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

solve :: [Integer] -> [Integer]
solve bs = [ maximum bs - minimum bs, if maxbs == minbs then lenmax * (lenmax - 1) `div` 2 else lenmax * lenmin ]
  where maxbs = maximum bs; minbs = minimum bs
        lenmax = genericLength (filter (==maxbs) bs); lenmin = genericLength (filter (==minbs) bs)

import qualified Data.ByteString.Char8 as B
import Data.List
main = do
    B.getLine
    fs <- fmap (group . sort . map readInteger . B.words) B.getLine
    let f = head (head fs) :: Integer
        nf = genericLength (head fs)
        l = head (last fs)
        nl = genericLength (last fs)
    putStrLn $ unwords $ map show $
        if f == l then [0, nf * (nf-1) `div` 2]
        else [l-f, nf*nl]
readInteger s = i where Just (i,_) = B.readInteger s

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

main= do
	 getLine
	 s<- map (fst.fromJust.C.readInt). C.words <$> C.getLine::IO [Int]
	 let hs = maximum s
	 let ts = minimum s
	 let s1 = length $ filter (==hs) s
	 let s2 = length $ filter (==ts) s
	 putStr $ show (hs-ts)
	 putStr " "
	 if (hs ==ts) then print $ div (fromIntegral s1*(fromIntegral s1-1)) 2
	              else print $ (fromIntegral s2)*(fromIntegral s1)

import Text.Printf

main :: IO ()
main = do
  getLine
  bs <- fmap (map read . words) getLine :: IO [Integer]
  printf "%d %d\n" (solve bs) (cnt bs)

solve :: [Integer] -> Integer
solve x = maximum x - minimum x

cnt :: [Integer] -> Integer
cnt x = if mx == mn then  lmax * (pred lmax) `div` 2
		   else lmax * lmin
  where
    lmax = toInteger $ length $ filter (== mx) x
    lmin = toInteger $ length $ filter (== mn) x
    mx = toInteger $ maximum x
    mn = toInteger $ minimum x

main :: IO ()
main = interact $ display . solve . fmap read . tail .words

display :: (Show a) => (a, a) -> String
display (a, b) = show a ++ " " ++ show b

solve :: [Integer] -> (Integer, Integer)
solve xs
    | mn == mx =  (0, (n * (n - 1)) `div` 2)
    | otherwise = (mx - mn, mnc * mxc)
        where mn = minimum xs
              mx = maximum xs
              mnc = toInteger $ length $ filter (== mn) xs
              mxc = toInteger $ length $ filter (== mx) xs
              n = toInteger $ length xs

import Data.List

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

solve :: [Int] -> [Integer]
solve (_:a) =
  let
    b = sort a
    p = head b
    q = last b
  in
    [toInteger (q-p), (count p b) * (count q b)]

count :: Int -> [Int] -> Integer
count x xs = toInteger $ foldl (\acc i -> acc + (if i == x then 1 else 0)) 0 xs

import Data.List

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

solve :: [Int] -> [Int]
solve (_:a) =
  let
    b = sort a
    p = head b
    q = last b
  in
    [q-p, (count p b) * (count q b)]

count :: Int -> [Int] -> Int
count x xs = foldl (\acc i -> acc + (if i == x then 1 else 0)) 0 xs

module Main (main)
    where

import Data.List (group, sort)

main :: IO ()
main = putStrLn . toStr . solve . map read . words =<< (getLine >> getLine)
    where solve xs = let q = [(head i, length i) | i <- group $ sort xs]
                         n = length xs
                         ((a, b), (c, d)) = (head q, last q)
                         sec | b == d    = n*(n - 1) `div` 2
                             | otherwise = b*d
                      in [c - a, sec]
          toStr = unwords . map show

module Main (main)
    where

import Data.List (elemIndices)

main :: IO ()
main = putStrLn . toStr . solve . map read . words =<< (getLine >> getLine)
    where solve xs = let n = length xs
                         (a,b) = (minimum xs, maximum xs)
                         [c,d] = map (length . (`elemIndices` xs)) [a,b]
                         count = if a == b then n*(n - 1) `div` 2 else c*d
                      in [b - a, count]
          toStr = unwords . map show

module Main (main)
    where

import Data.List (group, sort)

main :: IO ()
main = putStrLn . toStr . solve . map read . words =<< (getLine >> getLine)
    where solve xs = let q = [(head i, length i) | i <- group $ sort xs]
                         ((a, b), (c, d)) = (head q, last q)
                      in [c - a, b*d]
          toStr = unwords . map show

module Main (main)
    where

import Data.List (group, sort)

main :: IO ()
main = putStrLn . toStr . solve . map read . words =<< (getLine >> getLine)
    where solve xs = let q = [(head i, length i) | i <- group $ sort xs]
                         n = length xs
                         ((a, b), (c, d)) = (head q, last q)
                         sec | a == c    = n*(n - 1) `div` 2
                             | otherwise = b*d
                      in [c - a, sec]
          toStr = unwords . map show

module Main (main)
    where

import Data.List (elemIndices)

readIntegers :: String -> [Integer]
readIntegers = map read . words

solve :: [Integer] -> [Integer]
solve xs = let n = length xs
               (a,b) = (minimum xs, maximum xs)
               [c,d] = map (length . (`elemIndices` xs)) [a,b]
               count = if a == b then n*(n - 1) `div` 2 else c*d
            in [b - a, fromIntegral count]

main :: IO ()
main = putStrLn . toStr . solve . readIntegers =<< (getLine >> getLine)
    where toStr = unwords . map show

import Data.List

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

output :: (Integer, Integer) -> IO()
output (a, b) = putStrLn ((show a) ++ " " ++ (show b))

solve :: [Integer] -> (Integer, Integer)
solve b = let sb = sort b
              low = head sb
              high = last sb
              lowNum = fromIntegral $ length [x | x <- b, x == low]
              highNum = fromIntegral $ length [x | x <- b, x == high]
          in  ((high - low), lowNum * highNum)

import Data.List

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

output :: (Int, Integer) -> IO()
output (a, b) = putStrLn ((show a) ++ " " ++ (show b))

solve :: [Int] -> (Int, Integer)
solve (n:b) = let sb = sort b
                  low = head sb
                  high = last sb
                  lowNum = fromIntegral $ length [x | x <- b, x == low]
                  highNum = fromIntegral $ length [x | x <- b, x == high]
              in  if high == low then (0, fromIntegral (div (n * (n - 1)) 2))
                  else ((high - low), lowNum * highNum)

import Data.List

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

output :: (Int, Integer) -> IO()
output (a, b) = putStrLn ((show a) ++ " " ++ (show b))

solve :: [Int] -> (Int, Integer)
solve (n:b) = let sb = sort b
                  low = head sb
                  high = last sb
                  lowNum = toInteger $ length [x | x <- b, x == low]
                  highNum = toInteger $ length [x | x <- b, x == high]
              in  if high == low then (0, fromIntegral (div (n * (n - 1)) 2))
                  else ((high - low), lowNum * highNum)

import Data.List
import Data.Function
import Data.Char

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

getAns :: [Int] -> [Int]
getAns xs = let ts = group $ sort xs;
				as = head ts;
				bs = last ts;
			in [head bs - head as, length as * length bs]

import Data.List
import Data.Function
import Data.Char

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

getAns :: [Int] -> [Int]
getAns xs = let ts = group $ sort xs;
				as = head ts;
				bs = last ts;
			in [head bs - head as, if (head bs == head as) then (length as) * (length as - 1) `div` 2 else length as * length bs]

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

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

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

main = do
  getLine
  xs <- getInts

  let
    mi = minimum xs
    ma = maximum xs
    c1 = genericLength $ filter (== mi) xs :: Int64
    c2 = genericLength $ filter (== ma) xs

  putStrLn $ show (ma-mi) ++ " " ++ show (c1*c2)

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

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

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

main = do
  getLine
  xs <- getInts

  let
    mi = minimum xs
    ma = maximum xs
    c1 = length $ filter (== mi) xs
    c2 = length $ filter (== ma) xs

  putStrLn $ show (ma-mi) ++ " " ++ show (c1*c2)

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = getLine>>= \n-> (solve.concat =<< forM [1 ..1] ( \i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))
solve xs = let s =group $ sort xs;
                       mis=head s;
                       mas = last s;
                       mi=head mis;
                       ma=head mas;
                       nmi=length mis;
                       nma=length mas in putStrLn $ unwords $ map show [ma-mi, fromIntegral nmi* fromIntegral nma]

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = getLine>>= \n-> (solve.concat =<< forM [1 ..1] ( \i -> map (fst.fromJust.C.readInteger).C.words <$> C.getLine))
solve xs = let s =group $ sort xs;
                       mis=head s;
                       mas = last s;
                       mi=head mis;
                       ma=head mas;
                       nmi=length mis;
                       nma=length mas in if tail s == [] then putStrLn "0 1" else putStrLn $ unwords $ map show [ma-mi, fromIntegral nmi* fromIntegral nma]

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Maybe (mapMaybe)
import Text.Printf

readIntegers :: B.ByteString -> [Integer]
readIntegers = map fst . mapMaybe B.readInteger . B.words

getIntegers :: IO [Integer]
getIntegers = readIntegers <$> B.getLine

main = do
  _ <- getLine
  xs <- getIntegers
  let
    min_f = minimum xs
    max_f = maximum xs
    min_fn = fromIntegral . length . filter (==min_f) $ xs
    max_fn = fromIntegral . length . filter (==max_f) $ xs
   in printf "%d %d\n" (max_f-min_f) (if min_fn == max_fn then min_fn else min_fn*max_fn :: Integer)

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Maybe (mapMaybe)
import Text.Printf

readIntegers :: B.ByteString -> [Integer]
readIntegers = map fst . mapMaybe B.readInteger . B.words

getIntegers :: IO [Integer]
getIntegers = readIntegers <$> B.getLine

main = do
  _ <- getLine
  xs <- getIntegers
  let
    min_f = minimum xs
    max_f = maximum xs
    min_fn = fromIntegral . length . filter (==min_f) $ xs
    max_fn = fromIntegral . length . filter (==max_f) $ xs
   in printf "%d %d\n" (max_f-min_f) (min_fn*max_fn :: Integer)

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Maybe (mapMaybe)
import Text.Printf

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

getInts :: IO [Int]
getInts = readInts <$> B.getLine

main = do
  _ <- getLine
  xs <- getInts
  let
    min_f = minimum xs
    max_f = maximum xs
    min_fn = fromIntegral . length . filter (==min_f) $ xs
    max_fn = fromIntegral . length . filter (==max_f) $ xs
   in printf "%d %d\n" (max_f-min_f) (min_fn*max_fn :: Integer)

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Maybe (mapMaybe)
import Text.Printf

readIntegers :: B.ByteString -> [Integer]
readIntegers = map fst . mapMaybe B.readInteger . B.words

getIntegers :: IO [Integer]
getIntegers = readIntegers <$> B.getLine

main = do
  _ <- getLine
  xs <- getIntegers
  let
    min_f = minimum xs
    max_f = maximum xs
    min_fn = fromIntegral . length . filter (==min_f) $ xs
    max_fn = fromIntegral . length . filter (==max_f) $ xs
   in printf "%d %d\n" (max_f-min_f) (if min_fn == max_fn then min_fn*(min_fn-1)`div`2 :: Integer else min_fn*max_fn :: Integer)

import Control.Applicative
import Data.List

main=do
    n<-getLine
    q<- map read <$> words <$> getLine ::IO [Integer]
    let ma = maximum q
    let mi = minimum q
    let lma = fromIntegral $ length $ filter (==ma) q
    let lmi = fromIntegral $ length $ filter (==mi) q
    putStrLn $ intercalate " " $ map show [ma-mi, if ma>mi then lma*lmi else 1]

import Control.Applicative
import Data.List

main=do
    n<-getLine
    q<- map read <$> words <$> getLine ::IO [Integer]
    let ma = maximum q
    let mi = minimum q
    let lma = fromIntegral $ length $ filter (==ma) q
    let lmi = fromIntegral $ length $ filter (==mi) q
    putStrLn $ intercalate " " $ map show [ma-mi, lma*lmi]

import Control.Applicative
import Data.List

main=do
    n<-getLine
    q<- map read <$> words <$> getLine ::IO [Integer]
    let ma = maximum q
    let mi = minimum q
    let lma = fromIntegral $ length $ filter (==ma) q
    let lmi = fromIntegral $ length $ filter (==mi) q
    putStrLn $ intercalate " " $ map show [ma-mi, if lma>lmi then lma*lmi else lma]

import Control.Applicative
import Data.List

main=do
    n<-getLine
    q<- map read <$> words <$> getLine ::IO [Integer]
    let ma = maximum q
    let mi = minimum q
    let lma = fromIntegral $ length $ filter (==ma) q
    let lmi = fromIntegral $ length $ filter (==mi) q
    putStrLn $ intercalate " " $ map show [ma-mi, if ma>mi then lma*lmi else lma]

import Control.Applicative
import Data.List

main=do
    n<-getLine
    q<- map read <$> words <$> getLine ::IO [Int]
    let ma = maximum q
    let mi = minimum q
    let lma = length $ filter (==ma) q
    let lmi = length $ filter (==mi) q
    putStrLn $ intercalate " " $ map show [ma-mi, lma*lmi]

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

solve :: [Int] -> [Int]
solve bs = [ maximum bs - minimum bs, length (filter (==maxbs) bs) * length (filter (==minbs) bs) ]
  where maxbs = maximum bs; minbs = minimum bs

import Data.List (genericLength)

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

solve :: [Integer] -> [Integer]
solve bs = [ maximum bs - minimum bs, genericLength (filter (==maxbs) bs) * genericLength (filter (==minbs) bs) ]
  where maxbs = maximum bs; minbs = minimum bs

import Data.List
main = do
    getLine
    fs <- fmap (group . sort . map read . words) getLine
    let f = head (head fs)
        nf = length (head fs)
        l = head (last fs)
        nl = length (last fs)
    putStrLn $ unwords $ map show $
        if f == l then [0, nf * (nf-1) `div` 2]
        else [l-f, nf*nl]

import Control.Applicative
import Data.List

main= do
	 getLine
	 s<- map read. words <$> getLine::IO [Int]
	 let hs = maximum s
	 let ts = minimum s
	 let s1 = length $ filter (==hs) s
	 let s2 = length $ filter (==ts) s
	 putStr $ show (ts-hs)
	 putStr " "
	 print $ s2*s1

import Control.Applicative
import Data.List

main= do
	 getLine
	 s<- sort. map read. words <$> getLine::IO [Integer]
	 let hs = head s
	 let ts = last s
	 let s1 = length $ takeWhile (==hs) s
	 let s2 = length $ takeWhile (==ts) (reverse s)
	 putStr $ show (ts-hs)
	 putStr " "
	 print $ s2*s1

import Control.Applicative
import Data.List

main= do
	 getLine
	 s<- map read. words <$> getLine::IO [Integer]
	 let hs = maximum s
	 let ts = minimum s
	 let s1 = length $ filter (==hs) s
	 let s2 = length $ filter (==ts) s
	 putStr $ show (hs-ts)
	 putStr " "
	 print $ (fromIntegral s2)*(fromIntegral s1)

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

main= do
	 getLine
	 s<- map (fst.fromJust.C.readInt). C.words <$> C.getLine::IO [Int]
	 let hs = maximum s
	 let ts = minimum s
	 let s1 = length $ filter (==hs) s
	 let s2 = length $ filter (==ts) s
	 putStr $ show (hs-ts)
	 putStr " "
	 if (hs ==ts) then print $ div (s1*(s1-1)) 2
	              else print $ (fromIntegral s2)*(fromIntegral s1)

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

main= do
	 getLine
	 s<- map (fst.fromJust.C.readInt). C.words <$> C.getLine::IO [Int]
	 let hs = maximum s
	 let ts = minimum s
	 let s1 = length $ filter (==hs) s
	 let s2 = length $ filter (==ts) s
	 putStr $ show (hs-ts)
	 putStr " "
	 if (hs ==ts) then print 1
	              else print $ (fromIntegral s2)*(fromIntegral s1)

import Control.Applicative
import Data.List

main= do
	 getLine
	 s<- sort. map read. words <$> getLine::IO [Int]
	 let hs = head s
	 let ts = last s
	 let s1 = length $ takeWhile (==hs) s
	 let s2 = length $ takeWhile (==ts) (reverse s)
	 putStr $ show (ts-hs)
	 putStr " "
	 print $ s2*s1

import Control.Applicative
import Data.List

main= do
	 getLine
	 s<- map read. words <$> getLine::IO [Int]
	 let hs = maximum s
	 let ts = minimum s
	 let s1 = length $ filter (==hs) s
	 let s2 = length $ filter (==ts) s
	 putStr $ show (hs-ts)
	 putStr " "
	 print $ s2*s1

import Control.Applicative
import Data.List

main= do
	 getLine
	 s<- map read. words <$> getLine::IO [Integer]
	 let hs = maximum s
	 let ts = minimum s
	 let s1 = length $ filter (==hs) s
	 let s2 = length $ filter (==ts) s
	 putStr $ show (hs-ts)
	 putStr " "
	 print $ s2*s1

import Text.Printf

main :: IO ()
main = do
  getLine
  bs <- fmap (map read . words) getLine :: IO [Integer]
  printf "%d %d\n" (solve bs) (cnt bs)

solve :: [Integer] -> Integer
solve x = maximum x - minimum x

cnt :: [Integer] -> Integer
cnt x = if mx > mn then toInteger $ lmax * lmin
		   else mx * (pred mx) `div` 2
  where
    lmax = length $ filter (== mx) x
    lmin = length $ filter (== mn) x
    mx = maximum x
    mn = minimum x

import Text.Printf

main :: IO ()
main = do
  getLine
  bs <- fmap (map read . words) getLine :: IO [Integer]
  printf "%d %d\n" (solve bs) (cnt bs)

solve :: [Integer] -> Integer
solve x = maximum x - minimum x

cnt :: [Integer] -> Integer
cnt x = if mx == mn then  mx * (pred mx) `div` 2
		   else lmax * lmin
  where
    lmax = toInteger $ length $ filter (== mx) x
    lmin = toInteger $ length $ filter (== mn) x
    mx = toInteger $ maximum x
    mn = toInteger $ minimum x

main :: IO ()
main = interact $ display . solve . fmap read . tail .words

display :: (Show a) => (a, a) -> String
display (a, b) = show a ++ " " ++ show b

solve :: [Integer] -> (Integer, Integer)
solve xs
    | mn == mx =  (mn, (n * (n - 1)) `div` 2)
    | otherwise = (mx - mn, mnc * mxc)
        where mn = minimum xs
              mx = maximum xs
              mnc = toInteger $ length $ filter (== mn) xs
              mxc = toInteger $ length $ filter (== mx) xs
              n = toInteger $ length xs


There is a road with length $$$l$$$ meters. The start of the road has coordinate $$$0$$$, the end of the road has coordinate $$$l$$$.There are two cars, the first standing at the start of the road and the second standing at the end of the road. They will start driving simultaneously. The first car will drive from the start to the end and the second car will drive from the end to the start.Initially, they will drive with a speed of $$$1$$$ meter per second. There are $$$n$$$ flags at different coordinates $$$a_1, a_2, \ldots, a_n$$$. Each time when any of two cars drives through a flag, the speed of that car increases by $$$1$$$ meter per second.Find how long will it take for cars to meet (to reach the same coordinate).

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$): the number of test cases. The first line of each test case contains two integers $$$n$$$, $$$l$$$ ($$$1 \leq n \leq 10^5$$$, $$$1 \leq l \leq 10^9$$$): the number of flags and the length of the road. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ in the increasing order ($$$1 \leq a_1 < a_2 < \ldots < a_n < l$$$). It is guaranteed that the sum of $$$n$$$ among all test cases does not exceed $$$10^5$$$.

For each test case print a single real number: the time required for cars to meet. Your answer will be considered correct, if its absolute or relative error does not exceed $$$10^{-6}$$$. More formally, if your answer is $$$a$$$ and jury's answer is $$$b$$$, your answer will be considered correct if $$$\frac{|a-b|}{\max{(1, b)}} \leq 10^{-6}$$$.

NoteIn the first test case cars will meet in the coordinate $$$5$$$.The first car will be in the coordinate $$$1$$$ in $$$1$$$ second and after that its speed will increase by $$$1$$$ and will be equal to $$$2$$$ meters per second. After $$$2$$$ more seconds it will be in the coordinate $$$5$$$. So, it will be in the coordinate $$$5$$$ in $$$3$$$ seconds.The second car will be in the coordinate $$$9$$$ in $$$1$$$ second and after that its speed will increase by $$$1$$$ and will be equal to $$$2$$$ meters per second. After $$$2$$$ more seconds it will be in the coordinate $$$5$$$. So, it will be in the coordinate $$$5$$$ in $$$3$$$ seconds.In the second test case after $$$1$$$ second the first car will be in the coordinate $$$1$$$ and will have the speed equal to $$$2$$$ meters per second, the second car will be in the coordinate $$$9$$$ and will have the speed equal to $$$1$$$ meter per second. So, they will meet after $$$\frac{9-1}{2+1} = \frac{8}{3}$$$ seconds. So, the answer is equal to $$$1 + \frac{8}{3} = \frac{11}{3}$$$.

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

main :: IO ()
main = getLine >>= flip replicateM_ test . read

test :: IO ()
test = do
  [_, l] <- map read . words <$> getLine
  as <- map read . words <$> getLine
  print $ solve l as

solve :: Integer -> [Integer] -> Double
solve l as = drive 0 1 as' (fromIntegral l) 1 (reverse as')
  where
    as' = fromIntegral <$> as

drive :: (Ord a, Fractional a) => a -> a -> [a] -> a -> a -> [a] -> a
drive p r (a : as) q s (b : bs)
  | meet <= pt && meet <= qt = meet
  | pt <= qt = pt + drive a (r + 1) as (q - s * pt) s (b : bs)
  | otherwise = qt + drive (p + qt * r) r (a : as) b (s + 1) bs
  where
    meet = (q - p) / (r + s)
    pt = (a - p) / r
    qt = (q - b) / s
drive p r _ q s _ = (q - p) / (r + s)

import Control.Monad

steps :: Fractional t => [Int] -> [t]
steps = let
  go s p li = case  li  of
    a1 : tli@(a2 : _)  -> p : go (s+1) (p + fromIntegral (a2 - a1) / s) tli
    _  -> p <$ li
  in  go 1 0

solve :: (Ord t, Fractional t) => Int -> [Int] -> t
solve len a = let
  sa = 0 : (a ++ [len])
  ra = reverse $ map (len -) sa
  st = steps sa
  rt = reverse $ steps ra
  (before, after) = span (uncurry (<)) $ zip st rt
  (prevs, prevr) = last before
  (nexts, nextr) = head after
  slop = (nextr - nexts) - (prevr - prevs)
  coord = (prevs - prevr) / slop
  in  prevs + (nexts - prevs) * coord

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [_n, len] <- map read . words <$> getLine
    a <- map read . words <$> getLine
    --let  ans = solve len a :: Rational
    --print (fromRational ans :: Double)
    print (solve len a :: Double)


A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left).  Alice and Bob play dice. Alice has built a tower from n dice. We know that in this tower the adjacent dice contact with faces with distinct numbers. Bob wants to uniquely identify the numbers written on the faces of all dice, from which the tower is built. Unfortunately, Bob is looking at the tower from the face, and so he does not see all the numbers on the faces. Bob sees the number on the top of the tower and the numbers on the two adjacent sides (on the right side of the picture shown what Bob sees).Help Bob, tell whether it is possible to uniquely identify the numbers on the faces of all the dice in the tower, or not.

The first line contains a single integer n (1 ≤ n ≤ 100) — the number of dice in the tower. The second line contains an integer x (1 ≤ x ≤ 6) — the number Bob sees at the top of the tower. Next n lines contain two space-separated integers each: the i-th line contains numbers ai, bi (1 ≤ ai, bi ≤ 6; ai ≠ bi) — the numbers Bob sees on the two sidelong faces of the i-th dice in the tower. Consider the dice in the tower indexed from top to bottom from 1 to n. That is, the topmost dice has index 1 (the dice whose top face Bob can see). It is guaranteed that it is possible to make a dice tower that will look as described in the input.

Print "YES" (without the quotes), if it is possible to to uniquely identify the numbers on the faces of all the dice in the tower. If it is impossible, print "NO" (without the quotes).

possible :: Int -> [(Int,Int)] -> Bool
possible x [] = True
possible x ((y,z):xs) = if x == y || x == 7 - y || x == z || x == 7 - z then False else possible x xs

main :: IO ()
main = do str <- getLine
          let n = read str
          str <- getLine
          let x = read str
          getLine
          l <- loop (n-1)
          putStrLn (if possible x l then "YES" else "NO")
    where
        loop 0 = return []
        loop n = do str <- getLine
                    xs <- loop (n-1)
                    let [a,b] = map read . words $ str
                    return ((a,b):xs)

import Control.Applicative
import Control.Monad

t [] = []
t (a:b:s) = (a,b) : t s

solve x [] = True
solve x ((a, b) : s) = let
    c = 7 - a
    d = 7 - b
  in if (a == x) || (b == x) || (c == x) || (d == x)
     then False
     else solve x s

main = do
  n <- read <$> getLine :: IO Int
  x <- read <$> getLine :: IO Int
  a <- t <$> map read <$> (words <$> getContents) :: IO [(Int, Int)]
  putStrLn $ if solve x a then "YES" else "NO"

main :: IO ()
main = interact $ (\(_:[x]:xs) -> testcase x xs) . map (map read . words) . lines

testcase :: Int -> [[Int]] -> String
testcase b [] = "YES"
testcase b ([x,y]:xs) | (7-b) `elem` [x,y,7-x,7-y] = "NO"
							 | otherwise = testcase (7-b) xs

import Control.Monad (replicateM)

(<?>) :: a -> a -> Bool -> a
(<?>) a b p  =  if p then a else b

solve :: Int -> [(Int, Int)] -> Bool
solve x ax  =  all (\(a, b) -> a + x /= 7 && b + x /= 7 && a /= x && b /= x) ax

readPair :: IO (Int, Int)
readPair  =  do
    [x, y]  <-  fmap (map read . words) getLine
    return (x, y)

main :: IO ()
main  =  do
    n  <-  readLn
    x  <-  readLn
    ax  <-  replicateM n readPair
    putStrLn . ("YES" <?> "NO") . solve x $ ax

import Data.List
f x|x>3=7-x|1>0=x
q x|x>2="NO"|1>0="YES"
main=interact$q.length.group.sort.map f.drop 2.map read.words

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

_find n [] = "YES"
_find n (a:as)
 | n == a  || n == (7-a)= "NO"
 | otherwise = _find n as

main :: IO ()
main = do
	_ <- getLine
	_n <- getLine
	arrT <- getContents
	let
		n = read _n :: Int
		arr = map (\x -> read x :: Int).words $ arrT
	putStrLn  $_find n arr

import Control.Monad (replicateM)

(<?>) :: a -> a -> Bool -> a
(<?>) a b p  =  if p then a else b

solve :: Int -> [(Int, Int)] -> Bool
solve x ax  =  all (\(a, b) -> a + x /= 7 && b + x /= 7) ax

readPair :: IO (Int, Int)
readPair  =  do
    [x, y]  <-  fmap (map read . words) getLine
    return (x, y)

main :: IO ()
main  =  do
    n  <-  readLn
    x  <-  readLn
    ax  <-  replicateM n readPair
    putStrLn . ("YES" <?> "NO") . solve x $ ax

import Data.List
f x|x>3=x-3|1>0=x
q x|x>2="NO"|1>0="YES"
main=interact$q.length.group.sort.map f.drop 2.map read.words

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

_find n [] = "YES"
_find n (a:as)
 | n == a = "NO"
 | otherwise = _find n as

main :: IO ()
main = do
	_ <- getLine
	_n <- getLine
	arrT <- getContents
	let
		n = read _n :: Int
		arr = map (\x -> read x :: Int).words $ arrT
	putStrLn  $_find n arr


Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone.In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules of the game, Jury must use this second to touch the corresponding strip to make the square go away. As Jury is both smart and lazy, he counted that he wastes exactly ai calories on touching the i-th strip.You've got a string s, describing the process of the game and numbers a1, a2, a3, a4. Calculate how many calories Jury needs to destroy all the squares?

The first line contains four space-separated integers a1, a2, a3, a4 (0 ≤ a1, a2, a3, a4 ≤ 104). The second line contains string s (1 ≤ |s| ≤ 105), where the і-th character of the string equals "1", if on the i-th second of the game the square appears on the first strip, "2", if it appears on the second strip, "3", if it appears on the third strip, "4", if it appears on the fourth strip.

Print a single integer — the total number of calories that Jury wastes.

module Main
    where

import System.IO

main = do
    first <- getLine
    squares <- getLine
    print $ solve (parsePoints first) squares
    where
        parsePoints =
            map read . words

        solve :: [Int] -> String -> Int
        solve _ "" =
            0
        solve points (x : xs) =
            (points !! (read [x] - 1)) + solve points xs

import Data.Char

sol :: [Int] -> [Char] -> Int
sol cs is = sum (map (\i -> cs!!((digitToInt i) - 1)) is)

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

readInps :: IO [Char]
readInps = getLine

main :: IO ()
main = do
  cost <- readInts
  inps <- readInps
  print(sol cost inps)

import Data.Char

sol :: [Int] -> String -> Int
sol cs is = sum (map (\i -> cs!!((digitToInt i) - 1)) is)

main :: IO ()
main = do
  cost <- fmap (map read.words) getLine
  inps <- getLine
  print(sol cost inps)

data Tree a = Null | Node (Tree a) a (Tree a)

data Array a =  Array Int Int (Tree a)

newArray l r v | l <= r = Array l r (newArray' l r)
         where newArray' l r | l <= r = Node (newArray' l (m - 1)) v (newArray' (m + 1) r)
                         where m = div (l + r) 2
               newArray' _ _ = Null

writeArray (Array l r rt) i ai = Array l r (writeArray' l r rt)
           where writeArray' l r (Node lc val rc) | m > i = Node (writeArray' l (m - 1) lc) val rc
                             where m = div (l + r) 2
                 writeArray' l r (Node lc val rc) | m < i = Node lc val (writeArray' (m + 1) r rc)
                             where m = div (l + r) 2
                 writeArray' _ _ (Node lc _ rc) = Node lc ai rc

readArray (Array l r rt) i = readArray' l r rt
          where readArray' l r (Node lc _ _) | m > i = readArray' l (m - 1) lc
                           where m = div (l + r) 2
                readArray' l r (Node _ _ rc) | m < i = readArray' (m + 1) r rc
                           where m = div (l + r) 2
                readArray' l r (Node _ val _) = val

main = do
     as <- getLine
     s <- getLine
     let f x '1' = x + a1
         f x '2' = x + a2
         f x '3' = x + a3
         f x '4' = x + a4
         [a1,a2,a3,a4] = map read $ words as :: [Int]
     putStrLn $ show $ foldl f 0 s

import Data.Char

main :: IO()
main = print . solve . words =<< getContents

solve :: [String] -> Int
solve (a:b:c:d:s:_) = solve' (map read [a, b, c, d]) s

solve' :: [Int] -> String -> Int
solve' _ "" = 0
solve' a (s:ss) = a !! (ord s - ord '1') + solve' a ss

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

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

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

main = do
  xs <- map read . words <$> getLine
  s <- getLine

  print $ sum $ map ((xs!!) . (flip (-) 1) . digitToInt) s

import Data.List

main = do
  (a1:a2:a3:a4:_) <- fmap (map read . words) getLine
  touches <- getLine
  let go '1' = a1
      go '2' = a2
      go '3' = a3
      go '4' = a4
      go _   = (0::Int)
  print $ sum $ map go touches

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Function
import Data.Ord
import Data.Bits
import Data.Monoid
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main= someFunc
rIn x= fst $ fromJust  $ C.readInteger x
someFunc::IO()
someFunc = solve=<<forM [1..2] (\i->C.getLine)
slv1 [ns,ms] = sum $ map  (uncurry (*).((!!) ns.fromIntegral.flip (-) 1.head&&&fromIntegral.length)) $ group $ sort ms
solve [ns,ms] = print $ slv1 [map rIn $ C.words ns,map rIn $ C.words$ C.intersperse ' '  ms]

import Control.Monad
import Data.Char

main = readInput >>= putStrLn . show . calc

readInput :: IO ([Int], String)
readInput = liftM2 toTuple getLine getLine
  where toTuple a b = (map read $ words a, b)

calc (cals, game) = foldr calc' 0 game
  where calc' c ans = cals !! pos + ans
          where pos = digitToInt c - 1

import Control.Monad
import Data.Char

main = readInput >>= putStrLn . show . calc

readInput :: IO ([Int], String)
readInput = liftM2 toTuple getLine getLine
  where toTuple a b = (map read $ words a, b)

calc (cals, game) = calc' cals game
  where calc' cals [] = 0
        calc' cals (g:gs) = cals !! pos + calc' cals gs
          where pos = digitToInt g - 1

import Text.Printf
import Data.List
import Data.Functor
import Control.Applicative
import Prelude
import Control.Monad
import Data.Maybe
import Data.Function
import Data.Array
import qualified Data.ByteString.Char8 as B8
import Data.Foldable (foldr')

readInt :: String -> Int
readInt = Prelude.read

readB8Int :: B8.ByteString -> Int
readB8Int = fst . fromJust . B8.readInt

main :: IO ()
main = do
    as <- (map readB8Int . B8.words) <$> B8.getLine
    -- line <- B8.getLine
    -- let is = B8.groupBy (\x y -> False) line
    -- print is
    is <- (map readB8Int . B8.groupBy (\x y -> False) . head . B8.words) <$> B8.getLine
    let answer = sum . map (\i -> as !! (i - 1)) $ is
    printf "%d\n" answer

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

process a | even s = s
          | otherwise = s-m
  where s = sum a
        m = minimum $ filter odd a

main=do

  a<- map read <$> words <$> getLine ::IO [Int]
  b<- map digitToInt <$> getLine ::IO [Int]
  print $ sum $ map (\z->a!!(z-1)) b

import Data.Char (ord)

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

solve :: [String] -> Int
solve [bs, ss] = sum $ map ((as !!) . subtract (ord '1') . ord) ss where as = map read (words bs)
solve _ = undefined

import Data.Char (digitToInt)

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

solve :: [String] -> Int
solve [bs, ss] = sum $ map ((as !!) . pred . digitToInt) ss where as = map read (words bs)
solve _ = undefined

import Data.Char (digitToInt)
main = do
  cs <- fmap ((0:) . map read . words) getLine
  print . sum . map ((cs!!) . digitToInt) =<< getLine

import Data.Char
main = do
    as <- fmap (map read . words) getLine
    s <- getLine
    print . sum . map (\c -> as !! (digitToInt c - 1)) $ s

import Data.Char

solve :: [Int] -> String -> Int
solve a [] = 0
solve a (b:c) = (a !! (ord(b) - ord('1'))) + (solve a c)

main = do
         line <- getLine
         s <- getLine
         print $ solve (map read $ words line) s

-- la la la no testing at all
import Data.List
import Data.Char
main :: IO ()
main = do
  xs <- fmap (map (read :: String -> Int) . words) getLine
  cs <- getLine
  print . sum . map ((xs !!) . subtract 1 . digitToInt) $ cs

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

main= do
	s<- map read .words <$>getLine  ::IO [Int]
	t<- map read. words. intersperse ' '<$> getLine::IO [Int]
	let s1 = 0:s
	print $ sum $ map (s1!!) t

--ghc 7.10

import Data.Array((!), listArray)
import Data.Char(digitToInt)

sumCalory :: (Num a) => [a] -> [Int] -> a
sumCalory a s = sum (map (\x -> a' ! x) s)
    where
        n = length a
        a' = listArray (1,n) a

main = do
    aStr <- getLine
    let a = map read . words $ aStr :: [Int]
    sStr <- getLine
    let s = map digitToInt $ sStr
    print $ sumCalory a s

-- Codeforces Round #247 (Div. 2) - Problem A: Black Square (https://codeforces.com/problemset/problem/431/A)
parseInput input = (as, s) where
    ls = lines input
    as = map read $ words $ head ls :: [Int]
    s = ls !! 1

solve as s = sum $ zipWith (*) as bs where
    q1 = length $ filter (=='1') s
    q2 = length $ filter (=='2') s
    q3 = length $ filter (=='3') s
    q4 = length $ filter (=='4') s
    bs = [q1, q2, q3, q4]

main = do
    input <- getContents
    let (as, s) = parseInput input
    print $ solve as s


The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.

The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle.  Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.

Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).

NoteIn the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less. In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up. In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles.

{-# LANGUAGE FlexibleContexts      #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RecordWildCards       #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IArray
import           Data.Array.Unboxed
import qualified Data.IntMap.Strict  as IntMap
import           Data.List           (find, null)

type Pos = (Int, Int)
type Lab = UArray Pos

data Board = Board {lab::Lab Char, start::(Int, Int)}

free, robo::Char->Bool
free = (/= '*')
robo = (== 'X')

base::Int
base = 10000
encode::(Int, Int)->Int
encode (x,y) = x * base + y
decode::Int->Pos
decode u = (quot u base, rem u base)

ways::Board->Pos->[Pos]
ways (Board lab _) (x, y) = let vacant p = inRange (bounds lab) p && free (lab ! p)
                            in filter vacant [(x+1,y),(x,y-1),(x, y+1),(x-1, y)]

command::Pos->Pos->Char
command (x, y) (a, b) = case (a - x, b - y) of
  ( 1, 0) -> 'D'
  ( 0,-1) -> 'L'
  ( 0, 1) -> 'R'
  (-1, 0) -> 'U'

dists::Board->Lab Int
dists board@Board{..} = array (bounds lab) result  where
  initial = IntMap.singleton (encode start) 0
  layer = fmap encode . ways board
  result = fmap (first decode) . IntMap.toList $ go 1 [start] initial
  go k prevs acc =
    let nextSteps = zip (prevs >>= layer) (repeat k)
        nextMap = IntMap.fromList nextSteps `IntMap.difference` acc
        nextAcc = IntMap.union acc nextMap
        nextLst = decode <$> IntMap.keys nextMap
    in if null nextLst then acc else go (k + 1) nextLst nextAcc

cyclic::Board->Int->String
cyclic board = go (start board) where
  dst = dists board
  go _ 0 = ""
  go pos cnt = let Just next = find ((cnt >=).(dst !)) $ ways board pos
               in command pos next : go next (cnt - 1)

printLab::(Show a, IArray UArray a)=>Lab a->IO ()
printLab lab = let ((fx,fy),(tx,ty)) = bounds lab
               in forM_ [fx..tx] $ \x-> print [lab ! (x, y) | y <- [fy..ty]]

main :: IO ()
main = do
  [n,m,k] <- (fmap read . words) <$> getLine
  lab <- listArray ((1,1), (n,m)) . join <$> replicateM n getLine :: IO (Lab Char)
  let Just (start, _) = find (robo.snd) $ assocs lab
      board = Board lab start
      dst = dists board
      possible = mod k 2 == 0 && not (null $ ways board start)
  putStrLn $ if possible then cyclic board k else "IMPOSSIBLE"

  -- printLab lab
  -- print start
  -- print (lab ! start)
  -- printLab dst


The Smart Beaver from ABBYY plans a space travel on an ultramodern spaceship. During the voyage he plans to visit n planets. For planet i ai is the maximum number of suitcases that an alien tourist is allowed to bring to the planet, and bi is the number of citizens on the planet.The Smart Beaver is going to bring some presents from ABBYY to the planets he will be visiting. The presents are packed in suitcases, x presents in each. The Beaver will take to the ship exactly a1 + ... + an suitcases.As the Beaver lands on the i-th planet, he takes ai suitcases and goes out. On the first day on the planet the Beaver takes a walk and gets to know the citizens. On the second and all subsequent days the Beaver gives presents to the citizens — each of the bi citizens gets one present per day. The Beaver leaves the planet in the evening of the day when the number of presents left is strictly less than the number of citizens (i.e. as soon as he won't be able to give away the proper number of presents the next day). He leaves the remaining presents at the hotel.The Beaver is going to spend exactly c days traveling. The time spent on flights between the planets is considered to be zero. In how many ways can one choose the positive integer x so that the planned voyage will take exactly c days?

The first input line contains space-separated integers n and c — the number of planets that the Beaver is going to visit and the number of days he is going to spend traveling, correspondingly. The next n lines contain pairs of space-separated integers ai, bi (1 ≤ i ≤ n) — the number of suitcases he can bring to the i-th planet and the number of citizens of the i-th planet, correspondingly. The input limitations for getting 30 points are:    1 ≤ n ≤ 100  1 ≤ ai ≤ 100  1 ≤ bi ≤ 100  1 ≤ c ≤ 100  The input limitations for getting 100 points are:    1 ≤ n ≤ 104  0 ≤ ai ≤ 109  1 ≤ bi ≤ 109  1 ≤ c ≤ 109  Due to possible overflow, it is recommended to use the 64-bit arithmetic. In some solutions even the 64-bit arithmetic can overflow. So be careful in calculations!

Print a single number k — the number of ways to choose x so as to travel for exactly c days. If there are infinitely many possible values of x, print -1. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

NoteIn the first example there is only one suitable value x = 5. Then the Beaver takes 1 suitcase with 5 presents to the first planet. Here he spends 2 days: he hangs around on the first day, and he gives away five presents on the second day. He takes 2 suitcases with 10 presents to the second planet. Here he spends 3 days — he gives away 4 presents on the second and the third days and leaves the remaining 2 presents at the hotel. In total, the Beaver spends 5 days traveling.For x = 4 or less the Beaver won't have enough presents for the second day on the first planet, so the voyage will end too soon. For x = 6 and more the Beaver will spend at least one more day on the second planet, and the voyage will take too long.

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

daysX abs x = (foldl sumDiv 0 abs)
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

solve n c as bs | ((all (== 0) as) && (n == c))                 = -1
                | ((all (== 0) as) || (n > c) || (maxX < minX)) = 0
                | otherwise                                     = maxX - minX + 1
                where m = maximum bs
                      uBound = (c + 1 - n) * m + m - 1
                      abs = zip as bs
                      maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1
                      minX = binSearchMinX n c abs 1 (maxX + 1)

main =
    do all <- BS.getContents
       let Just (n, r1) = readInteger all
       let Just (c, r2) = readInteger r1
       let (as, bs) = readMany readInteger r2 [] []
       print (solve n c as bs)
    where readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
          readMany readf s xs ys = case readf s of
              Just (xi, r) -> readMany readf r ys (xi : xs)
              Nothing      -> (xs, ys)

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

daysX abs x = (foldl sumDiv 0 abs)
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

solve n c as bs | ((all (\a -> a == 0) as) && (n == c))                                = -1
                | ((all (\a -> a == 0) as) || (n > c) || (maxX == 0) || (maxX < minX)) = 0
                | otherwise                                                            = maxX - minX + 1
                where m = maximum bs
                      uBound = (c + 1 - n) * m + m - 1
                      abs = zip as bs
                      maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1
                      minX = binSearchMinX n c abs 1 (maxX + 1)

main =
    do all <- BS.getContents
       let Just (n, r1) = readInteger all
       let Just (c, r2) = readInteger r1
       let (as, bs,  _) = readAs readInteger r2
       print (solve n c as bs)
    where readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
          readAs readf s = case readf s of
              Just (ai, r) -> (ai : as, bs, t)
                               where (as, bs, t) = readBs readf r
              Nothing     -> ([], [], s)
          readBs readf s = case readf s of
              Just (bi, r) -> (as, bi : bs, t)
                               where (as, bs, t) = readAs readf r
              Nothing     -> ([], [], s)

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

daysX abs x = (foldl sumDiv 0 abs)
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

solve n c as bs | ((all (== 0) as) && (n == c))                                = -1
                | ((all (== 0) as) || (n > c) || (maxX == 0) || (maxX < minX)) = 0
                | otherwise                                                    = maxX - minX + 1
                where m = maximum bs
                      uBound = (c + 1 - n) * m + m - 1
                      abs = zip as bs
                      maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1
                      minX = binSearchMinX n c abs 1 (maxX + 1)

main =
    do all <- BS.getContents
       let Just (n, r1) = readInteger all
       let Just (c, r2) = readInteger r1
       let (as, bs) = readMany readInteger r2 [] []
       print (solve n c as bs)
    where readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
          readMany readf s xs ys = case readf s of
              Just (xi, r) -> readMany readf r ys (xi : xs)
              Nothing      -> (xs, ys)
{-
          readAs readf s = case readf s of
              Just (ai, r) -> (ai : as, bs, t)
                              where (as, bs, t) = readBs readf r
              Nothing     -> ([], [], s)
          readBs readf s = case readf s of
              Just (bi, r) -> (as, bi : bs, t)
                              where (as, bs, t) = readAs readf r
              Nothing     -> ([], [], s)
-}

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

daysX :: [(Integer, Integer)] -> Integer -> Integer
daysX abs x = foldl sumDiv 0 abs
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

binSearchMaxX n c abs lo hi | (lo == hi) && (daysX abs lo == c - n) = lo
                            | (lo == hi)                           = 0
                            | (daysX abs mid <= c - n)             = binSearchMaxX n c abs mid hi
                            | otherwise                            = binSearchMaxX n c abs lo (mid - 1)
                            where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2

solve n c as bs | (n > c)   = 0
                | otherwise =
                    if (all (\a -> a == 0) as) then special n c
                    else if (maxX == 0) then 0
                         else maxX - minX + 1
                         where  m = maximum bs
                                uBound = (c - n) * m + m - 1
                                abs = zip as bs
                                maxX = binSearchMaxX n c abs 0 uBound
                                minX = binSearchMinX n c abs 1 maxX

special n c = if (n == c) then -1
              else 0

main :: IO ()
main =
    do all <- BS.getContents
       let Just (n, r1) = readInt all
       let Just (c, r2) = readInt r1
       let (as, bs,  _) = readAs readInt r2
       print (solve n c as bs)
    where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)
          readAs readf s = case readf s of
              Just (ai, r) -> (ai : as, bs, t)
                               where (as, bs, t) = readBs readf r
              Nothing     -> ([], [], s)
          readBs readf s = case readf s of
              Just (bi, r) -> (as, bi : bs, t)
                               where (as, bs, t) = readAs readf r
              Nothing     -> ([], [], s)

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

daysX abs x = (foldl sumDiv 0 abs)
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

solve n c as bs | (n > c)                               = 0
                | ((all (\a -> a == 0) as) && (n == c)) = -1
                | (all (\a -> a == 0) as)               = 0
                | ((maxX == 0) || (maxX < minX))        = 0
                | otherwise                             = maxX - minX + 1
                where m = maximum bs
                      uBound = (c + 1 - n) * m + m - 1
                      abs = zip as bs
                      maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1
                      minX = binSearchMinX n c abs 1 (maxX + 1)

main =
    do all <- BS.getContents
       let Just (n, r1) = readInt all
       let Just (c, r2) = readInt r1
       let (as, bs,  _) = readAs readInt r2
       print (solve n c as bs)
    where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)
          readAs readf s = case readf s of
              Just (ai, r) -> (ai : as, bs, t)
                               where (as, bs, t) = readBs readf r
              Nothing     -> ([], [], s)
          readBs readf s = case readf s of
              Just (bi, r) -> (as, bi : bs, t)
                               where (as, bs, t) = readAs readf r
              Nothing     -> ([], [], s)

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

daysX abs x = (foldl sumDiv 0 abs)
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

solve n c as bs | ((all (== 0) as) && (n == c))                 = -1
                | ((all (== 0) as) || (n > c) || (maxX < minX)) = 0
                | otherwise                                     = maxX - minX + 1
                where m = maximum bs
                      uBound = (c + 1 - n) * m + m - 1 -- c-n = Sum(x*ai div bi) >= x div m -> x<= (x div m)*m + (m-1) <= (c-n)*m+(m-1)
                      abs = zip as bs
                      maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1
                      minX = binSearchMinX n c abs 1 (maxX + 1)

main =
    do all <- BS.getContents
       let Just (n, r1) = readInteger all
       let Just (c, r2) = readInteger r1
       let (as, bs) = readMany readInteger r2 [] []
       print (solve n c as bs)
    where readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
          readMany readf s xs ys = case readf s of
              Just (xi, r) -> readMany readf r ys (xi : xs)
              Nothing      -> (xs, ys)

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

daysX abs x = (foldl sumDiv 0 abs)
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

solve n c as bs | (n > c)                               = 0
                | ((all (\a -> a == 0) as) && (n == c)) = -1
                | (all (\a -> a == 0) as)               = 0
                | (maxX == 0)                           = 0
                | otherwise                             = maxX - minX + 1
                where m = maximum bs
                      uBound = (c - n) * m + m - 1
                      abs = zip as bs
                      maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1
                      minX = binSearchMinX n c abs 1 maxX

main =
    do all <- BS.getContents
       let Just (n, r1) = readInt all
       let Just (c, r2) = readInt r1
       let (as, bs,  _) = readAs readInt r2
       print (solve n c as bs)
    where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)
          readAs readf s = case readf s of
              Just (ai, r) -> (ai : as, bs, t)
                               where (as, bs, t) = readBs readf r
              Nothing     -> ([], [], s)
          readBs readf s = case readf s of
              Just (bi, r) -> (as, bi : bs, t)
                               where (as, bs, t) = readAs readf r
              Nothing     -> ([], [], s)

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

daysX :: [(Integer, Integer)] -> Integer -> Integer
daysX abs x = foldl sumDiv 0 abs
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

binSearchMaxX n c abs lo hi | (lo == hi) && (daysX abs lo == c - n) = lo
                            | (lo == hi)                           = 0
                            | (daysX abs mid <= c - n)             = binSearchMaxX n c abs mid hi
                            | otherwise                            = binSearchMaxX n c abs lo (mid - 1)
                            where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2

solve n c as bs | (n > c)   = 0
                | otherwise =
                    if (maxX == 0) then 0
                    else maxX - minX + 1
                    where  m = maximum bs
                           uBound = (c - n) * m + m - 1
                           abs = zip as bs
                           maxX = binSearchMaxX n c abs 0 uBound
                           minX = binSearchMinX n c abs 1 maxX

main :: IO ()
main =
    do all <- BS.getContents
       let Just (n, r1) = readInt all
       let Just (c, r2) = readInt r1
       let (as, bs,  _) = readAs readInt r2
       print (solve n c as bs)
    where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)
          readAs readf s = case readf s of
              Just (ai, r) -> (ai : as, bs, t)
                               where (as, bs, t) = readBs readf r
              Nothing     -> ([], [], s)
          readBs readf s = case readf s of
              Just (bi, r) -> (as, bi : bs, t)
                               where (as, bs, t) = readAs readf r
              Nothing     -> ([], [], s)

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

daysX abs x = foldl sumDiv 0 abs
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

binSearchMaxX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid <= c - n) = binSearchMaxX n c abs mid hi
                            | otherwise                = binSearchMaxX n c abs lo (mid - 1)
                            where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2

solve n c as bs | (n > c)   = 0
                | otherwise =
                    if (maxX == 0) then 0
                    else maxX - minX + 1
                    where  m = maximum bs
                           uBound = (c - n) * m + m - 1
                           abs = zip as bs
                           maxX = binSearchMaxX n c abs 0 uBound
                           minX = binSearchMinX n c abs 1 maxX

main :: IO ()
main =
    do all <- BS.getContents
       let Just (n, r1) = readInt all
       let Just (c, r2) = readInt r1
       let (as, bs,  _) = readAs readInt r2
       print (solve n c as bs)
    where readInt s = BSC.readInt (BSC.dropWhile isSpace s)
          readAs readf s = case readf s of
              Just (ai, r) -> (ai : as, bs, t)
                               where (as, bs, t) = readBs readf r
              Nothing     -> ([], [], s)
          readBs readf s = case readf s of
              Just (bi, r) -> (as, bi : bs, t)
                               where (as, bs, t) = readAs readf r
              Nothing     -> ([], [], s)

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

daysX abs x = foldl sumDiv 0 abs
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

binSearchMaxX n c abs lo hi | (lo == hi) && (daysX abs lo == c - n) = lo
                            | (lo == hi)                           = 0
                            | (daysX abs mid <= c - n)             = binSearchMaxX n c abs mid hi
                            | otherwise                            = binSearchMaxX n c abs lo (mid - 1)
                            where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2

solve n c as bs | (n > c)   = 0
                | otherwise =
                    if (maxX == 0) then 0
                    else maxX - minX + 1
                    where  m = maximum bs
                           uBound = (c - n) * m + m - 1
                           abs = zip as bs
                           maxX = binSearchMaxX n c abs 0 uBound
                           minX = binSearchMinX n c abs 1 maxX

main :: IO ()
main =
    do all <- BS.getContents
       let Just (n, r1) = readInt all
       let Just (c, r2) = readInt r1
       let (as, bs,  _) = readAs readInt r2
       print (solve n c as bs)
    where readInt s = BSC.readInt (BSC.dropWhile isSpace s)
          readAs readf s = case readf s of
              Just (ai, r) -> (ai : as, bs, t)
                               where (as, bs, t) = readBs readf r
              Nothing     -> ([], [], s)
          readBs readf s = case readf s of
              Just (bi, r) -> (as, bi : bs, t)
                               where (as, bs, t) = readAs readf r
              Nothing     -> ([], [], s)

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

daysX abs x = foldl sumDiv 0 abs
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

binSearchMaxX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid <= c - n) = binSearchMaxX n c abs mid hi
                            | otherwise                = binSearchMaxX n c abs lo (mid - 1)
                            where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2

main :: IO ()
main =
    do all <- BS.getContents
       let Just (n, r1) = readInt all
       let Just (c, r2) = readInt r1
       let (as, bs,  _) = readAs readInt r2
       let m = maximum bs
       let uBound = (c - n) * m + m - 1
       let abs = zip as bs
       let maxX = binSearchMaxX n c abs 1 uBound
       let minX = binSearchMinX n c abs 1 maxX
       print (maxX - minX + 1)
    where readInt s = BSC.readInt (BSC.dropWhile isSpace s)
          readAs readf s = case readf s of
              Just (ai, r) -> (ai : as, bs, t)
                               where (as, bs, t) = readBs readf r
              Nothing     -> ([], [], s)
          readBs readf s = case readf s of
              Just (bi, r) -> (as, bi : bs, t)
                               where (as, bs, t) = readAs readf r
              Nothing     -> ([], [], s)

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

daysX :: [(Integer, Integer)] -> Integer -> Integer
daysX abs x = foldl sumDiv 0 abs
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

binSearchMaxX n c abs lo hi | (lo == hi) && (daysX abs lo == c - n) = lo
                            | (lo == hi)                           = 0
                            | (daysX abs mid <= c - n)             = binSearchMaxX n c abs mid hi
                            | otherwise                            = binSearchMaxX n c abs lo (mid - 1)
                            where mid = (lo + hi) `div` 2 + (lo + hi) `mod` 2

solve n c as bs | (n > c)   = 0
                | otherwise =
                    if (all (\a -> a == 0) as) then -1
                    else if (maxX == 0) then 0
                         else maxX - minX + 1
                         where  m = maximum bs
                                uBound = (c - n) * m + m - 1
                                abs = zip as bs
                                maxX = binSearchMaxX n c abs 0 uBound
                                minX = binSearchMinX n c abs 1 maxX

main :: IO ()
main =
    do all <- BS.getContents
       let Just (n, r1) = readInt all
       let Just (c, r2) = readInt r1
       let (as, bs,  _) = readAs readInt r2
       print (solve n c as bs)
    where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)
          readAs readf s = case readf s of
              Just (ai, r) -> (ai : as, bs, t)
                               where (as, bs, t) = readBs readf r
              Nothing     -> ([], [], s)
          readBs readf s = case readf s of
              Just (bi, r) -> (as, bi : bs, t)
                               where (as, bs, t) = readAs readf r
              Nothing     -> ([], [], s)

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

daysX abs x = (foldl sumDiv 0 abs)
    where sumDiv s (ai, bi) = s + (x * ai) `div` bi

binSearchMinX n c abs lo hi | (lo == hi)               = lo
                            | (daysX abs mid >= c - n) = binSearchMinX n c abs lo mid
                            | otherwise                = binSearchMinX n c abs (mid + 1) hi
                            where mid = (lo + hi) `div` 2

solve n c as bs | (n > c)                               = 0
                | ((all (\a -> a == 0) as) && (n == c)) = -1
                | (all (\a -> a == 0) as)               = 0
                | (maxX == 0)                           = 0
                | otherwise                             = maxX - minX + 1
                where m = maximum bs
                      uBound = (c + 1 - n) * m + m - 1
                      abs = zip as bs
                      maxX = (binSearchMinX n (c + 1) abs 1 uBound) - 1
                      minX = binSearchMinX n c abs 1 maxX

main =
    do all <- BS.getContents
       let Just (n, r1) = readInt all
       let Just (c, r2) = readInt r1
       let (as, bs,  _) = readAs readInt r2
       print (solve n c as bs)
    where readInt s = BSC.readInteger (BSC.dropWhile isSpace s)
          readAs readf s = case readf s of
              Just (ai, r) -> (ai : as, bs, t)
                               where (as, bs, t) = readBs readf r
              Nothing     -> ([], [], s)
          readBs readf s = case readf s of
              Just (bi, r) -> (as, bi : bs, t)
                               where (as, bs, t) = readAs readf r
              Nothing     -> ([], [], s)