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

solve :: [Int] -> String
solve [1, 0]  =  "0"
solve [_, 0]  =  "No solution"
solve [k, d]  =  show d ++ replicate (k-1) '0'

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

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

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

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

main = do
	[ k, d ] <- map read . words <$> getLine
	putStrLn $ if d == 0 && 1 < k
		then "No solution"
		else show d ++ replicate ( k - 1 ) '0'

import Control.Applicative
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let k = inp !! 0
        d = inp !! 1
    if d == 0 && k > 1
        then putStrLn $ "No solution"
        else putStrLn $ show d ++ replicate (k-1) '0'

import Data.Functor

main = do
     [k,d] <- (map read) <$> (words <$> getLine) :: IO [Int]
     putStrLn $ solve k d
     return ()

solve k d
      | 1<k && d==0 = "No solution"
      | otherwise   = show d ++ replicate (k-1) '0'

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

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

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

main = do
  [k, d] <- getInts
  putStrLn $ if d == 0 && k /= 1 then "No solution" else show d ++ replicate (k-1) '0'

import Data.Char

solve :: Int -> Int -> String

solve d k = (replicate (k-1) '1')  ++ [ intToDigit d0 ]
  where d0 = head [ d0 | d0 <- [0..9], dr ((k-1)+d0) == d ]

dr :: (Show a, Integral a) => a -> Int
dr n | n < 10 = fromIntegral n
     | otherwise = dr $ sum $ map digitToInt $ show n

test d k = let n = solve d k in dr ((read n) :: Integer) == d

testAll = all (uncurry test) [ (d,k) | k <-  [1..1000], d <- [1..9] ]

solve' 0 1 = Just "0"
solve' 0 _ = Nothing
solve' d k = Just $ solve d k

main = do
  (k:d:_) <- fmap (map read . words) getLine
  case solve' d k of
    Nothing -> putStrLn "No solution"
    Just n  -> putStrLn n

#!/usr/bin/env runghc
import Data.List
main = do
  c <- getContents
  putStr . unlines . solve . lines $ c

solve::[String]->[String]
solve [] = []
solve (kd:cs) = (if k<2 || d/=0 then (replicate m (head $ show (n+1)) ++ replicate (k-m) (head $ show n)) else "No solution"): solve cs
  where
    [k,d] = map read . words $ kd
    (n,m) = d `divMod` k

minNum k n
	| n == 0 && k == 1 = 0
	| n == 0 = -1
	| otherwise = (10 ^ (k-1) ) + (n-1)

find x
	| x>=0  = show x
	| otherwise = "No solution"

parse l = map read $ words l

cal fn kn = fn (head kn) (head $ tail kn)

main = do
	l <- getLine
	putStr $ find $ cal minNum $ parse l

import Control.Applicative
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let k = inp !! 0
        d = inp !! 1
    if d == 0 || k > 1
        then putStrLn $ "No solution"
        else putStrLn $ show d ++ replicate (k-1) '0'

import Control.Applicative
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let k = inp !! 0
        d = inp !! 1
    if d == 0
        then print 0
        else putStrLn $ show d ++ replicate (k-1) '0'

import Control.Applicative
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let k = inp !! 0
        d = inp !! 1
    if d == 0
        then putStrLn $ "No solution"
        else putStrLn $ show d ++ replicate (k-1) '0'

import Control.Applicative
main :: IO ()
main = do
    inp <- map read <$> words <$> getLine
    let k = inp !! 0
        d = inp !! 1
    putStrLn $ show d ++ replicate (k-1) '0'

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

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

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

main = do
  [k, d] <- getInts
  putStrLn $ show d ++ replicate (k-1) '0'

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

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

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

main = do
  [k, d] <- getInts
  putStrLn $ if d == 0 then "No solution" else show d ++ replicate (k-1) '0'

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

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

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

main = do
  [k, d] <- getInts
  putStrLn $ if d == 0 then show 0 else show d ++ replicate (k-1) '0'

#!/usr/bin/env runghc
import Data.List
main = do
  c <- getContents
  putStr . unlines . solve . lines $ c

solve::[String]->[String]
solve [] = []
solve (kd:cs) = (replicate m (head $ show (n+1)) ++ replicate (k-m) (head $ show n)): solve cs
  where
    [k,d] = map read . words $ kd
    (n,m) = (if k<2 || d/=0 then d else 10) `divMod` k

#!/usr/bin/env runghc
import Data.List
main = do
  c <- getContents
  putStr . unlines . solve . lines $ c

solve::[String]->[String]
solve [] = []
solve (kd:cs) = (replicate m (head $ show (n+1)) ++ replicate (k-m) (head $ show n)): solve cs
  where
    [k,d] = map read . words $ kd
    (n,m) = d `divMod` k

import Data.Char
sum' [] = 0
sum' (x:xs) = (digitToInt x) + (sum' xs)

dr n
	| s<10 =  s
	| otherwise = dr s
	where s = sum' $ show n

rg n = [10 ^ (n-1) .. 10^n]

minNum k n = filter (\x -> (dr x) == n) $ rg k

find [] = "No solution"
find (x:_) = show x

parse l = map read $ words l

cal fn kn = fn (head kn) (head $ tail kn)

main = do
	l <- getLine
	print $ find $ cal minNum $ parse l


solve :: Int -> [Int]
solve n = if even n
          then [n `div` 2, n `div` 2, 0]
          else [-1]

testCaseMain :: Int -> IO ()
testCaseMain t = do n <- (readLn :: IO Int)
                    putStrLn $ unwords $ map show $ solve n
                    if t > 1
                    then testCaseMain (t - 1)
                    else return ()

main :: IO ()
main = do t <- (readLn :: IO Int)
          testCaseMain t

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String
import qualified Data.ByteString.Char8 as C

type D = (String, String, String)

a110 :: D -> D
a110 (a, b, c) = ('1' : a, '1' : b, '0' : c)

a000 :: D -> D
a000 (a, b, c) = ('1' : a, '1' : b, '1' : c)

prIntegerAns :: D -> IO ()
prIntegerAns (a, b, c) = putStrLn $ unwords $ show <$> toDec <$> reverse <$> [a, b, c]

toBin :: Integer -> String
toBin a = reverse $ go a
  where
    go x
      | x == 0 = ""
      | odd x = '1' : go (x `div` 2)
      | otherwise = '0' : go (x `div` 2)

toDec :: String -> Integer
toDec = foldl (\acc x -> acc * 2 + fromIntegral (digitToInt x)) 0

solve :: Integer -> IO ()
solve x =
  -- print (x `div` 2, a) >>
  if odd x then do print (-1) else prIntegerAns (go a True ("", "", ""))
  where
    a = toBin $ x `div` 2
    go :: String -> Bool -> D -> D
    go "" _ x = x
    go ('0' : xs) b d = go xs b (a000 d)
    go (x : xs) True d = go xs False (a110 d)
    go (x : xs) False d = go xs False (a110 d)

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (solve =<< parseInteger <$> getLine)

module Main where

import Control.Monad (liftM2, replicateM_)
import Data.Bits
import Data.Char (digitToInt)
import Data.Maybe (fromJust)
import Data.String
import qualified Data.ByteString.Char8 as C

type D = (String, String, String)

a110 :: D -> D
a110 (a, b, c) = ('1' : a, '1' : b, '0' : c)

a001 :: D -> D
a001 (a, b, c) = ('1' : a, '0' : b, '1' : c)

a000 :: D -> D
a000 (a, b, c) = ('1' : a, '1' : b, '1' : c)

prIntegerAns :: D -> IO ()
prIntegerAns (a, b, c) = do
  -- print $ (a, b, c)
  -- print $ check (a, b, c)
  putStrLn $ unwords $ show <$> toDec <$> reverse <$> [a, b, c]

toBin :: Integer -> String
toBin a = reverse $ go a
  where
    go x
      | x == 0 = ""
      | odd x = '1' : go (x `div` 2)
      | otherwise = '0' : go (x `div` 2)

toDec :: String -> Integer
toDec = foldl (\acc x -> acc * 2 + fromIntegral (digitToInt x)) 0

solve :: Integer -> IO ()
solve x =
  -- print (x `div` 2, a) >>
  if odd x then do print (-1) else prIntegerAns (go a True ("", "", ""))
  where
    a = toBin $ x `div` 2
    go :: String -> Bool -> D -> D
    go "" _ x = x
    go ('0' : xs) b d = go xs b (a000 d)
    go (x : xs) True d = go xs False (a110 d)
    go (x : xs) False d = go xs False (a001 d)

parseInteger :: String -> Integer
parseInteger = fromIntegral . fst . fromJust . C.readInt . fromString

-- check' :: (Integer, Integer, Integer) -> Integer
-- check' (a, b, c) = (a `xor` b) + (b `xor` c) + (a `xor` c)

-- check :: D -> Integer
-- check (a, b, c) = check' (toDec $ reverse a, toDec $ reverse  b, toDec $ reverse c)

main :: IO ()
main = do
  n <- parseInteger <$> getLine
  replicateM_ (fromIntegral n) (solve =<< parseInteger <$> getLine)

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

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [n] <- ri
        return n
    mapM_ (putStrLn.showL.solve) tcs

showL = unwords . map show

solve n = ans
  where
    ans | n `mod` 2 /= 0  = [-1 :: Int]
        | otherwise       = [0, 0, n `div` 2]

--
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}

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

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

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

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Bifunctor (bimap)
import Data.Maybe (fromJust, fromMaybe, isJust)
import qualified Data.Maybe as MB

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List   as L
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Ix as Ix
import qualified Data.Ratio as R

import Control.Monad.Cont (MonadIO (liftIO))
import Data.IORef (modifyIORef, newIORef, readIORef)
import GHC.IO.Handle (hDuplicateTo)
import System.IO (
    IOMode (ReadMode, WriteMode),
    openFile,
    stdin,
    stdout,
    hFlush
 )
import System.Posix.Internals (puts)
import Text.Printf (printf)
import qualified Data.Array.IO.Safe as UOA

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace
--
-- tracing t x = trace (t ++ " = " ++ show x) x
-- debugging x t = tracing t x

-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

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

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

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

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "YES"
                else "NO"
    printf "%s\n" result

m :: Int64
m = 998_244_353

newtype M = M { unM :: Int64 }
  deriving (Eq, Ord)

mI :: Int -> M
mI = M . fromIntegral

instance Show M where
    show (M v) = "M" ++ show v

instance Num M where
    fromInteger n = M $ fromInteger (n `mod` fromIntegral m)

    (M a) + (M b) | a + b >= m = M $ a + b - m
    (M a) + (M b) = M $ a + b

    (M a) - (M b) | a - b < 0 = M $ m + a - b
    (M a) - (M b) = M $ a - b

    (M a) * (M b) = M $ (a * b) `mod` m

    abs    = id
    signum = undefined

powM :: M -> Int64 -> M
powM a@(M ma) x
    | x == 0 = M 1
    | x == 1 = a
    | even x = let t = powM a (x `div` 2) in t * t
    | odd x = a * powM a (x - 1)

instance Fractional M where
    recip a = powM a $ m - 2
    fromRational d = (M . fromInteger . R.numerator $ d) * (recip . M . fromInteger . R.denominator $ d)

type GraphA = A.Array Int [Int]

graphFromEdges :: Int -> [(Int, Int)] -> GraphA
graphFromEdges n edges = graph
    where
        graph = STA.runSTArray $ do
            graphA <- MA.newArray (1, n) ([] :: [Int])
            forM_ edges $ \(u, v) -> do
                modifyArray graphA u (v:)
                modifyArray graphA v (u:)
            return graphA

{- END OF GENERAL -}

solve :: Int -> Maybe (Int, Int, Int)
solve x
    | even x = Just (x `div` 2, 0, 0)
    | odd x = Nothing

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        x <- B8.getLine <&> readIntB8
        let answer = solve x
        case answer of
            Nothing -> putStrLn "-1\n"
            Just (a, b, c) -> printf "%d %d %d\n" a b c

(>>>) = flip (.)

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

solve :: Int -> [Int]
solve n
  | even n = [0, 0, n `div` 2]
  | otherwise = [-1]

solveCase :: IO ()
solveCase = do
    s_num <- getLine
    let num = read s_num :: Int
    if num `mod` 2 == 0 then
        putStrLn $ "0 0 " ++ ( show $ num `quot` 2 )
    else
        putStrLn "-1"

solve :: Int -> IO ()
solve cases_left = do
    if cases_left == 1 then
        solveCase
    else do
        solveCase
        solve $ cases_left - 1

main = do
    s_testcases <- getLine
    solve $ (read s_testcases :: Int)

{-# LANGUAGE CPP #-}
import qualified Data.ByteString.Lazy.Char8 as P
import Control.Monad.ST
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
-- import qualified Data.ByteString.Lazy.Char8 as B
import System.IO
import Control.Monad.Trans.State
import Control.Monad.Trans
import Data.Maybe
import Data.Bits
import Prelude hiding (reverse)
import Data.List
import Debug.Trace

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

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

str = string7

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

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

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

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

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
#ifdef LOCAL
  handle <- openFile "input" ReadMode
  inp <- P.hGetContents handle
#else
  inp <- P.getContents
#endif
  let outp = evalState tloop inp
  P.putStr $ toLazyByteString outp

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

solve :: SP Builder
solve = do
  n <- getInt
  pure $ if not (even n) then putInts [-1] else putInts [div n 2, div n 2, 0]

for :: Int -> IO ()
for 0 = pure ()
for i = do
  a <- readLn :: IO Int
  if a `mod` 2 == 0
    then putStrLn $ "0 0 " ++ show (a `div` 2)
    else print (-1)
  for $ i - 1

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


--ghc 7.10

winnerStr = ["Chris","Friendship is magic!^^","Mishka"]

result :: (Ord a) => (a,a) -> Int
result (a,b)
    | a < b = 1
    | a > b = -1
    | otherwise = 0

winner :: (Ord a) => [(a,a)] -> String
winner g = (!!) winnerStr . fromEnum . compare 0 . sum .map result $ g

readPair :: (Read a) => String -> (a,a)
readPair str = (a,b)
    where [a,b] = map read . words $ str

main = do
    nStr <- getLine
    gStr <- getContents
    let g = map (readPair) . lines $ gStr :: [(Int,Int)]
    putStrLn $ winner g

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

process n x	| x==[] = if n>0 then "Mishka" else if n==0 then "Friendship is magic!^^" else "Chris"
     		| otherwise = process n1 (tail x)
	where 	aa= head x
		n1 | aa!!0>aa!!1 = n+1
                   | aa!!0==aa!!1 = n
                   | otherwise = n-1

main = do

	n<-  read <$> getLine ::IO Int
	x<-map(map read) <$> map words <$> lines <$> getContents:: IO [[Int]]
	putStrLn $ process 0  x

import qualified Data.ByteString.Char8 as B
import Data.Array.Unboxed
import Data.List
import Data.Maybe

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

process_case :: Int -> Int -> [[Int]] -> String
process_case m c []
  | m > c     = "Mishka"
  | m < c     = "Chris"
  | otherwise = "Friendship is magic!^^"
process_case m c ([m', c']:rest)
  | m' > c'   = process_case (m+1) c rest
  | m' < c'   = process_case m (c+1) rest
  | otherwise = process_case m c rest

process :: B.ByteString -> B.ByteString
process str =
  let (sn:rest) = B.lines str
      n         = btoi sn
  in B.pack $ process_case 0 0 (map (map btoi . B.words) $ take n rest)

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

module Main where

import Control.Monad

type Result = (Int, Int)

solve :: [Result] -> String
solve rs | m < c = "Chris"
         | m > c = "Mishka"
         | otherwise = "Friendship is magic!^^"
    where update (m, c) (m', c') | m' < c' = (m, c + 1)
                                 | m' > c' = (m + 1, c)
                                 | otherwise = (m + 1, c + 1)
          (m, c) = foldl update (0, 0) rs

main :: IO ()
main = do
  n <- liftM read getLine
  rs <- replicateM n $ do
          [n, m] <- liftM (map read . words) getLine
          return (n, m)
  putStrLn $ solve rs

import Data.Maybe
import Control.Monad
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

getInt = read `fmap` getLine :: IO Int
getInts = (map (fst . fromJust . BS8.readInt) . BS8.words) `fmap` BS.getLine :: IO [Int]

main = do
    n <- getInt
    dices <- replicateM n getInts
    let (x,y) = solve dices
    if x == y
    then putStrLn "Friendship is magic!^^"
    else if x > y
    then putStrLn "Mishka"
    else putStrLn "Chris"

solve ds = f ds (0,0) where
    f [] res = res
    f ([d1,d2]:ds) (x,y) = f ds (x',y') where
        x' = if d1 > d2 then x+1 else x
        y' = if d2 > d1 then y+1 else y

import Control.Monad

sol :: [[Int]] -> Int -> Int -> String
sol [] a b = if a > b
  then "Mishka"
  else if b > a
  then "Chris"
  else "Friendship is magic!^^"

sol res a b = if (head (head res)) > (last (head res))
  then (sol (tail res) (a+1) b)
  else if (head (head res)) < (last (head res))
  then (sol (tail res) a (1+b))
  else (sol (tail res) a b)

main :: IO ()
main = do
  n_s <- getLine
  let n = read n_s :: Int
  inputs <- replicateM n getLine :: IO [String]
  let input_i = fmap (map read.words) inputs :: [[Int]]
  putStrLn (sol input_i 0 0)

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

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

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

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

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

main = do
	getLine
	ps :: [ ( Int, Int ) ] <- map ( mp . map read . words ) . lines <$> getContents

	let
		m = length $ filter ( f (>) ) ps
		c = length $ filter ( f (<) ) ps

	if m == c
		then putStrLn "Friendship is magic!^^"
		else putStrLn $ which "Mishka" "Chris" $ m > c

f g ( a, b ) = g a b

{-# LANGUAGE NPlusKPatterns #-}
module Main where

main :: IO ()
main = communicate track

track :: [(Int, Int)] -> Ordering
track = stat . map (uncurry compare)

stat :: [Ordering] -> Ordering
stat = categ . assess

categ :: Int -> Ordering
categ n | n < 0 = LT
        | n > 0 = GT
        | otherwise = EQ

assess :: [Ordering] -> Int
assess = sum . map value

value :: Ordering -> Int
value LT = -1
value EQ =  0
value GT =  1

communicate :: ([(Int, Int)] -> Ordering) -> IO ()
communicate f = do
    n <- (readLn :: IO Int)
    ps <- iter n getPair
    putStrLn $ report $ track ps

iter :: (Functor m, Monad m) => Int -> m a -> m [a]
iter 0 p = return []
iter (n + 1) p = p >>= (\a -> fmap (a :) (iter n p))

getPair :: IO (Int, Int)
getPair = fmap ((\pl -> (head pl, (head . tail) pl)) . map read . words) getLine

report :: Ordering -> String
report LT = "Chris"
report EQ = "Friendship is magic!^^"
report GT = "Mishka"

import Control.Monad

main :: IO()
main = do
  n <- getLine
  inputs <- replicateM (read n) getLine
  let ds = map convert (map words inputs) where
        convert :: [String] -> (Int, Int)
        convert (x:xs) = (read x :: Int, read (head xs) :: Int)
  putStrLn (winner ds)

winner :: [(Int, Int)] -> String
winner xs = winner' 0 0 xs where
  winner' :: Int -> Int -> [(Int, Int)] -> String
  winner' a b []
    | a > b     = "Mishka"
    | a < b     = "Chris"
    | otherwise = "Friendship is magic!^^"
  winner' a b (x:xs)
    | fst x > snd x = winner' (a+1) b xs
    | fst x < snd x = winner' a (b+1) xs
    | otherwise     = winner' a b xs

main = do
    n <- readLn
    let for x y []
            |x==y = putStrLn "Friendship is magic!^^"
            |x>y  = putStrLn "Mishka"
            |otherwise = putStrLn "Chris"
        for x y (i:is) = do
                [a,b] <- fmap ((map read) . words) getLine :: IO [Int]
                if a==b then for x y is
                else if a<b then for x (y+1) is else for (x+1) y is
    for 0 0 [1..n]

module Main where

import Data.List
import Data.Function

main = do
  count <- read <$> getLine
  inputs <- sequence $ replicate count getLine

  let (mishka, chris) = inputs
                        & map (map read . words)
                        & map (\[x,y] -> x - y)
                        & filter (/= 0)
                        & partition (> 0)

  putStrLn $ case compare (length mishka) (length chris) of
            GT -> "Mishka"
            LT -> "Chris"
            EQ -> "Friendship is magic!^^"

main = interact $ f.tail.lines
f inp = g (map (\x -> map read (words x) :: [Integer]) inp) 0 0

g [] m c
  | m > c = "Mishka"
  | m < c = "Chris"
  | otherwise = "Friendship is magic!^^"

g (x:xs) m c
  | (head x) > (head (tail x)) = g xs (m + 1) c
  | (head x) == (head (tail x)) = g xs m c
  | otherwise = g xs m (c+1)

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

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

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

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

  let
    c1 = length $ filter id $ zipWith (<) (map (!!0) ps) (map (!!1) ps)
    c2 = length $ filter id $ zipWith (>) (map (!!0) ps) (map (!!1) ps)

  putStrLn $ case compare c1 c2 of
    LT -> "Mishka"
    EQ -> "Friendship is magic!^^"
    GT -> "Chris"

main = do
    n <- fmap read getLine :: IO Int
    a <- fmap (map (map read . words)) . sequence $ replicate n getLine :: IO [[Int]]
    putStrLn . getAns . solve $ a

solve :: [[Int]] -> Int
solve = sum . map (trans . (\[x, y] -> x `compare` y))

trans :: Ordering -> Int
trans LT = -1
trans EQ = 0
trans GT = 1

getAns :: Int -> String
getAns n
    | n > 0 = "Mishka"
    | n < 0 = "Chris"
    | otherwise = "Friendship is magic!^^"

module Main where
import Data.List
import Data.Char
main :: IO ()
main = interact $ solve . lines

solve :: [String] -> String
solve xs = let n = read . head $ xs :: Integer
               xs1 = take (fromInteger n) . tail $ xs
               xs2 :: [(Int, Int)]
               xs2 = map (\(a:' ':c:"") -> (ord a - 48, ord c - 48)) xs1
               sctup = foldr (\(a,b) (za, zb) -> if a > b
                                                 then (za+1, zb)
                                                 else if a == b
                                                 then (za, zb)
                                                 else (za, zb+1)) (0,0) xs2
            in case sctup of
                 (a, b) | a > b -> "Mishka"
                        | a == b -> "Friendship is magic!^^"
                        | otherwise -> "Chris"

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = readLn >>= \n-> solve =<< forM [1..n] (\i -> map (fst.fromJust.C.readInt).C.words<$>C.getLine)
--solve::Int->IO()
solve xs = let s= sum $ map (\[a1,a2]-> signum (a2-a1) ) xs in if s<0 then putStr "Mishka" else if s>0 then putStr "Chris" else putStr "Friendship is magic!^^"

import Control.Monad

main = readInput >>= putStrLn . decide . count

readInput :: IO [(Int, Int)]
readInput = getLine >>= readLines . read >>= return . (map toTuple)
  where readLines n = mapM (\_ -> getLine) [1..n]
        toTuple str = (parse 0, parse 1)
          where strs = words str
                parse i = read $ strs !! i

count :: [(Int, Int)] -> Int
count plays = foldr count' 0 plays
  where count' (m, c) tally
          | m < c = tally - 1
          | c < m = tally + 1
          | otherwise = tally

decide :: Int -> String
decide tally
  | tally < 0 = "Chris"
  | 0 < tally = "Mishka"
  | otherwise = "Friendship is magic!^^"

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

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

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

main :: IO ()
main = do
    n <- readB8Int <$> B8.getLine
    qs <- replicateM n $ do
        [a, b] <- (map readB8Int . B8.words) <$> B8.getLine
        return [a, b]
    let delta = sum . map (\[a, b] -> signum (a - b)) $ qs
        answer
            | delta > 0 = "Mishka"
            | delta < 0 = "Chris"
            | otherwise = "Friendship is magic!^^"
    printf "%s" answer

import Control.Applicative
import Data.List

process   r1 r2 | x==y = "Friendship is magic!^^"
                | x>y = "Mishka"
                | otherwise = "Chris"
  where x = length $ filter (\(z1, z2) ->z1 >z2) $ zip   r1 r2
        y = length $ filter (\(z1, z2) ->z1 >z2) $ zip   r2 r1

main = do
  n<-read <$> getLine ::IO Int
  [r1,r2]<- transpose <$> map (map read) <$> map words <$> lines <$> getContents ::IO [[Int]]
  putStrLn $ process   r1 r2

main = interact $ format . uncurry compare . foldl resolve (0,0) . parse
format GT = "Mishka"
format LT = "Chris"
format EQ = "Friendship is magic!^^"
parse = pairs . map read . tail . words where
  pairs (a:b:xs) = (a,b :: Int) : pairs xs
  pairs [] = []
resolve (a,b) (c,d) = case compare c d of
  GT -> (a+1,b)
  LT -> (a,b+1)
  EQ -> (a,b)

main = getContents >>= putStrLn . solve . map (map read . words) . tail . lines

solve :: [[Int]] -> String
solve ls
    | 0 < x = "Mishka"
    | 0 > x = "Chris"
    | otherwise = "Friendship is magic!^^"
    where x = sum $ map (\[m, c] -> if m > c then 1 else if m < c then -1 else 0) ls

module Main where
  import Data.List
  import Control.Monad

  winnerCounter :: Int -> Int -> (Int, Int) -> (Int, Int)
  winnerCounter x y (a, b)
    | x < y = (a, b + 1)
    | x > y = (a + 1, b)
    | x == y = (a, b)

  winnerCounterLoop :: [(Int, Int)] -> (Int, Int) -> (Int, Int)
  winnerCounterLoop [] result = result
  winnerCounterLoop ((p, q):xs) acc  = winnerCounterLoop xs $ winnerCounter p q acc

  winner :: (Int, Int) -> String
  winner (x, y)
    | x > y = "Mishka"
    | x < y = "Chris"
    | x == y = "Friendship is magic!^^"

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

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

  main :: IO ()
  main = do
    n <- getLine >>= return . readInt
    inputs <- replicateM n (getLine >>= return . toTuple . map readInt . words)
    putStrLn $ winner $ winnerCounterLoop inputs (0, 0)

import Control.Monad( replicateM)
data Winner = Mishka | Chrith deriving Eq
main = do
    n <- readLn
    let inning = do
	    [m,c] <- return . map (read::String->Int) . words =<< getLine
	    if m<c
		then return $ Just Chrith
		else if m>c
		    then return $ Just Mishka
		    else return Nothing
    wins <- replicateM n inning
    let ws = filter (/= Nothing) wins
	chris = length $ filter (==Just Chrith) ws
	mishka = length $ filter (==Just Mishka) ws
    if chris>mishka
	then putStrLn "Chris"
	else if chris<mishka
	    then putStrLn "Mishka"
	    else putStrLn "Friendship is magic!^^"

import Control.Monad

sol :: [[Int]] -> Int -> Int -> String
sol [] a b = if a > b
  then "Mishka"
  else if b > a
  then "Chris"
  else "Friendship is magic!^^"

sol res a b = if (head (head res)) > (last (head res))
  then (sol (tail res) (a+1) b)
  else (sol (tail res) a (1+b))

main :: IO ()
main = do
  n_s <- getLine
  let n = read n_s :: Int
  inputs <- replicateM n getLine :: IO [String]
  let input_i = fmap (map read.words) inputs :: [[Int]]
  putStrLn (sol input_i 0 0)

module Main where

import Data.List
import Data.Function

main = do
  count <- read <$> getLine
  inputs <- sequence $ replicate count getLine

  let (mish, chris) =
        inputs
        & map (map read . words)
        & map (\[x,y] -> compare x (y::Int))
        & filter (/= EQ)
        & partition (== LT)
      mishLen = length mish
      chrisLen = length chris

  print $ if mishLen > chrisLen
            then "Mishka"
            else if mishLen < chrisLen
                  then "Chris"
                  else "Friendship is magic!^^"

module Main where

import Data.List
import Data.Function

main = do
  count <- read <$> getLine
  inputs <- sequence $ replicate count getLine

  let (mishka, chris) = inputs
                        & map (map read . words)
                        & map (\[x,y] -> x - y)
                        & filter (/= 0)
                        & partition (> 0)

  print $ case compare (length mishka) (length chris) of
            GT -> "Mishka"
            LT -> "Chris"
            EQ -> "Friendship is magic!^^"

import Control.Applicative
import Data.List

process   r1 r2 | x==y = "Friendship is magic!^^"
                | x>y = "Mishka"
                | otherwise = "Chris"
  where x = zipWith (\z1 z2 ->z1 >z2) r1 r2
        y = zipWith (\z1 z2 ->z1 >z2) r2 r1

main = do
  n<-read <$> getLine ::IO Int
  [r1,r2]<- transpose <$> map (map read) <$> map words <$> lines <$> getContents ::IO [[Int]]
  putStrLn $ process   r1 r2

import Control.Applicative
import Data.List

process   r1 r2 | x==y = "Friendship is magic!^^"
                | x<y = "Mishka"
                | otherwise = "Chris"
  where x = zipWith (\z1 z2 ->z1 >z2) r1 r2
        y = zipWith (\z1 z2 ->z1 >z2) r2 r1

main = do
  n<-read <$> getLine ::IO Int
  [r1,r2]<- transpose <$> map (map read) <$> map words <$> lines <$> getContents ::IO [[Int]]
  putStrLn $ process   r1 r2

module Main where
  import Data.List
  import Control.Monad

  winnerCounter :: Int -> Int -> (Int, Int) -> (Int, Int)
  winnerCounter x y (a, b)
    | x < y = (a, b + 1)
    | x > y = (a + 1, b)
    | x == y = (a, b)

  winnerCounterLoop :: [(Int, Int)] -> (Int, Int) -> (Int, Int)
  winnerCounterLoop [] result = result
  winnerCounterLoop ((p, q):xs) acc  = winnerCounterLoop xs $ winnerCounter p q acc

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

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

  main :: IO ()
  main = do
    n <- getLine >>= return . readInt
    inputs <- replicateM n (getLine >>= return . toTuple . map readInt . words)
    putStrLn $ show $ winnerCounterLoop inputs (0, 0)

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

process n x	| x==[] = if n>0 then "Mishka" else if n==0 then "Friendship is magic!^^" else "Chris"
     		| otherwise = process n1 (tail x)
	where 	aa= head x
		n1 | aa!!0<aa!!1 = n+1
                   | aa!!0==aa!!1 = n
                   | otherwise = n-1

main = do

	n<-  read <$> getLine ::IO Int
	x<-map(map read) <$> map words <$> lines <$> getContents:: IO [[Int]]
	putStrLn $ process 0  x


{-# LANGUAGE GeneralizedNewtypeDeriving #-}

import Control.Monad
import Data.Int
import Data.Array

p :: Int64
p = 10^9 + 7

newtype Mod = Mod { rsdu :: Int64 }
  deriving (Enum, Eq)

instance Num Mod where
  (Mod a) + (Mod b) = Mod $ if c < p then c else c - p
    where c = a + b
  (Mod a) * (Mod b) = Mod $ c `mod` p
    where c = a * b
  abs = id
  signum (Mod a) = Mod $ if a /= 0 then 1 else 0
  fromInteger a = Mod $ fromInteger $ a `mod` toInteger p
  negate (Mod a) = Mod $ if a /= 0 then p - a else 0

invmod a = a ^ (p-2)

fact :: Int -> Mod
fact = (a !)
  where
    a = listArray (0, maxn) $ scanl (*) 1 [1 .. fromIntegral maxn]
    maxn = 2 * 10^5 + 5

ifact = invmod . fact

n `choose` k
  | k < 0 || n-k < 0 = 0
  | otherwise = fact n * ifact k * ifact (n-k)

cs n
  | odd n = offset [0, 1]
  | otherwise = offset [0]
  where offset = map (+ n `div` 2)

solve n l r c = fromIntegral k' * calc 0 0 + sum (takeWhile (/= 0) $ zipWith calc lo ro)
  where
    k' = min (1-l) (r-n)
    ks = [k'+1..]

    lo = map (max 0 . subtract (1-l)) ks
    ro = map (max 0 . subtract (r-n)) ks

    calc lo ro = (n - lo - ro) `choose` (c - lo)

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [n, l, r] <- map read . words <$> getLine
    print $ rsdu $ sum $ map (solve n l r) $ cs n

import Control.Monad ( replicateM_ )
import Data.Array.IArray ( (!), amap, listArray, Array )
import Data.Int ( Int64 )

m :: Int64
m = 1000000007

newtype MInt = MInt Int64 deriving Show

toInt64 :: MInt -> Int64
toInt64 (MInt a) = a

instance Num MInt where
    MInt a + MInt b = MInt $ if c >= m then c - m else c where c = a + b
    MInt a - MInt b = MInt $ if c < 0 then c + m else c where c = a - b
    MInt a * MInt b = MInt $ a * b `mod` m
    abs             = id
    signum (MInt a) = MInt $ signum a
    fromInteger i   = MInt $ fromInteger i `mod` m

inv :: MInt -> MInt
inv a = a ^ (m - 2)

choose :: Int -> Int -> MInt
choose = c where
    c n k | k < 0 || k > n = 0
          | otherwise      = (fac!n) * (ifac!k) * (ifac!(n - k))
    fac' = 1 : zipWith ((*) . fromIntegral) [1..] fac'
    fac = listArray (0, 2 * 10^5) fac' :: Array Int MInt
    ifac = amap inv fac

solve :: IO ()
solve = do
    [n, l, r] <- readMany :: IO [Int]
    let h = n `div` 2
        p = min (1 - l) (r - n)
        ans1 = choose n h * (if odd n then 2 else 1) * fromIntegral p
        calc k = if rem < 0 then 0 else c where
            c = choose rem (h - fl) + if odd n then choose rem (h - fl + 1) else 0
            fl = max 0 $ k - 1 + l
            fr = max 0 $ k - r + n
            rem = n - fl - fr
        ans2 = sum $ map calc [p + 1 .. p + n]
    print $ toInt64 $ ans1 + ans2

readMany :: Read a => IO [a]
readMany = map read . words <$> getLine

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

{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE NumericUnderscores  #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict              #-}
{-# OPTIONS_GHC -Wno-incomplete-patterns #-}

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             guard, join, replicateM,
                                             replicateM_)
import qualified Control.Monad.ST.Strict    as ST
import qualified Control.Monad.State.Strict as S
import qualified Data.Array                 as A
import qualified Data.Array.IO.Safe         as IOA
import qualified Data.Array.MArray.Safe     as MA
import qualified Data.Array.ST.Safe         as STA
import qualified Data.Array.Unboxed         as UA
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Function              (on)
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             foldl', intersect, isPrefixOf, nub,
                                             sort, sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (for, forM)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             hFlush, openFile, stdin, stdout)
import           Text.Printf                (printf)

import           Debug.Trace                (trace, traceM, traceShowM)
import           GHC.IO.Handle              (hDuplicateTo)

debug :: c -> String -> c
debug = flip trace
traced x = trace (show x) x
withTrace s x = trace (s ++ " -> " ++ show x) x

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

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

readIntegralB8 :: (Integral a) => B8.ByteString -> a
readIntegralB8 = B8.readInteger >>> fst . fromJust >>> fromInteger

newtype Cache = Cache {
    factorialMods :: A.Array Int Int64
}

md :: Int64
md = 1_000_000_007

powMod :: Int64 -> Int64 -> Int64 -> Int64
powMod md _ 0 = 1 `mod` md
powMod md a 1 = a `mod` md
powMod md a n | even n =
    let sqrtResult = powMod md a (n `div` 2)
    in (sqrtResult ^ 2) `mod` md
powMod md a n | odd n =
    let prevPowMod = powMod md a (n - 1)
    in (prevPowMod * a) `mod` md

factorialMod :: Cache -> Int64 -> Int64
factorialMod cache n = factorialMods' A.! fromIntegral n
    where
        factorialMods' :: A.Array Int Int64
        factorialMods' = factorialMods cache

combinationsMod :: Cache -> Int64 -> (Int64, Int64) -> Int64
combinationsMod _ _ (n, _) | n < 0 = 0
combinationsMod _ _ (n, k) | k < 0 = 0
combinationsMod _ _ (n, k) | n < k = 0
combinationsMod cache md (n, k) =
        nFactorial * denomInverse `mod` md
    where
        nFactorial = factorialMod cache n
        kFactorial = factorialMod cache k
        n_kFactorial = factorialMod cache (n - k)

        denomInverse = powMod md (n_kFactorial * kFactorial `mod` md) (md - 2)

buildCache :: Int -> Int64 -> Cache
buildCache maxN md =
        Cache factorialMods'
    where
        factorialMods' = A.listArray (0, maxN) . scanl (\prod e -> prod * fromIntegral e `mod` md) 1 $ [1 .. maxN]

solve :: Cache -> Int -> (Int64, Int64) -> Int64
solve cache n (l, r) = (`mod` md) $
        (trailingK - fromK) * subtaskSolve 1 +
        (sum . map subtaskSolve $ [trailingK .. toK])
    where
        fromK = 1
        trailingK = max fromK . (+ (-10)) $ min (r - fromIntegral n) (1 - l)
        toK = 1 + min (r - 1) (fromIntegral n - l)

        subtaskSolve k =
                subarraySolve (usedMinus, usedPlus)
            where
                usedPlus  = max 0 $ l + k - 1
                usedMinus = max 0 $ fromIntegral n - (r - k)

        subarraySolve (usedMinus, usedPlus) | even n =
                combinationsMod cache md (minusCount + plusCount, plusCount)
            where
                minusCount = fromIntegral n `div` 2 - usedMinus
                plusCount  = fromIntegral n `div` 2 - usedPlus

        subarraySolve (usedMinus, usedPlus) | odd n = (`mod` md) $
                combinationsMod cache md (minusCount + plusCount + 1, plusCount) +
                combinationsMod cache md (minusCount + plusCount + 1, minusCount)
            where
                minusCount = fromIntegral (n `div` 2) - usedMinus
                plusCount  = fromIntegral (n `div` 2) - usedPlus

main :: IO ()
main = do
    tests <- B8.getLine <&> readIntB8
    let cache = buildCache 300_000 md
    replicateM_ tests $ do
        [n, l, r] :: [Int64] <- B8.getLine <&> map readIntegralB8 . B8.words

        let answer = solve cache (fromIntegral n) (l, r)

        printf "%lld\n" answer


main :: IO ()

main = interact (format' . solve . format)

solve :: [[Int]] -> [String]
solve = map solver

format' = unlines

solver :: [Int] -> String
solver xs
    | all odd xs    = "YES"
    | all even xs   = "YES"
    | otherwise         = "NO"

format :: String -> [[Int]]
format xs = map (map read . words . snd) . filter (odd . fst) . (zip [0..]) . tail . lines $ xs

import Control.Monad
import Data.List
main = readLn >>= (`replicateM` solve)
solve = do
  getLine
  a <- map read.words <$> getLine
  putStrLn $ if (==1).length.group.map(`mod`2) $ a then "YES" else "NO"

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

main = getLine >>= test.read
test 0 = return ()
test i = do
  getLine
  as <- map read.words <$> getLine
  putStrLn $ if all ((== odd (head as)).odd) as then "YES" else "NO"
  test (i - 1)

import Control.Monad

main = do
    numTests <- read <$> getLine
    replicateM_ numTests $ do
        getLine
        xs <- map ((`mod` 2) . read) . words <$> getLine
        if allEqual xs then
            putStrLn "YES"
        else
            putStrLn "NO"

allEqual [] = True
allEqual [x] = True
allEqual (x:y:zs) = x == y && allEqual (y:zs)

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

onecase = do
		getLine
		d<-map read <$> words <$> getLine ::IO [Integer]
		putStrLn $ if all even d || all odd d then "YES" else "NO"

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

import Control.Monad

solve [] = return ()
solve (ts:tss) = do
  putStrLn res
  solve tss
  where
    res
      | anye && anyo = "NO"
      | otherwise = "YES"
    anye = any even ts
    anyo = any odd ts

main = do
  t <- readLn :: IO Int
  tss <- replicateM t $ do
    getLine
    xs <- map read  . words <$> getLine :: IO [Int]
    return xs
  solve tss

process :: [Int] -> Bool
process xs@(x:_) = and.map even.map (subtract x) $ xs

readInt :: String -> Int
readInt = read

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

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

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}
{-# LANGUAGE MultiWayIf #-}
main = getLine >>= test.read
test 0 = return ()
test i = do
  n <- read <$> getLine
  as <- map read.words <$> getLine
  putStrLn $ if
    | odd n || even (sum as) -> "YES"
    | otherwise -> "NO"
  test (i - 1)

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

onecase = do
		getLine
		d<-map read <$> words <$> getLine ::IO [Integer]
		putStr $ if all even d || all odd d then "YES" else "NO"

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

import Control.Monad

solve [] = return ()
solve (ts:tss) = do
  putStrLn res
  solve tss
  where
    res
      | even (maximum ts - minimum ts) = "YES"
      | otherwise = "NO"

main = do
  t <- readLn :: IO Int
  tss <- replicateM t $ do
    getLine
    xs <- map read  . words <$> getLine :: IO [Int]
    return xs
  solve tss


import Data.Char (ord)

solve :: IO ()
solve = map ((\c -> c - ord 'a') . ord) <$> getLine >>= \ [a, b] ->
    print $ a * 25 + if b < a then b + 1 else b

main :: IO ()
main =
    let f 0 = return ()
        f t = solve >> f (t - 1)
    in readInt <$> getLine >>= f

readInt :: String -> Int
readInt = read

import Control.Monad
import Data.Char
import Data.List

encodeChar x = ord x - ord 'a'

solve (x:y:z) = encodeChar x * 25 + encodeChar y + 1 - if x < y then 1 else 0

main = do
  t <- readInt
  lines <- replicateM t getLine
  putStrLn $ intercalate "\n" (map (\x -> show $ solve x) lines)

-- Just IO
readInt = do
  line <- getLine
  return (read line :: Int)


import Data.List

main :: IO ()

main = do
	firstVals <- fmap (map read . words) getLine :: IO [Int]
	controlPoints <- fmap (map read . words) getLine :: IO [Int]
	print (calcAllButOne (sort controlPoints) (firstVals !! 1))

calcAll :: (Integral a) => [a] -> a -> a
calcAll [] stpoint = 0
calcAll points stpoint
	| stpoint < firstelem = lastelem - stpoint
	| stpoint > lastelem = stpoint - firstelem
	| otherwise = min (stpoint - firstelem) (lastelem - stpoint) + lastelem - firstelem
	where 	firstelem = head points
		lastelem = last points

calcAllButOne :: (Integral a) => [a] -> a -> a
calcAllButOne [] stpoint = 0
calcAllButOne points stpoint = min (calcAll (tail points) stpoint) (calcAll (init points) stpoint)

-- quicksort works
--quicksort :: (Ord a) => [a] -> [a]
--quicksort [] = []
--quicksort (x:xs) =
--	let smallerSorted = quicksort [a | a <- xs, a <= x]
--	    biggerSorted = quicksort [a | a <- xs, a > x]
--	in smallerSorted ++ [x] ++ biggerSorted

import Data.List

import Numeric

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

main = interact $ show.f.parse.words
parse = map fastRead

g [] cur ans = ans
g (x:xs) cur ans = g xs x (ans + (abs (cur-x)))

f (cnt:x:xs) = minimum [(g (aa++ba) x 0),
                        (g (ca++da) x 0),
                        (g (ab++bb) x 0),
                        (g (cb++db) x 0)]
  where y = (sort xs)
        i = init y
        j = tail y

        aa = (reverse (filter (<=x) i))
        ba = (filter (>x) i)
        ca = (reverse (filter (<=x) j))
        da = (filter (>x) j)

        ab = (filter (>=x) i)
        bb = (reverse (filter (<x) i))
        cb = (filter (>=x) j)
        db = (reverse (filter (<x) j))

import Data.List

dist :: Int -> Int -> Int
dist x y = abs $ x - y

process' :: Int -> [Int] -> Int
process' a [_] = 0
process' a x =
  let (fst: snd: _) = x
      (ufst:usnd:_) = reverse x
  in minimum
      [
        dist a fst  + dist fst  usnd,
        dist a snd  + dist snd  ufst,
        dist a ufst + dist ufst snd,
        dist a usnd + dist usnd fst
      ]

process :: String -> String
process str =
  let [header, body] = lines str
      [n, a]         = map read . words $ header
      x              = sort . map read . take n . words  $ body
  in show $ process' a x

main :: IO ()
main = interact process

main :: IO ()

main = do
        firstVals <- fmap (map read . words) getLine :: IO [Int]
        controlPoints <- fmap (map read . words) getLine :: IO [Int]
        print (calcAllButOne (quicksort controlPoints) (firstVals !! 1))

walkleft :: (Integral a) => [a] -> a -> a
walkleft [] stpoint = 0
walkleft (firstElem: points) stpoint
        | firstElem < stpoint = stpoint - firstElem
        | firstElem >= stpoint = 0

walkright :: (Integral a) => [a] -> a -> a
walkright [] stpoint = 0
walkright points stpoint
        | lastElem > stpoint = lastElem - stpoint
        | lastElem <= stpoint = 0
        where lastElem = last points

calcAllButOne :: (Integral a) => [a] -> a -> a
calcAllButOne [] stpoint = 0
calcAllButOne points stpoint
        | leftFull == 0 = rightm1
        | rightFull == 0 = leftm1
        | leftm1 == 0 || rightm1 == 0 = min
                                        (min (2 * leftFull + rightm1) rightFull)
                                        (min (2 * rightFull + leftm1) leftFull)
        | otherwise = min (2 * leftFull + rightm1) (2 * rightFull + leftm1)
        where leftFull = walkleft points stpoint
              rightFull = walkright points stpoint
              leftm1 = walkleft (tail points) stpoint
              rightm1 = walkright (init points) stpoint

-- quicksort works
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
        let smallerSorted = quicksort [a | a <- xs, a <= x]
            biggerSorted = quicksort [a | a <- xs, a > x]
        in smallerSorted ++ [x] ++ biggerSorted

import Data.List

import Numeric

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

main = interact $ show.f.parse.words
parse = map fastRead

g [] cur ans = ans
g (x:xs) cur ans = g xs x (ans + (abs (cur-x)))

f (cnt:x:xs) = minimum [(g (aa++ba) x 0),
                        (g (ca++da) x 0),
                        (g (ab++bb) x 0),
                        (g (cb++db) x 0)]
  where y = (sort xs)
        i = init y
        j = tail y

        aa = (reverse (filter (<=x) i))
        ba = (filter (>x) i)
        ca = (reverse (filter (<=x) j))
        da = (filter (>x) j)

        ab = (reverse (filter (>=x) i))
        bb = (filter (<x) i)
        cb = (reverse (filter (>=x) j))
        db = (filter (<x) j)

import Data.List

import Numeric

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

main = interact $ show.f.parse.words
parse = map fastRead

g i j cur ans 0 = ans
g [] (y:ys) cur ans cnt = g [] ys y (ans + (abs (cur-y))) (cnt-1)
g (x:xs) [] cur ans cnt = g xs [] x (ans + (abs (cur-x))) (cnt-1)
g i@(x:xs) j@(y:ys) cur ans cnt
  | (abs (cur-x)) <= (abs (cur-y)) = g xs j x (ans + (abs (cur-x))) (cnt-1)
  | otherwise = g i ys y (ans + (abs (cur-y))) (cnt-1)

f (cnt:x:xs) = g (reverse (filter (<=x) y)) (filter (>x) y) x 0 (cnt-1)
  where y = (sort xs)


{-# LANGUAGE ViewPatterns #-}

import Data.List ( sort )

solve :: [Int] -> [Int]
solve ints = take n $ concat $ zipWith (\a b -> [a, b]) rotated nums where
    rotated = drop (n `div` 2) nums
    n = length ints
    nums = sort ints

main = interact $ unlines . map (unwords . map show) . loop . tail . lines where
    loop (_ : (map read . words -> nums) : rest) = solve nums : loop rest
    loop _ = []

{-# LANGUAGE ViewPatterns #-}

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

solve :: Int -> [Int] -> [Int]
solve n (sort -> nums)
    = take n nums `zip` drop n nums >>= \(a, b) -> [a, b]

getInt = read <$> getLine
getInts = map read . words <$> getLine
putInts = putStrLn . unwords . map show

main = do n <- getInt
          replicateM_ n (solve <$> getInt <*> getInts >>= putInts)

import Data.List ( sort, transpose )
import Control.Monad ( replicateM_ )

solve :: Int -> [Int] -> [Int]
solve n ints = concat (transpose [take n nums, drop n nums]) where
    nums = sort ints

getInt = read <$> getLine
getInts = map read . words <$> getLine
putInts = putStrLn . unwords . map show
main = do
    n <- getInt
    replicateM_ n (solve <$> getInt <*> getInts >>= putInts)

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

solve :: Int -> [Int] -> [Int]
solve n ints = concat $ zipWith (++) rotated nums where
    nums = pure <$> sort ints
    rotated = drop n nums

getInt = read <$> getLine
getInts = map read . words <$> getLine

main = do
    n <- getInt
    replicateM_ n (solve <$> getInt <*> getInts >>= putStrLn . unwords . map show)

{-# LANGUAGE ViewPatterns #-}

import Data.List ( sort )

solve :: Int -> [Int] -> [Int]
solve n ints = concat $ zipWith (++) rotated nums where
    nums = pure <$> sort ints
    rotated = drop n nums

main = interact $ unlines . loop . tail . lines where
    loop ((read -> n) : (map read . words -> nums) : rest)
           = unwords (map show $ solve n nums) : loop rest
    loop _ = mempty

import Data.List (transpose, sort)

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

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

split a = [take l a, drop l a]
  where l = length a `div` 2

solve :: [Int] -> [Int]
solve = concat . transpose . split . sort

solveLine =
  unwords . map show . solve . map read . words

main = interact $ unlines . map solveLine . evens . tail . lines

import Data.List
import Control.Monad

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

print1 [] [] = ""
print1 (x:xs) (y:ys) = (show x)++" "++(show y)++" " ++ print1 xs ys

main = do
  entry <- getLine
  let timer = read entry :: Int
  forM_ [1..timer] $ \_ -> do
    n <- readLn :: IO Int
    array <- readInts
    let sorted = sort array
        b = take n sorted
        c = take n $ reverse sorted
    let ans = print1 b c
    putStrLn(ans)

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

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

print1 [] [] = ""
print1 (x:xs) (y:ys) = (show x)++" "++(show y)++" " ++ print1 xs ys

printS = do
    n<-readLn :: IO Int
    a<-readInts
    let sorted = sort a
        b = take n sorted
        c = reverse $ drop n sorted
    putStrLn $ print1 b c

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

import Control.Monad
import Data.List (sort)

main = do
    t <- read <$> getLine
    replicateM_ t $ do
        n <- read <$> getLine
        a <- sort . map read . words <$> getLine :: IO [Int]
        putStrLn $ unwords $ [0 .. n - 1] >>= \x -> show . (a !!) <$> [x, x + n]

import Control.Monad
import Data.List
main = do
    t <- (read <$> getLine) :: IO Int
    --putStrLn $ show t

    replicateM_ t $ do
        n <- (read <$> getLine) :: IO Int
        xs <- (sort . map read . words <$> getLine) :: IO [Int]
        let ys = reverse xs
        forM_ (take n $ zip xs ys) $ (\(x, y) -> putStr $ show x ++ " " ++ show y ++ " ")
        putStrLn ""
       -- putStrLn $ show xs

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

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

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

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    as <- getInts
    let (xs, ys) = splitAt n $ sort as
        str = mconcat $ intersperse (charUtf8 ' ') $ map intDec $ concatMap (\(x, y) -> [x, y]) $ zip xs ys
    return $ str `mappend` charUtf8 '\n'
  hPutBuilder stdout output

import Data.List ( sort, transpose )
import Control.Monad ( replicateM_ )

solve :: Int -> [Int] -> [Int]
solve n ints = concat (transpose [nums, rotated]) where
    nums = sort ints
    rotated = drop n nums

getInt = read <$> getLine
getInts = map read . words <$> getLine
putInts = putStrLn . unwords . map show
main = do
    n <- getInt
    replicateM_ n (solve <$> getInt <*> getInts >>= putInts)

import Data.List (transpose)

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

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

split a = [take l a, drop l a]
  where l = length a `div` 2

solve :: [Int] -> [Int]
solve = concat . transpose . split

solveLine =
  unwords . map show . solve . map read . words

main = interact $ unlines . map solveLine . evens . tail . lines


import Control.Monad

solve :: [Int] -> Int
solve l = min (div (sum l) 2) (sum l - (maximum l))

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

routine :: IO ()
routine = do
    l <- (map read).words <$> getLine
    print $ solve l

import Data.List
import Control.Monad

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

getNLists :: (Read a) => Int -> IO [[a]]
getNLists n = sequence $ replicate n getList

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [a, b, c] <- sort <$> getList
        print $ f a b c

f :: Int -> Int -> Int -> Int
f a b c
    | a + b <= c = a + b
    | otherwise = div (a + b + c) 2

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

main = getLine >>= test.read
test 0 = return ()
test i = do
  (r:g:b:_) <- sort.map read.words <$> getLine
  print $ solve r g b
  test (i - 1)

solve r g b
  | r + g < b = r + g
  | otherwise = div (r + g + b) 2


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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

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

import Prelude
import Control.Monad

main :: IO ()
main = do
    t <- readLn
    tcs <- replicateM t getLine

    (putStr . unlines . map solve) tcs

solve xs = show $ (length xs -) . maximum . map length . filter ((>=2).length) . map drop2 . filter (not.null.snd) . map (dropTail xs) $ "05"

dropTail xs c = (,) c . reverse . dropWhile (/= c) . reverse $ xs

drop2 (c, xs) = reverse . (c:) . dropPref2 (next c) . tail . reverse $ xs

dropPref2 cs xs = dropWhile (not . (`elem` cs)) xs

next '5' = "27"
next '0' = "05"
next  _  = error "Internal: bad char"

import Data.Function (on)
import Data.List

yesNo False = "NO"
yesNo True = "YES"

readInt :: String -> Int
readInt = read

readBigInt :: String -> Integer
readBigInt = read

solve_task :: String -> String
solve_task line = let number = readBigInt line
                      kToS xs n   | n == 0               = 0
                                  | n `mod` 10 `elem` xs = 0
                                  | otherwise            = 1 + kToS xs (n `div` 10)
                      k0 = kToS [0] number
                      k5 = kToS [5] number
                      in show $ min (k0 + kToS [0,5] (number `div` 10^(k0+1))) (k5 + kToS [2,7] (number `div` 10^(k5+1)))

solve_tasks (t:tasks) = map solve_task tasks

solve = unlines . solve_tasks . lines

main = interact solve

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}

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 Data.List
import Data.Maybe

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

data TC = TC {s :: String}

input :: Scanner TC
input = do
  s <- str
  return TC {..}

output = showB

solve :: TC -> Int
solve TC {..} = minimum $ map (cost $ reverse s) ["00", "52", "05", "57"]
  where
    cost _ [] = 0
    cost [] _ = 10^5
    cost (x:xs) (p:ps)
      | p == x = cost xs ps
      | otherwise = 1 + cost xs (p:ps)

-------------------------- 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 (replicateM_, forM_, forM)
import Control.Applicative ()

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

go :: [Char] -> Char -> Char -> Int -> Int -> Int
go _ _ _ (-1) _ = -20
go arr first second current state =
    case state of
        0 -> if first == (arr !! current) then go arr first second (current - 1) 1 else go arr first second (current - 1) 0
        1 -> if second == (arr !! current) then current else go arr first second (current - 1) 1
        _ -> 0

solve = do
    n <- getLine
    let ans = [go n '0' '0' (length n - 1) 0
             , go n '5' '2' (length n - 1) 0
             , go n '0' '5' (length n - 1) 0
             , go n '5' '7' (length n - 1) 0]
    print $ length n - maximum ans - 2
    return ()

main = do
    [t] <- nextList
    replicateM_ t solve


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

import Data.Array.MArray
import Data.Array.ST

import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

a ! i = readArray a i
a !< i = \e -> writeArray a i e

main = putStrLn . show . solve . readInput =<< B.getContents

readInput s = let n:m:xs = map (fst . fromJust . B.readInt) $ B.words s
              in (n, m, xs)

solve (n, m, xs0) =
    let xs1 = sortBy (flip compare) . zip xs0 $ map (`divMod` m) [0..length xs0 - 1]
    in runST $ do
        row <- newArray (0, n-1) [] :: ST s (STArray s Int [Int])
        col <- newArray ((0, 0), (m-1, m-1)) False :: ST s (STUArray s (Int, Int) Bool)

        let go [] = return 0
            go ((x, (r, c)):xs) = do
                cs <- row ! r

                res <- forM cs $ \c' -> do
                    got <- col ! (c, c')
                    if got
                        then return True
                        else do
                            col !< (c, c') $ True
                            col !< (c', c) $ True
                            return False

                if or res
                    then return x
                    else do
                        row !< r $ c:cs
                        go xs
        go xs1

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

import Data.Array.MArray
import Data.Array.ST

import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

main = putStrLn . show . solve . readInput =<< B.getContents

readInput s = let n:m:xs = map (fst . fromJust . B.readInt) $ B.words s
              in (n, m, xs)

solve (n, m, xs0) =
    let xs1 = sortBy (flip compare) . zip xs0 $ map (`divMod` m) [0..length xs0 - 1]
    in runST $ do
        row <- newArray (0, n-1) [] :: ST s (STArray s Int [Int])
        col <- newArray ((0, 0), (m-1, m-1)) False :: ST s (STUArray s (Int, Int) Bool)

        let go [] = return 0
            go ((x, (r, c)):xs) = do
                cs <- readArray row r

                res <- forM cs $ \c1 -> do
                    got <- readArray col (c, c1)
                    if got
                        then return True
                        else do
                            writeArray col (c, c1) True
                            writeArray col (c1, c) True
                            return False

                if or res
                    then return x
                    else do
                        writeArray row r (c:cs)
                        go xs
        go xs1


{-# LANGUAGE InstanceSigs, MultiParamTypeClasses, UndecidableSuperClasses, MultiWayIf, KindSignatures,
OverloadedLists,ApplicativeDo,OverloadedStrings,MonadComprehensions,ParallelListComp,TransformListComp, TupleSections,
BlockArguments, TypeApplications, PostfixOperators, TypeOperators, BangPatterns, LambdaCase, UnboxedSums, UnboxedTuples, RankNTypes,
FlexibleContexts,DeriveFoldable, DeriveTraversable, ScopedTypeVariables, GADTs, PatternSynonyms, ViewPatterns, FunctionalDependencies #-}
import Data.List (group, sort, groupBy, partition)
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Function ((&),fix,on)
import Data.Maybe (fromJust, isNothing)
import Data.Bifunctor (bimap)
import GHC.Int (Int64)
int :: L.ByteString -> Int
int = fst . fromJust . L.readInt
readInts ::L.ByteString -> [Int]
readInts = map int . L.split ' '

-- solve :: [Int] -> L.ByteString
-- solve = L.pack . show . uncurry min . bimap length length . partition even

twos :: [L.ByteString] -> [(Int,Int,L.ByteString)]
twos [] = []
twos (x:y:xs) = (a,b,y) : twos xs
 where (a:b:_) = readInts x

process :: L.ByteString -> (Maybe (Int,Int), Int)
process xs = (f $ L.elemIndices '1' xs, 11* (fromIntegral $ L.count '1' xs))
 where f :: [Int64] -> Maybe (Int,Int)
       f []      = Nothing
       f [x]     = Just (1+fromIntegral x,1+fromIntegral x)
       f (x:zs)  = Just (1+fromIntegral x,succ$fromIntegral $ last zs)

solve'::(Maybe (Int,Int),Int) -> Int -> Int -> Int
solve' (Just (a, b), points) len k
 | points' == 1 = 1 --moved only 1 to far right
 | k' >= a - 1  = pred points'
 | otherwise    = points'
 where (k',points') = if k >= len - b then (k - (len - b),points-10) else (k,points)
solve' _ _ _ = 0

solve :: (Int, Int, L.ByteString) -> Int
solve (len,k,xs) = solve' (process xs) len k

main :: IO ()
main = do (n:xs) <- L.lines <$> L.getContents
          L.putStr . L.unlines . map (L.pack.show.solve) . twos $ take (2*int n) xs

    --L.interact (L.unlines . map (solve . readInts) . twos . tail . L.lines)

calculate :: String -> Int
calculate [_] = 0
calculate s = (read (take 2 s) :: Int) + calculate (drop 1 s)

search :: Eq t => Int -> t -> [t] -> Int
search i k [] = -1
search i k (x : xs)
 | (k == x) = i
 | otherwise = search (i + 1) k xs

indexOf :: Eq t => t -> [t] -> Int
indexOf k a = search 0 k a

lastIndexOf :: Eq t => t -> [t] -> Int
lastIndexOf k a
 | (index > -1) = (length a) - 1 - index
 | otherwise = -1
 where
  index = indexOf k (reverse a)

ans :: IO String
ans = do
 nkInput <- getLine
 sInput <- getLine
 let (n : k : []) = [read x :: Int | x <- words nkInput]
 let s = sInput
 let lastIndex = lastIndexOf '1' s
 let firstIndex = indexOf '1' s
 let needLast = n - 1 - lastIndex
 let needFirst = firstIndex
 let total = calculate s
 if lastIndex == -1 then do
  return "0"
 else if (lastIndex == firstIndex) then do
  if (k == 0) || (k < min needLast needFirst) then do
   return (show total)
  else if (needLast == 0) || (k >= needLast) then do
   return "1"
  else if (k >= needFirst) then do
   return "10"
  else do
   return "must have else 1"
 else if (k == 0) || (needLast == 0 && needFirst == 0) || (k < min needLast needFirst) || (needFirst == 0 && k < needLast) || (needLast == 0 && k < needFirst) then do
  return (show total)
 else if (needLast > 0) && (k >= needLast) && (needFirst > 0) && (k - needLast >= needFirst) then do
  return (show (total - 11))
 else if (needLast > 0) && (k >= needLast) && (needFirst == 0 || k - needLast < needFirst) then do
  return (show (total - 10))
 else if (needLast == 0 || k < needLast) && (needFirst > 0) && (k >= needFirst) then do
  return (show (total - 1))
 else do
  return "must have else 2"

main :: IO ()
main = do
 tInput <- getLine
 let t = read tInput :: Int
 results <- sequence (replicate t ans)
 putStrLn (unwords results)