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 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 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

{-# 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

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

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 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


{- 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)


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

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 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


-- 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

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

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


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 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 :: [(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)


m :: Int->Int->Integer
m 2 2 = 3;
m 2 x | x == 0 = 2 | x == 1 = 1
m x 2 = m 2 x
m 1 1 = 0
m _ _ = 1

z :: [Int]->[Int]->Integer
z a b = foldl (\x y->x*y) 1 (zipWith m a b)

slv :: [[Int]]->Integer
slv xs = foldl (\x y->x+y) 0 [z x ye | x <- xs, ye <- xs]

bi :: Int->Int->[Int]
bi 0 _ = []
bi n x = (mod x 2: bi (n-1) (quot x 2))

mk :: Int->Int->Int->[[Int]]
mk _ _ 1 = []
mk _ _ 0 = []
mk f n x = if (x `mod` 2) == f then ((replicate n 2)++[1-f]++(bi (30-n-1) (quot x 2))):ls else ls where ls = mk f (n + 1) (quot x 2)

cn :: Int->Int->Int->[[Int]]
cn 30 _ _ = []
cn pt le ri = if le < 2^pt && 2^(pt+1) <= ri then ((replicate pt 2)++[1]++(replicate (30-pt-1) 0)):ls else ls where ls = cn (pt+1) le ri

wr :: [Int]->Integer
wr (0:0:_) = 1
wr (0:ri:x) = (wr (1:ri:x)) + (toInteger ri) * 2 + 1
wr (le:ri:_) = slv((cn 0 (le-1) (ri+1))++(mk 0 0 (le-1))++(mk 1 0 (ri+1)))

rdd :: String->[Int]
rdd = map read . words

main = do
 t <- getLine
 semi <- sequence (replicate ((read t)::Int) getLine)
 mapM_ print (map (wr . rdd) semi)

m 2 2 =3
m 2 x |x==0=2|x==1=1
m x 2 =m 2 x
m 1 1 =0
m _ _ =1
z a b = foldl (\x y->x*y) 1 (zipWith m a b)
slv xs = foldl (\x y->x+y) 0 [z x ye | x <- xs, ye <- xs]
bi 0 _ = []
bi n x = (mod x 2: bi (n-1) (quot x 2))
mk _ _ 1 = []
mk _ _ 0 = []
mk f n x = if (x `mod` 2) == f then ((replicate n 2)++[1-f]++(bi (30-n-1) (quot x 2))):ls else ls where ls = mk f (n + 1) (quot x 2)
cn 30 _ _ = []
cn pt le ri = if le < 2^pt && 2^(pt+1) <= ri then ((replicate pt 2)++[1]++(replicate (30-pt-1) 0)):ls else ls where ls = cn (pt+1) le ri
wr (0:0:_) = 1
wr (0:ri:x) = (wr (1:ri:x)) + (toInteger ri) * 2 + 1
wr (le:ri:_) = slv((cn 0 (le-1) (ri+1))++(mk 0 0 (le-1))++(mk 1 0 (ri+1)))
rdd = map read . words
main = do
 t <- getLine
 semi <- sequence (replicate ((read t)::Int) getLine)
 mapM_ print (map (wr . rdd) semi)

m 2 2=3
m 2 x|x==0=2|x==1=1
m x 2=m 2 x
m 1 1=0
m _ _=1
l=getLine
k=replicate
q=quot
o=foldl
z a b=o(\x y->x*y)1(zipWith m a b)
s u=o(\x y->x+y)0[z x y|x<-u,y<-u]
b 0 _=[]
b n x=mod x 2:b(n-1)(q x 2)
c _ _ 1=[]
c _ _ 0=[]
c f n x=if(x`mod`2)==f then((k n 2)++[1-f]++(b(30-n-1)(q x 2))):ls else ls where ls=c f(n+1)(q x 2)
e 30 _ _=[]
e pt l r=if l<2^pt&&2^(pt+1)<=r then((k pt 2)++[1]++(k(30-pt-1)0)):ls else ls where ls=e(pt+1)l r
w(0:0:_)=1
w(0:ri:x)=(w(1:ri:x))+(toInteger ri)*2+1
w(le:ri:_)=s((e 0(le-1)(ri+1))++(c 0 0(le-1))++(c 1 0(ri+1)))
r=map read.words
main=do
 t<-l
 semi<-sequence(k((read t)::Int)l)
 mapM_ print(map(w.r)semi)

m :: Int->Int->Integer
m 2 2 = 3;
m 2 x | x == 0 = 2 | x == 1 = 1
m x 2 = m 2 x
m 1 1 = 0
m _ _ = 1

z :: [Int]->[Int]->Integer
z a b = foldl (\x y->x*y) 1 (zipWith m a b)

slv :: [[Int]]->Integer
slv xs = foldl (\x y->x+y) 0 [z x ye | x <- xs, ye <- xs]

bi :: Int->Int->[Int]
bi 0 _ = []
bi n x = (mod x 2: bi (n-1) (quot x 2))

mk :: Int->Int->Int->[[Int]]
mk _ _ 1 = []
mk _ _ 0 = []
mk f n x = if (x `mod` 2) == f then ((replicate n 2)++[1-f]++(bi (30-n-1) (quot x 2))):ls else ls where ls = mk f (n + 1) (quot x 2)

cn :: Int->Int->Int->[[Int]]
cn 30 _ _ = []
cn pt le ri = if le < 2^pt && 2^(pt+1) <= ri then ((replicate pt 2)++[1]++(replicate (30-pt-1) 0)):ls else ls where ls = cn (pt+1) le ri

wr :: [Int]->Integer
wr (0:0:_) = 1
wr (0:ri:x) = (wr (1:ri:x)) + (toInteger ri) * 2 - 1
wr (le:ri:_) = slv((cn 0 (le-1) (ri+1))++(mk 0 0 (le-1))++(mk 1 0 (ri+1)))

rdd :: String->[Int]
rdd = map read . words

main = do
 t <- getLine
 semi <- sequence (replicate ((read t)::Int) getLine)
 mapM_ print (map (wr . rdd) semi)


{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

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

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,p,k] <- map readInt . B.words <$> B.getLine
    l <- replicateM n (parse <$> B.getLine)
    putStrLn $ unwords $ map show $ solve n p k l

parse s = let [a,b] = map readInt $ B.words $ s in (a,b)

cmp1 (a,b) (c,d) = compare c a `mappend` compare d b
cmp2 (a,b) (c,d) = compare b d `mappend` compare c a

newtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)
instance Ord Order where
    compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d
instance Show Order where
    show (Order a) = show a

insert' a s = S.insert (Order a) s
member' a s = S.member (Order a) s
delete' a s = S.delete (Order a) s

solve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)
    where
    l1 = sortBy (\(a,b) (c,d) -> cmp1 a c) (zip l [1..])
    s2 = (S.fromList $ map Order (zip l [1..])) S.\\ init
    init = S.fromList $ map Order (take k l1)
    loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++
                                   (take (p-k) $ reverse $ S.toList s21)
                    | otherwise  = let s1' = insert' hd $ S.delete o s1
                                       s2' = S.insert o $ delete' hd s2
                                   in {-traceShow ("swap "++show hd++show o) $-}
                                      loop s1' s2' l1'
        where
        o = S.findMin s1
        (hd:l1') = l1
        (s21,s22) = S.split o s2
        d =  S.size s21

{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

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

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,p,k] <- map readInt . B.words <$> B.getLine
    l <- replicateM n (parse <$> B.getLine)
    putStrLn $ unwords $ map show $ solve2 n p k l

parse s = let [a,b] = map readInt $ B.words $ s in (a,b)

cmp1 (a,b) (c,d) = compare c a `mappend` compare d b
cmp2 (a,b) (c,d) = compare b d `mappend` compare c a

newtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)
instance Ord Order where
    compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d
instance Show Order where
    show (Order a) = show a

insert' a s = S.insert (Order a) s
member' a s = S.member (Order a) s
delete' a s = S.delete (Order a) s

sort' = map unOrder . sort . map Order
solve2 n p k l = map (snd) $ e ++ c
    where
    l2 = sort' (zip l [1..])
    (a,b)= splitAt (p-k) l2
    l1 = reverse $ sort $ b
    (c,d)= splitAt k l1
    x = minimum $ map Order c
    e = take (p-k) $ reverse $ a++(takeWhile f $ sort' d)
    f a = Order a `compare` x == LT

solve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)
    where
    l1 = sortBy (\(a,b) (c,d) -> cmp1 a c) (zip l [1..])
    s2 = (S.fromList $ map Order (zip l [1..])) S.\\ init
    init = S.fromList $ map Order (take k l1)
    loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++
                                   (take (p-k) $ reverse $ S.toList s21)
                    | otherwise  = let s1' = insert' hd $ S.delete o s1
                                       s2' = S.insert o $ delete' hd s2
                                   in {-traceShow ("swap "++show hd++show o) $-}
                                      loop s1' s2' l1'
        where
        o = S.findMin s1
        (hd:l1') = l1
        (s21,s22) = S.split o s2
        d =  S.size s21

{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

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

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,p,k] <- map readInt . B.words <$> B.getLine
    l <- replicateM n (parse <$> B.getLine)
    putStrLn $ unwords $ map show $ solve2 n p k l

parse s = let [a,b] = map readInt $ B.words $ s in (a,b)

cmp1 (a,b) (c,d) = compare c a `mappend` compare d b
cmp2 (a,b) (c,d) = compare b d `mappend` compare c a

newtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)
instance Ord Order where
    compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d
instance Show Order where
    show (Order a) = show a

insert' a s = S.insert (Order a) s
member' a s = S.member (Order a) s
delete' a s = S.delete (Order a) s

solve2 n p k l = map (snd) $ take (p-k) a ++ take k l1
    where
    l2 = map unOrder$ sort $ map Order (zip l [1..])
    (a,b) = go l2 undefined k []
    go [] _ 0 acc = (acc,[])
    go (x:xs) k 0 acc | cmp2 (fst x) k == EQ = go xs k 0 (x:acc)
                      | otherwise            = (acc,x:xs)
    go (x:xs) k n acc = go xs (fst x) (n-1) (x:acc)
    l1 = reverse $ sort $ b

solve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)
    where
    l1 = sortBy (\(a,b) (c,d) -> cmp1 a c) (zip l [1..])
    s2 = (S.fromList $ map Order (zip l [1..])) S.\\ init
    init = S.fromList $ map Order (take k l1)
    loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++
                                   (take (p-k) $ reverse $ S.toList s21)
                    | otherwise  = let s1' = insert' hd $ S.delete o s1
                                       s2' = S.insert o $ delete' hd s2
                                   in {-traceShow ("swap "++show hd++show o) $-}
                                      loop s1' s2' l1'
        where
        o = S.findMin s1
        (hd:l1') = l1
        (s21,s22) = S.split o s2
        d =  S.size s21

{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

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

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,p,k] <- map readInt . B.words <$> B.getLine
    l <- replicateM n (parse <$> B.getLine)
    putStrLn $ unwords $ map show $ solve2 n p k l

parse s = let [a,b] = map readInt $ B.words $ s in (a,b)

cmp1 (a,b) (c,d) = compare c a `mappend` compare d b
cmp2 (a,b) (c,d) = compare b d `mappend` compare c a

newtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)
instance Ord Order where
    compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d
instance Show Order where
    show (Order a) = show a

insert' a s = S.insert (Order a) s
member' a s = S.member (Order a) s
delete' a s = S.delete (Order a) s

sort' = map unOrder . sort . map Order
solve2 n p k l = map (snd) $ e ++ c
    where
    l2 = sort' (zip l [1..])
    (a,b)= splitAt (p-k) l2
    l1 = reverse $ sort $ b
    (c,d)= splitAt k b
    x = minimum $ map Order c
    e = take (p-k) $ reverse $ a++(takeWhile f $ sort' d)
    f a = Order a `compare` x == LT

solve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)
    where
    l1 = sortBy (\(a,b) (c,d) -> cmp1 a c) (zip l [1..])
    s2 = (S.fromList $ map Order (zip l [1..])) S.\\ init
    init = S.fromList $ map Order (take k l1)
    loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++
                                   (take (p-k) $ reverse $ S.toList s21)
                    | otherwise  = let s1' = insert' hd $ S.delete o s1
                                       s2' = S.insert o $ delete' hd s2
                                   in {-traceShow ("swap "++show hd++show o) $-}
                                      loop s1' s2' l1'
        where
        o = S.findMin s1
        (hd:l1') = l1
        (s21,s22) = S.split o s2
        d =  S.size s21

{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

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

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,p,k] <- map readInt . B.words <$> B.getLine
    l <- replicateM n (parse <$> B.getLine)
    putStrLn $ unwords $ map show $ solve2 n p k l

parse s = let [a,b] = map readInt $ B.words $ s in (a,b)

cmp1 (a,b) (c,d) = compare c a `mappend` compare d b
cmp2 (a,b) (c,d) = compare b d `mappend` compare c a

newtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)
instance Ord Order where
    compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d
instance Show Order where
    show (Order a) = show a

insert' a s = S.insert (Order a) s
member' a s = S.member (Order a) s
delete' a s = S.delete (Order a) s

solve2 n p k l = map (snd.unOrder) $ a ++ take k (map Order l1)
    where
    l2 = sort $ map Order (zip l [1..])
    (a,b) = splitAt (p-k) l2
    l1 = reverse $ sort $ map unOrder b

solve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)
    where
    l1 = sortBy (\(a,b) (c,d) -> cmp1 a c) (zip l [1..])
    s2 = (S.fromList $ map Order (zip l [1..])) S.\\ init
    init = S.fromList $ map Order (take k l1)
    loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++
                                   (take (p-k) $ reverse $ S.toList s21)
                    | otherwise  = let s1' = insert' hd $ S.delete o s1
                                       s2' = S.insert o $ delete' hd s2
                                   in {-traceShow ("swap "++show hd++show o) $-}
                                      loop s1' s2' l1'
        where
        o = S.findMin s1
        (hd:l1') = l1
        (s21,s22) = S.split o s2
        d =  S.size s21

{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

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

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,p,k] <- map readInt . B.words <$> B.getLine
    l <- replicateM n (parse <$> B.getLine)
    putStrLn $ unwords $ map show $ solve n p k l

parse s = let [a,b] = map readInt $ B.words $ s in (a,b)

cmp1 (a,b) (c,d) = compare c a `mappend` compare d b
cmp2 (a,b) (c,d) = compare d b `mappend` compare c a

newtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)
instance Ord Order where
    compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d
instance Show Order where
    show (Order a) = show a

insert' a s = S.insert (Order a) s
member' a s = S.member (Order a) s
delete' a s = S.delete (Order a) s

solve n p k l = {-traceShow l1 $ traceShow l2 $ -} map (snd.unOrder)$ loop S.empty S.empty l1 l2
    where
    l1 = sortBy (\(a,b) (c,d) -> cmp1 a c) (zip l [1..])
    l2 = S.fromList $ map Order (zip l [1..])
    loop !s1 !s2 l1 l2
        | S.size s1 < k   = let s1' = insert' hd1 s1
                                s2' = insert' hd1 s1
                            in {-trace ("insert1 "++show hd1) $  -}
                                 loop s1' s2' l1' l2
        | S.size s1 >= p  = S.toList s1
        | S.member hd2 s1  = loop s1 s2 l1 l2'
        | Order o > hd2   = {- trace ("insert2 "++show hd2) $  -}
                            loop (S.insert hd2 s1) s2 l1 l2'
        | otherwise       = let s1' = insert' hd1 $ delete' o s1
                                s2' = insert' hd1 $ delete' o s2
                                l2'' = insert' o l2
                            in {- traceShow (compare (Order o) hd2) $
                               trace ("swap "++show o++show hd1++show hd2) $ -}
                            loop s1' s2' l1' l2''
        where
        hd1:l1' = l1
        (hd2,l2') = S.deleteFindMin l2
        o = unOrder $ S.findMin s2

{-# LANGUAGE MultiParamTypeClasses,FlexibleInstances,TypeSynonymInstances,BangPatterns #-}

import Control.Monad
import Control.Applicative
import Control.Arrow
import Debug.Trace

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

type Array1 a = Array Int a
type Array2 a = Array (Int,Int) a
type UArray1 a = UArray Int a
type UArray2 a = UArray (Int,Int) a

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

fibs = 1:1:zipWith (+) fibs (tail fibs)

primeArray :: Int -> UArray1 Bool
primeArray n = runSTUArray $ do
    arr <- newArray (0,n) True
    writeArray arr 0 False
    writeArray arr 1 False
    forM_ (2:[3,5..n]) $ \i -> do
        b <- readArray arr i
        when b $ forM_ [2*i,3*i..n] $ \j -> writeArray arr j False
    return arr

binSearch f a b = go a b
    where
    go i j | i + 1 == j = i
           | f m        = go m j
           | otherwise  = go i m
        where m = div (i+j) 2

main = do
    [n,p,k] <- map readInt . B.words <$> B.getLine
    l <- replicateM n (parse <$> B.getLine)
    putStrLn $ unwords $ map show $ solve2 n p k l

parse s = let [a,b] = map readInt $ B.words $ s in (a,b)

cmp1 (a,b) (c,d) = compare c a `mappend` compare d b
cmp2 (a,b) (c,d) = compare b d `mappend` compare c a

newtype Order = Order { unOrder :: ((Int,Int),Int) } deriving (Eq)
instance Ord Order where
    compare (Order (a,b)) (Order (c,d)) = cmp2 a c `mappend` compare b d
instance Show Order where
    show (Order a) = show a

insert' a s = S.insert (Order a) s
member' a s = S.member (Order a) s
delete' a s = S.delete (Order a) s

solve2 n p k l = map (snd) $ take (p-k) a ++ take k l1
    where
    l2 = map unOrder$ sort $ map Order (zip l [1..])
    (a,b) = go l2 (0,0) (p-k) []
    go [] _ 0 acc = (acc,[])
    go (x:xs) k 0 acc | cmp2 (fst x) k == EQ = go xs k 0 (x:acc)
                      | otherwise            = (acc,x:xs)
    go (x:xs) k n acc = go xs (fst x) (n-1) (x:acc)
    l1 = reverse $ sort $ b

solve n p k l = map (snd.unOrder)$ loop init s2 (drop k l1)
    where
    l1 = sortBy (\(a,b) (c,d) -> cmp1 a c) (zip l [1..])
    s2 = (S.fromList $ map Order (zip l [1..])) S.\\ init
    init = S.fromList $ map Order (take k l1)
    loop !s1 !s2 l1 | d >= p - k = S.toList s1 ++
                                   (take (p-k) $ reverse $ S.toList s21)
                    | otherwise  = let s1' = insert' hd $ S.delete o s1
                                       s2' = S.insert o $ delete' hd s2
                                   in {-traceShow ("swap "++show hd++show o) $-}
                                      loop s1' s2' l1'
        where
        o = S.findMin s1
        (hd:l1') = l1
        (s21,s22) = S.split o s2
        d =  S.size s21