import Control.Monad
import Data.List
import Data.Bits

modulo = 10 ^ 9 + 7

timer :: Int -> Int
timer 1 = 0
timer n = 1 + timer (n `div` 2)

bpow :: Int -> Int -> Int -> Int -> Int
bpow a b modu acc
  | b == 0 = acc
  | otherwise = bpow na nb modu nacc
  where na = a * a `mod` modu
        nb = b `div` 2
        nacc = if even b then acc else (acc * a) `mod` modu

fastPow :: Int -> Int -> Int -> Int
fastPow a b c = bpow a b c 1

process :: Int -> Int -> Int -> Int -> Int
process n k timer acc | k == 0 = acc | otherwise = process n nk (timer + 1) nacc
                      where nk = div k 2
                            nacc = if even k then acc else mod (acc + fastPow n timer modulo) modulo

solve = do
  a <- getLine
  let arr = words a
      n = read (head arr) :: Int
      k = read (last arr) :: Int
  print(process n k 0 0 )

main = do
  entry <- getLine
  let timer = read entry :: Int
  forM_ [1..timer] $ \_ -> do
    solve

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B8
import qualified Data.ByteString.Builder as Bu -- Lazy.Builder deprecated
import Data.Functor.Identity
import Control.Monad.Trans.State
import Control.Monad
import Control.Applicative
import Control.Arrow
import Data.Function
import Data.Bits
import Data.List (unfoldr)
type St = StateT [B8.ByteString] Identity

numberOfTestcases :: St [Int]
numberOfTestcases = explicit
  where implicit = return [1] :: St [Int]
        explicit = getIntegrals 1

data Input = Input {nk :: [Int]}
data Output = Output Int deriving Show

solve :: Input -> Output
solve (Input [n,k]) = let
  powers = 1 : map (mult n) powers
  ks = k : map (flip shiftR 1) ks
  lsbs = (`mod` 2) <$> ks
  prime = 1000000007
  long x = fromIntegral x :: Integer
  short x = fromIntegral x :: Int
  mult a b = short $ (long a * long b) `mod` (long prime)
  add a b = short $ (long a + long b) `mod` (long prime)
  in
    Output $ foldr1 add $ zipWith const (zipWith mult powers lsbs) (takeWhile (/=0) ks)

-- gives a State(T) monad which when run gives Input
input :: StateT [B8.ByteString] Identity Input
input = do
  ~[n,k] <- getIntegrals 2
  return $ Input [n,k]

output :: Output -> Bu.Builder
output = go where
  str = Bu.string7
  nl  = Bu.string7 "\n"
  sp  = Bu.string7 " "
  dec = Bu.intDec
  go (Output n) = dec n <> nl
  --go (Yes l xs) = mconcat $ (<>nl) <$> [str "Yes", dec l, (mconcat $ fmap ((<> sp).dec) xs)]

doTestcase :: StateT [B8.ByteString] Identity Bu.Builder
doTestcase = input >>= (solve >>> output >>> return)

getNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])
getNext [] =  (B8.take 0 (B8.pack "."),[])
getNext (w:ws) =  (w,ws)

getIntegral :: Num t => B8.ByteString -> t
getIntegral x =  fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x

getIntegrals :: Num t => Int -> StateT [B8.ByteString] Identity [t]
getIntegrals n = replicateM n $ getIntegral <$> state getNext `const` B8.putStrLn

implicit :: St [Int]
implicit = return [1]
explicit :: St [Int]
explicit = getIntegrals 1

main :: IO ()
main = do
  raw <- B8.getContents
  let bytestrings = B8.words raw
  let outputs = flip evalState bytestrings $ do
        ~[nTc] <- numberOfTestcases
        let answers = replicateM nTc doTestcase
        fmap mconcat answers
  B8.putStr $ Bu.toLazyByteString outputs

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

bound :: Int64
bound = 1000000007

calc1 :: Int64->Int64->Int64->Int64->Int64
calc1 _ 0 _ acc = acc
calc1 n k p acc | k `mod` 2 == 1
  = calc1 n (k `div` 2) ((p*n) `mod` bound) ((p+acc) `mod` bound)
calc1 n k p acc
  = calc1 n (k `div` 2) ((p*n) `mod` bound) acc

calc :: Int64->Int64->Int64
calc n k =
  calc1 n k 1 0

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let [n,k] = map read $ words line
    print $ calc n k

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

-- (ghc -Werror -O1 -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out > temp.txt  &&  diff -sdu -- output.txt temp.txt)  &&  echo OKAY  ||  echo ERROR

import Prelude
import Control.Monad

main :: IO ()
main = do
    t <- readLn
    tcs <- replicateM t (map read . words <$> getLine)  :: IO [[Integer]]

    (putStr . unlines . map solve) tcs

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

solve [n, k] = show $ fromBin n . toBin $ k
solve _      = error "bad TC"

toBin 0 = []
toBin n = (n `mod` 2) : toBin (n `div` 2)

fromBin n bits = (`mod` theMod) . sum . zipWith (*) bits $ (iterate (*n) 1)

theMod = 10^(9::Int) + 7

{-# LANGUAGE BangPatterns               #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE GADTs                      #-}
{-# LANGUAGE RankNTypes                 #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE DeriveFunctor              #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import           Control.Arrow             ((>>>))
import           Control.Monad             as M (guard, liftM, liftM3,
                                                 replicateM, replicateM_, when, ap)
import qualified Control.Monad.ST          as ST
import qualified Control.Monad.Trans       as MS
import           Control.Monad.Trans.Maybe (MaybeT (runMaybeT))
import qualified Data.Array                as A (elems)
import qualified Data.Array.IArray         as IA
import qualified Data.Array.MArray         as MA
import qualified Data.Array.ST             as STA
import qualified Data.Array.Unboxed        as UA
import qualified Data.ByteString.Char8     as B8
import qualified Data.Foldable             as F
import           Data.Functor              ((<&>))
import           Data.Int                  (Int64)
import           Data.Ix                   (Ix (range))
import           Data.List                 (sort)
import           Data.Maybe                (fromJust, isJust)
import           Data.Ratio                (denominator, numerator)
import qualified Data.Traversable          as T
import           Data.Word                 (Word32)
import           Debug.Trace               as D
import           System.IO
import           Text.Printf               (printf)

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

readInt64 :: B8.ByteString -> Int64
readInt64 = B8.readInteger >>> fromJust >>> fst >>> fromInteger

updateArray :: (MA.MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
updateArray arr i func =
    MA.readArray arr i >>=
    MA.writeArray arr i <$> func

newtype Md109_7 a = Md109_7 a
    deriving (Functor, Show)

fromMd109_7 (Md109_7 a) = a

md109_7 :: (Num a) => a
md109_7 = fromInteger $ 10^9 + 7

instance (Num a, Ord a, Integral a) => Num (Md109_7 a) where
  (+) aa@(Md109_7 a) bb@(Md109_7 b)
    | a + b >= 2 * md109_7 = Md109_7 $ (a + b) `mod` md109_7
    | a + b >= md109_7     = Md109_7 $ a + b - md109_7
    | a + b < 0            = (-aa) + (-bb)
    | otherwise            = Md109_7 $ a + b

  (*) (Md109_7 a) (Md109_7 b)
    | a == 0 || b == 0 = Md109_7 0
    | otherwise        = Md109_7 $ a * b `mod` md109_7

  abs = id

  signum (Md109_7 a)
    | a > 0     = Md109_7 1
    | otherwise = Md109_7 0

  fromInteger x
    | x >= 2 * md109_7 = Md109_7 $ (fromInteger x :: a) `mod` md109_7
    | x >= md109_7     = Md109_7 $ (fromInteger x :: a) - md109_7
    | x < 0            = negate $ fromInteger (-x)
    | otherwise        = Md109_7 $ fromInteger x

  negate (Md109_7 a)
    | a > 0     = Md109_7 $ md109_7 - a
    | otherwise = Md109_7 0

binPower :: (Num a, Ord a, Integral a, Integral b) => Md109_7 a -> b -> Md109_7 a
binPower a b
    | b == 0    = fromInteger $ (1:: Integer)
    | even b    = let !v = binPower a (b `div` 2) in v * v
    | otherwise = a * binPower a (b - 1)

instance (Num a, Ord a, Integral a) => Fractional (Md109_7 a) where
  recip x = binPower x (md109_7 - 2)
  fromRational x = fromInteger (numerator x) * recip (fromInteger $ denominator x)

solve :: Int64 -> Int64 -> Int64
solve n k = fromMd109_7 $ solve' 32 k
    where
        nMd = Md109_7 n

        solve' :: Int64 -> Int64 -> Md109_7 Int64
        solve' index k
            | index == -1    = Md109_7 0
            | k >= 2 ^ index = (nMd `binPower` index) + solve' (index - 1) (k - 2 ^ index)
            | otherwise      = solve' (index - 1) k

main :: IO ()
main = do
    test <- B8.getLine <&> readInt
    replicateM_ test $ do
        [n, k] <- B8.getLine <&> B8.words <&> map readInt64
        let answer = solve n k
        printf "%lld\n" answer

import Control.Monad

modp = 10^9 + 7

_bp :: Int -> Int -> Int -> Int -> Int
_bp a b p res
    | b == 0 = res
    | otherwise = _bp newa newb p newres
    where newa = a * a `mod` p
          newb = if even b then b `div` 2 else (b - 1) `div` 2
          newres = if even b then res else (res * a) `mod` p

bp :: Int -> Int -> Int
bp a b = _bp a b modp 1

cal :: Int -> Int -> Int -> Int -> Int
cal n k res cur
    | k == 0 = res
    | otherwise = cal n newk newres (cur + 1)
    where newk = if even k then k `div` 2 else (k - 1) `div` 2
          newres = if even k then res else (res + bp n cur) `mod` modp

solve :: IO ()
solve = do
    [n, k] <- map read.words <$> getLine :: IO [Int]
    print(cal n k 0 0)

main = do
    line <- getLine
    let tc = read line :: Int
    forM_ [1..tc] $ \_ -> do
        solve

import Control.Monad
_bp :: Int -> Int -> Int -> Int -> Int
_bp a b p res
    | b == 0 = res
    | otherwise = _bp newa newb p newres
    where newa = a * a `mod` p
          newb = if even b then b `div` 2 else (b - 1) `div` 2
          newres = if even b then res else (res * a) `mod` p

bp :: Int -> Int -> Int
bp a b = _bp a b 1000000007 1

cal :: Int -> Int -> Int -> Int -> Int
cal n k res cur
    | k == 0 = res
    | otherwise = cal n newk newres (cur + 1)
    where newk = if even k then k `div` 2 else (k - 1) `div` 2
          newres = if even k then res else (res + bp n cur) `mod` 1000000007

solve :: IO ()
solve = do
    [n, k] <- map read.words <$> getLine :: IO [Int]
    print(cal n k 0 0)

main = do
    line <- getLine
    let tc = read line :: Int
    forM_ [1..tc] $ \_ -> do
        solve

import Control.Monad
import Data.Int ( Int64 )
_bp :: Int64 -> Int64 -> Int64 -> Int64 -> Int64
_bp a b p res
    | b == 0 = res
    | otherwise = _bp newa newb p newres
    where newa = a * a `mod` p
          newb = if even b then b `div` 2 else (b - 1) `div` 2
          newres = if even b then res else (res * a) `mod` p

bp :: Int64 -> Int64 -> Int64
bp a b = _bp a b 1000000007 1

cal :: Int64 -> Int64 -> Int64 -> Int64 -> Int64
cal n k res cur
    | k == 0 = res
    | otherwise = cal n newk newres (cur + 1)
    where newk = if even k then k `div` 2 else (k - 1) `div` 2
          newres = if even k then res else (res + bp n cur) `mod` 1000000007

solve = do
    [n, k] <- map read.words <$> getLine :: IO [Int64]
    print(cal n k 0 0)

main = do
    line <- getLine
    let tc = read line :: Int64
    forM_ [1..tc] $ \_ -> do
        solve

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B8
import qualified Data.ByteString.Builder as Bu -- Lazy.Builder deprecated
import Data.Functor.Identity
import Control.Monad.Trans.State
import Control.Monad
import Control.Applicative
import Control.Arrow
import Data.Function
import Data.Bits
import Data.List (unfoldr)
type St = StateT [B8.ByteString] Identity

numberOfTestcases :: St [Int]
numberOfTestcases = explicit
  where implicit = return [1] :: St [Int]
        explicit = getIntegrals 1

data Input = Input {nk :: [Int]}
data Output = Output Int deriving Show

solve :: Input -> Output
solve (Input [n,k]) = let
  powers = 1 : map (mult n) powers
  ks = k : map (flip shiftR 1) ks
  lsbs = (`mod` 2) <$> ks
  prime = 1000000007 :: Int
  mult a b = (a*b) `mod` prime
  add a b = (a+b) `mod` prime
  in
    Output $ foldr1 add $ zipWith const (zipWith mult powers lsbs) (takeWhile (/=0) ks)

-- gives a State(T) monad which when run gives Input
input :: StateT [B8.ByteString] Identity Input
input = do
  ~[n,k] <- getIntegrals 2
  return $ Input [n,k]

output :: Output -> Bu.Builder
output = go where
  str = Bu.string7
  nl  = Bu.string7 "\n"
  sp  = Bu.string7 " "
  dec = Bu.intDec
  go (Output n) = dec n <> nl

doTestcase :: StateT [B8.ByteString] Identity Bu.Builder
doTestcase = input >>= (solve >>> output >>> return)

getNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])
getNext [] =  (B8.take 0 (B8.pack "."),[])
getNext (w:ws) =  (w,ws)

getIntegral :: Num t => B8.ByteString -> t
getIntegral x =  fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x

getIntegrals :: Num t => Int -> StateT [B8.ByteString] Identity [t]
getIntegrals n = replicateM n $ getIntegral <$> state getNext `const` B8.putStrLn

implicit :: St [Int]
implicit = return [1]
explicit :: St [Int]
explicit = getIntegrals 1

main :: IO ()
main = do
  raw <- B8.getContents
  let bytestrings = B8.words raw
  let outputs = flip evalState bytestrings $ do
        ~[nTc] <- numberOfTestcases
        let answers = replicateM nTc doTestcase
        fmap mconcat answers
  B8.putStr $ Bu.toLazyByteString outputs

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B8
import qualified Data.ByteString.Builder as Bu -- Lazy.Builder deprecated
import Data.Functor.Identity
import Control.Monad.Trans.State
import Control.Monad
import Control.Applicative
import Control.Arrow
import Data.Function
import Data.Bits
import Data.List (unfoldr)
type St = StateT [B8.ByteString] Identity

numberOfTestcases :: St [Int]
numberOfTestcases = implicit

data Input = Input {nk :: [Int]}
data Output = Output Int deriving Show

solve :: Input -> Output
solve (Input [n,k]) = let
  powers = 1 : map (mult n) powers
  ks = k : map (flip shiftR 1) ks
  lsbs = (`mod` 2) <$> ks
  prime = 1000000007 :: Int
  mult a b = (a*b) `mod` prime
  add a b = (a+b) `mod` prime
  in
    Output $ foldr1 add $ zipWith const (zipWith mult powers lsbs) (takeWhile (/=0) ks)

-- gives a State(T) monad which when run gives Input
input :: StateT [B8.ByteString] Identity Input
input = do
  ~[n,k] <- getIntegrals 2
  return $ Input [n,k]

output :: Output -> Bu.Builder
output = go where
  str = Bu.string7
  nl  = Bu.string7 "\n"
  sp  = Bu.string7 " "
  dec = Bu.intDec
  go (Output n) = dec n <> nl

doTestcase :: StateT [B8.ByteString] Identity Bu.Builder
doTestcase = input >>= (solve >>> output >>> return)

getNext :: [B8.ByteString] -> (B8.ByteString, [B8.ByteString])
getNext [] =  (B8.take 0 (B8.pack "."),[])
getNext (w:ws) =  (w,ws)

getIntegral :: Num t => B8.ByteString -> t
getIntegral x =  fromIntegral $ fromMaybe 0 $ liftA fst $ B8.readInteger x

getIntegrals :: Num t => Int -> StateT [B8.ByteString] Identity [t]
getIntegrals n = replicateM n $ getIntegral <$> state getNext `const` B8.putStrLn

implicit :: St [Int]
implicit = return [1]
explicit :: St [Int]
explicit = getIntegrals 1

main :: IO ()
main = do
  raw <- B8.getContents
  let bytestrings = B8.words raw
  let outputs = flip evalState bytestrings $ do
        ~[nTc] <- numberOfTestcases
        let answers = replicateM nTc doTestcase
        fmap mconcat answers
  B8.putStr $ Bu.toLazyByteString outputs

import Control.Monad
import Data.List
import Data.Bits

modulo = 10 ^ 9 + 7

timer :: Int -> Int
timer 1 = 0
timer n = 1 + timer (n `div` 2)

bpow :: Int -> Int -> Int -> Int -> Int
bpow a b modu acc
  | b == 0 = acc
  | otherwise = bpow na nb modu nacc
  where na = a * a `mod` modu
        nb = b `div` 2
        nacc = if even b then acc else (acc * a) `mod` modu

fastPow :: Int -> Int -> Int -> Int
fastPow a b c = bpow a b c 1

process :: Int -> Int -> Int
process n 0 = 0
process n k = (fastPow n (timer (k .&. (-k))) modulo) + process n (k - (k .&. (-k))) `mod` modulo

solve = do
  a <- getLine
  let arr = words a
      n = read (head arr) :: Int
      k = read (last arr) :: Int
  print(process n k)

main = do
  entry <- getLine
  let timer = read entry :: Int
  forM_ [1..timer] $ \_ -> do
    solve

import Control.Monad
import Data.List
import Data.Bits

modulo = 10 ^ 9 + 7

timer :: Int -> Int
timer 1 = 0
timer n = 1 + timer (n `div` 2)

fastPow :: Int -> Int -> Int -> Int
fastPow _ 0 _ = 1
fastPow base 1 modp = mod base modp
fastPow base pow modp | even pow = mod ((fastPow base (div pow 2) modp) ^ 2) modp
                   | odd  pow = mod ((fastPow base (div (pow-1) 2) modp) ^ 2 * base) modp

process :: Int -> Int -> Int
process n 0 = 0
process n k = mod ((fastPow n (timer (k .&. (-k))) modulo) + process n (k - (k .&. (-k)))) modulo

solve = do
  a <- getLine
  let arr = words a
      n = read (head arr) :: Int
      k = read (last arr) :: Int
  print(process n k)

main = do
  entry <- getLine
  let timer = read entry :: Int
  forM_ [1..timer] $ \_ -> do
    solve

import Control.Monad
import Data.List

bound = 1000000007

calc1 :: Int->Int->Int->Int->Int
calc1 _ 0 _ acc = acc
calc1 n k p acc | k `mod` 2 == 1
  = calc1 n (k `div` 2) ((p*n) `mod` bound) ((p+acc) `mod` bound)
calc1 n k p acc
  = calc1 n (k `div` 2) ((p*n) `mod` bound) acc

calc :: Int->Int->Int
calc n k =
  calc1 n k 1 0

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let [n,k] = map read $ words line
    print $ calc n k


import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = read <$> getLine >>=
        \n -> case numBuses n of
                Just (n1, n2) -> putStrLn (show n1 ++ " " ++ show n2)
                Nothing -> putStrLn "-1"
numBuses :: Int -> Maybe (Int, Int)
numBuses n | n `mod` 2 == 1 = Nothing
           | otherwise = case (numMin n, numMax n) of
                           (Just m1, Just m2) -> Just (m1, m2)
                           _ -> Nothing

numMax :: Int -> Maybe Int
numMax n | n `mod` 4 == 0 = Just $ n `div` 4
         | n == 2 = Nothing
         | n > 0 = Just $ (div n 4) -- one less 4 wheeler, one more 6 wheeler

numMin :: Int -> Maybe Int
numMin n | n `mod` 6 == 0 = Just $ div n 6
         | n `mod` 6 == 2 = Just $ 1 + div n 6 -- one less 6, two more 4
         | n `mod` 6 == 4 = Just $ 1 + div n 6 -- one more 4

main :: IO ()
main = do
	n <- getLine
	let number = read n :: Int
	solve number number
	return ()

solve :: Int -> Int -> IO ()
solve number 0 = return ()
solve number current = 	do
				line <- getLine
				let bruh = read line :: Integer
				let m = minim bruh
				let ma = maxim bruh
				if m == -1 then
					putStrLn "-1"
				else putStrLn $ (show m) ++ " " ++ (show ma)
				solve number (current - 1)

minim :: Integer -> Integer
minim n | (n < 4) || ((mod n 2) /= 0) = -1
		  | otherwise = let
							k = div n 6
							ost = mod n 6
							in if ost /= 0 then k + 1 else k

maxim :: Integer -> Integer
maxim n | (n < 4) || ((mod n 2) /= 0) = -1
		| otherwise = div n 4

import Control.Monad

routine :: IO ()
routine = do
  n <- read <$> getLine

  case solve n of
    Just (a,b) -> putStrLn $ show a ++ " "++ show b
    _ -> putStrLn "-1"

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

solve :: Integer -> Maybe (Integer, Integer)
solve n
  |n < 4 = Nothing
  |n `mod` 2 == 1 = Nothing
  |otherwise = Just ((n+5) `div` 6,n `div` 4)

import Control.Arrow ((>>>))

solve :: Integer -> String
solve n =
    if n == 2 || n `mod` 2 == 1
        then "-1"
        else
            show
                ( m `div` 3 + (if n `mod` 3 /= 0 then 1 else 0)
                )
                ++ " "
                ++ show (m `div` 2)
  where
    m = n `div` 2

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

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

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

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

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

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

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

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

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

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

solve :: Int64 -> Maybe (Int64, Int64)
solve x
    | (x < 4) || odd x  = Nothing
    | otherwise = Just ((n + 3 - 1) `div` 3, n `div` 2)
        where
            n = x `div` 2

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    forM_ [1 .. t] $ \_ -> do
        x :: Int64 <- B8.getLine <&> readIntegerB8 <&> fromInteger
        let answer = solve x
        case answer of
            Just (minN, maxN) -> printf "%lld %lld" minN maxN
            Nothing -> printf "-1"
        printf "\n"

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

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

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

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

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

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

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

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

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

solve :: Int64 -> Maybe (Int64, Int64)
solve x
    | (x < 4) || odd x  = Nothing
    | otherwise = Just ((n + 3 - 1) `div` 3, n `div` 2)
        where
            n = x `div` 2

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    forM_ [1 .. t] $ \_ -> do
        x :: Int64 <- B8.getLine <&> readIntegerB8 <&> fromInteger
        let answer = solve x
        case answer of
            Just (minN, maxN) -> printf "%lld %lld\n" minN maxN
            Nothing -> puts "-1"

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

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

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

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

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

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

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

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

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

solve :: Int64 -> Maybe (Int64, Int64)
solve x
    | (x < 4) || odd x  = Nothing
    | otherwise = Just ((n + 3 - 1) `div` 3, n `div` 2)
        where
            n = x `div` 2

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        x :: Int64 <- B8.getLine <&> readIntegerB8 <&> fromInteger
        let answer = solve x
        case answer of
            Just (minN, maxN) -> printf "%lld %lld\n" minN maxN
            Nothing -> puts "-1"

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

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

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

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

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

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

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

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

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

solve :: Int64 -> Maybe (Int64, Int64)
solve x
    | (x < 4) || odd x  = Nothing
    | otherwise = Just ((n + 3 - 1) `div` 3, n `div` 2)
        where
            n = x `div` 2

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        x :: Int64 <- B8.getLine <&> readIntegerB8 <&> fromInteger
        let answer = solve x
        case answer of
            Just (minN, maxN) -> printf "%lld %lld\n" minN maxN
            Nothing -> puts ""


module Main where

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

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

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

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

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

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

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

main :: IO ()
main = tCase process

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

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

f :: [Int] -> Int -> [Int]
f [x]      z = [z]
f (x:y:xs) z =
    let t = x `xor` z
        r = y `xor` (t .|. y)
    in z : f (y:xs) r

import Control.Monad (replicateM_)
import Data.Bits ((.&.), xor, complement)

solve :: [Int] -> [Int]
solve (x : xs) = map snd $ scanl next (x, 0) xs where
  next (xprev, yprev) x = let y = (xprev `xor` yprev) .&. complement x in (x, y)

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    getLine
    xs <- map read . words <$> getLine
    putStrLn $ unwords $ map show $ solve xs

import Control.Arrow ((>>>))
import Data.Bits ((.&.), xor)

dropCounts :: [a] -> [a]
dropCounts [] = []
dropCounts [_] = error "Odd number of elements!"
dropCounts (_:x:xs) =  x : dropCounts xs

parseInt :: String -> Int
parseInt = read

solve :: [Int] -> [Int]
solve = aux [0]
    where
        aux :: [Int] -> [Int] -> [Int]
        aux res [_] = reverse res
        aux res (x:xs) = let y = (x `xor` head xs) .&. x
            in aux (y : res) (head xs `xor` y : tail xs)

main :: IO ()
main = interact $ lines >>> tail >>> dropCounts >>> map (words >>> map parseInt >>> solve >>> map show >>> unwords) >>> unlines

import Control.Arrow ((>>>))
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromMaybe)
import Data.Bits ((.&.), Bits (xor))

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

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

solve :: [Int] -> [Int]
solve = reverse . snd . foldl upd (0, [])
  where
    upd (x, ys) x' = let e = x - (x .&. x') in (x' `xor` e, e : ys)


import Data.List

main = getContents >>= print . solve . tail . words

solve = length . nub . map (map head . group . sort)

import Data.List

sg :: Ord a => [a] -> [[a]]
sg = group . sort

-- unique :: Ord a => [a] -> [a]
unique a = map head $ sg a

main :: IO ()
main = do
    sN <- getLine
    sC <- getLine
    let c = words sC
    let cc = map unique c
    let ccc = unique cc
    print $ length ccc

import Control.Applicative
import Data.List (sort, nub)

main = do
  _ <- getLine
  xs <- words <$> getLine :: IO [String]
  print $ length $ nub $ map (sort . nub) xs


{-# LANGUAGE FlexibleInstances #-}
module Main (printShit, printShitV, readShit, main, yN) where
import Data.ByteString.Builder
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe
-- Meat
solve :: [Double] -> [[Double]] -> Double
solve [ox, oy] = minimum. (1000000000:) . fmap (dist ox oy)
solve _ = error "sucker"

dist :: Double -> Double -> [Double] -> Double
dist ox oy [ax,ay,v] = sqrt ((ax - ox)**2 + (ay - oy) ** 2) / v
dist _ _ _= error "sucker"

-- Shit
main :: IO ()
main = do
        (o:_:xs)  <- readShit
        printShit [[solve o xs]]

class Shit a where
    printShit :: a -> IO ()
    printShitV :: a -> IO ()
    readShit :: IO a
    printShitV = printShit

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

instance  Shit Int where
    printShit = print
    readShit = fmap read getLine

instance  Shit [Int] where
    printShit = putStrLn . unwords . fmap show
    printShitV = putStrLn . unlines . fmap show
    readShit = fmap (fmap read . words) getLine

instance  Shit [Integer] where
    printShit = putStrLn . unwords . fmap show
    printShitV = putStrLn . unlines . fmap show
    readShit = fmap (fmap read . words) getLine

instance Shit [[Int]] where
    printShit = printShit . (fmap.fmap)  (toLazyByteString . integerDec .toInteger)
    readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit

instance Shit [[Double]] where
    printShit = printShit . (fmap.fmap) show
    readShit = fmap (fmap.fmap $ read) readShit

instance Shit [[Integer]] where
    printShit  = printShit . (fmap.fmap)  (toLazyByteString . integerDec)
    readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit

instance Shit [String] where
    printShit = putStrLn. unwords
    printShitV = putStrLn . unlines
    readShit = fmap lines getContents

instance Shit [[String]] where
    printShit = putStrLn . unlines . fmap unwords
    readShit = fmap (fmap (fmap words) lines) getContents

instance Shit [BS.ByteString] where
    printShit = BS.putStrLn. BS.unwords
    printShitV = BS.putStrLn . BS.unlines
    readShit = fmap BS.lines BS.getContents

instance Shit [[BS.ByteString]] where
    printShit = BS.putStrLn . BS.unlines . fmap BS.unwords
    readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents

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

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

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

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

main = do
	[ a, b ] :: [ Double ] <- map read . words <$> getLine
	n <- readInt
	[ xs, ys, vs ] :: [[ Double ]] <- transpose <$> ( replicateM n $ map read . words <$> getLine )
	printf "%.9f\n" $ minimum $ flip ( zipWith (/) ) vs $ zipWith ( \x y -> sqrt ( ( x - a ) ** 2 + ( y - b ) ** 2 ) ) xs ys

module Main where

import Control.Monad

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

readI :: IO [Int]
readI = readL
readD :: IO [Double]

readD = readL

main = do
    [a,b] <- readL
    [n] <- readL
    crds <- replicateM n readL
    putStrLn $ show $ minimum $ map (\[x,y,v] -> sqrt ((x-a)^2 + (y-b)^2) / v) crds

module Main where

import Control.Monad

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

main = do
    [a,b] <- readL :: IO [Double]
    [n] <- readL :: IO [Int]
    crds <- replicateM n (readL :: IO [Double])
    putStrLn $ show $ minimum $ map (\[x,y,v] -> sqrt ((x-a)^2 + (y-b)^2) / v) crds

import Control.Monad

main :: IO ()
main = do
  startText <- getLine
  let
    start = convert (readSplit startText) where
      convert :: [Int] -> (Int, Int)
      convert [a, b] = (a, b)
  nText <- getLine
  let n = read nText :: Int
  taxisText <- replicateM n getLine
  let
    taxis = map convert' (map readSplit taxisText) where
      convert' :: [Int] -> ( (Int, Int), Int )
      convert' [a, b, c] = ( (a, b), c )
    taxiStart = map fst taxis
    taxiSpeed = map snd taxis
  putStrLn (show (minTime start taxiStart taxiSpeed))

minTime :: (Int, Int) -> [(Int, Int)] -> [Int] -> Double
minTime _ [] [] = 0.0
minTime start (x:xs) (v:vs) = minTime' (time start x v) start xs vs where
  minTime' :: Double -> (Int, Int) -> [(Int, Int)] -> [Int] -> Double
  minTime' minT _ [] [] = minT
  minTime' minT start (x:xs) (v:vs)
    | curT < minT = minTime' curT start xs vs
    | otherwise   = minTime' minT start xs vs
    where curT = time start x v

time :: (Int, Int) -> (Int, Int) -> Int -> Double
time start taxi speed = (hypot start taxi) / (fromIntegral speed) where
  hypot :: (Int, Int) -> (Int, Int) -> Double
  hypot (x1, y1) (x2, y2) = sqrt (fromIntegral ((x1-x2)^2 + (y1-y2)^2))

readSplit :: String -> [Int]
readSplit text = map read (words text) :: [Int]

main = do
    [x,y] <- fmap ((map read) . words) getLine :: IO [Int]
    n <- readLn :: IO Int
    ls <- flip mapM [1..n] $ \i -> do
        [p,q,v] <- fmap ((map read) . words) getLine :: IO [Int]
        let dist = sqrt . fromIntegral $ (x-p)^2 + (y-q)^2 :: Float
            time = dist / (fromIntegral v)
        return time
    print . minimum $ ls

import Control.Monad (replicateM)

main = do
  [x, y] <- fmap (map read . words) getLine
  [n] <- fmap (map read . words) getLine
  ps <- replicateM n (fmap (map read . words) getLine) :: IO [[Int]]

  let
    f :: [Int] -> Double
    f [xx, yy, v] = (sqrt (fromIntegral ((xx-x)^2 + (yy-y)^2))) / fromIntegral (v)

  print $ minimum $ map f ps

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 = forM [1..2]( \is ->map rIn.C.words <$>C.getLine)>>=(\[[a,b],[n]]->solve.([a,b]:)=<<forM [1..n] (\i->map rIn.C.words <$>C.getLine) )
solve ([a,b]:xs) = print $ minimum $ map (\ [x,y,v]->sqrt (fromIntegral ((x-a)^2 +(y-b)^2))/fromIntegral v) xs

import Control.Applicative

process a b x = minimum t
  where t = map (ti a b ) x
        ti a b [c,d,v] = (/(fromIntegral v)) $ sqrt $ fromIntegral $ (c-a)^2 + (d-b)^2

main::IO ()
main=do
  [a,b]<-  map read <$> words <$> getLine ::IO [Int]
  getLine
  x<- map (map read)<$> map words <$> lines <$> getContents ::IO [[Int]]
  print $ process a b x

import Control.Monad
main = do
  [a,b] <- map read . words <$> getLine
  n <- readLn
  ts <- replicateM n (map read . words <$> getLine)
  let d [x,y,v] = sqrt((a-x)^2 + (b-y)^2) / v
  print $ minimum $ map d ts

import Control.Applicative

timeTaken :: Int -> Int -> Int -> Double
timeTaken x y v = (sqrt . fromIntegral $ x*x + y*y) / (fromIntegral v)

main :: IO ()
main = do
    [a,b] <- map read . words <$> getLine
    n <- read <$> getLine
    vals <- mapM (\_ -> map read . words <$> getLine) [1..n]
    let xs = map (\[x,y,v] -> timeTaken (x-a) (y-b) v) vals
    putStrLn . show . minimum $ xs

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

main = do
  [a, b] <- map (read :: String -> Double) . words <$> getLine
  _ <- getLine
  ls <- map (map (read:: String -> Double) . words). lines <$> getContents
  printf "%.10f\n" $ minimum $ map (\[x, y, v] -> ((x - a)**2 + (y - b)**2)**0.5 / v) ls

module Main where
  import Data.List
  import Control.Monad
  import Data.Array

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

  readInt :: String -> Int
  readInt s = read s :: Int

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  data Coordinat = Coordinat { x :: Int, y :: Int } deriving (Show, Eq)
  data Taxi = Taxi { coordinat :: Coordinat, speed :: Int } deriving (Show, Eq)

  mkTaxi :: String -> Taxi
  mkTaxi s =
    let [xi, yi, vi] = map readInt $ words s
        in Taxi (Coordinat xi yi) vi

  mkCoordinat :: [Int] -> Coordinat
  mkCoordinat [x,y] = Coordinat x y

  distance :: Floating a => Coordinat -> Coordinat -> a
  distance (Coordinat p q) (Coordinat x y) =
    let dx = fromIntegral $ p - x
        dy = fromIntegral $ q - y
        in (sqrt $ dx * dx + dy * dy)

  timeToArrive :: Floating a => Coordinat -> Taxi -> a
  timeToArrive co1@(Coordinat _ _) (Taxi co2@(Coordinat _ _) v) = (distance co1 co2) / (fromIntegral v)

  main :: IO()
  main = do
    [x,y] <- getLine >>= return . (map readInt) . words
    n <- getLine >>= return . readInt
    taxis <- readMultilineInput n $ return . mkTaxi
    putStrLn $ show $ minimum $ map (timeToArrive (Coordinat x y)) taxis

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

type I = Double

main :: IO ()
main = do
  [a,b] <- map readi . words <$> getLine
  n <- read <$> getLine
  cs <- map (toTriple . map readi . words) <$> replicateM n getLine
  print $ solve a b cs

solve :: I -> I -> [(I,I,I)] -> I
solve a b cs = minimum $ map (time a b) cs where
  time a b (x,y,v) = sqrt ((abs (a-x))^2 + (abs (b-y))^2) / v

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

readi :: String -> I
readi = read

toTuple :: [a] -> (a, a)
toTuple [x, y] = (x, y)

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

module Main where

import Control.Monad
import Prelude
import Text.Printf

type Car = (Double, Double, Double)

getTime:: Double -> Double -> Car -> Double
getTime x1 y1 (x2, y2, v) = len / v
    where dx = x1 - x2
          dy = y1 - y2
          len = sqrt (dx * dx + dy * dy)

solve :: Double -> Double -> [Car] -> Double
solve x y cars = minimum (map (getTime x y) cars)

main = do
    [x, y] <- liftM (map read . words) getLine
    n <- liftM read getLine
    cars <- replicateM n $ do
        [a, b, v] <- liftM (map read . words) getLine
        return (a, b, v)
    printf "%.10f\n" (solve x y cars)

dist :: (Int, Int) -> (Int, Int) -> Double
dist (a, b) (c, d) = sqrt. fromIntegral $ x^2 + y^2
  where x = a - c
        y = b - d

go :: Int -> (Int, Int) -> IO Double
go 0 v = return 1e18
go n v = do
  [c, d, s] <- getLine >>= return. map read. words :: IO [Int]
  next <- go (n - 1) v
  return. min (dist v (c, d) / fromIntegral s) $ next

main = do
  [a, b] <- getLine >>= return. map read. words :: IO [Int]
  n <- readLn :: IO Int
  (go n (a, b)) >>= print

import           Control.Monad

dist (x1,y1) (x2,y2) = sqrt $ (x1 - x2)^2 + (y1 - y2)^2

main :: IO ()
main = do
  [a, b] <- map (read :: String -> Double) . words <$> getLine
  n <- (read :: String -> Int) <$> getLine
  print =<< minimum . map ((\[x,y,v]-> dist (a,b) (x,y) / v) . map (read :: String -> Double) . words) <$> replicateM n getLine

import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Maybe
import Control.Monad

btoi :: B.ByteString -> Int
btoi = fst . fromJust . B.readInt

process_case :: Int -> Int -> [(Int, Int, Int)] -> Double
process_case a b = minimum . map distance_to
  where
    distance_to :: (Int, Int, Int) -> Double
    distance_to (x, y, v) = (sqrt . fromIntegral $ ((x - a)^2 + (y - b)^2)) / (fromIntegral v)

process :: B.ByteString -> B.ByteString
process str =
  let (a:b:n:rest) = map btoi $ B.words str
      taxis        = triple n rest
      triple :: Int -> [Int] -> [(Int, Int, Int)]
      triple 0 _            = []
      triple n (a:b:c:rest) = (a,b,c):(triple (n-1) rest)
  in B.pack . show $ process_case a b taxis

main :: IO ()
main = B.interact process


import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST
import Data.Array.Unboxed
import Data.Bits
import Data.Int
import Data.List
import Data.Maybe
import Data.Ratio
import qualified Data.Set as Set
import System.IO
import System.IO.Unsafe

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

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

type Graph = Array Int [Int]

buildG :: (Int, Int) -> [(Int, Int)] -> Graph
buildG = accumArray (flip (:)) []

runMm :: Graph -> (UArray Int Int, UArray Int Bool)
runMm g =
    runST $ do
        mt <- newArray (bounds g) (-1)
        forM_ (indices g) $ \i -> do
            vis <- newArray (bounds g) False
            go vis mt i
        vis <- newArray (bounds g) False
        mt' <- unsafeFreezeSTUArray mt
        let matched = Set.fromList (filter (>=0) (elems mt'))
        forM_ (indices g) $ \i -> do
            unless (Set.member i matched) $
                void (go vis mt i)
        vis' <- unsafeFreezeSTUArray vis
        return (mt', vis')
    where
        go :: STUArray s Int Bool -> STUArray s Int Int -> Int -> ST s Bool
        go vis mt x = do
            visx <- readArray vis x
            if visx then
                return False
            else do
                writeArray vis x True
                trav (g ! x)
            where
                trav [] = return False
                trav (y:ys) = do
                    v <- readArray mt y
                    if v < 0 then win
                    else do
                        can <- go vis mt v
                        if can then win
                        else
                            trav ys
                    where
                        win = do
                            writeArray mt y x
                            return True

getMvc :: Graph -> [Int]
getMvc g =
    let (mt, vis) = runMm g
    in
        [i | (i, t) <- assocs vis, not t] ++ [-i | (i, t) <- assocs mt, t >= 0 && vis ! t]

solve :: [Int] -> [(Int64, Int64)] -> Int -> Int -> [Int]
solve os vs' n k = runST $ do
    mem <- newArray ((0,0), (k+1,mm+1)) (-1)
    c <- newArray ((0,0), (k+1,mm+1)) (-1)
    r <- f mem c 0 mm
    build c 0 mm os
    where
        mm = length os
        vs = listArray (0, k-1) vs' :: Array Int (Int64,Int64)
        f :: STUArray s (Int, Int) Int64 -> STUArray s (Int, Int) Int -> Int -> Int -> ST s Int64
        f mem c i j = do
            rr <- readArray mem (i,j)
            if rr >= 0 then
                return rr
            else do
                if i == k then
                    writeArray mem (i,j) 0
                else do
                    let (x,y) = vs ! i
                    writeArray mem (i,j) (1 `shift` 60)
                    forM_ [0..j] $ \t -> do
                        when (j-t <= n-2-i) $ do
                            rcost <- f mem c (i+1) (j-t)
                            let cost = rcost + ((y * fromIntegral t) `min` x)
                            curcost <- readArray mem (i,j)
                            when (cost < curcost) $ do
                                writeArray mem (i,j) cost
                                writeArray c (i,j) t
                readArray mem (i,j)
        build :: STUArray s (Int, Int) Int -> Int -> Int -> [Int] -> ST s [Int]
        build c i j os
            | i == k = return []
            | otherwise = do
                t <- readArray c (i, j)
                rr <- build c (i+1) (j-t) (drop t os)
                return $ take t os ++ [0] ++ rr

main = do
    [n, m, k] <- map parseInt . BS.words <$> BS.getLine
    es <- replicateM m $ do
        [x, y] <- map parseInt . BS.words <$> BS.getLine
        return (x, y)
    vs <- replicateM k $ do
        [x, y] <- map (fromIntegral . parseInt) . BS.words <$> BS.getLine
        return (x, y)
    let g = buildG (1,n) es
        mvc = getMvc g
        r = solve mvc vs n k
    print $ length r
    putStrLn $ unwords (map show r)

import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST
import Data.Array.Unboxed
import Data.Bits
import Data.Int
import Data.List
import Data.Maybe
import Data.Ratio
import qualified Data.Set as Set
import System.IO
import System.IO.Unsafe

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

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

type Graph = Array Int [Int]

buildG :: (Int, Int) -> [(Int, Int)] -> Graph
buildG = accumArray (flip (:)) []

runMm :: Graph -> (UArray Int Int, UArray Int Bool)
runMm g =
    runST $ do
        mt <- newArray (bounds g) (-1)
        forM_ (indices g) $ \i -> do
            vis <- newArray (bounds g) False
            go vis mt i
        vis <- newArray (bounds g) False
        mt' <- unsafeFreezeSTUArray mt
        let matched = Set.fromList (filter (>=0) (elems mt'))
        forM_ (indices g) $ \i -> do
            unless (Set.member i matched) $
                void (go vis mt i)
        vis' <- unsafeFreezeSTUArray vis
        return (mt', vis')
    where
        go :: STUArray s Int Bool -> STUArray s Int Int -> Int -> ST s Bool
        go vis mt x = do
            visx <- readArray vis x
            if visx then
                return False
            else do
                writeArray vis x True
                trav (g ! x)
            where
                trav [] = return False
                trav (y:ys) = do
                    v <- readArray mt y
                    if v < 0 then win
                    else do
                        can <- go vis mt v
                        if can then win
                        else
                            trav ys
                    where
                        win = do
                            writeArray mt y x
                            return True

getMvc :: Graph -> [Int]
getMvc g =
    let (mt, vis) = runMm g
    in
        [i | (i, t) <- assocs vis, not t] ++ [-i | (i, t) <- assocs mt, t >= 0 && vis ! t]

solve :: [Int] -> [(Int64, Int64)] -> Int -> Int -> [Int]
solve os vs' n k = runST $ do
    mem <- newArray ((0,0), (k+1,mm+1)) (-1)
    c <- newArray ((0,0), (k+1,mm+1)) (-1)
    r <- f mem c 0 mm
    cc <- unsafeFreezeSTUArray c
    return $ build cc 0 mm os
    where
        mm = length os
        vs = listArray (0, k-1) vs' :: Array Int (Int64,Int64)
        f :: STUArray s (Int, Int) Int64 -> STUArray s (Int, Int) Int -> Int -> Int -> ST s Int64
        f mem c i j = do
            rr <- readArray mem (i,j)
            if rr >= 0 then
                return rr
            else do
                if i == k then
                    writeArray mem (i,j) 0
                else do
                    let (x,y) = vs ! i
                    writeArray mem (i,j) (1 `shift` 60)
                    forM_ [0..j] $ \t -> do
                        when (j-t <= n-2-i) $ do
                            rcost <- f mem c (i+1) (j-t)
                            let cost = rcost + ((y * fromIntegral t) `min` x)
                            curcost <- readArray mem (i,j)
                            when (cost < curcost) $ do
                                writeArray mem (i,j) cost
                                writeArray c (i,j) t
                readArray mem (i,j)
        build :: UArray (Int, Int) Int -> Int -> Int -> [Int] -> [Int]
        build c i j os
            | i == k = []
            | otherwise =
                let t = c ! (i,j) in
                    take t os ++ [0] ++ build c (i+1) (j-t) (drop t os)

main = do
    [n, m, k] <- map parseInt . BS.words <$> BS.getLine
    es <- replicateM m $ do
        [x, y] <- map parseInt . BS.words <$> BS.getLine
        return (x, y)
    vs <- replicateM k $ do
        [x, y] <- map (fromIntegral . parseInt) . BS.words <$> BS.getLine
        return (x, y)
    let g = buildG (1,n) es
        mvc = getMvc g
        r = solve mvc vs n k
    print $ length r
    putStrLn $ unwords (map show r)

import qualified Data.ByteString.Char8 as BS
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST
import Data.Array.Unboxed
import Data.Bits
import Data.Int
import Data.List
import Data.Maybe
import Data.Ratio
import qualified Data.Set as Set
import System.IO
import System.IO.Unsafe

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

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

type Graph = Array Int [Int]

buildG :: (Int, Int) -> [(Int, Int)] -> Graph
buildG = accumArray (flip (:)) []

runMm :: Graph -> (UArray Int Int, UArray Int Bool)
runMm g =
    runST $ do
        mt <- newArray (bounds g) (-1)
        forM_ (indices g) $ \i -> do
            vis <- newArray (bounds g) False
            go vis mt i
        vis <- newArray (bounds g) False
        mt' <- unsafeFreezeSTUArray mt
        let matched = Set.fromList (filter (>=0) (elems mt'))
        forM_ (indices g) $ \i -> do
            unless (Set.member i matched) $
                void (go vis mt i)
        vis' <- unsafeFreezeSTUArray vis
        return (mt', vis')
    where
        go :: STUArray s Int Bool -> STUArray s Int Int -> Int -> ST s Bool
        go vis mt x = do
            visx <- readArray vis x
            if visx then
                return False
            else do
                writeArray vis x True
                trav (g ! x)
            where
                trav [] = return False
                trav (y:ys) = do
                    v <- readArray mt y
                    if v < 0 then win
                    else do
                        can <- go vis mt v
                        if can then win
                        else
                            trav ys
                    where
                        win = do
                            writeArray mt y x
                            return True

getMvc :: Graph -> [Int]
getMvc g =
    let (mt, vis) = runMm g
    in
        [i | (i, t) <- assocs vis, not t] ++ [-i | (i, t) <- assocs mt, t >= 0 && vis ! t]

solve :: [Int] -> [(Int64, Int64)] -> Int -> [Int]
solve os vs' k = runST $ do
    mem <- newArray ((0,0), (k+1,mm+1)) (-1)
    c <- newArray ((0,0), (k+1,mm+1)) (-1)
    r <- f mem c 0 mm
    build c 0 mm os
    where
        mm = length os
        vs = listArray (0, k-1) vs' :: Array Int (Int64,Int64)
        f :: STUArray s (Int, Int) Int64 -> STUArray s (Int, Int) Int -> Int -> Int -> ST s Int64
        f mem c i j = do
            rr <- readArray mem (i,j)
            if rr >= 0 then
                return rr
            else do
                if i == k then
                    writeArray mem (i,j) 0
                else do
                    let (x,y) = vs ! i
                    writeArray mem (i,j) (1 `shift` 60)
                    forM_ [0..j] $ \t -> do
                        when (j-t <= k-1-i) $ do
                            rcost <- f mem c (i+1) (j-t)
                            let cost = rcost + ((y * fromIntegral t) `min` x)
                            curcost <- readArray mem (i,j)
                            when (cost < curcost) $ do
                                writeArray mem (i,j) cost
                                writeArray c (i,j) t
                readArray mem (i,j)
        build :: STUArray s (Int, Int) Int -> Int -> Int -> [Int] -> ST s [Int]
        build c i j os
            | i == k = return []
            | otherwise = do
                t <- readArray c (i, j)
                rr <- build c (i+1) (j-t) (drop t os)
                return $ take t os ++ [0] ++ rr

main = do
    [n, m, k] <- map parseInt . BS.words <$> BS.getLine
    es <- replicateM m $ do
        [x, y] <- map parseInt . BS.words <$> BS.getLine
        return (x, y)
    vs <- replicateM k $ do
        [x, y] <- map (fromIntegral . parseInt) . BS.words <$> BS.getLine
        return (x, y)
    let g = buildG (1,n) es
        mvc = getMvc g
        r = solve mvc vs k
    print $ length r
    putStrLn $ unwords (map show r)


{-# LANGUAGE ScopedTypeVariables #-}

import Prelude
import Data.List
import Text.Printf
import Control.Monad
import Data.Ratio
import Data.Int
import Data.Functor
import Control.Monad.ST.Safe
import qualified Data.Array.IArray as IA
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as A
import qualified Data.Array.Unboxed as UA

solve :: Int -> [[Int]] -> ST s [Int]
solve m segments = do
    arr <- A.newArray (1, m) 0 :: ST s (A.STUArray s Int Int)
    forM_ segments $ \[l, r] -> do
        forM_ [l .. r] $ \i -> do
            A.writeArray arr i 1
    lst <- A.getElems arr
    return . map (+ 1) . findIndices (== 0) $ lst

main :: IO ()
main = do
    ([n, m] :: [Int]) <- (map read . words) <$> getLine
    (segments :: [[Int]]) <- replicateM n ((map read . words) <$> getLine)
    let answer = runST $ solve m segments
    printf "%d\n" $ length answer
    forM_ answer $ printf "%d "

main = interact foo

foo :: String -> String
foo inp =
    let (_:n:_):nn = map (map read . words) . lines $ inp :: [[Int]]
        ns = map (\u -> (u!!0, u!!1)) nn :: [(Int, Int)]
        out = filter (\ u -> not $ any (\(a, b) -> u `elem` [a..b]) ns) [1..n]
    in unlines [show . length $ out, unwords . map show $ out]

import Data.List

f ::String->(Int,Int)
f x=let (a:b:[])=map read (words x)::[Int]
    in (a,b)

g ::[(Int,Int)]->Int->Int
g [] p=p
g ((a,b):xs) p
   |a<=p && p<=b=(-1)
   |otherwise=g xs p

main=do
     e1<-getLine
     es<-getContents
     let xs=map f $ lines es
         (n:m:[])=map read (words e1)::[Int]
         ys=(-1):map (g xs) [1..m]
         ans=tail $ nub $ ys
     putStrLn $ if length(ans)==0 then "0" else (show(length(ans)))++"\n"++(unwords(map show ans))

import Data.List
import Control.Monad
main = do
  [n,m] <- map read . words <$> getLine
  ps <- ([1..m] \\) . concat <$> replicateM n getI
  print (length ps)
  putStrLn $ unwords $ map show ps
getI = do
  [a,b] <- map read . words <$> getLine
  return [a..b]

zipPairs          :: [Int] -> [(Int, Int)]
zipPairs []       = []
zipPairs (l:r:xs) = (l,r):(zipPairs xs)

solve            :: [Int] -> [Int]
solve (_:m:rest) = [x | x <- [1..m], not . elem x . concat . map list $ zipPairs rest]
    where list xs = [(fst xs)..(snd xs)]
          concat [] = []
          concat (a:as) = a ++ (concat as)

parseStr :: [Int] -> String
parseStr r = unlines [(show n),(seperates r)]
    where n = length r
          seperates []     = ""
          seperates (x:xs) = show x ++ " " ++ (seperates xs)

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

import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array
import qualified Data.Set as S

process s = foldl (S.union) S.empty $ map (\[a,b]->S.fromList[a..b]) s

main= do
		[n,m]<- map read <$> words <$> getLine ::IO [Int]
		s<- map(map read) <$> map words <$> replicateM n getLine ::IO [[Int]]
		let y = S.difference (S.fromList [1..m]) (process s)
		print $S.size y
		putStrLn $ intercalate " "$ map show  $ S.elems y

--ghc 7.10

import Data.List(sort)

outPoints :: Int -> [(Int,Int)] -> [Int]
outPoints m ss = concat . map (\(r,l) -> [r+1..l-1]) $ zip (0:rs') (ls'++[m+1])
    where
        (ls',rs') = unzip . f . sort $ ss
        f :: [(Int,Int)] -> [(Int,Int)]
        f [] = []
        f [x] = [x]
        f (x:xs@(y:ys))
            | snd x >= snd y = f (x:ys)
            | otherwise = x:(f xs)

readLine line = (l,r)
    where [l,r] = map read . words $ line

main = do
    nmStr <- getLine
    let [n,m] = map read . words $ nmStr :: [Int]
    contents <- getContents
    let ss = map readLine . lines $ contents :: [(Int, Int)]
    let ps = outPoints m ss
    let k = length ps
    print k
    putStrLn . unwords . map show $ ps

{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Function (fix)
import Data.Array (Array, array, (!))
import System.IO
import Data.ByteString.Lazy.Builder
import Data.ByteString.Lazy.Builder.ASCII
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

construct :: BS.ByteString -> [Int]
construct str
    | BS.null str = []
    | isSpace (BS8.head str) = construct (BS8.tail str)
    | otherwise = let Just (i, other) = BS8.readInt str in i : construct other

getInts :: IO [Int]
getInts = construct `fmap` BS.getLine

fastPrint :: Char -> [Int] -> IO ()
fastPrint mid arr = hPutBuilder stdout  $ build arr
    where build = foldr (\n b -> intDec n <> charUtf8 mid <> b) mempty

ok segs p = all (\[l,r] -> l > p || p > r) segs

main = do
    [n,m] <- getInts
    segs <- replicateM n getInts
    let pos = filter (ok segs) [1..m]
    print (length pos)
    putStrLn $ (intercalate " ") (map show pos)

main = interact foo

foo :: String -> String
foo inp =
    let (m:n:_):nn = map (map read . words) . lines $ inp :: [[Int]]
        ns = map (\u -> (u!!0, u!!1)) nn :: [(Int, Int)]
        out = filter (\ u -> not $ any (\(a, b) -> u `elem` [a..b]) ns) [m..n]
    in unlines [show . length $ out, unwords . map show $ out]

import Data.List

f ::String->(Int,Int)
f x=let (a:b:[])=map read (words x)::[Int]
    in (a,b)

g ::[(Int,Int)]->Int->Int
g [] p=p
g ((a,b):xs) p
   |a<=p && p<=b=(-1)
   |otherwise=g xs p

main=do
     e1<-getLine
     es<-getContents
     let xs=map f $ lines es
         (n:m:[])=map read (words e1)::[Int]
         ys=map (g xs) [1..m]
         ans=tail $ nub $ ys
     putStrLn $ if length(ans)==0 then "0" else (show(length(ans)))++"\n"++(unwords(map show ans))

--ghc 7.10

import Data.List(sort)

outPoints m ss = concat . map (\(r,l) -> [r+1..l-1]) $ zip (0:rs') (ls'++[m+1])
    where
        (ls',rs') = unzip . sort $ ss

readLine line = (l,r)
    where [l,r] = map read . words $ line

main = do
    nmStr <- getLine
    let [n,m] = map read . words $ nmStr :: [Int]
    contents <- getContents
    let ss = map readLine . lines $ contents :: [(Int, Int)]
    let ps = outPoints m ss
    let k = length ps
    print k
    putStrLn . unwords . map show $ ps


p[]= -1
p l=minimum l+3
s(_:i:w)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$x$x$repeat[[]],[b,c]<-l]where n=length i-1;m=[[max k j|[k,j]<-w,min k j==i]|i<-[0..n]];x e=map(\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n]
main=interact$show.p.s.map(map(pred.read).words).lines

module Main where

import Array
import Control.Monad
import Data.List

main = do
    inputNM <- getLine
    let [n, m] = map read $ words inputNM

    inputPrice <- getLine
    let price = array (1, n) $ zip [1..] $ map ( \w -> read w ) $ words inputPrice :: Array Int Int

    let initMatch = array ((1,1), (n, n)) [ ((x,y), 0) | x <- [1..n], y <- [1..n] ]

    matchList <- replicateM m $ do
        inputMatch <- getLine
        let [a, b] = map read $ words inputMatch :: [Int]
        return [ ((a, b), 1), ((b, a), 1) ]

    let match = initMatch // concat matchList
        best =
            foldl' ( \best i ->
                foldl' ( \best j ->
                    foldl' ( \best k ->
                        let best' = ( price ! i ) + ( price ! j ) + ( price ! k ) in
                        if best < best' then best else best'
                    ) best $ filter ( \k -> ( match ! (i,k) ) == 1 && ( match ! (j,k) ) == 1 ) [j+1..n]
                ) best $ filter ( \j -> ( match ! (i,j) ) == 1 ) [i+1..n-1]
            ) worst [1..n-2]

    putStrLn $ if best == worst then "-1" else show best

worst = 99999999

import Array (Array, (!), accumArray, bounds, listArray)
import List (sort)
import Maybe (fromMaybe, listToMaybe)
import Monad (liftM)

solve :: Array Int Int -> Array (Int, Int) Bool -> Maybe Int
solve costs graph  =  listToMaybe (sort solve')
  where
    n  =  snd $ bounds costs
    solve'  =  [costs ! i + costs ! j + costs ! k |
        i <- [1..n],
        j <- [i+1..n],
        k <- [j+1..n],
        and [graph ! (i,j), graph ! (i,k), graph ! (j,k)]]

readPair :: String -> (Int, Int)
readPair line  =  case (words line) of
  [a, b]  ->  (read a, read b)
  _  ->  error $ concat ["readPair: ", "string ", show line, " dos't two words"]

swap :: (a, b) -> (b, a)
swap (a, b)  =  (b, a)

main :: IO ()
main  =  do
    (n, m)  <-  liftM readPair getLine
    costs  <-  liftM (map read . words) getLine
    pairs  <-  liftM (map readPair . take m . lines) getContents
    let costs'  =  listArray (1, length costs) costs
    let graph'  =  accumArray (flip const) False ((1,1), (n,n)) (concatMap (\a -> [(a, True), (swap a, True)]) pairs)
    print $ fromMaybe (-1) $ solve costs' graph'

import Data.Array
import Control.Monad

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

solve n a vu = if null l then -1 else minimum l
	where
		rng = ((1,1),(n,n))
		arr' = array rng [((i,j),0) | (i,j) <- range rng]
		arr = arr' // [((i,j),1) | [i,j] <- vu]
		cost = listArray (1,n) a
		l = [cost!i + cost!j + cost!k | i <- [1..n], j <- [i+1..n], arr!(i,j)==1, k <- [j+1..n], arr!(j,k)==1 && arr!(k,i)==1]

main = do
	[n,m] <- readInts
	a <- readInts
	l <- forM [1..m] (\_ -> readInts)
	let vu = l ++ map reverse l
	putStrLn . show $ solve n a vu

import Data.Array.IArray
import Control.Monad (mplus, guard)
import qualified Data.IntMap as M
import qualified Data.IntSet as S
import Data.Maybe (fromJust, isJust)
main = do
    [n, m] <- (map read . words) `fmap` getLine
    цены <- (listArray (1, n) . map read . words) `fmap` getLine :: IO (Array Int Int)
    пары <- mapM (\_ -> (map read . words) `fmap` getLine) [1..m]
    let совместимые = foldl (\совместимые [перваяОдёжка, втораяОдёжка] ->
            M.insertWith S.union перваяОдёжка (S.singleton втораяОдёжка) $
            M.insertWith S.union втораяОдёжка (S.singleton перваяОдёжка) совместимые) M.empty пары
        (минимальнаяЦена, _) = foldl (\(мц, совместимые) [перваяОдёжка, втораяОдёжка] ->
            let a = S.delete втораяОдёжка (совместимые M.! перваяОдёжка)
                b = S.delete перваяОдёжка (совместимые M.! втораяОдёжка)
                x = S.toList $ S.intersection a b
                s = цены ! перваяОдёжка + цены ! втораяОдёжка
                y = (map ((s+).(цены !)) x) `mplus` мц in
            (guard (y > []) >> return (minimum y), M.insert перваяОдёжка a $ M.insert втораяОдёжка b совместимые))
            ([], совместимые) пары
    print $ head $ минимальнаяЦена ++ [-1]

import Array

getIntPairs :: IO (Int,Int)
getIntPairs = do ns <- getLine
                 return (make_pair [(read n::Int)|n<-(words ns)])
                        where
                          make_pair (x:y:_) = (x,y)
                          make_pair _ = (0,0)

getInts :: IO [Int]
getInts = do ns <- getLine
             return [(read n::Int)|n<-(words ns)]

getPairLines :: Int -> IO [(Int,Int)]
getPairLines n = if n > 0 then
                     do l <- getIntPairs
                        ls <- getPairLines (n-1)
                        return (l:ls)
                 else
                     return []

putAnsLn :: (Show a) => a -> IO ()
putAnsLn ans = putStrLn (show ans)

include x [] = False
include x (l:ls) = if x==l then True else include x ls

mins m [] = m
mins m (x:xs) = if m>x then mins x xs else mins m xs

loop_find n ms = filter (\(j,k) -> include n (ms!k)&&n/=j&&n/=k ) [(j,k)|j<-(ms!n),k<-(ms!j)]

solve n m a uv = solve_rec 100000000 [1..n]
    where
      solve_rec ans [] = if ans==100000000 then -1 else ans
      solve_rec ans (i:is) = solve_rec (mins ans [prices!i + prices!j + prices!k|(j,k)<-loops]) is
          where
            loops = loop_find i matchings
            prices = array (1,n) (zip [1..n] a)
            matchings = make_matching (array (1,n) [(i,[])|i<-[1..n]]) uv
                where
                  make_matching ary [] = ary
                  make_matching ary ((u,v):uvs) = make_matching ((ary//[(u,v:(ary!u))])//[(v,u:(ary!v))]) uvs

main = do (n,m) <- getIntPairs
          a <- getInts
          uv <- getPairLines m
          putAnsLn (solve n m a uv)

import List
p[]= -1
p l=minimum l+3
x :: [[Int]] -> Int -> [[[Int]]] -> [[[Int]]]
x m n e=map(\i->[j:l|j<-m!!i,l<-e!!j,all(`elem`m!!i)l])[0..n-1]
r m n=[[j|[k,j]<-m,k==i]|i<-[0..n-1]]
s(_:i:m)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$e$e$repeat[[]],[b,c]<-l]where e=r(map sort m)(length i)`x`length i
main=interact$show.p.s.map(map(pred.read).words).lines

import Array

getIntPairs :: IO (Int,Int)
getIntPairs = do ns <- getLine
                 return (make_pair [(read n::Int)|n<-(words ns)])
                        where
                          make_pair (x:y:_) = (x,y)
                          make_pair _ = (0,0)

getInts :: IO [Int]
getInts = do ns <- getLine
             return [(read n::Int)|n<-(words ns)]

getPairLines :: Int -> IO [(Int,Int)]
getPairLines n = if n > 0 then
                     do l <- getIntPairs
                        ls <- getPairLines (n-1)
                        return (l:ls)
                 else
                     return []

putAnsLn :: (Show a) => a -> IO ()
putAnsLn ans = putStrLn (show ans)

include x [] = False
include x (l:ls) = if x==l then True else include x ls

mins m [] = m
mins m (x:xs) = if m>x then mins x xs else mins m xs

loop_find n ms = filter (\(j,k) -> include n (ms!k) ) [(j,k)|j<-(ms!n),k<-(ms!j)]

solve n m a uv = solve_rec 10000000 [1..n]
    where
      solve_rec ans [] = if ans==10000000 then -1 else ans
      solve_rec ans (i:is) =if loops == [] then
                                solve_rec ans is
                            else
                                solve_rec (mins ans [prices!i + prices!j + prices!k|(j,k)<-loops]) is
                                    where
                                      loops = loop_find i matchings
                                      prices = array (1,n) (zip [1..n] a)
                                      matchings = make_matching (array (1,n) [(i,[])|i<-[1..n]]) uv
                                          where
                                            make_matching ary [] = ary
                                            make_matching ary ((u,v):uvs) = make_matching (ary//[(u,v:(ary!u))]) uvs

main = do (n,m) <- getIntPairs
          a <- getInts
          uv <- getPairLines m
          putAnsLn (solve n m a uv)

import List
p[]= -1
p l=minimum l+3
x m n e=map(\i->[j:l|[k,j]<-m,i==k,l<-e!!j])[0..n-1]
s(_:i:m)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$e$e$repeat[[]],[b,c]<-l]where e=map sort m`x`length i
main=interact$show.p.s.map(map(pred.read).words).lines

p[]= -1
p l=minimum l+3
x m n e=map(\i->[j:l|[k,j]<-m,i==k,l<-e!!j])[0..n-1]
s(_:i:m)=[i!!a+i!!b+i!!c|(a,l)<-zip[0..]$e$e$repeat[[]],[b,c]<-l]where e=m`x`length i
main=interact$show.p.s.map(map(pred.read).words).lines


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

import Data.Maybe
import Control.Monad
import Data.List (nub, reverse, group, sort)

solve :: C.ByteString -> Int -> Int
solve time x = do
    let sec = timeToSec time
    let xs = sec : takeWhile (/= sec) (iterate (calc x) (calc x sec))

    length $ filter (==True) $ map (isPal . secToTime) xs

read = do
    s <- C.getLine

    let a = C.words s

    print $ solve (a !! 0) (fst $ fromJust $ C.readInt (a !! 1))

main = do
   t <- C.getLine

   replicateM_ (fst $ fromJust $ C.readInt t) Main.read

calc :: Int -> Int -> Int
calc x t = rem (t + x * 60) 86400

isPal :: C.ByteString -> Bool
isPal s = s == (C.reverse s)

timeToSec :: C.ByteString -> Int
timeToSec str = do
    let (f, s) = C.span (/= ':') str
    let hours = fst $ fromJust $ C.readInt f
    let minutes = fst $ fromJust $ C.readInt (C.tail s)

    3600 * hours + 60 * minutes

secToTime :: Int -> C.ByteString
secToTime x = do
    let hours = quot x 3600 :: Int
    let minutes = quot (x - hours * 3600) 60 :: Int

    C.append (C.append (format hours) (C.pack ":")) (format minutes)

format :: Int -> C.ByteString
format x
    | x < 10 = C.append (C.pack "0") (C.pack $ show x)
    | otherwise = C.pack $ show x

module Main where

import Data.List

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep = id

parse :: String -> (Int, Int)
parse xs = (60 * read hh + read mm, read k)
  where (hh,r1) = splitAt 2 xs
        (mm,r2) = splitAt 2 $ drop 1 r1
        k = drop 1 r2

format = show

p = 24*60

solve :: (Int, Int) -> Int
solve (time, k) = length $ filter isPalindrome $ nub orbit
  where orbit = map (`mod` p) [time + k*i | i <- [0..p-1]]

isPalindrome time = (reverse $ f hh) == f mm
  where (hh,mm) = divMod time 60
        f x = show (10*x+1001)

parseT :: IO (Int, Int, Int)
parseT = do
  s <- getLine
  let (a: b: _) = words s
  let (h1: h2: _: m1: m2: _) = a
  return (read [h1, h2] :: Int, read [m1, m2] :: Int, read b :: Int)

calc :: Int -> Int -> Int
calc h m = 60 * h + m

checkH :: Int -> Int -> [Int] -> Int -> Int
checkH _ _ _ 1440 = 0
checkH t s a b = let t1 = (t + s * b) `mod` 1440 in if (&&) (t1 `elem` [calc 0 0, calc 1 10, calc 2 20, calc 3 30, calc 4 40, calc 5 50, calc 10 1, calc 11 11, calc 12 21, calc 13 31, calc 14 41, calc 15 51, calc 20 2, calc 21 12, calc 22 22, calc 23 32]) ((t1 `elem` a) == False)
  then checkH t s (t1: a) (b + 1) + 1
  else checkH t s a (b + 1)

check :: Int -> Int -> Int
check t s = checkH t s [] 0

solve :: Int -> IO ()
solve 0 = pure ()
solve i = do
  (h, m, s) <- parseT
  print $ check (calc h m) s
  solve $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  solve n


import Control.Arrow
import Data.List
import Data.Maybe
import Data.Ord
import qualified Data.ByteString.Char8 as C

parse s =
  case C.readInt s of
    Just (l, s') ->
      case C.readInt (C.tail s') of
        Just (r, _) ->
          (l, r)

gao a = if r < r' then -1 else k + 1
  where
    (l, r) = minimumBy (comparing $ second negate) a
    k = fromJust $ elemIndex (l, r) a
    r' = maximum $ map snd a

main = do
  a <- fmap (map parse . tail . C.lines) C.getContents
  print $ gao a

import Data.List
import Debug.Trace

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

solve ([n] : segments) = fst $ foldl1' test $ zip [1..n] segments

test x@(n, [a, b]) y@(m, [c, d])
  | c <= a, b <= d = y
  | a <= c, d <= b = x
  | otherwise = (-1, [min a c, max b d])

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Data.Array
-- 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.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import System.IO
-- import Debug.Trace

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

main = do
  n <- readLn
  ss <- replicateM n getInts

  let
    l = minimum $ map (!!0) ss
    r = maximum $ map (!!1) ss

  print $ fromMaybe (-1) ((+1) <$> [l, r] `elemIndex` ss)

main = do
    x <-getContents
    putStrLn $ show $ f $ map (\x -> read x::Int) $ words $ unwords $ tail $ lines x

f :: [Int] -> Int
f x =
    if e > 0
    then -1
    else thd3 m
    where
        l = toPairs 1 x
        m = foldl1 f1 l
        e = length $ filter (\x -> snd3 m<snd3 x) l

toPairs :: Int -> [Int] -> [(Int,Int,Int)]
toPairs _ [] = []
toPairs n (a:b:t) = (a,b,n):toPairs (n+1) t

f1 :: (Int,Int,Int) -> (Int,Int,Int) -> (Int,Int,Int)
f1 a a0
    | fst3 a < fst3 a0 = a
    | fst3 a == fst3 a0 && snd3 a > snd3 a0 = a
    | otherwise = a0

fst3 :: (a,b,c)-> a
fst3 (a,_,_) = a
snd3 :: (a,b,c)-> b
snd3 (_,b,_) = b
thd3 :: (a,b,c)-> c
thd3 (_,_,c) = c

main = do
    x <-getContents
    putStrLn $ show $ f $ map (\x -> read x::Int) $ words $ unwords $ tail $ lines x

f :: [Int] -> Int
f x =
    if e > 0
    then -1
    else thd3 m
    where
        l = toPairs 1 x
        m = foldl1 f1 l
        e = length $ take 1 $ filter (\x -> snd3 m<snd3 x) l

toPairs :: Int -> [Int] -> [(Int,Int,Int)]
toPairs _ [] = []
toPairs n (a:b:t) = (a,b,n):toPairs (n+1) t

f1 :: (Int,Int,Int) -> (Int,Int,Int) -> (Int,Int,Int)
f1 a a0
    | fst3 a < fst3 a0 = a
    | fst3 a == fst3 a0 && snd3 a > snd3 a0 = a
    | otherwise = a0

fst3 :: (a,b,c)-> a
fst3 (a,_,_) = a
snd3 :: (a,b,c)-> b
snd3 (_,b,_) = b
thd3 :: (a,b,c)-> c
thd3 (_,_,c) = c

import Control.Monad (liftM)

type Pair  =  (Int, Int)

parsePair :: String -> Pair
parsePair line  =  case map read (words line) of
    [a, b]  ->  (a, b)

solve :: [Pair] -> Int
solve ps  =  last $ ((-1) :) $ map fst $ filter big ps'
  where
    ps'  =  zip [1..] ps
    mn  =  minimum (map fst ps)
    mx  =  maximum (map snd ps)
    big (_, (a, b))  =  a == mn && b == mx

main :: IO ()
main  =  do
    n   <-  readLn
    ps  <-  liftM (take n . map parsePair . lines) getContents
    print $ solve ps

import Data.List

compareLength (_, [l1, r1]) (_, [l2, r2]) =
  let len1 = r1 - l1 + 1
      len2 = r2 - l2 + 1
  in compare len1 len2

solve segments
  | checkLeft && checkRight = index
  | otherwise = -1
    where (index, [left, right]) = maximumBy compareLength $ zip [1..] segments
          checkLeft  = all (\[x, _] -> left <= x) segments
          checkRight = all (\[_, x] -> x <= right) segments

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

import Data.Maybe
import Data.List
import Data.Function

main = do
    n <- fmap read getLine
    segs <- mapM (\_ -> fmap ((\[x,y] -> (x,y)) . map read . words) getLine) [1..n]
    print $ solve segs

solve :: [(Int,Int)] -> Int
solve segs | all (\(_,y) -> y <= maxY) segs = fromJust (elemIndex bestSeg segs) + 1
           | otherwise = -1
    where minX = minimum $ map fst segs
          segsWithX = filter (\(x,_) -> x == minX) segs
          bestSeg@(_,maxY) = maximumBy (compare `on` snd) segsWithX

import qualified Data.ByteString.Char8 as B

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

toPairs :: [Int] -> [(Int,Int)]
toPairs (x:y:xys) = (x,y):toPairs xys
toPairs _ = []

main=B.getContents>>=print.solve.map readInt.tail.B.words

solve xys = case filter (\ (_,(x,y))->x==l&&y==r)$zip [1..] $ toPairs xys of
              ((i,_):_) -> i
              [] -> -1
   where
     l = minimum xys
     r = maximum xys

import Control.Arrow
import Data.List
import Data.Maybe
import Data.Ord
import qualified Data.ByteString.Char8 as C

parse s =
  case C.readInt s of
    Just (l, s') ->
      case C.readInt (C.tail s') of
        Just (r, _) ->
          (l, r)

solve a = if r < r' then -1 else k + 1
  where
    (l, r) = minimumBy (comparing $ second negate) a
    k = fromJust $ elemIndex (l, r) a
    r' = maximum $ map snd a

main = do
  a <- fmap (map parse . tail . C.lines) C.getContents
  print $ solve a

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

getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine
main = do
  n <- readLn
  ss <- replicateM n getInts

  let
    l = minimum $ map (!!0) ss
    r = maximum $ map (!!1) ss

  print $ fromMaybe (-1) ((+1) <$> [l, r] `elemIndex` ss)

import Data.List

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

solve :: [[Int]] -> Int
solve ([n] : segments) = fst $ foldl1' test $ zip [1..n] segments

test (m, [a, b]) (n, [c, d])
  | a <= c, c <= d, d <= b = (m, [a, b])
  | c <= a, a <= b, b <= d = (n, [c, d])
  | otherwise = (-1, [min a c, max b d])

import Data.List

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

solve :: [[Int]] -> Int
solve (_ : [l1, r1] : segments) = fst $ foldl' test (1, [l1, r1]) (zip [2..] segments)

test (m, [a, b]) (n, [c, d])
  | a <= c, d <= b = (m, [a, b])
  | c <= a, b <= d = (n, [c, d])
  | otherwise = (-1, [min a c, max b d])

import Control.Monad (liftM)

type Pair  =  (Int, Int)

parsePair :: String -> Pair
parsePair line  =  case map read (words line) of
    [a, b]  ->  (a, b)

solve :: [Pair] -> Bool
solve pairs  =  any (\(l,r) -> l == mn && r == mx) pairs
  where
    mn  =  minimum (map fst pairs)
    mx  =  maximum (map snd pairs)

main :: IO ()
main  =  do
    n   <-  readLn
    ps  <-  liftM (take n . map parsePair . lines) getContents
    putStrLn $ if solve ps
        then "YES"
        else "NO"


{-# LANGUAGE UnicodeSyntax #-}

import Control.Applicative

solve' starts i prev [] = map (\j -> (j, i - 1)) starts
solve' starts i prev (x:xs)
	| x > prev = solve' (replicate (x - prev) i ++ starts) (i + 1) x xs
	| x < prev = map (\j -> (j, i - 1)) starts' ++ solve' starts'' (i + 1) x xs
	| x == prev = solve' starts (i + 1) prev xs
	where
		(starts', starts'') = splitAt (prev - x) starts

solve xs = solve' [] 1 0 xs

main = do
	getLine
	xs <- map read . words <$> getLine
	let r = solve xs
	print $ length r
	mapM_ putStrLn $ map (\(a, b) -> show a ++ " " ++ show b) r

import Control.Applicative

solve' :: [Int] -> Int -> Int -> [Int] -> [(Int, Int)]
solve' starts i prev [] = map (\j -> (j, i - 1)) starts
solve' starts i prev (x:xs)
	| x > prev = solve' (replicate (x - prev) i ++ starts) (i + 1) x xs
	| x < prev = map (\j -> (j, i - 1)) starts' ++ solve' starts'' (i + 1) x xs
	| x == prev = solve' starts (i + 1) prev xs
	where
		(starts', starts'') = splitAt (prev - x) starts

solve xs = solve' [] 1 0 xs

main = do
	getLine
	xs <- map read . words <$> getLine
	let r = solve xs
	print $ length r
	mapM_ putStrLn $ map (\(a, b) -> show a ++ " " ++ show b) r

main = interact $ unlines.map (unwords.map show).solve.map read.words

solve :: [Int] -> [[Int]]
solve (_:xs)= let ys  = 0:xs++[0]
                  ans = step [] $ zip [0..] ys
              in [length ans]:ans

step :: [(Int,Int)] -> [(Int,Int)] -> [[Int]]
step _ [] = []
step [] ((r,y):ys) = step [(r,y)] ys
step xxs@((l,x):xs) yys@((r,y):ys)
  | x<y  = step ((r,y):xxs) ys
  | x==y = step xxs ys
  | x>y  = case xs of
             (z:zs)|snd z==x-1 -> [l,r-1]:step xs yys
             _                 -> [l,r-1]:step ((l,x-1):xs) yys

{-# LANGUAGE UnicodeSyntax #-}

import Control.Applicative

solve' starts i prev [] = map (\j -> (j, i - 1)) starts
solve' starts i prev (x:xs)
	| x > prev = solve' (replicate (x - prev) i ++ starts) (i + 1) x xs
	| x < prev = map (\j -> (j, i - 1)) starts' ++ solve' starts'' (i + 1) x xs
	| x == prev = solve' starts (i + 1) prev xs
	where
		(starts', starts'') = splitAt (prev - x) starts

solve xs = solve' [] 1 0 xs

main = do
	getLine
	xs <- map (read :: String -> Int) . words <$> getLine
	let r = solve xs
	print $ length r
	mapM_ putStrLn $ map (\(a, b) -> show a ++ " " ++ show b) r

{-# LANGUAGE UnicodeSyntax #-}

solve' starts i prev [] = map (\j -> (j, i - 1)) starts
solve' starts i prev (x:xs)
	| x > prev = solve' (replicate (x - prev) i ++ starts) (i + 1) x xs
	| x < prev = map (\j -> (j, i - 1)) starts' ++ solve' starts'' (i + 1) x xs
	| x == prev = solve' starts (i + 1) prev xs
	where
		(starts', starts'') = splitAt (prev - x) starts

solve xs = solve' [] 1 0 xs

main = interact $ unlines . map (\(a, b) -> show a ++ " " ++ show b) . solve . map read . tail . words


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

solve :: IO ()
solve = do
    ~[n] <- readInts
    s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine
    let [ds, rs] = flip map s . (==) <$> "DR"
        [td, tr] = sum . map fromEnum <$> [ds, rs]
        [id, ir] = elemIndex True <$> [ds, rs]
        [bd, br] = map (snd . foldl' countf (0, 0)) [ds, rs] where
            countf (cur, acc) True  = (cur + 1, acc)
            countf (cur, acc) False = (cur,     acc + cur)
        xd = (n - td - 1) * fromMaybe n id
        xr = (n - tr - 1) * fromMaybe n ir
    print $ n * n - (xr + xd + bd + br)

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

main :: IO ()
main = flip replicateM_ solve . head =<< readInts

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

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

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    s <- getNext
    let
      numDs = fromIntegral $ P.count 'D' s
      numRs = fromIntegral $ P.count 'R' s
      h = n - numDs
      w = n - numRs
      wasteC acc 'D' = acc + w - 1
      wasteC acc 'R' = acc + h - 1
      wasteC _ _ = error "bad path char"
      initSeg = head $ P.group s
      ans
        | numDs == 0 && numRs == 0  = 1
        | numDs == 0 || numRs == 0  = n
        | otherwise = h * w + numDs * w + h * numRs - P.foldl' wasteC 0 initSeg
    pure $ putInts [ans]

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

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

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

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

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

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

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

solve :: IO ()
solve = do
    ~[n] <- readInts
    s <- C.unpack <$> C.getLine
    let [ds, rs] = flip map s . (==) <$> "DR"
        [td, tr] = sum . map fromEnum <$> [ds, rs]
        [id, ir] = elemIndex True <$> [ds, rs]
        [bd, br] = map (snd . foldl' countf (0, 0)) [ds, rs] where
            countf (cur, acc) True  = (cur + 1, acc)
            countf (cur, acc) False = (cur,     acc + cur)
        xr = (n - tr - 1) * fromMaybe n ir
        xd = (n - td - 1) * fromMaybe n id
    print $ n * n - (xr + xd + bd + br)

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

main :: IO ()
main = flip replicateM_ solve . head =<< readInts


{-# 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.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 (Map)
import qualified Data.Map as Map
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
  n <- readLn
  a <- replicateM n getLine

  b :: IOUArray (Int, Int) Char <- newListArray ((1, 1), (n, n)) $ concat a

  forM_ [(x, y) | x <- [2..n-1], y <- [2..n-1]] $ \(x, y) -> do
    let near = [(x-1,y),(x+1,y), (x,y-1), (x,y+1), (x,y)]
    v <- all (== '#') <$> mapM (readArray b) near
    when v $ mapM_ (\xy -> writeArray b xy '.') near

  c <- getElems b
  putStrLn $ if all (== '.') c then "YES" else "NO"

import Data.List
import qualified Data.Set as Set

main :: IO()
main = output . solve . tail . lines =<< getContents

output :: Bool -> IO()
output True  = putStrLn "YES"
output False = putStrLn "NO"

solve :: [String] -> Bool
solve strs = let n = length strs
                 s = foldl1 Set.union (map (initSet 0) (zip strs [0..]))
             in check n 0 0 s

initSet :: Int -> (String, Int) -> Set.Set (Int, Int)
initSet _   ("",     _)   = Set.empty
initSet col ((s:ss), row) = let next = initSet (col + 1) (ss, row)
                            in if s == '#'
                               then Set.insert (row, col) next
                               else next

check :: Int -> Int -> Int -> Set.Set (Int, Int) -> Bool
check n r c s | r >= n = True
              | c >= n = check n (r + 1) 0 s
              | Set.member (r, c) s = if Set.member (r + 1, c - 1) s &&
                                         Set.member (r + 1, c    ) s &&
                                         Set.member (r + 1, c + 1) s &&
                                         Set.member (r + 2, c    ) s
                                      then check n r (c + 1) $ Set.delete (r + 1, c - 1) $
                                                               Set.delete (r + 1, c    ) $
                                                               Set.delete (r + 1, c + 1) $
                                                               Set.delete (r + 2, c    ) s
                                      else False
              | otherwise = check n r (c + 1) s

import Data.List
import qualified Data.Set as Set

main :: IO()
main = output . solve . tail . lines =<< getContents

output :: Bool -> IO()
output True  = putStrLn "YES"
output False = putStrLn "NO"

solve :: [String] -> Bool
solve strs = let n = length strs
                 s = foldl1 Set.union (map (initSet 0) (zip strs [0..]))
             in check n 0 0 s

initSet :: Int -> (String, Int) -> Set.Set (Int, Int)
initSet _   ("",     _)   = Set.empty
initSet col (s : ss, row) = let next = initSet (col + 1) (ss, row)
                            in if s == '#'
                               then Set.insert (row, col) next
                               else next

check :: Int -> Int -> Int -> Set.Set (Int, Int) -> Bool
check n r c s | r >= n = True
              | c >= n = check n (r + 1) 0 s
              | Set.member (r, c) s = Set.member (r + 1, c - 1) s &&
                                      Set.member (r + 1, c    ) s &&
                                      Set.member (r + 1, c + 1) s &&
                                      Set.member (r + 2, c    ) s &&
                                      (check n r (c + 1) $ Set.delete (r + 1, c - 1) $
                                                           Set.delete (r + 1, c    ) $
                                                           Set.delete (r + 1, c + 1) $
                                                           Set.delete (r + 2, c    ) s)
              | otherwise = check n r (c + 1) s

import Data.List
import qualified Data.Set as Set

main :: IO()
main = output . solve . tail . lines =<< getContents

output :: Bool -> IO()
output True  = putStrLn "YES"
output False = putStrLn "NO"

solve :: [String] -> Bool
solve strs = let n = length strs
                 s = foldl1 Set.union (map (initSet 0) (zip strs [0..]))
             in check n 0 0 s

initSet :: Int -> (String, Int) -> Set.Set (Int, Int)
initSet _   ("",     _)   = Set.empty
initSet col (s : ss, row) = let next = initSet (col + 1) (ss, row)
                            in if s == '#'
                               then Set.insert (row, col) next
                               else next

check :: Int -> Int -> Int -> Set.Set (Int, Int) -> Bool
check n r c s | r >= n = True
              | c >= n = check n (r + 1) 0 s
              | Set.member (r, c) s = Set.member (r + 1, c - 1) s &&
                                      Set.member (r + 1, c    ) s &&
                                      Set.member (r + 1, c + 1) s &&
                                      Set.member (r + 2, c    ) s &&
                                      check n r (c + 1) (Set.delete (r + 1, c - 1) $
                                                         Set.delete (r + 1, c    ) $
                                                         Set.delete (r + 1, c + 1) $
                                                         Set.delete (r + 2, c    ) s)
              | otherwise = check n r (c + 1) s

{-# 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.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 (Map)
import qualified Data.Map as Map
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
  n <- readLn
  a <- replicateM n getLine

  let
    a' = listArray ((1, 1), (n, n)) $ concat a
    cs = filter center [(x, y) | x <- [2..n-1], y <- [2..n-1]]
      where
        center (x, y) = all (== '#') $ map (a'!) [(x-1,y),(x+1,y), (x,y-1), (x,y+1), (x,y)]

    b = runSTArray $ do
      a <- newArray ((1, 1), (n, n)) '.'

      forM_ cs $ \(x, y) ->
        forM_ [(x-1,y),(x+1,y), (x,y-1), (x,y+1), (x,y)] $ \(x, y) ->
          writeArray a (x, y) '#'
      return a

  putStrLn $ if a' == b then "YES" else "NO"


import Text.Printf
import Debug.Trace

diff :: [Int] -> [Int]
diff [x]    = []
diff (x:xs) = (head xs - x) : diff xs

f k x = (x - 1) `div` k

main = do
    [n, k]   <- (map read . words) `fmap` getLine
    (_:list) <- (map read . words) `fmap` getLine

    let list' = [0] ++ list ++ [n+1]
    let ans   = sum $ map (f k) $ diff list'
    let ans'  = length list + ans

    printf "%d\n" ans'

main = do
	[n, k] <- getA
	_:c <- getA
	putStrLn $ show $ pred $ sum $ zipWith (\i j -> ceiling $ (j - i) / k) (0:c) $ c ++ [n + 1] where
	getA = fmap (map read . words) getLine

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

solve :: [Int] -> Int
solve (n:k:c:a) = solve' 0 0 a
    where solve' :: Int -> Int -> [Int] -> Int
          solve' ni ki a | ni > n = 0
                         | ki == k && ((length a) > 0 && ni == (head a)) = 1 + solve' (ni + 1) 1 (tail a)
                         | ki == k = 1 + solve' (ni + 1) 1 a
                         | ((length a) > 0 && ni == (head a)) = 1 + solve' (ni + 1) 1 (tail a)
                         | otherwise = solve' (ni + 1) (ki + 1) a

solve :: Int -> Int -> [Int] -> Int
solve n k xs  =  solve' 0 0 xs
  where
  solve' d s []
    | d + k > n  =  s
    | otherwise  =  solve' (d+k) (s+1) []
  solve' d s (x:xs)
    | d + k < x  =  solve' (d+k) (s+1) (x:xs)
    | otherwise  =  solve' x (s+1) xs

main :: IO ()
main  =  do
    [n, k]  <-  fmap (map read . words) getLine
    xs  <-  fmap (map read . words) getLine
    print $ solve n k $ tail xs

import Data.List
import Control.Arrow
import Control.Applicative

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

untilNextHoliday k from nextH = (nextH - from) `div` k

countPresents n k hls' =
  let hls = hls' ++ [n+1]
  in  second (subtract 1) $
      foldl
      (\(tdy, sum) nxt -> (nxt + 1, sum + untilNextHoliday k tdy nxt + 1))
      (1, 0)
      hls

main = do
  [n, k] <- getInts
  (c: hs) <- getInts
  print . snd $ countPresents n k hs

main=interact$show.g.map read.words
g(n:k:_:x)=f 0 x where
 f l(x:s)|l+k<x=1+f(l+k)(x:s)|1>0=1+f(max l x)s
 f l x|l+k<=n=1+f(l+k)x|1>0=0

main = do
	[n, k] <- getA
	c <- getA
	putStrLn $ show $ pred $ sum $ zipWith (\i j -> ceiling $ (j - i) / k) (0:c) $ c ++ [n + 1] where
	getA = fmap (map read . words) getLine

main=interact$show.f 0.map read.words
f l(n:k:x:s)|l+k<x=1+f(l+k)(n:k:x:s)|1>0=1+f(max l x)(n:k:s)
f l(n:k:x)|l+k<=n=1+f(l+k)(n:k:x)|1>0=0


import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> -n
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

solve input =
  let asNum :: Int
      asNum = read input
      numArray = [(i, i2) | i <- [1..asNum], i2 <- [1..asNum]]
      asStrs = map numMapper numArray
      numMapper :: (Int, Int) -> String
      numMapper (i, i2)
        | (mod (i+i2) 2) == 1 && i2 == asNum = "W\n"
        | (mod (i+i2) 2) == 0 && i2 == asNum = "B\n"
        | (mod (i+i2) 2) == 1 = "W"
        | (mod (i+i2) 2) == 0 = "B"
  in concat asStrs

import Control.Monad
import qualified Data.ByteString.Lazy.Char8 as C8
import Data.List

main = do
  c <- read <$> getLine
  let s1 = C8.take (fromIntegral c) $ C8.concat $ repeat $ C8.pack "WB"
  let s2 = C8.take (fromIntegral c) $ C8.concat $ repeat $ C8.pack "BW"
  replicateM_ (c `div` 2) $ do
    C8.putStrLn s1
    C8.putStrLn s2
  when (odd c) $ C8.putStrLn s1


module Main where

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

main :: IO ()
main = interact solve

solve = unlines . getAns . map (map read . words) . tail . lines

getAns :: [[Int]] -> [String]
getAns = map doCase

doCase :: [Int] -> String
doCase [l, r, k] | l == 1 && r == 1 = "NO"
                 | l == r = "YES"
                 | otherwise = enumS $ ((r - l + 1) `div` 2) + fromEnum (odd l && odd r) <= k
doCase _ = error "cmon"

enumS True = "YES"
enumS False = "NO"

import Control.Monad (forM)

solve t = do
  input <- getLine
  let arr = map (read::String -> Int) $ words input
      l = arr !! 0
      r = arr !! 1
      k = arr !! 2
      req = (r - l + 1) - (r`div`2 - (l - 1)`div`2)
  if l == r && l == 1 then putStrLn "NO" else if l == r then putStrLn "YES" else (if req <= k then putStrLn "YES" else putStrLn "NO")

main = do
tlen <- readLn :: IO Int
forM [0..(tlen - 1)] (\t -> do solve t)

import Control.Monad (forM)

solve t = do
  input <- getLine
  let [l, r, k] = map (read::String -> Int) $ words input
      req = (r - l + 1) - (r`div`2 - (l - 1)`div`2)
      ans | (l == 1) && (l == r) = putStrLn "NO"
          | l == r = putStrLn "YES"
          | otherwise = if  req <= k then putStrLn "YES" else putStrLn "NO"
  ans

main = do
  tlen <- readLn :: IO Int
  forM [0..(tlen - 1)] (\t -> do solve t)

import Control.Monad (forM)

solve t = do
  input <- getLine
  let [l, k, r] = map (read::String -> Int) $ words input
      req = (r - l + 1) - (r`div`2 - (l - 1)`div`2)
      ans | (l == 1) && (l == r) = putStrLn "NO"
          | l == r = putStrLn "YES"
          | otherwise = if  req <= k then putStrLn "YES" else putStrLn "NO"
  ans

main = do
tlen <- readLn :: IO Int
forM [0..(tlen - 1)] (\t -> do solve t)

import Control.Monad (forM)

solve t = do
  input <- getLine
  let [l, k, r] = map (read::String -> Int) $ words input
      req = (r - l + 1) - (r`div`2 - (l - 1)`div`2)
      ans | l == r = putStrLn "YES"
          | (l == 1) && (l == r) = putStrLn "NO"
          | otherwise = if  req <= k then putStrLn "YES" else putStrLn "NO"
  ans

main = do
tlen <- readLn :: IO Int
forM [0..(tlen - 1)] (\t -> do solve t)