{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM
                                                , replicateM_
                                                )
import           Data.Bits                      ( Bits(..) )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( elemIndex
                                                , findIndex
                                                , foldl'
                                                , unfoldr
                                                )
import           Data.Maybe                     ( fromMaybe )
import           Text.Printf                    ( printf )

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a
-- eigenvector m = iterate (\x -> normalize (m !* x)) (m `dot` m) !! 1000

-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a
-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)
--     where
--         helper :: (Functor t, Conjugate a) => t a -> V1 (t a)
--         helper = adjoint . fmap V1

-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]
-- eigenvalues m = go [e0] (m - e0 *!! identity)
--     where
--         c0 = eigenvector m
--         e0 = eigenvalue m c0
--         go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc
--                   | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))
--                   where ec = eigenvector ma
--                         ev = eigenvalue ma ec
--                         ec' = (<$ unit _x) <$> ec

-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))
-- []

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, m] <- readChar8'
        a      <- C.getLine
        b      <- C.getLine
        if m == 1
            then if C.head b `C.elem` a then putStrLn "YES" else putStrLn "NO"
            else if m == n
                then if a == b then putStrLn "YES" else putStrLn "NO"
                else
                    let (hd,tl) = C.splitAt (n - m + 1) a
                    in do
                        -- print (hd, tl)
                        if tl /= C.tail b then putStrLn "NO" else if C.head b `C.elem` hd then putStrLn "YES" else putStrLn "NO"

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ solve
solve = map readInt . words <$> getLine >>= \[n,m] -> getLine >>= \a -> getLine >>= \b ->
    putStrLn . yn $ (tail b) == (drop (n - m + 1) a) && head b `elem` (take (n - m + 1) a)

yn True = "YES"
yn _ = "NO"

readInt :: String -> Int
readInt = read

{-# OPTIONS_GHC -Wno-incomplete-patterns #-}
import Data.List

main = interact $  unlines . aux . tail . lines

aux [] = []
aux (_:x:y:xs) = (if f x y then "YES" else "NO"): aux xs

f as (b:bs) = elem b xs && bs == ys
                where
                    bL = length bs
                    aL = length as
                    (xs,ys) = splitAt (aL-bL) as

{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM
                                                , replicateM_
                                                )
import           Data.Bits                      ( Bits(..) )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( elemIndex
                                                , findIndex
                                                , foldl'
                                                , unfoldr
                                                )
import           Data.Maybe                     ( fromMaybe )
import           Text.Printf                    ( printf )

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a
-- eigenvector m = iterate (\x -> normalize (m !* x)) (m `dot` m) !! 1000

-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a
-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)
--     where
--         helper :: (Functor t, Conjugate a) => t a -> V1 (t a)
--         helper = adjoint . fmap V1

-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]
-- eigenvalues m = go [e0] (m - e0 *!! identity)
--     where
--         c0 = eigenvector m
--         e0 = eigenvalue m c0
--         go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc
--                   | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))
--                   where ec = eigenvector ma
--                         ev = eigenvalue ma ec
--                         ec' = (<$ unit _x) <$> ec

-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))
-- []

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, m] <- readChar8'
        a      <- getLine
        b      <- getLine
        if m == 1
            then if head b `elem` a then putStrLn "YES" else putStrLn "NO"
            else if m == n
                then if a == b then putStrLn "YES" else putStrLn "NO"
                else
                    let (hd,tl) = splitAt (n - m + 1) a
                    in do
                        -- print (hd, tl)
                        if tl /= tail b then putStrLn "NO" else if head b `elem` hd then putStrLn "YES" else putStrLn "NO"

{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM
                                                , replicateM_
                                                )
import           Data.Bits                      ( Bits(..) )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( elemIndex
                                                , findIndex
                                                , foldl'
                                                , unfoldr
                                                )
import           Data.Maybe                     ( fromMaybe )
import           Text.Printf                    ( printf )

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a
-- eigenvector m = iterate (\x -> normalize (m !* x)) (m `dot` m) !! 1000

-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a
-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)
--     where
--         helper :: (Functor t, Conjugate a) => t a -> V1 (t a)
--         helper = adjoint . fmap V1

-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]
-- eigenvalues m = go [e0] (m - e0 *!! identity)
--     where
--         c0 = eigenvector m
--         e0 = eigenvalue m c0
--         go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc
--                   | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))
--                   where ec = eigenvector ma
--                         ev = eigenvalue ma ec
--                         ec' = (<$ unit _x) <$> ec

-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))
-- []

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, m] <- readChar8'
        a      <- getLine
        b      <- getLine
        if m == 1
            then if last a == head b then putStrLn "YES" else putStrLn "NO"
            else if m == n
                then if a == b then putStrLn "YES" else putStrLn "NO"
                else
                    let (hd,tl) = splitAt (n - m + 1) a
                    in do
                        -- print (hd, tl)
                        if tl /= tail b then putStrLn "NO" else if head b `elem` hd then putStrLn "YES" else putStrLn "NO"

{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM
                                                , replicateM_
                                                )
import           Data.Bits                      ( Bits(..) )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( elemIndex
                                                , findIndex
                                                , foldl'
                                                , unfoldr
                                                )
import           Data.Maybe                     ( fromMaybe )
import           Text.Printf                    ( printf )

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a
-- eigenvector m = iterate (\x -> normalize (m !* x)) (m `dot` m) !! 1000

-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a
-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)
--     where
--         helper :: (Functor t, Conjugate a) => t a -> V1 (t a)
--         helper = adjoint . fmap V1

-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]
-- eigenvalues m = go [e0] (m - e0 *!! identity)
--     where
--         c0 = eigenvector m
--         e0 = eigenvalue m c0
--         go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc
--                   | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))
--                   where ec = eigenvector ma
--                         ev = eigenvalue ma ec
--                         ec' = (<$ unit _x) <$> ec

-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))
-- []

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, m] <- readChar8'
        a      <- getLine
        b      <- getLine
        if m == 1
            then if last a == head b then putStrLn "YES" else putStrLn "NO"
            else if m == n
                then if a == b then putStrLn "YES" else putStrLn "NO"
                else
                    let (hd, _ : tl) = splitAt (length a - m + 1) a
                    in  if tl /= tail b then putStrLn "NO" else if head b `elem` hd then putStrLn "YES" else putStrLn "NO"

{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM
                                                , replicateM_
                                                )
import           Data.Bits                      ( Bits(..) )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( elemIndex
                                                , findIndex
                                                , foldl'
                                                , unfoldr
                                                )
import           Data.Maybe                     ( fromMaybe )
import           Text.Printf                    ( printf )

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a
-- eigenvector m = iterate (\x -> normalize (m !* x)) (m `dot` m) !! 1000

-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a
-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)
--     where
--         helper :: (Functor t, Conjugate a) => t a -> V1 (t a)
--         helper = adjoint . fmap V1

-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]
-- eigenvalues m = go [e0] (m - e0 *!! identity)
--     where
--         c0 = eigenvector m
--         e0 = eigenvalue m c0
--         go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc
--                   | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))
--                   where ec = eigenvector ma
--                         ev = eigenvalue ma ec
--                         ec' = (<$ unit _x) <$> ec

-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))
-- []

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, m] <- readChar8'
        a      <- getLine
        b      <- getLine
        if m == 1
            then if last a == head b then putStrLn "YES" else putStrLn "NO"
            else if m == n
                then if a == b then putStrLn "YES" else putStrLn "NO"
                else
                    let (hd, _ : tl) = splitAt (length a - m - 1) a
                    in  if tl /= tail b then putStrLn "NO" else if head b `elem` hd then putStrLn "YES" else putStrLn "NO"

{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM
                                                , replicateM_
                                                )
import           Data.Bits                      ( Bits(..) )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( elemIndex
                                                , findIndex
                                                , foldl'
                                                , unfoldr
                                                )
import           Data.Maybe                     ( fromMaybe )
import           Text.Printf                    ( printf )

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a
-- eigenvector m = iterate (\x -> normalize (m !* x)) (m `dot` m) !! 1000

-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a
-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)
--     where
--         helper :: (Functor t, Conjugate a) => t a -> V1 (t a)
--         helper = adjoint . fmap V1

-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]
-- eigenvalues m = go [e0] (m - e0 *!! identity)
--     where
--         c0 = eigenvector m
--         e0 = eigenvalue m c0
--         go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc
--                   | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))
--                   where ec = eigenvector ma
--                         ev = eigenvalue ma ec
--                         ec' = (<$ unit _x) <$> ec

-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))
-- []

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, m] <- readChar8'
        a      <- getLine
        b      <- getLine
        if n == m
            then if a == b then putStrLn "YES" else putStrLn "NO"
            else
                let (hd, _ : tl) = splitAt (length a - m) a
                in  if tl /= tail b then putStrLn "NO" else if head b `elem` hd then putStrLn "YES" else putStrLn "NO"

{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM
                                                , replicateM_
                                                )
import           Data.Bits                      ( Bits(..) )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( findIndex
                                                , foldl'
                                                , unfoldr, elemIndex
                                                )
import           Data.Maybe                     ( fromMaybe )
import           Text.Printf                    ( printf )

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

-- eigenvector :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a)) => r (r a) -> r a
-- eigenvector m = iterate (\x -> normalize (m !* x)) (m `dot` m) !! 1000

-- eigenvalue :: (Fractional a, Foldable t, Additive t, Conjugate a) => t (t a) -> t a -> a
-- eigenvalue m x = (let V1 (V1 p) = (helper x!*! m) !*! (V1 <$> x) in p) / (let V1 (V1 q) = helper x !*! (V1 <$> x) in q)
--     where
--         helper :: (Functor t, Conjugate a) => t a -> V1 (t a)
--         helper = adjoint . fmap V1

-- eigenvalues :: (Floating a, Metric r, Epsilon a, Foldable r, Num (r a), Finite r, KnownNat (Size r), Traversable r, Num (r (r a)), Applicative r, Eq a, Distributive r, Conjugate a, R1 r) => r (r a) -> [a]
-- eigenvalues m = go [e0] (m - e0 *!! identity)
--     where
--         c0 = eigenvector m
--         e0 = eigenvalue m c0
--         go acc ma | luDetFinite (m - ev *!! identity) /= 0 = acc
--                   | otherwise = go (ev : acc) (ma - (ec' * adjoint ec') !!* ev !!/ (ec `dot` ec))
--                   where ec = eigenvector ma
--                         ev = eigenvalue ma ec
--                         ec' = (<$ unit _x) <$> ec

-- >>> eigenvalues (V2 (V2 1 2) (V2 3 4))
-- []

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, m] <- readChar8'
        a      <- getLine
        b      <- getLine
        let (hd, _ : tl) = splitAt (length a - m) a
        if tl /= tail b then putStrLn "NO" else if head b `elem` hd then putStrLn "YES" else putStrLn "NO"

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ solve
solve = map readInt . words <$> getLine >>= \[n,m] -> getLine >>= \a -> getLine >>= \b ->
    putStrLn . yn $ (tail b) == (drop (n - m + 1) a) && head b `elem` (take (n - m) a)

yn True = "YES"
yn _ = "NO"

readInt :: String -> Int
readInt = read


import Data.List
import Control.Applicative
import Debug.Trace

solve :: [Int] -> [Int] -> String
solve [n, _, maxMark, maxPoints, minMedian] scores =
  if median full >= minMedian && maximum full <= maxMark && sum full <= maxPoints then
    unwords $ map show $ res
  else
    "-1"
  where
    track q = trace (show q) q
    maxOnes = (n `div` 2) - (length $ filter (<minMedian) scores)
    ones = replicate (min maxOnes (n - length scores)) 1
    medians = replicate (n - length ones - length scores) minMedian
    res = ones ++ medians
    full = res ++ scores
    median x = head $ drop (length x `div` 2) $ sort x

main = do
  x <- map read . words <$> getLine
  scores <- map read . words <$> getLine
  putStrLn $ solve x scores

import Data.List
answer::Int -> Int -> Int -> Int -> Int -> [Int] -> [Int]
answer n k p x y a | ll0 > med = [(-1)]
                   | ll1 >= med+1 = if (sum a) + n2 <= x then take n2 (repeat 1) else [(-1)]
                   | sum a + n0 + y*n1 <=x = (take n0 (repeat 1)) ++ (take n1 (repeat y))
                   | otherwise = [(-1)]
  where (l0,l1) = partition (<y) a
        med = n `div` 2
        ll0 = length l0
        ll1 = length l1
        n0 = med - ll0
        n1 = med -ll1 +1
        n2 = n - (length a)
main = do
  w <- getLine
  let aa = [read n::Int|n <- (words w)]
  let n = aa !! 0
  let k = aa !! 1
  let p = aa !! 2
  let x = aa !! 3
  let y = aa !! 4
  ww <- getLine
  let a = [read n::Int|n <- (words ww)]
  putStrLn $ intercalate " " $ map show $ answer n k p x y a

import Data.List

main :: IO ()

main = do
    l1 <- getLine
    l2 <- getLine
    putStrLn $ solundra
        (map (read :: String -> Int) (words l1))
        (sort (map (read :: String -> Int) (words l2)))

solundra :: [Int] -> [Int] -> String

solundra (n:k:_:x:y:[]) l = let
    wen = length [x | x <- l, x < y]
    gro = length [x | x <- l, x >= y]
    zol = bober wen gro (n-k) y
    in if wen >= gro && wen - gro > n-k || sum zol + sum l > x
    then "-1"
    else unwords $ map show zol

bober :: Int -> Int -> Int -> Int -> [Int]

bober _ _ 0 _ = []
bober w g a y = if w < g - 1
    then 1 : bober (w+1) g (a-1) y
    else y : bober w (g+1) (a-1) y

import Data.List
import Control.Applicative

solve :: [Int] -> [Int] -> String
solve [n, _, maxMark, maxPoints, minMedian] scores =
  if median full >= minMedian && maximum full <= maxMark && sum full <= maxPoints then
    unwords $ map show $ res
  else
    "-1"
  where
    maxOnes = (n `div` 2) - (length $ filter (<minMedian) scores)
    ones = replicate maxOnes 1
    medians = replicate (n - length ones - length scores) minMedian
    res = ones ++ medians
    full = res ++ scores
    median x = head $ drop (length x `div` 2) $ sort x

main = do
  x <- map read . words <$> getLine
  scores <- map read . words <$> getLine
  putStrLn $ solve x scores


import Data.List

solve x b e = length ( filter (\y->(y>b) && (y<e)) x)

main=do
	d<-getLine
	let [_,b,e]=map (\x->read x::Integer) (words d)
	_<-getLine
	x<-getLine
	let dat = map (\x->read x::Integer) (words x)
	print (solve dat b e)

import           Control.Applicative
import qualified Data.ByteString.Char8 as BS

getInts::IO [Int]
getInts = go <$> BS.getLine where
  go s = case  BS.readInt s of
      Nothing      -> []
      Just (x, s') -> x : go (BS.drop 1 s')

main = getInts >>= \[_, l, r] -> getLine >> getInts >>= print . length . filter (liftA2 (&&) (>l) (<r))

import Control.Applicative

solve :: [Int] -> Int -> Int -> Int
solve [] _ _ = 0
solve (x : xs) b c = r + (solve xs b c)
    where r = case x > b &&  x < c of
                True -> 1
                False -> 0

main :: IO ()
main = do
    [a, b, c] <- map (read :: String -> Int) . words <$> getLine
    n <- (read :: String -> Int) <$> getLine
    xis <- map (read :: String -> Int) . words <$> getLine
    putStrLn . show $ solve xis b c

import Control.Applicative( (<$>))
main = do
    [a_, b_, c_] <- map read . words <$> getLine
    n_ <- readLn::IO Int
    xs_ <- map (read::String->Int) . words <$> getLine
    print . length $ filter (\i->b_<i&&i<c_) xs_

module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.Int

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

solve a b c n xs = length $ filter (\x -> b < x && x < c) xs

main = do
  a:b:c:_ <- readInts <$> B.getLine
  n <- readInt <$> B.getLine
  xs <- readInts <$> B.getLine
  print $ solve a b c n xs

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

main = do
		[a,b,c]<- map read <$> words <$> getLine ::IO [Int]
		getLine
		d<- filter (<c) <$> filter (>b) <$> map read <$> words <$> getLine ::IO [Int]
		print $ length d


import Control.Monad
import Data.Int

getInt :: IO Int
getInt = readLn

solve :: Int -> Int -> (Int, Int)
solve a b = (a - b, min p t)
    where k = a - b
          p = b `mod` k
          t = k - p

main :: IO ()
main = do
    test <- getInt
    replicateM_ test $ do
        [a, b] <- map read.words <$> getLine :: IO[Int]
        if a == b then putStrLn "0 0"
                  else do
                      let (res1, res2) = solve (max a b) (min a b)
                      putStrLn $ show res1 ++ " " ++ show res2

import Control.Monad
import Data.Int (Int64)

getInt :: IO Int
getInt = readLn

solve :: Int -> Int -> (Int, Int)
solve a b = (a - b, min p t)
    where k = a - b
          p = b `mod` k
          t = k - p

main :: IO ()
main = do
    test <- readLn :: IO Int
    replicateM_ test $ do
        [a, b] <- map read.words <$> getLine :: IO[Int]
        if a == b then putStrLn "0 0"
                  else do
                      let (res1, res2) = solve (max a b) (min a b)
                      putStrLn $ show res1 ++ " " ++ show res2

import Control.Monad
import Data.Int

getInt :: IO Int
getInt = readLn

solve :: Int64 -> Int64 -> (Int64, Int64)
solve a b = (a - b, min p t)
    where k = a - b
          p = b `mod` k
          t = k - p

main :: IO ()
main = do
    test <- getInt
    replicateM_ test $ do
        [a, b] <- map read.words <$> getLine :: IO[Int64]
        if a == b then putStrLn "0 0"
                  else do
                      let (res1, res2) = solve (max a b) (min a b)
                      putStrLn $ show res1 ++ " " ++ show res2

module Main where
import Control.Monad ( replicateM )
main :: IO ()
main = do
    t <- read <$> getLine :: IO Int
    inp <- replicateM t $ do
        inpline <- getLine
        let spl = map read $ words inpline :: [Integer]
        return spl
    let solved = map ((\[a, b] -> show a ++ " " ++ show b) . solve) inp
    -- print inp
    traverse putStrLn solved
    return ()

solve :: [Integer] -> [Integer]
solve [a, b] =
    let
        ans1 = abs(a - b)
        frnt = (div a ans1 + 1) * ans1 - a
        back = (div a ans1) * ans1 - a
        ans2 = if ans1 == 0 then 0 else min (abs frnt) (abs back)
    in
        [ans1, ans2]

import Control.Monad (replicateM_)

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

solve :: Integer -> Integer -> (Integer, Integer)
solve x y = if x == y then (0, 0) else (d, min left right) where
  (a, b) = (max x y, min x y)
  d = a - b
  left = b `rem` d
  right = d - b `rem` d

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [a, b] <- readInts
    let (exc, steps) = solve a b
    putStrLn $ show exc ++ " " ++ show steps

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.List as L
import Data.Int (Int64)
--import Data.Char as C
--import Data.IntSet as S

solve :: IO ()
solve = do
  s <- getLine
  let [x, y] = map read $ words s :: [Int64]
      (a, b) = (max x y, min x y)
      best = if a == b then 0 else a - b
      re = rem b (a-b)
      steps = if best == 0 then 0 else min re ((a-b) - re)
    in putStrLn $ show best ++ " " ++ show steps

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

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

printResult = do
    [a,b] <- readInts
    if a == b then putStrLn "0 0"
    else do
        let m = max a b
            n = min a b
            s = m - n
            d = div m s
            g = min (m-d*s) (d*s+s-m)
        putStrLn $ show s ++ " " ++ show g

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

import Control.Monad ( replicateM_ )
import Data.Int ( Int64 )

solve :: IO ()
solve = do
    [a, b] <- readMany :: IO [Int64]
    let d = abs (a - b)
        m = a `mod` d
    putStrLn $ if a == b then "0 0" else show d ++ " " ++ show (min m (d - m))

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

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

module Main where
import Control.Monad ( replicateM )
main :: IO ()
main = do
    t <- read <$> getLine :: IO Int
    inp <- replicateM t $ do
        inpline <- getLine
        let spl = map read $ words inpline :: [Integer]
        return spl
    let solved = map ((\[a, b] -> show a ++ " " ++ show b) . solve) inp
    print inp
    print solved
    return ()

solve :: [Integer] -> [Integer]
solve [a, b] =
    let
        ans1 = abs(a - b)
        frnt = (div a ans1 + 1) * ans1 - a
        back = (div a ans1) * ans1 - a
        ans2 = if ans1 == 0 then 0 else min (abs frnt) (abs back)
    in
        [ans1, ans2]


import Data.Array
import Data.Bits
import Data.Foldable
import Data.Int
import Data.List
import qualified Data.Map as M

m :: Int64
m = 998244353

mulmod :: Int64 -> Int64 -> Int64
mulmod a b = a * b `mod` m
infixl 7 `mulmod`

solve :: IO ()
solve = do
    [k, a', h] <- readMany
    let a = fromIntegral a' :: Int64
        n = 2^k
        n' = n `div` 2
        apw = listArray (0, n + 1) $ iterate (mulmod a) 1
        hash ips = sum [fromIntegral i `mulmod` apw!p | (i, p) <- ips] `mod` m
        winlose b x y = if b then (x, y) else (y, x)
        pairs = flip go 0 where
            go [] _ = []
            go ~(x0:x1:xs) i = (i, x0, x1) : go xs (i + 1)

        genhashes :: Int -> Int -> (Int64, [(Int, Int)])
        genhashes l msk = (hash ips, reverse ips) where
            ips = go msk [l .. l + n' - 1]
            go _ [x] = [(x, 2)]
            go msk xs = ips ++ go (msk `shiftR` len) xs' where
                rs = [winlose (msk `testBit` i) x y | (i, x, y) <- pairs xs]
                len = length rs
                xs' = map fst rs
                ips = zip (map snd rs) $ repeat $ 2 * len + 1

        test mp0 mp1 =
            [ (ips'++) <$> mp1 M.!? h1
            | (h0, (w, 2):ips) <- M.assocs mp0
            , let h1 = (h - h0 - fromIntegral w * (apw!1 - apw!2)) `mod` m
                  ips' = (w, 1):ips
            ]

        [mp0, mp1] = M.fromList . (<$> [0 .. 2^(n'-1)-1]) . genhashes <$> [1, n' + 1]

    putStrLn $ maybe "-1" (unwords . map (show . snd) . sort) $ asum (test mp0 mp1 ++ test mp1 mp0)

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

main :: IO ()
main = solve


first2 l = (head l, head $ tail l)

getPair :: IO (Int, Int)
getPair = do
    s <- getLine
    let res = map read $ words s
    return $ first2 res

count :: [(Int, Int)] -> (Int, Int) -> Int
count l (a, b) = foldl check (-1) l
    where check i (x, y) = if x == a || x == b || y == a || y == b
                            then i + 1
                            else i
main = do
    n <- fmap read getLine
    mon <- sequence (replicate n getPair)
    putStr $ show $ (sum $ map (count mon) mon) `div` 2

import Data.Map (Map, insertWith, empty, toList)

first2 l = (head l, head $ tail l)

getPair :: IO (Int, Int)
getPair = do
    s <- getLine
    let res = map read $ words s
    return $ first2 res

count l (a, b) = foldl check (-1) l
    where check i (x, y) = if x == a || x == b || y == a || y == b
                            then i + 1
                            else i

combination n = n * (n - 1) `div` 2

allPairs m (a, b) | a == b    = insertWith (+) a 1 m
                  | otherwise = insertWith (+) a 1 $ insertWith (+) b 1 m

extraPairs m (a, b) | a < b     = insertWith (+) (a, b) 1 m
                    | a > b     = insertWith (+) (b, a) 1 m
                    | otherwise = m

solution l = (sum $ map (combination . snd) $ toList $ foldl allPairs empty l) -
             (sum $ map (combination . snd) $ toList $ foldl extraPairs empty l)

main = do
    n <- fmap read getLine
    mon <- sequence (replicate n getPair)
    putStr $ show $ solution mon

import Data.Map (Map, insertWith, empty, toList)

first2 l = (head l, head $ tail l)

getPair :: IO (Int, Int)
getPair = do
    s <- getLine
    let res = map read $ words s
    return $ first2 res

count :: [(Int, Int)] -> (Int, Int) -> Int
count l (a, b) = foldl check (-1) l
    where check i (x, y) = if x == a || x == b || y == a || y == b
                            then i + 1
                            else i

combination n = n * (n - 1) `div` 2

allPairs m (a, b) | a == b    = insertWith (+) a 1 m
                  | otherwise = insertWith (+) a 1 $ insertWith (+) b 1 m

extraPairs m (a, b) | a < b     = insertWith (+) (a, b) 1 m
                    | a > b     = insertWith (+) (b, a) 1 m
                    | otherwise = m

solution :: [(Int, Int)] -> Int
solution l = (sum $ map (combination . snd) $ toList $ foldl allPairs empty l) -
             (sum $ map (combination . snd) $ toList $ foldl extraPairs empty l)

main = do
    n <- fmap read getLine
    mon <- sequence (replicate n getPair)
    putStr $ show $ solution mon


check :: Int -> [Int] -> Bool
check _ [] = True
check _ (_: []) = True
check i (x: y: xs)
  | i == 1 = check 0 (y: xs)
  | i > 1  = if x < y
    then False
    else check (i - 1) (y: xs)
  | i == 0 = if x > y
    then False
    else check 0 (y: xs)

absA :: [Int] -> (Int, [Int])
absA [] = (0, [])
absA (x: xs) = let (c, ys) = absA xs in if x > 0
  then (c, (x: ys))
  else (c + 1, (-x: ys))

for :: Int -> IO ()
for 0 = pure ()
for i = do
  _ <- readLn :: IO Int
  arr <- (map (\s -> read s :: Int)) <$> (words <$> getLine)
  let (c, x) = absA arr
  if check c x
    then putStrLn "YES"
    else putStrLn "NO"
  for $ i - 1

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

import Control.Monad

isSorted :: Ord a => [a] -> Bool
isSorted (h1:h2:t) = (h1 <= h2) && isSorted (h2:t)
isSorted _ = True

solve :: [Int] -> Bool
solve ints = isSorted (negativeInts ++ positiveInts)
    where negativeCount = length $ filter (<0) ints
          negativeInts = map (\x -> - (abs x)) $ take negativeCount $ ints
          positiveInts = map abs $ drop negativeCount $ ints

readInt :: String -> Int
readInt = read

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

testCaseMain :: IO ()
testCaseMain = do _ <- getLine
                  line <- getLine
                  putStrLn . showBool . solve . map readInt . words $ line

main :: IO ()
main = do t <- (readLn :: IO Int)
          forM_ [1..t] (\_ -> testCaseMain)


import Data.Sequence as S
import Data.Foldable as F
main = getLine >>= print . fst . F.foldl f (0, 1) . tails . fromList
g c n d
  | n >= 4 = True
  | n >= S.length c = False
  | otherwise = index c n == index d n && g c (n + 1) d
f (a, b) c
  | g c 0 (fromList "bear") = (a + b * (S.length c - 3), 1)
  | otherwise = (a, b + 1)

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

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

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

main = do
  s <- getLine

  let
    f s = case findIndex (isPrefixOf "bear") (tails s) of
            Just i -> length s - (i+4) + 1
            Nothing -> 0

      where
  print $ sum $ map f $ tails s

import Data.Sequence as S
import Data.Foldable as F
main = getLine >>= print . fst . F.foldl f (0, 1) .
  S.tails . S.fromList
g :: Seq Char -> Int -> Seq Char -> Bool
g c n d
  | n >= 4 = True
  | n >= S.length c = False
  | otherwise = index c n == index d n && g c (n + 1) d
f :: (Int, Int) -> Seq Char -> (Int, Int)
f (a, b) c
  | g c 0 (fromList "bear") = (a + b * (S.length c - 3), 1)
  | otherwise = (a, b + 1)

main = getLine >>= print . (\x -> f 1 (length x) x)
f _ l _ | l < 4 = 0
f n l (a:b:c:d:s)
  | [a,b,c,d] == "bear" = n * (l - 3) + f 1 (l - 1) (b:c:d:s)
  | otherwise = f (n + 1) (l - 1) (b:c:d:s)

main = do
    str <- getLine
    let l = length str
    let n = countBear str
    print $ res n l

    where
        countBear s = countBear' s 1
        countBear' p@(_:xs) acc = if isBear p then acc:(countBear' xs $ acc + 1) else countBear' xs $ acc + 1
        countBear' _ _ = []
        isBear (x1:x2:x3:x4:_) = x1 == 'b' && x2 == 'e' && x3 == 'a' && x4 == 'r'
        isBear _ = False
        res (x:xs@(y:_)) ls = (res xs ls) + (x * (y - x))
        res (x:[]) ls = x * (ls - x - 2)
        res _ _ = 0

import Data.Functor ((<$>))
import Data.List (tails)
import Data.Maybe (fromMaybe, listToMaybe)

main :: IO ()
main = print =<< solve <$> getLine

solve :: String -> Int
solve xs = sum [ fromMaybe 0 $ ((length xs - 3)-) <$> listToMaybe (filter (>=i) bearIndices) | (i, _) <- zip [0..] xs ]
  where bearIndices = [ i | (i, ys) <- zip [0..] (tails xs), take 4 ys == "bear" ]

import Data.Functor ((<$>))
import Data.List (inits, tails)

main :: IO ()
main = print =<< solve <$> getLine

solve :: String -> Int
solve xs = length [ ys | ys <- concatMap inits $ tails xs, ys `contains` "bear" ]

contains :: Eq a => [a] -> [a] -> Bool
contains (x:xs) yys@(y:ys) = x == y && xs `contains` ys || xs `contains` yys
contains [] (_:_) = False
contains _ [] = True


import Data.Char
import System.IO
import Data.List
import Data.Maybe

-- reading functions

strToIntList :: String -> [Int]
strToIntList xs = map toInt (split xs ' ')

toInt :: String -> Int
toInt [] = 0
toInt (x:xs) = (digitToInt x) * 10^(length xs)  + toInt xs

-- first :: String -> Char -> String

split :: String -> Char -> [String]
split [] _ = []
split xs c = (first xs c) : split (rest xs c) c where
                            first [] c = []
                            first (x:xs) c| x==c = []
                                            | otherwise = x : first xs c
                            rest [] c = []
                            rest (x:xs) c| x==c = xs
                                         | otherwise = rest xs c

-- solving functions

subtract_list :: Num a => [a] -> [a] -> [a]
subtract_list xs [] = xs
subtract_list [] (y:ys) = -y: subtract_list [] ys
subtract_list (x:xs) (y:ys) = (x-y): subtract_list xs ys

diffs :: Num a=> [a] -> [a]
diffs xs = init (subtract_list (tail xs) xs)

-- todo for each problem
solve :: Int -> [Int] -> Int
solve 1 xs = last xs - head xs
solve n xs = solve 1 xs - (sum . (take (n-1)) . reverse . sort . diffs) xs

-- reads a 2 lines: 1st: n, 2nd: list of Ints
-- applies solve on the list and outputs the result
solveNf :: Int -> Handle -> IO ()
solveNf 0 h = return ()
solveNf n h =  do
                nk <- hGetLine h
                t  <- hGetLine h
                (putStrLn . show) (solve ((strToIntList nk)!!1) (strToIntList t))
                solveNf (n-1) h

main :: IO ()
main = do
            -- h <- openFile "C.in" ReadMode
            solveNf 1 stdin
            -- hClose h
            return ()

{-# OPTIONS_GHC -O2 #-}

import Data.Char (ord)
import Data.List (sortOn)
import Data.Ord (Down (Down))

parseInt = foldl (\acc c -> acc * 10 + ord c - 48) 0
parseInts = fmap parseInt . words

main = do
  [n, k] <- fmap parseInts getLine
  a <- fmap parseInts getLine
  let b = sortOn Down (zipWith (-) (tail a) a)
      m = last a - head a
  print (m - sum (take (k - 1) b))

import Data.List

jumpListOf :: [Int] -> [Int]
jumpListOf xs = zipWith (-) (tail xs) xs

solve :: [Int] -> Int -> Int
solve xs k = (sum . drop (k-1) . reverse . sort . jumpListOf) xs

main = do
 n_k <- map (read :: String -> Int) . words <$> getLine
 array_values <- map (read :: String -> Int) . words <$> getLine
 print $ solve array_values (n_k !! 1)


import qualified Data.List as List
import qualified Data.Map as Map

readInt x = read x :: Int
readInteger x = read x :: Integer
readDouble x = read x :: Double

lightRooms n = [ if x == 1 || x == n then 1 else 0 | x <- [1..n] ]
makeRooms lvl = [ lightRooms x | x <- [1..lvl] ]

showRooms (x:xlst) = show x ++ " " ++ showRooms xlst
showRooms [] = ""

showLevels (x:xlst) = showRooms x ++ "\n" ++ showLevels xlst
showLevels [] = ""

solve 0 = return ()
solve tc = do
    solve (tc-1)
    in1 <- getLine
    let n = readInt in1
    putStr (showLevels $ makeRooms n)

main = do
    in1 <- getLine
    let tc = readInt in1
    solve tc

--
-- 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_ (putStr.showAns.solve) tcs

showAns = unlines . map (unwords . map show)

solve n = map genRow [1..n]

genRow 1 = [1::Int]
genRow i = 1 : replicate (i-2) 0 ++ [1]

import Control.Monad (replicateM_)

bnb :: Int -> [[Int]]
bnb 1         = [[1]]
bnb level_num = (new_level :) $ bnb $ level_num - 1
  where
    new_level = 1 : replicate (level_num - 2) 0 ++ [1]

solveCase :: IO ()
solveCase = do
    level_num <- readLn :: IO Int
    mapM_ (putStrLn . unwords . map show) $
      reverse $
        bnb level_num

main :: IO ()
main = do
    test_case_num <- readLn :: IO Int
    replicateM_ test_case_num solveCase

import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = read <$> getLine >>= printTorches

printTorches :: Int -> IO ()
printTorches 1 = print 1
printTorches 2 = printTorches 1 >> putStrLn "1 1"
printTorches n = printTorches (n-1) >>
                 putStr "1 " >> replicateM_ (n-2) (putStr "0 ") >> putStrLn "1"

--
-- 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.Bits
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.show.solve) tcs

solve n = map (splitFor n) finiteBS
  where
    bitSeq = map (toBin numBits) $ nums
    numBits = (1 + n) * n `div` 2
    finiteBS = head bitSeq : takeWhile (/= head bitSeq) (tail bitSeq)

nums = [0..] :: [Integer]

toBin w x = map (b2c . testBit x) $ [w-1,w-2..0]

b2c False = '0'
b2c True  = '1'

splitFor = f 1
  where
    f _ 0 [] = []
    f _ 0 bs = error $ "Logic 1 splitFor : bs=" ++ show bs
    f _ _ [] = error "Logic 2 splitFor"
    f w n bs = xs : f (w+1) (n-1) ys
      where
        (xs,ys) = splitAt w bs

--
-- 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_ (putStr.showAns.solve) tcs

showAns = unlines . map (unwords . map show)

solve n = map (genRow n) [1..n]

genRow n i | (i == 1 || i == n-1)  = fillWith 1
           | (i >  2 && i == n  )  = mixed
           | (          i == n  )  = fillWith 1
           | otherwise             = fillWith 0
  where
    fillWith x = replicate i (x::Int)
    mixed = 1 : replicate (i-2) 0 ++ [1]

--
-- 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_ (putStr.showAns.solve) tcs

showAns = unlines . map (unwords . map show)

solve n = map (genRow n) [1..n]

genRow n i | (i == 1 || i == n-1)  = fillWith 1
           | (i >  2 && i == n  )  = mixed
           | (          i == n  )  = fillWith 1
           | otherwise             = fillWith 0
  where
    fillWith x = replicate i (x::Int)
    mixed = take i . cycle $ [1,0]


doit :: [Integer] -> Maybe [[Integer]]
doit [n, m, k]
  | (2*n*m) `mod` k /= 0 = Nothing
  | otherwise = let g = gcd n k
                    a = n `div` g
                    b = (2*g*m) `div` k
                in if b <= m then Just [[0, 0], [a, 0], [0, b]]
                   else Just [[0, 0], [2*a, 0], [0, b `div` 2]]

doit' :: [Integer] -> String
doit' x = case doit x of
  Nothing -> "NO\n"
  Just s -> unlines $ "YES" : map (unwords . map show) s

main :: IO ()
main = fmap (map read . words) getLine >>= putStr . doit'

{-# LANGUAGE MultiWayIf #-}

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

main = do
  [n,m,k] <- map read . words <$> getLine :: IO [Integer]

  let
    area = (n*m) % k
    d = denominator area

  if
    | d<=2 -> do
        let
          m' = m `div` (gcd m k)
          k' = k `div` (gcd m k)
          n' = n `div` (gcd n k')
        printf "YES\n"
        mapM_ (\(x,y) -> printf "%d %d\n" x y) $
          case d of
            1 -> if m' < m then [(0,0),(n',0),(0,2*m')] else [(0,0),(2*n',0),(0,m')]
            2 -> if m' < m then [(0,0),(n',0),(0,m')] else [(0,0),(n',0),(0,m')]
    | otherwise -> printf "NO\n"


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

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

check :: String -> Maybe Int
check [] = Just 0
check ('\r' : _) = Just 0
check (c : cs) = do
  rest <- check cs
  guard $ c == ')' || rest > 0
  return $ if c == ')' then rest + 1 else rest - 1

replace :: String -> (Char, Char, Char) -> String
replace [] _ = []
replace (c : cs) t@(x1, x2, x3)
  | c == 'A' = x1 : replace cs t
  | c == 'B' = x2 : replace cs t
  | c == 'C' = x3 : replace cs t
  | otherwise = ""

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    s <- C.unpack <$> C.getLine
    let bs = "()"
        results = filter (==0) . map fromJust . filter isJust . map (check . replace s) $ [(x1, x2, x3) | x1 <- bs, x2 <- bs, x3 <- bs]
    C.putStrLn $ C.pack $ if null results then "NO" else "YES"

-- import Debug.Trace
import Data.List (permutations)

type InType  = String
type OutType = Bool

inpLines :: Int
inpLines = 1

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf x l  = take x l : chunksOf x (drop x l)

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

perms :: [String]
perms = permutations "(()" ++ permutations "))("

checkPars :: String -> Bool
checkPars = go 0
    where go c [] = c == 0
          go c (x : xs) = c >= 0 && go (f x + c) xs
          f '(' = 1
          f ')' = -1

solve :: InType -> OutType
solve s = or [ go p | p <- perms ]
    where go [a, b, c] = checkPars $ map (make a b c) s
          make a b c 'A' = a
          make a b c 'B' = b
          make a b c 'C' = c

receive :: [String] -> InType
receive = head

main :: IO ()
main = interact (unlines . map (showb . solve . receive) . chunksOf inpLines . tail . lines)
    where showb True = "YES"
          showb False = "NO"

module Main where

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

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

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

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

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

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

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

main :: IO ()
main = tCase process

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

process :: IO ()
process = do
    s <- getLine
    putStrLn $ yesOrNo $ (head s /= last s) && f s

replace :: (Eq a) => a -> a -> [a] -> [a]
replace x y = map (\z -> if z == x then y else z)

f :: String -> Bool
f s = or [check 0 $ replace k '(' p, check 0 $ replace k ')' p]
    where p = replace (last s) ')' . replace (head s) '(' $ s
          k = last . ('-':) . filter (\c -> c /= '(' && c /= ')') $ p

check :: Int -> String -> Bool
check c [] = c == 0
check 0 (')':xs) = False
check c (')':xs) = check (c - 1) xs
check c ('(':xs) = check (c + 1) xs

isValid :: String -> Int -> Bool
isValid [] x = x == 0
isValid (s:ss) x | x < 0     = False
                 | s == '('  = isValid ss (x + 1)
                 | otherwise = isValid ss (x - 1)

replace :: String -> Char -> Char -> String
replace inp old new = map (\c -> if c == old then new else c) inp

loopHelper :: Int -> IO ()
loopHelper t | t == 0 = return ()
             | otherwise = do
                 inp <- getLine
                 let f = head inp
                     l = last inp
                     inp2 = replace (replace inp f '(') l ')'
                     r = head (filter (\c -> c /= f && c /= l) ['A', 'B', 'C'])

                 if (isValid (replace inp2 r '(') 0 || isValid (replace inp2 r ')') 0 ) then
                     putStrLn "YES"
                 else
                     putStrLn "NO"
                 loopHelper (t-1)
                 return ()

main :: IO ()
main = do
    t <- getLine
    loopHelper (read t :: Int)
    return ()

{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,
    FlexibleInstances, ConstraintKinds, BangPatterns #-}

import Control.Applicative
import Control.Exception (assert)
import Control.Monad hiding (mapM, mapM_, forM, forM_)
import Control.Monad.State hiding (mapM, mapM_, forM, forM_)
import Data.Array.IArray
import Data.Array.ST
import Data.Array.Unboxed (UArray)
import Data.Bits
import Data.Bool
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.Foldable
import Data.Int
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.Ix
import Data.List hiding (and, or, any, all, foldr, foldl')
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.STRef
import Data.Traversable
import Prelude hiding (and, or, any, all, mapM, mapM_)
import System.IO

------

data P a b = P !a !b
  deriving (Show, Eq, Ord)

data T a b c = T !a !b !c
  deriving (Show, Eq, Ord)

data Q a b c d = Q !a !b !c !d
  deriving (Show, Eq, Ord)

class HasFirst a t | t -> a where
  first :: t -> a

instance HasFirst a (P a b) where
  first (P x _) = x

instance HasFirst a (T a b c) where
  first (T x _ _) = x

instance HasFirst a (Q a b c d) where
  first (Q x _ _ _) = x

instance HasFirst a (a, b) where
  first (x, _) = x

instance HasFirst a (a, b, c) where
  first (x, _, _) = x

instance HasFirst a (a, b, c, d) where
  first (x, _, _, _) = x

class HasSecond b t | t -> b where
  second :: t -> b

instance HasSecond b (P a b) where
  second (P _ x) = x

instance HasSecond b (T a b c) where
  second (T _ x _) = x

instance HasSecond b (Q a b c d) where
  second (Q _ x _ _) = x

instance HasSecond b (a, b) where
  second (_, x) = x

instance HasSecond b (a, b, c) where
  second (_, x, _) = x

instance HasSecond b (a, b, c, d) where
  second (_, x, _, _) = x

class HasThird c t | t -> c where
  third :: t -> c

instance HasThird c (T a b c) where
  third (T _ _ x) = x

instance HasThird c (Q a b c d) where
  third (Q _ _ x _) = x

instance HasThird c (a, b, c) where
  third (_, _, x) = x

instance HasThird c (a, b, c, d) where
  third (_, _, x, _) = x

class HasFourth d t | t -> d where
  fourth :: t -> d

instance HasFourth d (Q a b c d) where
  fourth (Q _ _ _ x) = x

instance HasFourth d (a, b, c, d) where
  fourth (_, _, _, x) = x

------

type Hopper r = State [r]

type HopperT r = StateT [r]

runHopper :: Hopper r a -> [r] -> (a, [r])
runHopper = runState

evalHopper :: Hopper r a -> [r] -> a
evalHopper = evalState

runHopperT :: HopperT r m a -> [r] -> m (a, [r])
runHopperT = runStateT

evalHopperT :: Monad m => HopperT r m a -> [r] -> m a
evalHopperT = evalStateT

type MonadHopper r m = MonadState [r] m

pop :: MonadHopper r m => m (Maybe r)
pop = state f
  where
    f :: [r] -> (Maybe r, [r])
    f [] = (Nothing, [])
    f (q:qs) = (Just q, qs)

popJust :: (Functor m, MonadHopper r m) => m r
popJust = fromJust <$> pop

------

popInt :: (Functor m, MonadHopper B.ByteString m) => m Int
popInt = fst . fromJust . B.readInt <$> popJust

popInts :: (Functor m, MonadHopper B.ByteString m) => m [Int]
popInts = map (fst . fromJust . B.readInt) . B.words <$> popJust

popInteger :: (Functor m, MonadHopper B.ByteString m) => m Integer
popInteger = fst . fromJust . B.readInteger <$> popJust

popIntegers :: (Functor m, MonadHopper B.ByteString m) => m [Integer]
popIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust

------

dropCR :: B.ByteString -> B.ByteString
dropCR s | not (B.null s) && B.last s == '\r' = B.init s
         | otherwise = s

bshow :: Show a => a -> B.ByteString
bshow = B.pack . show

main = B.interact go
  where
    go :: B.ByteString -> B.ByteString
    go = evalHopper run . map dropCR . B.lines

------

run :: Hopper B.ByteString B.ByteString
run = do
  t <- popInt
  B.unlines <$> replicateM t run1

run1 = bool "NO" "YES" . solve . B.unpack <$> popJust

solve s = or $ map test [T a b c | a <- [1, -1], b <- [1, -1], c <- [1, -1]]
  where
    test repl = (\l -> all (>= 0) l && last l == 0) $
                second $
                mapAccumL (\x y -> (x + y, x + y)) 0 $ map (replace repl) s

    replace (T a b c) ch = case ch of
      'A' -> a
      'B' -> b
      'C' -> c

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List
import Data.Semigroup

import Data.Bits

count :: Char -> P.ByteString -> Int
count c = P.foldl' (\x y -> x + if  y == c  then  1  else  0) 0

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    s <- readLine
    let
      n = fromIntegral $ P.length s
      letters = "ABC"
      cts = map (`count` s) letters
      half = filter (\x -> 2 * fst x == n) $ zip cts letters
    lift $ P.putStrLn $ P.pack $ case  half  of
      [] -> "NO"
      (_, tarc) : _ -> let
        startWithTar = P.head s == tarc
        fun c = if  xor startWithTar (c == tarc)
          then  ')'
          else  '('
        newS = map fun $ P.unpack s
        prefTots :: [Int]
        prefTots = scanl (\x y -> x + if  y == '('  then  1  else  -1) 0 newS
        in  if  all (>= 0) prefTots && last prefTots == 0
        then  "YES"
        else  "NO"

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.dropWhile (<= '\r') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

putInts :: [Int] -> SIO ()
putInts li = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (map B.intDec li)
  in  lift $ B.hPutBuilder stdout outBuilder

module Main where

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

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

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

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

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

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

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

main :: IO ()
main = tCase process

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

process :: IO ()
process = do
    s <- getLine
    putStrLn $ yesOrNo $ and [f s, head s /= last s]

f :: String -> Bool
f = check . sort . map length . group . sort

check :: [Int] -> Bool
check [a] = False
check [a, b] = a == b
check [a, b, c] = a + b == c


{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, OverloadedStrings #-}
{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph

parseInput = do
    n <- readInt
    replicateM n $ do
        name <- readString
        score <- readInt
        return (name, score)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

main = BS.putStr =<< solve . evalState parseInput <$> BS.getContents

solve records = BS.unlines $
    (BS.pack $ show n) : map (\(name, s) ->
        name `BS.append` " " `BS.append` solvePlayer s) highScores
  where
    highScores = Map.toList $ Map.fromListWith max records
    n = length highScores

    solvePlayer score
        | r < 50 % 100 = "noob"
        | r < 80 % 100 = "random"
        | r < 90 % 100 = "average"
        | r < 99 % 100 = "hardcore"
        | otherwise    = "pro"
      where
        r = cnt % n
        cnt = length [ undefined
                     | (_, score') <- highScores
                     , score' <= score
                     ]

-- {{{ A minimal State Monad
class (Monad m) => MonadState s m | m -> s where
	get :: m s
	put :: s -> m ()

modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
	s <- get
	put (f s)

gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
	s <- get
	return (f s)

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

instance Functor (State s) where
	fmap f m = State $ \s -> let
		(a, s') = runState m s
		in (f a, s')

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

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

instance MonadState s (State s) where
	get   = State $ \s -> (s, s)
	put s = State $ \_ -> ((), s)

evalState :: State s a -> s -> a
evalState m s = fst (runState m s)

execState :: State s a -> s -> s
execState m s = snd (runState m s)

mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m

withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f

state = State
-- }}}

import Control.Monad
import Data.Map (Map)
import qualified Data.Map as Map

-- Pure Code

solve :: Int -> [(String, Int)] -> [(String, String)]
solve n records = map (categorize n records) records

getCategory :: Int -> String
getCategory p
  | p < 50    = "noob"
  | p < 80    = "random"
  | p < 90    = "average"
  | p < 99    = "hardcore"
  | otherwise = "pro"

categorize :: Int -> [(String, Int)] -> (String, Int) -> (String, String)
categorize n records (name, score) =
  let m = length $ filter (\(_, score1) -> score1 <= score) records
      p = 100 * m `div` n
  in (name, getCategory p)

-- Dirty Code

main = do n <- fmap read getLine
          records <- fmap (Map.toList . Map.fromListWith max) $ replicateM n getRecord
          let m = length records
          putStrLn $ show m
          sequence_ $ map printCategory $ solve m records

getRecord :: IO (String, Int)
getRecord = do [name, score] <- fmap words getLine
               return (name, read score)

printCategory (name, category) =
  putStrLn (name ++ " " ++ category)

import Data.List (nub)

main = do
    n <- fmap read getLine
    a <- fmap (map (\[name, score] -> (name, read score :: Double)) . map words . take n . lines) getContents
    let gamers = nub $ map (\(name, _) -> (name, maximum $ map snd $ filter ((== name) . fst) a)) a
    print $ length gamers
    mapM_ (\(name, rank) -> putStrLn $ name ++ " " ++ rank) $ map (\(name, score) -> (name, calcRank (fromIntegral $ length gamers) $ fromIntegral $ length $ filter ((<= score) . snd) gamers)) gamers
    where
        calcRank :: Double -> Double -> String
        calcRank n k | k >= 0.99 * n = "pro"
                     | k >= 0.9 * n  = "hardcore"
                     | k >= 0.8 * n  = "average"
                     | k >= 0.5 * n  = "random"
                     | otherwise     = "noob"

import Control.Monad (replicateM)
import Data.Map (Map, assocs, filter, fromListWith, map, size)
import Prelude hiding (filter, map)

readResult :: IO (String, Int)
readResult  =  do
    [s1, s2]  <-  getLine >>= return . words
    return (s1, read s2)

getNoob :: Map String Int -> Int -> String
getNoob results source
  | k < 50  =  "noob"
  | k < 80  =  "random"
  | k < 90  =  "average"
  | k < 99  =  "hardcore"
  | otherwise  =  "pro"
  where
    n  =  size results
    m  =  size $ filter (<= source) results
    k  =  div (100 * m) n

printAns :: Map String String -> IO ()
printAns results  =  print (size results) >> mapM_ printAns' (assocs results)
  where
    printAns' (name, result)  =  putStrLn $ concat [name, " ", result]

main :: IO ()
main  =  do
    n  <-  readLn
    allResults  <-  replicateM n readResult
    let results   =  fromListWith max allResults
    printAns $ map (getNoob results) results

import Data.List (nub)

main = do
    n <- fmap read getLine
    a <- fmap (map (\[name, score] -> (name, read score :: Double)) . map words . take n . lines) getContents
    let gamers = nub $ map (\(name, _) -> (name, maximum $ map snd $ filter ((== name) . fst) a)) a
    mapM_ (\(name, rank) -> putStrLn $ name ++ " " ++ rank) $ map (\(name, score) -> (name, calcRank (fromIntegral $ length gamers) $ fromIntegral $ length $ filter ((<= score) . snd) gamers)) gamers
    where
        calcRank :: Double -> Double -> String
        calcRank n k | k >= 0.99 * n = "pro"
                     | k >= 0.9 * n  = "hardcore"
                     | k >= 0.8 * n  = "average"
                     | k >= 0.5 * n  = "random"
                     | otherwise     = "noob"

import Control.Monad (replicateM)
import Data.Map (Map, assocs, filter, fromListWith, map, size)
import Prelude hiding (filter, map)

readResult :: IO (String, Int)
readResult  =  do
    [s1, s2]  <-  getLine >>= return . words
    return (s1, read s2)

getCool :: Map String Int -> Int -> Double
getCool results source  =  fromIntegral m / fromIntegral n
  where
    n  =  size results
    m  =  size $ filter (<= source) results

getNoob :: Double -> String
getNoob a
  | a < 0.50  =  "noob"
  | a < 0.80  =  "random"
  | a < 0.90  =  "average"
  | a < 0.99  =  "hardcore"
  | otherwise  =  "pro"

printAns :: Map String String -> IO ()
printAns results  =  print (size results) >> mapM_ printAns' (assocs results)
  where
    printAns' (name, result)  =  putStrLn $ concat [name, " ", result]

main :: IO ()
main  =  do
    n  <-  readLn
    allResults  <-  replicateM n readResult
    let results   =  fromListWith max allResults
    printAns $ map (getNoob . getCool results) results

import Control.Monad
import Data.Map (Map)
import qualified Data.Map as Map

-- Pure Code

solve :: Int -> [(String, Int)] -> [(String, String)]
solve n records = map (categorize n records) records

getCategory :: Double -> String
getCategory p
  | p < 50.0  = "noob"
  | p < 80.0  = "random"
  | p < 90.0  = "average"
  | p < 99.0  = "hardcore"
  | otherwise = "pro"

categorize :: Int -> [(String, Int)] -> (String, Int) -> (String, String)
categorize n records (name, score) =
  let m = length $ filter (\(_, score1) -> score1 <= score) records
      p = 100.0 / fromIntegral n * fromIntegral m
  in (name, getCategory p)

-- Dirty Code

main = do n <- fmap read getLine
          records <- fmap (Map.toList . Map.fromListWith max) $ replicateM n getRecord
          let m = length records
          putStrLn $ show m
          sequence_ $ map printCategory $ solve m records

getRecord :: IO (String, Int)
getRecord = do [name, score] <- fmap words getLine
               return (name, read score)

printCategory (name, category) =
  putStrLn (name ++ " " ++ category)

import Control.Monad
import Data.Map (Map)
import qualified Data.Map as Map

-- Pure Code

solve :: Int -> [(String, Int)] -> [(String, String)]
solve n records = map (categorize n records) records

getCategory :: Double -> String
getCategory p
  | 100.0 - p > 50.0              = "noob"
  | 50.0 <= p && 100.0 - p > 20.0 = "random"
  | 80.0 <= p && 100.0 - p > 10.0 = "average"
  | 90.0 <= p && 100.0 - p > 1.0  = "hardcore"
  | 99.0 <= p                     = "pro"
  | otherwise = undefined

categorize :: Int -> [(String, Int)] -> (String, Int) -> (String, String)
categorize n records (name, score) =
  let m = length $ filter (\(_, score1) -> score1 <= score) records
      p = 100.0 / fromIntegral n * fromIntegral m
  in (name, getCategory p)

-- Dirty Code

main = do n <- fmap read getLine
          records <- fmap (Map.toList . Map.fromListWith max) $ replicateM n getRecord
          let m = length records
          putStrLn $ show m
          sequence_ $ map printCategory $ solve m records

getRecord :: IO (String, Int)
getRecord = do [name, score] <- fmap words getLine
               return (name, read score)

printCategory (name, category) =
  putStrLn (name ++ " " ++ category)

import Control.Monad
import Data.Map (Map)
import qualified Data.Map as Map

-- Pure Code

solve :: Int -> [(String, Int)] -> [(String, String)]
solve n records = map (categorize n records) records

getCategory :: Double -> String
getCategory p
  | 100.0 - p > 50.0              = "noob"
  | 50.0 <= p && 100.0 - p > 20.0 = "random"
  | 80.0 <= p && 100.0 - p > 10.0 = "average"
  | 90.0 <= p && 100.0 - p > 1.0  = "hardcore"
  | 99.0 <= p                     = "pro"
  | otherwise = undefined

categorize :: Int -> [(String, Int)] -> (String, Int) -> (String, String)
categorize n records (name, score) =
  let m = length $ filter (\(_, score1) -> score1 <= score) records
      p = 100.0 / fromIntegral n * fromIntegral m
  in (name, getCategory p)

-- Dirty Code

main = do n <- fmap read getLine
          records <- fmap (Map.toList . Map.fromListWith max) $ replicateM n getRecord
          sequence_ $ map printCategory $ solve (length records) records

getRecord :: IO (String, Int)
getRecord = do [name, score] <- fmap words getLine
               return (name, read score)

printCategory (name, category) =
  putStrLn (name ++ " " ++ category)