import Control.Monad
import Data.List

calc :: String -> String
calc [] = []
calc ('R':'?':xs) = 'R':(calc ('B':xs))
calc ('B':'?':xs) = 'B':(calc ('R':xs))
calc ('?':'R':xs) = 'B':(calc ('R':xs))
calc ('?':'B':xs) = 'R':(calc ('B':xs))
calc ('?':'?':xs) = calc ('?':(calc ('?':xs)))
calc ['?'] = ['B']
calc (x:xs) = x:(calc xs)

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    unused <- getLine
    line <- getLine
    putStrLn $ calc line

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}

{-# OPTIONS_GHC -Wno-incomplete-patterns #-}

module Main where

import qualified Data.ByteString.Char8 as C8
import           Control.Monad.Reader (replicateM_)

readInput :: C8.ByteString -> [[Int]]
readInput = map
  (map
     (\str -> let (Just (i, _)) = C8.readInt str
              in i)
   . C8.words)
  . C8.lines

main :: IO ()
main = do
  t <- readLn :: IO Int
  replicateM_ t
    $ do
      n <- readLn :: IO Int
      colors <- head . C8.words <$> C8.getLine
      C8.putStrLn $ solve colors

solve :: C8.ByteString -> C8.ByteString
solve xs
  | C8.unpack xs == "?" = "B"
  | countMarks (C8.length xs - 1) xs == 0 = xs
  | otherwise = let len = C8.length rr - 1
                    rr = C8.pack . insertR $ C8.unpack xs
                    bb = C8.pack . insertB $ C8.unpack xs
                in if countImp len rr > countImp len bb
                   then bb
                   else rr

insertR :: String -> String
insertR [y] = [y]
insertR (x:y:xs)
  | x == '?' = insertR ('R':y:xs)
  | otherwise = if x == 'B' && y == '?'
                then insertR (x:'R':xs)
                else if x == 'R' && y == '?'
                     then insertR (x:'B':xs)
                     else x:insertR (y:xs)

insertB :: String -> String
insertB [y] = [y]
insertB (x:y:xs)
  | x == '?' = insertB ('B':y:xs)
  | otherwise = if x == 'B' && y == '?'
                then insertR (x:'R':xs)
                else if x == 'R' && y == '?'
                     then insertR (x:'B':xs)
                     else x:insertR (y:xs)

countImp :: Num p => Int -> C8.ByteString -> p
countImp 0 _ = 0
countImp len xs =
  if xs `C8.index` len == xs `C8.index` (len - 1) || xs `C8.index` len == '?'
  then 1 + countImp (len - 1) xs
  else countImp (len - 1) xs

countMarks :: Num p => Int -> C8.ByteString -> p
countMarks (-1) _ = 0
countMarks len xs = if xs `C8.index` len == '?'
                    then 1 + countMarks (len - 1) xs
                    else countMarks (len - 1) xs
{-
>>>solve "?B"
"RB"
>>>countMarks 1 "?B"
1

>>>solve "?R??RB??B?"
"BRBRRBRBBR"

>>>solve "?R??RB??B?"
"BRBRRBRBBR"

>>>insertR "?B"
"RB"

>>>insert
Variable not in scope: insert

>>>solve "BR?"
"BRB"

-}

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad (replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust)

main :: IO ()
main = C.interact $ runScanner (numberOf (int *> str)) >>> map (solve >>> C.pack) >>> C.unlines

solve :: String -> String
solve = reverse . tail . scanl fill 'R'  . reverse . scanl1 fill
  where
    fill 'R' '?' = 'B'
    fill 'B' '?' = 'R'
    fill _ c = c

twice :: (a -> a) -> (a -> a)
twice f = f . f

-------------------------- Template ------------------------------------------
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

bstr :: Scanner C.ByteString
bstr = get >>= \case s : ss -> put ss >> return s

str :: Scanner String
str = C.unpack <$> bstr

int :: Scanner Int
int = fst . fromJust . C.readInt <$> bstr

integer :: Scanner Integer
integer = read . C.unpack <$> bstr

double :: Scanner Double
double = read . C.unpack <$> bstr

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t
    then return []
    else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show

import qualified Data.List
import qualified Data.Map
import qualified Data.Set
import Control.Monad

calc :: String -> String
calc [] = []
calc ('R':'?':xs) = 'R':(calc ('B':xs))
calc ('B':'?':xs) = 'B':(calc ('R':xs))
calc ('?':'R':xs) = 'B':(calc ('R':xs))
calc ('?':'B':xs) = 'R':(calc ('B':xs))
calc ('?':'?':xs) = calc ('?':(calc ('?':xs)))
calc ['?'] = ['B']
calc (x:xs) = x:(calc xs)

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

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}

{-# OPTIONS_GHC -Wno-incomplete-patterns #-}

module Main where

import qualified Data.ByteString.Char8 as C8
import           Control.Monad.Reader (replicateM_)

readInput :: C8.ByteString -> [[Int]]
readInput = map
  (map
     (\str -> let (Just (i, _)) = C8.readInt str
              in i)
   . C8.words)
  . C8.lines

main :: IO ()
main = do
  t <- readLn :: IO Int
  replicateM_ t
    $ do
      n <- readLn :: IO Int
      colors <- head . C8.words <$> C8.getLine
      C8.putStrLn $ solve colors

solve :: C8.ByteString -> C8.ByteString
solve xs
  | C8.unpack xs == "?" = "B"
  | countImp (C8.length xs - 1) xs == 0 = xs
  | countMarks (C8.length xs - 1) xs == 0 = xs
  | otherwise = let len = C8.length rr - 1
                    rr = C8.pack . insertR $ C8.unpack xs
                    bb = C8.pack . insertB $ C8.unpack xs
                in if countImp len rr > countImp len bb
                   then bb
                   else rr

insertR :: String -> String
insertR [y] = [y]
insertR (x:y:xs)
  | x == '?' = insertR ('R':y:xs)
  | otherwise = if x == 'B' && y == '?'
                then insertR (x:'R':xs)
                else if x == 'R' && y == '?'
                     then insertR (x:'B':xs)
                     else x:insertR (y:xs)

insertB :: String -> String
insertB [y] = [y]
insertB (x:y:xs)
  | x == '?' = insertB ('B':y:xs)
  | otherwise = if x == 'B' && y == '?'
                then insertR (x:'R':xs)
                else if x == 'R' && y == '?'
                     then insertR (x:'B':xs)
                     else x:insertR (y:xs)

countImp :: Num p => Int -> C8.ByteString -> p
countImp 0 _ = 0
countImp len xs =
  if xs `C8.index` len == xs `C8.index` (len - 1) || xs `C8.index` len == '?'
  then 1 + countImp (len - 1) xs
  else countImp (len - 1) xs

countMarks :: Num p => Int -> C8.ByteString -> p
countMarks (-1) _ = 0
countMarks len xs = if xs `C8.index` len == '?'
                    then 1 + countMarks (len - 1) xs
                    else countMarks (len - 1) xs
{-
>>>solve "?BB"
"RBB"
>>>countMarks 2 "?BB"
1

>>>solve "?R??RB??B?"
"BRBRRBRBBR"

>>>solve "?R??RB??B?"
"BRBRRBRBBR"

>>>solve "BR?"
"BRB"

-}

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}

{-# OPTIONS_GHC -Wno-incomplete-patterns #-}

module Main where

import qualified Data.ByteString.Char8 as C8
import           Control.Monad.Reader (replicateM_)

readInput :: C8.ByteString -> [[Int]]
readInput = map
  (map
     (\str -> let (Just (i, _)) = C8.readInt str
              in i)
   . C8.words)
  . C8.lines

main :: IO ()
main = do
  t <- readLn :: IO Int
  replicateM_ t
    $ do
      n <- readLn :: IO Int
      colors <- head . C8.words <$> C8.getLine
      C8.putStrLn $ solve colors

solve :: C8.ByteString -> C8.ByteString
solve xs
  | C8.unpack xs == "?" = "B"
  | countImp (C8.length xs - 1) xs == 0 = xs
  | countMarks (C8.length xs - 1) xs == 0 = xs
  | otherwise = let len = C8.length rr - 1
                    rr = C8.pack . insertR $ C8.unpack xs
                    bb = C8.pack . insertB $ C8.unpack xs
                in if countImp len rr > countImp len bb
                   then bb
                   else rr

insertR :: String -> String
insertR [y] = [y]
insertR (x:y:xs)
  | x == '?' = insertR ('R':y:xs)
  | otherwise = if x == 'B' && y == '?'
                then insertR (x:'R':xs)
                else if x == 'R' && y == '?'
                     then insertR (x:'B':xs)
                     else x:insertR (y:xs)

insertB :: String -> String
insertB [y] = [y]
insertB (x:y:xs)
  | x == '?' = insertB ('B':y:xs)
  | otherwise = if x == 'B' && y == '?'
                then insertR (x:'R':xs)
                else if x == 'R' && y == '?'
                     then insertR (x:'B':xs)
                     else x:insertR (y:xs)

countImp :: Num p => Int -> C8.ByteString -> p
countImp 0 _ = 0
countImp len xs =
  if xs `C8.index` len == xs `C8.index` (len - 1) || xs `C8.index` len == '?'
  then 1 + countImp (len - 1) xs
  else countImp (len - 1) xs

countMarks 0 _ = 0
countMarks len xs = if xs `C8.index` len == '?'
                    then 1 + countMarks (len - 1) xs
                    else countMarks (len - 1) xs
{-
>>>solve "BB?"
"BBR"

>>>solve "?R??RB??B?"
"BRBRRBRBBR"

>>>solve "?R??RB??B?"
"BRBRRBRBBR"

>>>solve "BR?"
"BRB"

-}

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}

{-# OPTIONS_GHC -Wno-incomplete-patterns #-}

module Main where

import qualified Data.ByteString.Char8 as C8
import           Control.Monad.Reader (replicateM_)

readInput :: C8.ByteString -> [[Int]]
readInput = map
  (map
     (\str -> let (Just (i, _)) = C8.readInt str
              in i)
   . C8.words)
  . C8.lines

main :: IO ()
main = do
  t <- readLn :: IO Int
  replicateM_ t
    $ do
      n <- readLn :: IO Int
      colors <- C8.getLine
      C8.putStrLn $ solve colors

solve :: C8.ByteString -> C8.ByteString
solve xs
  | xs == "?" = "B"
  | countImp (C8.length xs - 1) xs == 0 = xs
  | otherwise = let len = C8.length xs - 2
                    rr = head . C8.words . C8.pack . insertR $ C8.unpack xs
                    bb = head . C8.words . C8.pack . insertB $ C8.unpack xs
                in if countImp len rr > countImp len bb
                   then bb
                   else rr

insertR :: String -> String
insertR [y] = []
insertR (x:y:xs)
  | x == '?' = 'R':insertR ('R':y:xs)
  | otherwise = if x == 'B' && y == '?'
                then 'R':insertR ('R':xs)
                else if x == 'R' && y == '?'
                     then 'B':insertR ('B':xs)
                     else y:insertR (y:xs)

insertB :: String -> String
insertB [y] = []
insertB (x:y:xs)
  | x == '?' = 'B':insertB ('B':y:xs)
  | otherwise = if x == 'B' && y == '?'
                then 'R':insertR ('R':xs)
                else if x == 'R' && y == '?'
                     then 'B':insertR ('B':xs)
                     else y:insertR (y:xs)

countImp :: Num p => Int -> C8.ByteString -> p
countImp 0 _ = 0
countImp len xs = if xs `C8.index` len == xs `C8.index` (len - 1)
                  then 1 + countImp (len - 1) xs
                  else countImp (len - 1) xs
{-
>>>solve "B"
"B"

>>>solve "?R??RB??B?"
"BRBRRBRBBR"

>>>solve "?R??RB??B?"
"BRBRRBRBBR"

>>>solve "BR"
"BR"

-}

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad (replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromJust)

main :: IO ()
main = C.interact $ runScanner (numberOf str) >>> map (solve >>> showB) >>> C.unlines

solve :: String -> String
solve = twice $ reverse . scanl1 fill
  where
    fill 'R' '?' = 'B'
    fill 'B' '?' = 'R'
    fill _ c = c

twice :: (a -> a) -> (a -> a)
twice f = f . f

-------------------------- Template ------------------------------------------
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

bstr :: Scanner C.ByteString
bstr = get >>= \case s : ss -> put ss >> return s

str :: Scanner String
str = C.unpack <$> bstr

int :: Scanner Int
int = fst . fromJust . C.readInt <$> bstr

integer :: Scanner Integer
integer = read . C.unpack <$> bstr

double :: Scanner Double
double = read . C.unpack <$> bstr

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t
    then return []
    else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show


{-# LANGUAGE TupleSections #-}

import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

binaryMedian :: Int -> [String] -> String
binaryMedian m _remove = toBinary m median
    where
        (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove
        remove = map (fromBinary m) _remove

        go (isOdd, med, seen) rem =
            let isOdd' = not isOdd
                seen' = Set.insert rem seen
                find = get med seen
                med' =
                    if  not isOdd && rem <= med then find succ
                    else if isOdd && rem >= med then find pred
                    else med
            in (isOdd', med', seen')

        get n seen f = let n' = f n in
            if Set.member n' seen
                then get n' seen f
                else n'

fromBit :: Num p => Char -> p
fromBit '0' = 0
fromBit '1' = 1

toBit :: (Eq a, Num a) => a -> Char
toBit 0 = '0'
toBit 1 = '1'

fromBinary :: (Foldable t, Num a) => p -> t Char -> a
fromBinary m = foldl' (\n c -> 2 * n + fromBit c) 0

toBinary :: Integral a => Int -> a -> [Char]
toBinary m num =
    foldl' (\b k -> toBit (k `mod` 2):b) "" (take m $ iterate (`div` 2) num)

readInput :: IO (Int, [String])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/H

{-# LANGUAGE TupleSections #-}
import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int

binaryMedian :: Width -> [Byte] -> Byte
binaryMedian width _remove = toByte width median'
    where
        median = 2^(width-1) - 1
        remove = fromByte `map` _remove
        (_, median', _) = foldl' go (False, median, Set.empty) remove

        go (isOdd, med, seen) rem = (isOdd', med', seen') where
                isOdd'= not isOdd
                seen' = Set.insert rem seen
                get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)
                med' =
                    if  not isOdd && rem <= med then get succ
                    else if isOdd && rem >= med then get pred
                    else med

fromBit :: Bit -> Integer
fromBit '0' = 0
fromBit '1' = 1

toBit :: Integer -> Bit
toBit 0 = '0'
toBit 1 = '1'

fromByte :: Byte -> Integer
fromByte = foldl' go 0
    where go num bit = 2*num + fromBit bit

toByte :: Width -> Integer -> Byte
toByte m = foldl' go "" . take m . iterate (`div` 2)
    where go bits k = toBit (k `mod` 2) : bits

readInput :: IO (Width, [Byte])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

{-# LANGUAGE TupleSections #-}

import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

binaryMedian :: (Int, [String]) -> String
binaryMedian (m, _remove) = toBinary m median
    where
        (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove
        remove = map (fromBinary m) _remove

        go (isOdd, med, seen) rem =
            let isOdd' = not isOdd
                seen' = Set.insert rem seen
                find = get med seen
                med' =
                    if  not isOdd && rem <= med then find succ
                    else if isOdd && rem >= med then find pred
                    else med
            in (isOdd', med', seen')

        get n seen f = let n' = f n in
            if Set.member n' seen
                then get n' seen f
                else n'

fromBit '0' = 0
fromBit '1' = 1

toBit 0 = '0'
toBit 1 = '1'

fromBinary m = foldl' (\n c -> 2 * n + fromBit c) 0

toBinary m num =
    foldl' (\b k -> toBit (k `mod` 2):b) "" (take m $ iterate (`div` 2) num)

main = do
    t <- read <$> getLine
    replicateM_ t (binaryMedian <$> readInput >>= putStrLn)

{- LANGUAGE BANGPATTERNS -}

import Data.Traversable (for)
import Data.Foldable (foldl', for_)
import Data.List (sort, unfoldr)

readBits :: String -> Integer
readBits = ($ 0) $ foldl' (\x y -> case  y  of
  '0' -> 2*x
  '1' -> 2*x+1
  _ -> error "bit"
  )

toBits :: Int -> Integer -> String
toBits k val = reverse . take k $ unfoldr step val  where
  step x = case  quotRem x 2  of
    (x', 0) -> Just ('0', x')
    (x', 1) -> Just ('1', x')
    _ -> error "overflow??"

--mockup to work around small size limits
data Seq t
  = Empty
  | Single t
  | Node !Integer (Seq t) (Seq t)

size :: Seq t -> Integer
size Empty = 0
size (Single _) = 1
size (Node sz _ _) = sz

deleteAt :: Integer -> Seq t -> Seq t
deleteAt k s = case  s  of
  _ | k < 0 || k >= size s  -> s
  Single _  -> Empty
  Node n le ri -> let  excess = k - size le  in  if  excess >= 0
    then  Node (n-1) le (deleteAt excess ri)
    else  Node (n-1) (deleteAt k le) ri
  -- in all cases this is caught by the first pattern, but GHC can't tell that
  Empty -> s

outOfBounds :: t
outOfBounds = error "index: out of bounds"

index :: Seq t -> Integer -> t
index Empty _ = outOfBounds
index (Single v) 0 = v
index (Single _) _ = outOfBounds
index (Node n le ri) k = let  excess = k - size le  in case  ()  of
  () | k < 0 || k >= n  -> outOfBounds
  () | excess < 0  -> index le k
  () | otherwise   -> index ri excess

fromFunction :: Integer -> (Integer -> t) -> Seq t
fromFunction = go 0  where
  go start stop fun = case  stop - start  of
    len | len < 0   -> error "fromFunction: negative length"
    len | len == 0  -> Empty
    len | len == 1  -> Single (fun start)
    len  -> Node len (go start mid fun) (go mid stop fun)  where
      mid = quot (start + stop) 2

main :: IO ()
main = do
  t <- read <$> getLine :: IO Int
  for_ [1..t] $ \_ -> do
    [n, k] <- (map read . words) <$> getLine :: IO [Int]
    let tot = 2 ^ k :: Integer
    removalList <- for [1..n] $ \_ -> readBits <$> getLine
    let rl = reverse $ sort removalList :: [Integer]
        startSeq = fromFunction tot id :: Seq Integer
        whatsLeft = foldl' (flip deleteAt) startSeq rl :: Seq Integer
        ix = div (tot - fromIntegral (length rl) - 1) 2
        tar = index whatsLeft ix
    putStrLn (toBits k tar)

import           Data.List
import           Control.Monad
import qualified Data.Set                      as Set
import           Data.Char
import           Data.Int
-- import           Debug.Trace

-- debug = flip trace

fromBinary :: String -> Int64
fromBinary = fromBinary' . reverse

fromBinary' :: String -> Int64
fromBinary' []       = 0
fromBinary' (x : xs) = fromIntegral (ord x - ord '0') + (2 * fromBinary' xs)

toBinary :: Int64 -> Int64 -> String
toBinary m = reverse . toBinary' m

toBinary' :: Int64 -> Int64 -> String
toBinary' 0 _ = []
toBinary' m x = chr (fromIntegral r + ord '0') : toBinary' (m - 1) q
    where (q, r) = divMod x 2

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t $ do
        n : m : _ <- map read . words <$> getLine :: IO [Int64]
        as        <- map fromBinary <$> replicateM (fromIntegral n) getLine
        let ans = solve m n (Set.fromList as)
        putStrLn . toBinary m $ ans

solve :: Int64 -> Int64 -> Set.Set Int64 -> Int64
solve m n as = go lo hi as (div (k + 1) 2)
  where
    lo = 0
    hi = 2 ^ m - 1
    k  = 2 ^ m - n

go :: Int64 -> Int64 -> Set.Set Int64 -> Int64 -> Int64
go lo hi as k | lo > hi            = error "Wrong recursion"
              | k <= leftCount     = go lo (mid - 1) left k
              | hasMid             = go (mid + 1) hi right (k - leftCount)
              | k == leftCount + 1 = mid
              | otherwise          = go (mid + 1) hi right (k - leftCount - 1)
  where
    mid                   = div (lo + hi) 2
    (left, hasMid, right) = Set.splitMember mid as
    leftSize              = fromIntegral $ Set.size left
    leftCount             = mid - lo - leftSize -- `debug` unwords
    --     (zipWith
    --         (\x y -> x ++ " = " ++ y ++ ", ")
    --         (words "lo hi mid k leftCount left right hasMid")
    --         (  map show [lo, hi, mid, k, mid - lo - leftSize]
    --         ++ map show [left, right]
    --         ++ [show hasMid]
    --         )
    --     )

import Control.Monad (replicateM_, replicateM)
import Data.Bits
import qualified Data.Sequence as S
import Data.Sequence ((<|), (|>))
import Data.Foldable (toList)

type Str = S.Seq Char

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

readStrings :: Int -> IO [Str]
readStrings n = replicateM n (S.fromList <$> getLine)

pow2Of :: Int -> Integer
pow2Of = shiftL 1

getMatchingPrefixes :: Int -> Str -> [Str] -> Int
getMatchingPrefixes prefSize pref = length . filter (==pref) . map (S.take prefSize)

getAllowed :: Int -> Int -> Str -> [Str] -> Integer
getAllowed m prefSize pref xss =
    pow2Of (m - prefSize) - toInteger (getMatchingPrefixes prefSize pref xss)

getMedian :: Int -> Int -> [Str] -> Str
getMedian n m xss = go medianPos S.empty [1..m] where
    medianPos = (pow2Of m - (toInteger n) + 1) `div` 2
    go _ _ [] = S.empty
    go searchSize pref (prefSize : xs) = bit <| go newSearchSize (pref |> bit) xs where
        allowedNumStrings = getAllowed m prefSize (pref |> '0') xss
        bit =
            if searchSize <= allowedNumStrings then '0'
            else '1'
        newSearchSize =
            if searchSize <= allowedNumStrings then searchSize
            else searchSize - allowedNumStrings

main =
    readInt >>= \t ->
    replicateM_ t (
        (map read) . words <$> getLine >>= \[n, m] ->
        readStrings n >>= \xss ->
        putStrLn $ toList $ getMedian n m xss
    )

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/H

{-# LANGUAGE TupleSections #-}
import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

binaryMedian :: Int -> [String] -> String
binaryMedian width _remove = toByte width median'
    where
        median = 2^(width-1) - 1
        remove = fromByte width `map` _remove
        (_, median', _) = foldl' go (False, median, Set.empty) remove

        go (isOdd, med, seen) rem = (isOdd', med', seen') where
                isOdd'= not isOdd
                seen' = Set.insert rem seen
                get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)
                med' =
                    if  not isOdd && rem <= med then get succ
                    else if isOdd && rem >= med then get pred
                    else med

fromBit '0' = 0
fromBit '1' = 1

toBit 0 = '0'
toBit 1 = '1'

fromByte m = foldl' go 0
    where go num bit = 2*num + fromBit bit

toByte m = foldl' go "" . take m . iterate (`div` 2)
    where go bits k = toBit (k `mod` 2) : bits

readInput :: IO (Int, [String])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

{-# LANGUAGE TupleSections #-}

import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

readInput :: IO (Int, [String])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

binaryMedian :: Int -> [String] -> String
binaryMedian m _remove = toBinary m median
    where
        (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove
        remove = map (fromBinary m) _remove

        go (isOdd, med, seen) rem =
            let isOdd' = not isOdd
                seen' = Set.insert rem seen
                find = get med seen
                med' =
                    if  not isOdd && rem <= med then find succ
                    else if isOdd && rem >= med then find pred
                    else med
            in (isOdd', med', seen')

        get n seen f = let n' = f n in
            if Set.member n' seen
                then get n' seen f
                else n'

fromBit :: Num p => Char -> p
fromBit '0' = 0
fromBit '1' = 1

toBit :: (Eq a, Num a) => a -> Char
toBit 0 = '0'
toBit 1 = '1'

fromBinary :: (Foldable t, Num a) => p -> t Char -> a
fromBinary m = foldl' (\n c -> 2 * n + fromBit c) 0

toBinary :: Integral a => Int -> a -> [Char]
toBinary m num =
    foldl' (\b k -> toBit (k `mod` 2):b) "" (take m $ iterate (`div` 2) num)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

{-# LANGUAGE TupleSections #-}

import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

readInput :: IO (Int, [String])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

binaryMedian :: (Int, [String]) -> String
binaryMedian (m, _remove) = toBinary m median
    where
        (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove
        remove = map (fromBinary m) _remove

        go (isOdd, med, seen) rem =
            let isOdd' = not isOdd
                seen' = Set.insert rem seen
                find = get med seen
                med' =
                    if  not isOdd && rem <= med then find succ
                    else if isOdd && rem >= med then find pred
                    else med
            in (isOdd', med', seen')

        get n seen f = let n' = f n in
            if Set.member n' seen
                then get n' seen f
                else n'

fromBit :: Num p => Char -> p
fromBit '0' = 0
fromBit '1' = 1

toBit :: (Eq a, Num a) => a -> Char
toBit 0 = '0'
toBit 1 = '1'

fromBinary :: (Foldable t, Num a) => p -> t Char -> a
fromBinary m = foldl' (\n c -> 2 * n + fromBit c) 0

toBinary :: Integral a => Int -> a -> [Char]
toBinary m num =
    foldl' (\b k -> toBit (k `mod` 2):b) "" (take m $ iterate (`div` 2) num)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (binaryMedian <$> readInput >>= putStrLn)

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/H

{-# LANGUAGE TupleSections #-}
import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

binaryMedian :: Int -> [String] -> String
binaryMedian width _remove = toByte width median'
    where
        median = 2^(width-1) - 1
        remove = fromByte `map` _remove
        (_, median', _) = foldl' go (False, median, Set.empty) remove

        go (isOdd, med, seen) rem = (isOdd', med', seen') where
                isOdd'= not isOdd
                seen' = Set.insert rem seen
                get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)
                med' =
                    if  not isOdd && rem <= med then get succ
                    else if isOdd && rem >= med then get pred
                    else med

fromBit :: Num p => Char -> p
fromBit '0' = 0
fromBit '1' = 1

toBit :: (Eq a, Num a) => a -> Char
toBit 0 = '0'
toBit 1 = '1'

fromByte :: [Char] -> Integer
fromByte = foldl' go 0
    where go num bit = 2*num + fromBit bit

toByte :: Integral a => Int -> a -> [Char]
toByte m = foldl' go "" . take m . iterate (`div` 2)
    where go bits k = toBit (k `mod` 2) : bits

readInput :: IO (Int, [String])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

import Control.Monad (replicateM_, replicateM)
import Data.Bits
import qualified Data.Sequence as S
import Data.Sequence ((<|), (|>))
import Data.Foldable (toList)

type Str = S.Seq Char

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

readStrings :: Int -> IO [Str]
readStrings n = replicateM n (S.fromList <$> getLine)

pow2Of :: Int -> Int
pow2Of = shiftL 1

getMatchingPrefixes :: Int -> Str -> [Str] -> Int
getMatchingPrefixes prefSize pref = length . filter (==pref) . map (S.take prefSize)

getAllowed :: Int -> Int -> Str -> [Str] -> Int
getAllowed m prefSize pref xss =
    pow2Of (m - prefSize) - (getMatchingPrefixes prefSize pref xss)

getMedian :: Int -> Int -> [Str] -> Str
getMedian n m xss = go medianPos S.empty [1..m] where
    medianPos = (pow2Of m - n + 1) `div` 2
    go :: Int -> Str -> [Int] -> Str
    go _ _ [] = S.empty
    go searchSize pref (prefSize : xs) = bit <| go newSearchSize (pref |> bit) xs where
        allowedNumStrings = getAllowed m prefSize (pref |> '0') xss
        bit =
            if searchSize <= allowedNumStrings then '0'
            else '1'
        newSearchSize =
            if searchSize <= allowedNumStrings then searchSize
            else searchSize - allowedNumStrings

main =
    readInt >>= \t ->
    replicateM_ t (
        (map read) . words <$> getLine >>= \[n, m] ->
        readStrings n >>= \xss ->
        putStrLn $ toList $ getMedian n m xss
    )

import Control.Monad (replicateM_, replicateM)
import Data.Bits
import qualified Data.Sequence as S
import Data.Sequence ((<|), (|>))
import Data.Foldable (toList)

type Str = S.Seq Char

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

readStrings :: Int -> IO [Str]
readStrings n = replicateM n (S.fromList <$> getLine)

pow2Of :: Int -> Int
pow2Of = shiftL 1

getMatchingPrefixes :: Int -> Str -> [Str] -> Int
getMatchingPrefixes prefSize pref = length . filter (==pref) . map (S.take prefSize)

getAllowed :: Int -> Int -> Str -> [Str] -> Int
getAllowed m prefSize pref xss =
    pow2Of (m - prefSize) - (getMatchingPrefixes prefSize pref xss)

getMedian :: Int -> Int -> [Str] -> Str
getMedian n m xss = go medianPos S.empty [1..m] where
    medianPos = (pow2Of m - n + 1) `div` 2
    go :: Int -> Str -> [Int] -> Str
    go _ _ [] = S.empty
    go searchSize pref (prefSize : xs) = bit <| go newSearchSize (pref |> bit) xs where
        allowedNumStrings = getAllowed m prefSize (pref |> '0') xss
        bit =
            if searchSize <= allowedNumStrings then '0'
            else '1'
        newSearchSize =
            if searchSize <= allowedNumStrings then searchSize
            else searchSize - allowedNumStrings

main =
    readInt >>= \t ->
    replicateM_ t (
        (map read) . words <$> getLine >>= \[n, m] ->
        readStrings n >>= \xss ->
        print $ show (maxBound :: Int)
        --putStrLn $ toList $ getMedian n m xss
    )

import Control.Monad (replicateM_, replicateM)
import Data.Bits
import qualified Data.Sequence as S
import Data.Sequence ((<|), (|>))
import Data.Foldable (toList)

type Str = S.Seq Char

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

readStrings :: Int -> IO [Str]
readStrings n = replicateM n (S.fromList <$> getLine)

pow2Of :: Int -> Int
pow2Of = shiftL 1

getMatchingPrefixes :: Int -> Str -> [Str] -> Int
getMatchingPrefixes prefSize pref = length . filter (==pref) . map (S.take prefSize)

getAllowed :: Int -> Int -> Str -> [Str] -> Int
getAllowed m prefSize pref xss =
    pow2Of (m - prefSize) - (getMatchingPrefixes prefSize pref xss)

getMedian :: Int -> Int -> [Str] -> Str
getMedian n m xss = go medianPos S.empty [1..m] where
    medianPos = (pow2Of m - n - 1) `div` 2
    go :: Int -> Str -> [Int] -> Str
    go _ _ [] = S.empty
    go searchSize pref (prefSize : xs) = bit <| go newSearchSize (pref |> bit) xs where
        allowedNumStrings = getAllowed m prefSize (pref |> '0') xss
        bit =
            if searchSize + 1 <= allowedNumStrings then '0'
            else '1'
        newSearchSize =
            if searchSize + 1 <= allowedNumStrings then searchSize
            else searchSize - allowedNumStrings

main =
    readInt >>= \t ->
    replicateM_ t (
        (map read) . words <$> getLine >>= \[n, m] ->
        readStrings n >>= \xss ->
        putStrLn $ toList $ getMedian n m xss
    )

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/H

{-# LANGUAGE TupleSections #-}
import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

-- type Bit   = Char
-- type Byte  = [Bit]
-- type Width = Int    -- width of byte

binaryMedian :: Int -> [String] -> String
binaryMedian width _remove = toByte width median'
    where
        median = 2^(width-1) - 1
        remove = fromByte width `map` _remove
        (_, median', _) = foldl' go (False, median, Set.empty) remove

        go (isOdd, med, seen) rem = (isOdd', med', seen') where
                isOdd'= not isOdd
                seen' = Set.insert rem seen
                get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)
                med' =
                    if  not isOdd && rem <= med then get succ
                    else if isOdd && rem >= med then get pred
                    else med

fromBit :: Char -> Int
fromBit '0' = 0
fromBit '1' = 1

toBit :: Int -> Char
toBit 0 = '0'
toBit 1 = '1'

fromByte :: Int -> String -> Int
fromByte m = foldl' go 0
    where go num bit = 2*num + fromBit bit

toByte :: Int -> Int -> String
toByte m = foldl' go "" . take m . iterate (`div` 2)
    where go bits k = toBit (k `mod` 2) : bits

readInput :: IO (Int, [String])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/H

{-# LANGUAGE TupleSections #-}
import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

binaryMedian :: Width -> [Byte] -> Byte
binaryMedian width _remove = toByte width median'
    where
        median = 2^(width-1) - 1
        remove = fromByte width `map` _remove
        (_, median', _) = foldl' go (False, median, Set.empty) remove

        go (isOdd, med, seen) rem = (isOdd', med', seen') where
                isOdd'= not isOdd
                seen' = Set.insert rem seen
                get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)
                med' =
                    if  not isOdd && rem <= med then get succ
                    else if isOdd && rem >= med then get pred
                    else med

fromBit :: Bit -> Int
fromBit '0' = 0
fromBit '1' = 1

toBit :: Int -> Bit
toBit 0 = '0'
toBit 1 = '1'

fromByte :: Width -> Byte -> Int
fromByte m = foldl' go 0
    where go num bit = 2*num + fromBit bit

toByte :: Width -> Int -> Byte
toByte m num =
    foldl' (\b k -> toBit (k `mod` 2):b) "" (take m $ iterate (`div` 2) num)
    -- foldl' go "" . take m . iterate (`div` 2)
    -- where go bits k = toBit (k `mod` 2) : bits

readInput :: IO (Width, [Byte])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

{-# LANGUAGE TupleSections #-}

import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

binaryMedian :: Width -> [Byte] -> Byte
binaryMedian m _remove = toBinary m median
    where
        (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove
        remove = map (fromBinary m) _remove

        go (isOdd, med, seen) rem =
            let isOdd' = not isOdd
                seen' = Set.insert rem seen
                find = get med seen
                med' =
                    if  not isOdd && rem <= med then find succ
                    else if isOdd && rem >= med then find pred
                    else med
            in (isOdd', med', seen')

        get n seen f = let n' = f n in
            if Set.member n' seen
                then get n' seen f
                else n'

fromBit :: Bit -> Int
fromBit '0' = 0
fromBit '1' = 1

toBit :: Int -> Bit
toBit 0 = '0'
toBit 1 = '1'

fromBinary :: Width -> Byte -> Int
fromBinary m = foldl' (\n c -> 2 * n + fromBit c) 0

toBinary :: Width -> Int -> Byte
toBinary m num =
    foldl' (\b k -> toBit (k `mod` 2):b) "" (take m $ iterate (`div` 2) num)

readInput :: IO (Width, [Byte])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/H

{-# LANGUAGE TupleSections #-}
import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

-- binaryMedian :: Width -> [Byte] -> Byte
-- binaryMedian width _remove = toByte width median'
--     where
--         median = 2^(width-1) - 1
--         remove = fromByte width `map` _remove
--         (_, median', _) = foldl' go (False, median, Set.empty) remove

--         go (isOdd, med, seen) rem = (isOdd', med', seen') where
--                 isOdd'= not isOdd
--                 seen' = Set.insert rem seen
--                 get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)
--                 med' =
--                     if  not isOdd && rem <= med then get succ
--                     else if isOdd && rem >= med then get pred
--                     else med
binaryMedian :: Width -> [Byte] -> String
binaryMedian m _remove = toByte m median
    where
        (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove
        remove = map (fromByte m) _remove

        go (isOdd, med, seen) rem =
            let isOdd' = not isOdd
                seen' = Set.insert rem seen
                find = get med seen
                med' =
                    if  not isOdd && rem <= med then find succ
                    else if isOdd && rem >= med then find pred
                    else med
            in (isOdd', med', seen')

        get n seen f = let n' = f n in
            if Set.member n' seen
                then get n' seen f
                else n'

fromBit :: Bit -> Int
fromBit '0' = 0
fromBit '1' = 1

toBit :: Int -> Bit
toBit 0 = '0'
toBit 1 = '1'

fromByte :: Width -> Byte -> Int
fromByte m = foldl' go 0
    where go num bit = 2*num + fromBit bit

toByte :: Width -> Int -> Byte
toByte m = foldl' go "" . take m . iterate (`div` 2)
    where go bits k = toBit (k `mod` 2) : bits

readInput :: IO (Width, [Byte])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/H

{-# LANGUAGE TupleSections #-}
import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

binaryMedian :: Width -> [Byte] -> Byte
binaryMedian width _remove = toByte width median'
    where
        median = 2^(width-1) - 1
        remove = fromByte width `map` _remove
        (_, median', _) = foldl' go (False, median, Set.empty) remove

        go (isOdd, med, seen) rem = (isOdd', med', seen') where
                isOdd'= not isOdd
                seen' = Set.insert rem seen
                get f = head $ dropWhile (`Set.member` seen') (iterate f med)
                med' =
                    if  not isOdd && rem <= med then get succ
                    else if isOdd && rem >= med then get pred
                    else med

fromBit :: Bit -> Int
fromBit '0' = 0
fromBit '1' = 1

toBit :: Int -> Bit
toBit 0 = '0'
toBit 1 = '1'

fromByte :: Width -> Byte -> Int
fromByte m = foldl' go 0
    where go num bit = 2*num + fromBit bit

toByte :: Width -> Int -> Byte
toByte m = foldl' go "" . take m . iterate (`div` 2)
    where go bits k = toBit (k `mod` 2) : bits

readInput :: IO (Width, [Byte])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/H

{-# LANGUAGE TupleSections #-}
import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

binaryMedian :: Width -> [Byte] -> Byte
binaryMedian width _remove = toByte width median'
    where
        median = 2^(width-1) - 1
        remove = fromByte width `map` _remove
        (_, median', _) = foldl' go (False, median, Set.empty) remove

        go (isOdd, med, seen) rem = (isOdd', med', seen') where
                isOdd'= not isOdd
                seen' = Set.insert rem seen
                -- get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)
                get f n = let n' = f n in
                    if Set.member n' seen
                        then get f n'
                        else n'
                med' =
                    if  not isOdd && rem <= med then get succ med
                    else if isOdd && rem >= med then get pred med
                    else med

fromBit :: Bit -> Int
fromBit '0' = 0
fromBit '1' = 1

toBit :: Int -> Bit
toBit 0 = '0'
toBit 1 = '1'

fromByte :: Width -> Byte -> Int
fromByte m = foldl' go 0
    where go num bit = 2*num + fromBit bit

toByte :: Width -> Int -> Byte
toByte m = foldl' go "" . take m . iterate (`div` 2)
    where go bits k = toBit (k `mod` 2) : bits

readInput :: IO (Width, [Byte])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/H

{-# LANGUAGE TupleSections #-}
import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

-- binaryMedian :: Width -> [Byte] -> Byte
-- binaryMedian width _remove = toByte width median'
--     where
--         median = 2^(width-1) - 1
--         remove = fromByte width `map` _remove
--         (_, median', _) = foldl' go (False, median, Set.empty) remove

--         go (isOdd, med, seen) rem = (isOdd', med', seen') where
--                 isOdd'= not isOdd
--                 seen' = Set.insert rem seen
--                 get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)
--                 med' =
--                     if  not isOdd && rem <= med then get succ
--                     else if isOdd && rem >= med then get pred
--                     else med
binaryMedian :: Width -> [Byte] -> String
binaryMedian m _remove = toByte m median
    where
        (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove
        remove = map (fromByte m) _remove

        go (isOdd, med, seen) rem =
            let isOdd' = not isOdd
                seen' = Set.insert rem seen
                find = get med seen
                med' =
                    if  not isOdd && rem <= med then find succ
                    else if isOdd && rem >= med then find pred
                    else med
            in (isOdd', med', seen')

        get n seen f = let n' = f n in
            if Set.member n' seen
                then get n' seen f
                else n'

fromBit '0' = 0
fromBit '1' = 1

toBit 0 = '0'
toBit 1 = '1'

fromBinary m = foldl' (\n c -> 2 * n + fromBit c) 0

toBinary m num =
    foldl' (\b k -> toBit (k `mod` 2):b) "" (take m $ iterate (`div` 2) num)

-- fromBit :: Bit -> Int
-- fromBit '0' = 0
-- fromBit '1' = 1

-- toBit :: Int -> Bit
-- toBit 0 = '0'
-- toBit 1 = '1'

fromByte :: Width -> Byte -> Int
fromByte m = foldl' go 0
    where go num bit = 2*num + fromBit bit

toByte :: Width -> Int -> Byte
toByte m num =
    foldl' (\b k -> toBit (k `mod` 2):b) "" (take m $ iterate (`div` 2) num)
    -- foldl' go "" . take m . iterate (`div` 2)
    -- where go bits k = toBit (k `mod` 2) : bits

readInput :: IO (Width, [Byte])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

--- frederick99, 6/2020
--- https://codeforces.com/contest/1360/problem/H

{-# LANGUAGE TupleSections #-}
import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

binaryMedian :: Width -> [Byte] -> Byte
binaryMedian width _remove = toByte width median'
    where
        median = 2^(width-1) - 1
        remove = fromByte width `map` _remove
        (_, median', _) = foldl' go (False, median, Set.empty) remove

        go (isOdd, med, seen) rem = (isOdd', med', seen') where
                isOdd'= not isOdd
                seen' = Set.insert rem seen
                get f = head $ dropWhile (`Set.member` seen) (tail $ iterate f med)
                med' =
                    if  not isOdd && rem <= med then get succ
                    else if isOdd && rem >= med then get pred
                    else med

fromBit :: Bit -> Int
fromBit '0' = 0
fromBit '1' = 1

toBit :: Int -> Bit
toBit 0 = '0'
toBit 1 = '1'

fromByte :: Width -> Byte -> Int
fromByte m = foldl' go 0
    where go num bit = 2*num + fromBit bit

toByte :: Width -> Int -> Byte
toByte m = foldl' go "" . take m . iterate (`div` 2)
    where go bits k = toBit (k `mod` 2) : bits

readInput :: IO (Width, [Byte])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

{-# LANGUAGE TupleSections #-}

import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

binaryMedian :: Int -> [String] -> String
binaryMedian m _remove = toBinary m median
    where
        (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove
        remove = map (fromBinary m) _remove

        go (isOdd, med, seen) rem =
            let isOdd' = not isOdd
                seen' = Set.insert rem seen
                find = get med seen
                med' =
                    if  not isOdd && rem <= med then find succ
                    else if isOdd && rem >= med then find pred
                    else med
            in (isOdd', med', seen')

        get n seen f = let n' = f n in
            if Set.member n' seen
                then get n' seen f
                else n'

fromBit :: Char -> Int
fromBit '0' = 0
fromBit '1' = 1

toBit :: (Eq a, Num a) => a -> Char
toBit 0 = '0'
toBit 1 = '1'

fromBinary :: p -> String -> Int
fromBinary m = foldl' (\n c -> 2 * n + fromBit c) 0

toBinary :: Integral a => Int -> a -> [Char]
toBinary m num =
    foldl' (\b k -> toBit (k `mod` 2):b) "" (take m $ iterate (`div` 2) num)

readInput :: IO (Int, [String])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

{-# LANGUAGE TupleSections #-}

import           Control.Monad ( replicateM_ )
import           Data.List     ( foldl' )
import qualified Data.Set as Set

type Bit   = Char
type Byte  = [Bit]
type Width = Int    -- width of byte

binaryMedian :: Int -> [String] -> String
binaryMedian m _remove = toBinary m median
    where
        (_, median, _) = foldl' go (False, 2^(m-1) - 1, Set.empty) remove
        remove = map (fromBinary m) _remove

        go (isOdd, med, seen) rem =
            let isOdd' = not isOdd
                seen' = Set.insert rem seen
                find = get med seen
                med' =
                    if  not isOdd && rem <= med then find succ
                    else if isOdd && rem >= med then find pred
                    else med
            in (isOdd', med', seen')

        get n seen f = let n' = f n in
            if Set.member n' seen
                then get n' seen f
                else n'

fromBit :: Char -> Int
fromBit '0' = 0
fromBit '1' = 1

toBit :: (Eq a, Num a) => a -> Char
toBit 0 = '0'
toBit 1 = '1'

fromBinary :: Int -> String -> Int
fromBinary m = foldl' (\n c -> 2 * n + fromBit c) 0

toBinary :: Integral a => Int -> a -> [Char]
toBinary m num =
    foldl' (\b k -> toBit (k `mod` 2):b) "" (take m $ iterate (`div` 2) num)

readInput :: IO (Int, [String])
readInput = do
    [n, m] <- map read . words <$> getLine
    (m, ) <$> (sequence $ replicate n getLine)

main :: IO ()
main = do
    t <- read <$> getLine
    replicateM_ t (uncurry binaryMedian <$> readInput >>= putStrLn)

import Data.Sequence (Seq, deleteAt, index, fromFunction)
import Data.Traversable (for)
import Data.Foldable (foldl', for_)
import Data.List (sort, unfoldr)

readBits :: String -> Int
readBits = foldl' (\x y -> case y of { '0' -> 2*x; '1' -> 2*x+1; _ -> error "bit" }) 0

toBits :: Int -> Int -> String
toBits k val = reverse . take k $ unfoldr step val  where
  step x = case  quotRem x 2  of
    (x', 0) -> Just ('0', x')
    (x', 1) -> Just ('1', x')
    _ -> error "overflow"

main :: IO ()
main = do
  print (maxBound :: Int)
  t <- read <$> getLine :: IO Int
  for_ [1..t] $ \_ -> do
    [n, k] <- (map read . words) <$> getLine :: IO [Int]
    let tot = 2 ^ k :: Integer
        tot' = fromInteger tot :: Int
    if  tot > fromIntegral (maxBound :: Int)
      then  error "too big? ask for 64-bit Int"
      else  return ()
    removalList <- for [1..n] $ \_ -> readBits <$> getLine
    let rl = reverse $ sort removalList :: [Int]
        startSeq = fromFunction tot' id :: Seq Int
        whatsLeft = foldl' (flip deleteAt) startSeq rl :: Seq Int
        ix = div (tot' - length rl - 1) 2
        tar = index whatsLeft ix
    putStrLn (toBits k tar)


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

mf n = head [i|i<-[2..n], mod n i ==0]
ans 0 n = n
ans k n | even n = n+k*2
	| otherwise = (n+(mf n)) +(k-1)*2

onecase = do
		[n,k]<-map read <$> words <$> getLine ::IO [Int]
		print $  ans k n

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

import qualified Data.List as L
import qualified Data.Map as M
import Data.Map (Map)
import qualified Data.Set as S
import Data.Set (Set)
import qualified Data.IntSet as IS
import Data.IntSet (IntSet)
import qualified Data.IntMap as IM
import Data.IntMap (IntMap)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)

type Long = Int

smallestDivisor :: Int -> Int
smallestDivisor n =
    case L.find (\d -> n `mod` d == 0) [2..1001] of
        Nothing -> n
        Just d -> d

solve :: Int -> Int -> Int
solve n 1 = n + smallestDivisor n
solve n k = (2*k-2) + n + smallestDivisor n

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    (n:k:_) <- readWords
    print $ solve n k
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readWords
    testCases t

readWords :: (Read a) => IO [a]
readWords = map read . words <$> getLine

import Data.Map as M
import Data.List as L

smallerDiv :: Integer -> Integer
smallerDiv n = head $ L.filter (\x -> mod n x == 0) [2..]

fun :: Integer -> Integer -> Integer
fun k n
  | even n = n+2*k
  | otherwise = fun (k-1) (n+smallerDiv n)

parseInput :: String -> (Integer, Integer)
parseInput raw = (n, k)
                  where n = read n' :: Integer
                        k = read k' :: Integer
                        [n', k'] = words raw

solve :: String -> String
solve input = show (fun k n)
  where (n, k) = parseInput input

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

import Control.Monad

f :: Int -> Int -> Int
f n k
  | even n = n+2*k
  | odd n = n+2*(k-1)+head (filter (\x -> mod n x == 0) [3,5..])

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [n,k] <- map read . words <$> getLine
    print $ f n k

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

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

solve :: Int -> Int -> Int
solve n k
  | odd n = solve (n+sm) (k-1)
  | even n = n+2*k
  | otherwise = error "Lol"
  where
    sm = head $ filter (\x -> n `mod` x == 0) [2..]

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

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

solve :: Int -> Int -> Int
solve n k
  | odd n = solve (n+sm) (k-1)
  | even n = n+2*k
  | otherwise = error "Lol"
  where
    sm = head $ filter (\x -> x `mod` n == 0) [2..]

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

mf n = head [i|i<-[2..n], mod n i ==0]
ans 0 n = n
ans k n | even n = n+k*2
	| otherwise = (n*2) +(k-1)*2

onecase = do
		[n,k]<-map read <$> words <$> getLine ::IO [Int]
		print $  ans k n

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


-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections, NoMonomorphismRestriction #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad
import Control.Monad.ST

import Data.Bits
import Data.Char
import Data.Either
import Data.Function
import Data.IORef
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Tuple

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

import Debug.Trace
import Text.Printf
-- }}}
-- silly utilities {{{
(#) = flip ($)
infixl 0 #

glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)

(!>) :: Seq a -> Int -> a
(!>) = Seq.index
-- }}}
-- input and output {{{
inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

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

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

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

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

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

fi = fromIntegral

main :: IO ()
main = do
	[n, pop] <- inputIntegers
	cities <- replicateM (fi n) $ do
		[x, y, pop] <- inputIntegers
		return (sqrt ((fi x) ** 2 + (fi y) ** 2), pop)
	let x = listToMaybe . dropWhile (\(_,p) -> p < 10^6) . scanl (\(r1,p1) (r2,p2) -> (r2,p1+p2)) (0,fi pop) $ sort cities
	case x of
		Just (r,_) -> print r
		Nothing -> print (-1)

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

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

main = do
  [n, s] <- readInts
  ls <- replicateM n readInts
  let
    binary_search :: Float -> Float -> Int -> Float
    binary_search _ ub 100 = ub
    binary_search lb ub depth = if can mid then binary_search lb mid (depth+1)else binary_search mid ub (depth+1)
      where
        mid = (lb+ub) / 2
    can r = total >= 1000000
      where
        total = s + (sum $ map (\[x,y,p] -> if doesContain x y r then p else 0) ls)
    doesContain x y r = x'*x' + y'*y' <= r*r
      where
        x' = fromIntegral x
        y' = fromIntegral y
    result = binary_search 0 14200 0
    in putStrLn $ if result > 14150 then "-1" else printf "%.7f" result

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main :: IO ()
main = do
  [n, s] <- map read.words <$> getLine :: IO [Int]
  xyks <- parse.map readInt.B.words <$> B.getContents
  if isValid s xyks then print $ solve s [(rr,k)|(x,y,k)<-xyks,let !rr=fi x*fi x+fi y*fi y]
  else print (-1)

fi :: Int -> Int64
fi = fromIntegral

isValid :: Int -> [(Int,Int,Int)] -> Bool
isValid s xyks= s + sum[k|(_,_,k)<-xyks] >= 1000000

parse :: [Int] -> [(Int,Int,Int)]
parse (x:y:k:xyks) = (x,y,k) : parse xyks
parse _ = []

solve :: Int -> [(Int64,Int)] -> Double
solve s rrks = sqrt.fromIntegral $ lowerBound p 0 $ fst $ maximum rrks
   where
     p rr = s + sum[k|(rr',k)<-rrks,rr'<=rr] >= 1000000

lowerBound :: (Integral i) => (i -> Bool) -> i -> i -> i
lowerBound p low high = go low high
   where
     go !low !high
       | high <= low = high
       | p mid       = go low       mid
       | otherwise   = go (mid + 1) high
      where
        mid = (low + high) `quot` 2
{-# INLINE lowerBound #-}


import Control.Monad (replicateM_, guard)
import Data.List (intercalate)

genElems :: Int -> [a] -> [a]
genElems n = take n . concat . repeat

appendColumn :: [a] -> [[a]] -> [[a]]
appendColumn = zipWith (:)

evenMatrix :: (Int, Int, Int) -> [[Char]]
evenMatrix (n, m, k) = go (n, m, k) "xy" where
  go (0, _, _) _ = []
  go (n, m, remHorz)  vertChars = (r1 ++ c1) : (r2 ++ c2) : next where
    numHorz = if remHorz >= m then m else remHorz
    numVert = m - numHorz
    nextVertChars = if vertChars == "xy" then "ij" else "xy"
    r1 = genElems numHorz "aabb"
    r2 = genElems numHorz "ccdd"
    c1 = genElems numVert nextVertChars
    c2 = genElems numVert nextVertChars
    next = go (n - 2, m, remHorz - numHorz) nextVertChars

solve :: (Int, Int, Int) -> Maybe [[Char]]
solve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems m "aabb"]
solve (n, 1, k) = do guard $ k == 0 ; return $ genElems n ["p", "p", "q", "q"]
solve (n, m, k)
  | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)
  | odd m = do
      let x = (n * m) `div` 2 - k - n `div` 2
      guard $ x >= 0 && even x
      let col = genElems n "ppqq" ; mat = evenMatrix (n, m - 1, k)
      return $ appendColumn col mat
  | otherwise = do
      let x = k - m `div` 2
      guard $ x >= 0 && even x
      return $ genElems m "eeff" : evenMatrix (n - 1, m, k - m `div` 2)

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, m, k] <- readInts
    let mat = solve (n, m, k)
    putStrLn $ maybe "NO" (intercalate "\n" . ("YES":)) mat

import Control.Arrow ((>>>))
import Data.Bool (bool)
import Control.Monad (guard)
import Data.List (intercalate)

main :: IO ()
main =
  interact $
    lines
      >>> drop 1
      >>> map (words >>> map read >>> solve >>> maybe "NO" (intercalate "\n" . ("YES":)))
      >>> unlines

type Sol = Maybe [[Char]]

solve :: [Int] -> Sol
solve [0, _, 0] = Just []
solve [0, _, _] = Nothing
solve [n, m, k]
  | n == 2 = do
      guard $ k <= n * m'
      guard $ even k
      let rowH0 = stream k "aabb"
      let rowH1 = stream k "ccdd"
      let rowV = stream (m - k) "pq"
      return [rowH0 ++ rowV, rowH1 ++ rowV]
  | even n = do
      guard $ k <= n * m'
      guard $ even k
      let pick = min k (2 * m')
      top <- conv <$> solve [2, m, pick]
      rest <- solve [n - 2, m, k - pick]
      return $ top ++ rest
  | odd n = do
      guard $ k >= m'
      g <- solve [n - 1, m, k - m']
      let top = stream m "yyzz"
      return $ top : g
  where
    m' = m `div` 2
    stream l = take l . concat . repeat
    conv = if n `mod` 4 == 2 then id else map (map change)
    change 'p' = 'r'
    change 'q' = 's'
    change c = c

import Control.Monad (replicateM_, guard)
import Data.List (intercalate)

genElems :: Int -> [a] -> [a]
genElems n = take n . concat . repeat

appendColumn :: [a] -> [[a]] -> [[a]]
appendColumn = zipWith (:)

evenMatrix :: (Int, Int, Int) -> [[Char]]
evenMatrix (n, m, k) = go (n, m, k) "xy" where
  go (0, _, _) _ = []
  go (n, m, remHorz)  vertChars = (r1 ++ c1) : (r2 ++ c2) : next where
    numHorz = if remHorz >= m then m else remHorz
    numVert = m - numHorz
    nextVertChars = if vertChars == "xy" then "ij" else "xy"
    r1 = genElems numHorz "aabb"
    r2 = genElems numHorz "ccdd"
    c1 = genElems numVert nextVertChars
    c2 = genElems numVert nextVertChars
    next = go (n - 2, m, remHorz - numHorz) nextVertChars

solve :: (Int, Int, Int) -> Maybe [[Char]]
solve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k "aabb"]
solve (n, 1, k) = do guard $ k == 0 ; return $ genElems n ["p", "p", "q", "q"]
solve (n, m, k)
  | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)
  | odd m = do
      let x = (n * m) `div` 2 - k - n `div` 2
      guard $ x >= 0 && even x
      let col = genElems n "ppqq" ; mat = evenMatrix (n, m - 1, k)
      return $ appendColumn col mat
  | otherwise = do
      let x = k - m `div` 2
      guard $ x >= 0 && even x
      return $ genElems m "eeff" : evenMatrix (n - 1, m, k - m `div` 2)

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, m, k] <- readInts
    let mat = solve (n, m, k)
    putStrLn $ maybe "NO" (intercalate "\n" . ("YES":)) mat

import Control.Monad (replicateM_, guard)
import Data.List (intercalate)

genElems :: Int -> [a] -> [a]
genElems n = take n . concat . repeat

appendColumn :: [a] -> [[a]] -> [[a]]
appendColumn = zipWith (:)

evenMatrix :: (Int, Int, Int) -> [[Char]]
evenMatrix (n, m, k) = go (n, m, k) "xy" where
  go (0, _, _) _ = []
  go (n, m, remHorz)  vertChars = (r1 ++ c1) : (r2 ++ c2) : next where
    numHorz = if remHorz >= m then m else remHorz
    numVert = m - numHorz
    nextVertChars = if vertChars == "xy" then "ij" else "xy"
    r1 = genElems numHorz "aabb"
    r2 = genElems numHorz "ccdd"
    c1 = genElems numVert nextVertChars
    c2 = genElems numVert nextVertChars
    next = go (n - 2, m, remHorz - numHorz) nextVertChars

solve :: (Int, Int, Int) -> Maybe [[Char]]
solve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k "aabb"]
solve (n, 1, k) = do guard $ k == 0 ; return $ genElems n ["p", "p", "q", "q"]
solve (n, m, k)
  | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)
  | odd m = do
      guard $ even $ (n * m) `div` 2 - k - n `div` 2
      let col = genElems n "ppqq" ; mat = evenMatrix (n, m - 1, k)
      return $ appendColumn col mat
  | otherwise = do
      guard $ even $ k - m `div` 2
      return $ genElems m "eeff" : evenMatrix (n - 1, m, k - m `div` 2)

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, m, k] <- readInts
    let mat = solve (n, m, k)
    putStrLn $ maybe "NO" (intercalate "\n" . ("YES":)) mat

import Control.Monad (replicateM_, guard)
import Data.List (intercalate)

genElems :: Int -> [a] -> [a]
genElems n = take n . concat . repeat

appendColumn :: [a] -> [[a]] -> [[a]]
appendColumn = zipWith (:)

evenMatrix :: (Int, Int, Int) -> [[Char]]
evenMatrix (n, m, k) = go (n, m, k) "xy" where
  go (0, _, _) _ = []
  go (n, m, remHorz)  vertChars = (r1 ++ c1) : (r2 ++ c2) : next where
    numHorz = if remHorz >= m then m else remHorz
    numVert = m - numHorz
    nextVertChars = if vertChars == "xy" then "ij" else "xy"
    r1 = genElems numHorz "aabb"
    r2 = genElems numHorz "ccdd"
    c1 = genElems numVert nextVertChars
    c2 = genElems numVert nextVertChars
    next = go (n - 2, m, remHorz - numHorz) nextVertChars

solve :: (Int, Int, Int) -> Maybe [[Char]]
solve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k "aabb"]
solve (n, 1, k) = do guard $ k == 0 ; return $ genElems n ["p", "p", "q", "q"]
solve (n, m, k)
  | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)
  | odd m = do
      guard $ even $ (n * m) `div` 2 - k - n `div` 2
      let col = genElems n "ppqq" ; mat = evenMatrix (n, m - 1, k)
      return $ appendColumn col mat
  | otherwise = do
      guard $ even $ k - m `div` 2
      return $ genElems m "eeff" : evenMatrix (n - 1, m, k)

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, m, k] <- readInts
    let mat = solve (n, m, k)
    putStrLn $ maybe "NO" (intercalate "\n" . ("YES":)) mat

import Control.Monad (replicateM_, guard)
import Data.List (intercalate)

genElems :: Int -> [a] -> [a]
genElems n = take n . concat . repeat

appendColumn :: [a] -> [[a]] -> [[a]]
appendColumn = zipWith (:)

evenMatrix :: (Int, Int, Int) -> [[Char]]
evenMatrix (n, m, k) = go (n, m, k) "xy" where
  go (0, _, _) _ = []
  go (n, m, remHorz)  vertChars = (r1 ++ c1) : (r2 ++ c2) : next where
    numHorz = if remHorz >= m then m else remHorz
    numVert = m - numHorz
    nextVertChars = if vertChars == "xy" then "ij" else "xy"
    r1 = genElems numHorz "aabb"
    r2 = genElems numHorz "ccdd"
    c1 = genElems numVert nextVertChars
    c2 = genElems numVert nextVertChars
    next = go (n - 2, m, remHorz - numHorz) nextVertChars

solve :: (Int, Int, Int) -> Maybe [[Char]]
solve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k "aabb"]
solve (n, 1, k) = do guard $ k == 0 ; return $ genElems n ["p", "q"]
solve (n, m, k)
  | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)
  | odd m = do
      guard $ even $ (n * m) `div` 2 - k - n `div` 2
      let col = genElems n "pq" ; mat = evenMatrix (n, m - 1, k)
      return $ appendColumn col mat
  | otherwise = do
      guard $ even $ k - m `div` 2
      return $ genElems m "eeff" : evenMatrix (n - 1, m, k)

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, m, k] <- readInts
    let mat = solve (n, m, k)
    putStrLn $ maybe "NO" (intercalate "\n" . ("YES":)) mat

import Control.Arrow ((>>>))
import Data.Bool (bool)
import Control.Monad (guard)

main :: IO ()
main =
  interact $
    lines
      >>> drop 1
      >>> map (words >>> map read >>> solve >>> maybe "NO" (unlines . ("YES":)))
      >>> unlines

type Sol = Maybe [[Char]]

solve :: [Int] -> Sol
solve [0, _, 0] = Just []
solve [0, _, _] = Nothing
solve [n, m, k]
  | n == 2 = do
      guard $ k <= n * m'
      guard $ even k
      let rowH0 = stream k "aabb"
      let rowH1 = stream k "ccdd"
      let rowV = stream (m - k) "pq"
      return [rowH0 ++ rowV, rowH1 ++ rowV]
  | even n = do
      guard $ k <= n * m'
      guard $ even k
      let pick = min k (2 * m')
      top <- conv <$> solve [2, m, pick]
      rest <- solve [n - 2, m, k - pick]
      return $ top ++ rest
  | odd n = do
      guard $ k >= m'
      g <- solve [n - 1, m, k - m']
      let top = stream m "yyzz"
      return $ top : g
  where
    m' = m `div` 2
    stream l = take l . concat . repeat
    conv = if n `mod` 4 == 2 then id else map (map change)
    change 'p' = 'r'
    change 'q' = 's'
    change c = c


module Main where

readInt :: IO Int
readInt = readLn

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

solve :: Int -> IO ()
solve 0 = return ()
solve t = do n <- readInt
             ns <- readInts
             let ans = maximum ns - minimum ns in
               print ans
             solve (t - 1)

main :: IO ()
main = do t <- readInt
          solve t

import Control.Monad

solve = do
  n <- readLn :: IO Int
  str <- getLine

  let as = map (read :: String -> Int) (words str)

  print (maximum as - minimum as)

main = do
  t <- readLn :: IO Int

  replicateM_ t solve

import Control.Monad(replicateM)
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Builder.Prim as Prim
import Data.ByteString.Builder
import Control.Monad.Trans.State
import Data.Maybe
import System.IO

solve :: SB Builder
solve = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n]  <- getInts 1
    xs    <- getInts n
    return $ putInts [maximum xs - minimum xs]

-- stdin/out from solution by clyring
type SB = State [B.ByteString]

getNext :: Int -> SB [B.ByteString]
getNext = state . splitAt

parseInt = fst . fromJust . B.readInt

getInts :: Int -> SB [Int]
getInts n = map parseInt <$> getNext n

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 <- B.getContents
  let  out = evalState solve $ B.words inp
  B.putStr $ toLazyByteString out

import Control.Monad(replicateM)
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Builder.Prim as Prim
import Data.ByteString.Builder
import Control.Monad.Trans.State
import Data.Maybe
import System.IO

solve :: SB Builder
solve = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n]  <- getInts 1
    xs    <- getInts n
    return $ putInts [maximum xs - minimum xs]

-- stdin/out from solution by clyring
type SB = State [B.ByteString]

getNext :: Int -> SB [B.ByteString]
getNext = state . splitAt

getInts :: Int -> SB [Int]
getInts n = map parseInt <$> getNext n
  where
    parseInt = fst . fromJust . B.readInt

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 <- B.getContents
  let  out = evalState solve $ B.words inp
  B.putStr $ toLazyByteString out

import Control.Monad(replicateM_)

solve :: [Int] -> Int
solve xs = max - min
  where
    max = maximum xs
    min = minimum xs

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    getLine
    xs  <- readInts
    let ans = solve xs
    print ans

-- https://codeforces.com/contest/1624/problem/A
import Control.Monad (replicateM_)

main = getLine >>= flip replicateM_ run . read
run = do
    getLine
    a <- (read <$>) . words <$> getLine
    print $ maximum a - minimum a

import Control.Monad()
import Data.List()

solve [] = 0
solve lst = maximum lst - minimum lst

rep 0 = return ()
rep x = do
    n <- getLine
    arr <- getLine
    let intList = map (read::String->Int) (words arr)
    print(solve intList)
    rep (x - 1)

main :: IO ()
main = do
    t <- getLine
    rep (read t)

import Control.Monad
import Data.List

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    n <- readLn
    a <- map read . words <$> getLine
    print $ solve n a

solve :: Integer -> [Integer] -> Integer
solve _ a = sum $ zipWith subtract a' (tail a')
  where
    a' = sort a

main = readLn >>= sequence_ . flip replicate (getLine >> getLine >>= print . ((-) <$> maximum <*> minimum) . map read . words)

readInt :: IO Int
readInt = readLn

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

main :: IO ()
main = do
    test <- readInt
    solve test

solve :: Int -> IO ()
solve 0 = pure ()
solve test = do
    n <- readInt
    dt <- readIntArray
    print $ maximum dt - minimum dt
    solve $ test - 1

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf i xs = take i xs : chunksOf i (drop i xs)

toArr :: Read a => String -> [a]
toArr = map read . words

type InType  = [Int]
type OutType = Int

solve :: InType -> OutType
solve xs = maximum xs - minimum xs

receive :: [String] -> InType
receive [_, s] = toArr s
receive x = error  "wrong input"

main :: IO ()
main = interact $ unlines . map (show . solve . receive) . chunksOf 2 . tail . lines

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

prefMins :: Ord t => (a -> t) -> [a] -> [t]
prefMins f li = tail $ scanl' min (f $ head li) $ map f li

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    a <- getInts n
    let
      b = sort a
      z = last b - head b
    pure $ putInts [z]

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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 $ P.words inp
  P.putStr $ toLazyByteString outp

import Data.Char
main :: IO()
main = do
    -- print 5
    tStr <- getLine
    -- print $ show tStr
    let t = read tStr :: Int
    solve t

solve :: Int -> IO()
solve 0 = return ()
solve t = do
    nStr <- getLine
    -- print nStr
    let n = read nStr :: Int

    aStr <- getLine
    -- print aStr
    let as = readIntList aStr  :: [Int]

    -- print as

    print (maxVal as - minVal as)
    solve (t-1)

readIntList :: String -> [Int]
readIntList [] = []
readIntList (h : t)
    | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)
    | otherwise = readIntList t

maxVal :: [Int] -> Int
maxVal = foldr max 0

minVal :: [Int] -> Int
minVal = foldr min 1000000000

module Main where

import           Control.Monad (replicateM_)

main = do
  t <- read <$> getLine
  replicateM_ t
    $ do
      n <- getLine
      xs <- map read . words <$> getLine
      print (maximum xs - minimum xs)

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] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    a <- getInts n
    pure $ putInts [maximum a - minimum a]

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

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 $ P.words inp
  P.putStr $ toLazyByteString outp

-- https://codeforces.com/contest/1624/problem/A
-- A. Plus One on the Subset
import qualified Data.List as L
import System.IO
import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder.Prim as Prim
import Data.ByteString.Builder

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'

handleData1 [] = []
handleData1 intss = do
	let
		ints = head intss
		maxi = L.maximum ints
		mini = L.minimum ints
		in (maxi - mini) : (handleData1 (tail intss))

-- read_intss :: Int -> IO ([[Int]])
read_intss 0 = do return []
read_intss ints_count = do
	int_count_str <- getLine
	ints_str <- getLine
	last_intss <- read_intss (ints_count-1)
	let now_inst =map (\x -> read x :: Int) $ words ints_str
		in return (now_inst : last_intss)

main = do
	hSetBuffering stdout NoBuffering
	data_count_str <- getLine
	intss <- read_intss $ read $ data_count_str
	-- putStrLn $ L.intercalate "\n" $ putInts $ handleData1 intss
	P.putStr $ toLazyByteString $ putInts $ handleData1 intss

-- https://codeforces.com/contest/1624/problem/A
-- A. Plus One on the Subset
import qualified Data.List as L

handleData1 [] = []
handleData1 intss = do
	let
		ints = head intss
		maxi = L.maximum ints
		mini = L.minimum ints
		in (show (maxi - mini)) : (handleData1 (tail intss))

-- read_intss :: Int -> IO ([[Int]])
read_intss 0 = do return []
read_intss ints_count = do
	int_count_str <- getLine
	ints_str <- getLine
	last_intss <- read_intss (ints_count-1)
	let now_inst =map (\x -> read x :: Int) $ words ints_str
		in return (now_inst : last_intss)

main = do
	data_count_str <- getLine
	intss <- read_intss $ read $ data_count_str
	putStrLn $ L.intercalate "\n" $ handleData1 intss

import System.IO
import qualified Data.List as L

handleData1 0 = do return ()
handleData1 dataCount = do
	int_count_str <- getLine
	ints_str <- getLine
	let ints = map (\x -> read x :: Int) $ words ints_str
		in print $ (L.maximum ints) - (L.minimum ints)
	handleData1 (dataCount-1)

main = do
	data_count_str <- getLine
	let data_count = read data_count_str
		in handleData1 data_count

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

import Data.Maybe
import Control.Monad

solve = do
  nStr <- B.getLine
  asStr <- B.getLine

  let n = fst $ fromJust $ C.readInt nStr
  let as = map (fst . fromJust . C.readInt) (C.words asStr)

  print (maximum as - minimum as)

main = do
  str <- B.getLine

  let t = fst $ fromJust $ C.readInt str

  replicateM_ t solve

import Control.Monad
import System.IO

solve = do
  n <- readLn :: IO Int
  str <- getLine

  let as = map (read :: String -> Int) (words str)

  print (maximum as - minimum as)

main :: IO()
main = do
  hSetBuffering stdout LineBuffering

  t <- readLn :: IO Int

  replicateM_ t solve

-- https://codeforces.com/contest/1624/problem/A
import Control.Monad (replicateM_)
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)

main = getLine >>= flip replicateM_ run . read
run = do
    getLine
    a <- (fst.fromJust.B.readInt <$>) . B.words <$> B.getLine
    print $ maximum a - minimum a

-- https://codeforces.com/contest/1624/problem/A
import Control.Monad (replicateM_)
import Data.Maybe (fromJust)
import qualified Data.ByteString.Char8 as B

main = getLine >>= flip replicateM_ run . read
run = do
    getLine
    a <- (fst.fromJust.B.readInt <$>) . B.words <$> B.getLine
    print $ maximum a - minimum a


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.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
import Data.Array.Unboxed
import Data.Int
import qualified Data.Map.Strict as M

binSearch :: (Int -> Bool) -> Int -> Int -> Int
binSearch fun = go  where
  go x y = if x == y
    then  x
    else  let  m = x + div (y - x) 2
    in  if  fun m
    then  go x m
    else  go (m+1) y

getIx :: UArray Int Int -> Int -> Int
getIx arr val = let
  (p, q) = bounds arr
  in  binSearch (\i -> arr ! i >= val) p $ q + 1

solve :: UArray Int Int -> UArray Int Int -> [(Int, Int)] -> Int64
solve xs ys ps = let
  (1, n) = bounds xs
  (1, m) = bounds ys
  interest :: [(Bool, Int, Int)]
  interest = do
    (xp, yp) <- ps
    let  [xix, yix] = zipWith getIx [xs, ys] [xp, yp]
    case  (xp == xs ! xix, yp == ys ! yix)  of
      (True, True) -> []
      (False, True) -> [(False, xix, yix)]
      (True, False) -> [(True, xix, yix)]
      _ -> error "invalid input"
  uff :: M.Map (Bool, Int, Int) Int
  uff = M.fromListWith (+) $ zip interest $ repeat 1
  rows :: UArray Int Int
  rows = accumArray (+) 0 (1, n)
    $ [(xix, 1) | (False, xix, _) <- interest]
  cols :: UArray Int Int
  cols = accumArray (+) 0 (1, m)
    $ [(yix, 1) | (True,  _, yix) <- interest]
  w2 x = let
    x64 = fromIntegral x
    in  x64 * (x64 - 1)
  in  (`div` 2) $ foldl' (+) 0 $ map w2 (concatMap elems [rows, cols])
      ++ do
  (_k, ct) <- M.toList uff
  pure $ negate (w2 ct)

mainFun :: SO
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n, m, k] <- getInts 3
    xs <- listArray (1, n) <$> getInts n
    ys <- listArray (1, m) <$> getInts m
    ps <- replicateM k $ do
      ~[xp, yp] <- getInts 2
      pure (xp, yp)
    pure $ putInt64s [solve xs ys ps]

type SP = State [P.ByteString]
type SO = SP Builder

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

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

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

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE Strict #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Function
import Data.Int
import qualified Data.IntMap as M
import qualified Data.IntSet as S
import Data.List
import Data.Maybe
import Data.Tuple (swap)
import Debug.Trace (trace)

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines

type PII = (Int, Int)
type Input = ([Int], [Int], [PII])
type Output = Int64

input :: Scanner Input
input = do
  n <- int
  m <- int
  k <- int
  xs <- n >< int
  ys <- m >< int
  ps <- k >< pair int int
  return (xs, ys, ps)

output :: Output -> C.ByteString
output = showB

solve :: Input -> Output
solve (S.fromList -> xs, S.fromList -> ys, ps) = compute ps xs ys + compute (map swap ps) ys xs

compute :: [PII] -> S.IntSet -> S.IntSet -> Int64
compute ps xs ys = fst $ foldl update (0, (0, M.empty)) ps'
  where
    ps' = sort $ [(x, -1) | x <- S.elems xs] ++ [(x, y) | (x, y) <- ps, S.notMember x xs]

    update (acc, (prv, m)) (x, -1) = (acc, (0, M.empty))
    update (acc, (prv, m)) (x, y) = (acc + prv - find y m, (prv + 1, incr y m))

    find y = fromMaybe 0 . M.lookup y
    incr y = M.insertWith (+) y 1

fi = fromIntegral

-- debug a = trace (show a) a
-- debugS v a = trace (v ++ " = " ++ show a) a
debug = id
debugS _ = id

-------------------------- Template ------------------------------------------
-- Lists
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn = groupBy . on (==)

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

adjacents :: [a] -> [(a, a)]
adjacents xs = zip xs (tail xs)

adjacentsWith :: (a -> a -> b) -> [a] -> [b]
adjacentsWith f xs = zipWith f xs (tail xs)

count :: Eq a => a -> [a] -> Int
count = countBy . (==)

countBy :: (a -> Bool) -> [a] -> Int
countBy p = length . filter p

-- Scanner
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

bstr :: Scanner C.ByteString
bstr = get >>= \case s : ss -> put ss >> return s

str :: Scanner String
str = C.unpack <$> bstr

readStr :: Read a => Scanner a
readStr = read <$> str

int :: Scanner Int
int = fst . fromJust . C.readInt <$> bstr

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t
    then return []
    else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Function
import Data.Int
import qualified Data.IntMap as M
import qualified Data.IntSet as S
import Data.List
import Data.Maybe
import Data.Tuple (swap)
import Debug.Trace (trace)

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines

type PII = (Int, Int)
type Input = ([Int], [Int], [PII])
type Output = Int64

input :: Scanner Input
input = do
  n <- int
  m <- int
  k <- int
  xs <- n >< int
  ys <- m >< int
  ps <- k >< pair int int
  return (xs, ys, ps)

output :: Output -> C.ByteString
output = showB

solve :: Input -> Output
solve (S.fromList -> xs, S.fromList -> ys, ps) = compute ps xs ys + compute (map swap ps) ys xs

compute :: [PII] -> S.IntSet -> S.IntSet -> Int64
compute ps xs ys = fst $ foldl update (0, (0, M.empty)) ps'
  where
    ps' = sort $ [(x, -1) | x <- S.elems xs] ++ [(x, y) | (x, y) <- ps, S.notMember x xs]

    update (acc, (prv, m)) (x, -1) = (acc, (0, M.empty))
    update (acc, (prv, m)) (x, y) = (acc + prv - find y m, (prv + 1, incr y m))

    find y = fromMaybe 0 . M.lookup y
    incr y = M.insertWith (+) y 1

fi = fromIntegral

-- debug a = trace (show a) a
-- debugS v a = trace (v ++ " = " ++ show a) a
debug = id
debugS _ = id

-------------------------- Template ------------------------------------------
-- Lists
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn = groupBy . on (==)

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

adjacents :: [a] -> [(a, a)]
adjacents xs = zip xs (tail xs)

adjacentsWith :: (a -> a -> b) -> [a] -> [b]
adjacentsWith f xs = zipWith f xs (tail xs)

count :: Eq a => a -> [a] -> Int
count = countBy . (==)

countBy :: (a -> Bool) -> [a] -> Int
countBy p = length . filter p

-- Scanner
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

bstr :: Scanner C.ByteString
bstr = get >>= \case s : ss -> put ss >> return s

str :: Scanner String
str = C.unpack <$> bstr

readStr :: Read a => Scanner a
readStr = read <$> str

int :: Scanner Int
int = fst . fromJust . C.readInt <$> bstr

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t
    then return []
    else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show

import Control.Monad
import Data.Function
import Data.Int
import Data.List
import Data.Maybe
import Data.Tuple
import qualified Data.ByteString.Char8 as C
import qualified Data.IntSet as IS

solve :: IO ()
solve = do
    [n, m, k] <- readInts
    xs <- IS.fromList <$> readInts
    ys <- IS.fromList <$> readInts
    pts <- replicateM k $ (\[x, y] -> (x, y)) <$> readInts
    let ways xs = sum $ zipWith (*) xs $ scanl (+) 0 xs :: Int64
        go xs pts =
            sum $ map (ways . map (fromIntegral . length) . group . sort . map snd) $
            groupBy ((==) `on` fst) $ sort $
            [(l, y) | pt@(x, y) <- pts, let l = fromJust $ IS.lookupLE x xs, l /= x]
    print $ go xs pts + go ys (map swap pts)

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

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


main = do [n, m, k] <- (map read . words) `fmap` getLine
          print $ solve n m k

solve n m k | n+k < m = 0.0
            | k >= m  = 1.0
            | otherwise = 1.0 - product [(m-k+i) / (n+k-i+1) | i <-[0.0..k]]

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

main :: IO ()
main = getLine >>= solve

solve :: String -> IO ()
solve = do
  [n, m, k] <- map read . words
  return . printf "%f\n" $ p n m k

p :: Integer -> Integer -> Integer -> Double
p n m k
  | m <= k    = 1
  | n + k < m = 0
  | otherwise = 1 - fromRational (a % b)
 where a = product [m - k .. m]
       b = product [n + 1 .. n + k + 1]

main :: IO()
main = interact work

work :: String -> String
work input = show $ solve n m k
    where [n, m, k] = map (\i -> read i :: Int) . words $ input

solve :: Int -> Int -> Int -> Double
solve n m k = max 0 (1 - product [fromIntegral (m - i) / fromIntegral (n + i + 1) | i <- [0..k]])

main = do
    [n,m,k] <- fmap (map read . words) getLine :: IO [Int]
    print $ 1.0 - if n + k - m < 0 then 1.0 else f m n k where
        f m n k
            | k == 0 = fromIntegral m / fromIntegral (n + 1)
            | otherwise = fromIntegral (m - k) / fromIntegral (n + k + 1) * (f m n $ k - 1)

main = do
    [n,m,k] <- fmap (map read . words) getLine :: IO [Int]
    print $ 1.0 - f m n k where
        f m n 0 = fromIntegral m / fromIntegral (n + 1)
        f m n k = fromIntegral (m - k) / fromIntegral (n + k + 1) * (f m n $ k - 1)

main = do
    [n,m,k] <- fmap (map read . words) getLine :: IO [Int]
    print $ 1.0 - f m n k where
        f m n k
            | n + k - m < 0 = 0
            | k == 0 = fromIntegral m / fromIntegral (n + 1)
            | otherwise = fromIntegral (m - k) / fromIntegral (n + k + 1) * (f m n $ k - 1)