Daniel has a string s, consisting of lowercase English letters and period signs (characters '.'). Let's define the operation of replacement as the following sequence of steps: find a substring ".." (two consecutive periods) in string s, of all occurrences of the substring let's choose the first one, and replace this substring with string ".". In other words, during the replacement operation, the first two consecutive periods are replaced by one. If string s contains no two consecutive periods, then nothing happens.Let's define f(s) as the minimum number of operations of replacement to perform, so that the string does not have any two consecutive periods left.You need to process m queries, the i-th results in that the character at position xi (1 ≤ xi ≤ n) of string s is assigned value ci. After each operation you have to calculate and output the value of f(s).Help Daniel to process all queries.

The first line contains two integers n and m (1 ≤ n, m ≤ 300 000) the length of the string and the number of queries. The second line contains string s, consisting of n lowercase English letters and period signs. The following m lines contain the descriptions of queries. The i-th line contains integer xi and ci (1 ≤ xi ≤ n, ci — a lowercas English letter or a period sign), describing the query of assigning symbol ci to position xi.

Print m numbers, one per line, the i-th of these numbers must be equal to the value of f(s) after performing the i-th assignment.

NoteNote to the first sample test (replaced periods are enclosed in square brackets).The original string is ".b..bz....". after the first query f(hb..bz....) = 4    ("hb[..]bz...."  →  "hb.bz[..].."  →  "hb.bz[..]."  →  "hb.bz[..]"  →  "hb.bz.") after the second query f(hbс.bz....) = 3    ("hbс.bz[..].."  →  "hbс.bz[..]."  →  "hbс.bz[..]"  →  "hbс.bz.") after the third query f(hbс.bz..f.) = 1    ("hbс.bz[..]f."  →  "hbс.bz.f.")Note to the second sample test.The original string is ".cc.". after the first query: f(..c.) = 1    ("[..]c."  →  ".c.") after the second query: f(....) = 3    ("[..].."  →  "[..]."  →  "[..]"  →  ".") after the third query: f(.a..) = 1    (".a[..]"  →  ".a.") after the fourth query: f(aa..) = 1    ("aa[..]"  →  "aa.")

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Control.Monad
import Control.Monad.ST.Safe
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  getLine >>= \ns -> C.getLine >>= \bs -> let [f1,f2] = map read $ words ns in (mapM_ print).(solve f1 bs) =<< (forM [1..f2] $ \ i ->C.getLine>>= \js -> let [a,b] = C.words js in return $ (fst $ fromJust $ C.readInt a,C.head b) )
solve n xs1 xs2 = map (snd) $ tail $ scanl f (ms,s) xs2
  where
  ms=Map.fromList $ [(0,'a')] ++ (zip [1..] $ C.unpack xs1) ++ [(n+1,'a')]
  s=sum $ map (\a -> C.length a -1 ) $ C.groupBy (\a b -> a==b && a=='.') xs1
  f (b1,b2) (a1,a2) | (a2=='.' && b1 Map.! a1=='.') || (a2/='.' && b1 Map.! a1/='.')  = (Map.insert a1 a2 b1, b2)
                    | a2=='.' && b1 Map.! (a1-1)=='.' &&  b1 Map.! (a1+1)=='.'        = (Map.insert a1 a2 b1, b2+2)
                    | a2/='.' && b1 Map.! (a1-1)=='.' &&  b1 Map.! (a1+1)=='.'        = (Map.insert a1 a2 b1, b2-2)
                    | a2=='.' && (b1 Map.! (a1-1)=='.' ||  b1 Map.! (a1+1)=='.')      = (Map.insert a1 a2 b1, b2+1)
                    | a2/='.' && (b1 Map.! (a1-1)=='.' ||  b1 Map.! (a1+1)=='.')      = (Map.insert a1 a2 b1, b2-1)
                    | otherwise  = (Map.insert a1 a2 b1, b2)

{-# LANGUAGE BangPatterns, RecordWildCards #-}

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

data Tree =
    Leaf !Char |
    Node {
        left    :: !Tree,
        right   :: !Tree,
        _size   :: !Int,
        _prefix :: !Int,
        _suffix :: !Int,
        _count  :: !Int
    }

size (Leaf _)    = 1
size (Node {..}) = _size

prefix (Leaf '.')  = 1
prefix (Leaf _)    = 0
prefix (Node {..}) = _prefix

suffix (Leaf '.')  = 1
suffix (Leaf _)    = 0
suffix (Node {..}) = _suffix

count (Leaf _)    = 0
count (Node {..}) = _count

dotsOnly (Leaf '.')  = True
dotsOnly (Leaf _)    = False
dotsOnly (Node {..}) = _prefix == _size

make left right = Node left right newSize newPrefix newSuffix newCount
    where
    newSize   = size left + size right
    newPrefix = prefix left + if dotsOnly left then prefix right else 0
    newSuffix = suffix right + if dotsOnly right then suffix left else 0
    newCount  = count left + count right + joint
    joint     = if suffix left > 0 && prefix right > 0 then 1 else 0

construct s
    | B.length s == 1 = Leaf $ B.head s
    | otherwise =
        let (left, right) = B.splitAt (B.length s `unsafeShiftR` 1) s
        in make (construct left) (construct right)

update c = update'
    where
    update' (Leaf _) !_ = Leaf c
    update' (Node {..}) !i
        | i < size left = make (update' left i) right
        | otherwise     = make left (update' right (i - size left))

run 0 !_ = return ()

run q !tree = do
    (i, tl) <- liftM (fromJust . B.readInt) B.getLine
    let next = update (tl `B.index` 1) tree (i - 1)
    putStrLn $ show $ count next
    run (q - 1) next

main = do
    m <- liftM (fst . fromJust . B.readInt . head . tail . B.split ' ') B.getLine
    B.getLine >>= run m . construct

{-# LANGUAGE OverloadedStrings #-}
import Data.Maybe (fromJust)
import Control.Applicative ((<$>))
import Control.Monad (replicateM, forM)
import Control.Arrow (second)
import Data.List (group)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

import Data.Array.Unboxed (UArray, listArray)
import Control.Monad.ST.Strict (ST, runST)
import Data.Array.ST (STUArray,readArray, writeArray, thaw)
import Data.STRef (newSTRef, readSTRef, writeSTRef)

update :: Int -> Bool -> (Bool, Bool, Bool) -> Int
update val t (x, y, z)
    | t == y    = val
    | t         = val + inc
    | otherwise = val - inc
    where inc = (if x then 1 else 0) + if z then 1 else 0

solve :: Int -> UArray Int Bool -> [(Int, Bool)] -> [Int]
solve val' arr' query = runST $ do
    arr <- thaw arr' :: ST s (STUArray s Int Bool)
    val <- newSTRef val'

    forM query $ \(i, t) -> do
        x <- readArray arr $ pred i
        y <- readArray arr i
        z <- readArray arr $ succ i
        cur <- readSTRef val

        writeSTRef val $ update cur t (x, y, z)
        writeArray arr i t
        readSTRef val

wrap :: Int -> ByteString -> [ByteString] -> [Int]
wrap n line query = solve val arr mut
    where
    mut = second pred . fromJust . C.readInt <$> query
        where pred = (== " .") . C.take 2

    arr = listArray (0, n + 1) run
    run = False: C.foldr (\i acc -> (i == '.'):acc) [False] line
    val = sum . map (pred . length) . filter head . group $ run

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = do
    [n, m] <- parse <$> B.getLine
    line   <- C.take n <$> B.getLine
    query  <- replicateM m B.getLine
    mapM_ print $ wrap n line query

{-# LANGUAGE OverloadedStrings #-}
import Data.Maybe (fromJust)
import Control.Applicative ((<$>))
import Control.Monad (replicateM, forM)
import Control.Arrow (second)
import Data.List (group)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

import Data.Array.Unboxed (UArray, listArray)
import Control.Monad.ST.Strict (ST, runST)
import Data.Array.ST (STUArray,readArray, writeArray, thaw)

count :: Bool -> [Bool] -> Int
count t xs = if t then inc else -inc
    where inc = length $ filter id xs

solve :: Int -> UArray Int Bool -> [(Int, Bool)] -> [Int]
solve val inp query = tail . scanl (+) val $ runST $ do
    arr <- thaw inp :: ST s (STUArray s Int Bool)

    forM query $ \(i, t) -> do
        xi <- readArray arr i
        if xi == t
        then return 0
        else do
            a <- readArray arr $ pred i
            b <- readArray arr $ succ i
            writeArray arr i t
            return $ count t [a, b]

wrap :: Int -> ByteString -> [ByteString] -> [Int]
wrap n line query = solve val arr mut
    where
    mut = second pred . fromJust . C.readInt <$> query
        where pred = (== " .") . C.take 2

    arr = listArray (0, n + 1) run
    run = False: C.foldr (\i acc -> (i == '.'):acc) [False] line
    val = sum . map (pred . length) . filter head . group $ run

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = do
    [n, m] <- parse <$> B.getLine
    line   <- C.take n <$> B.getLine
    query  <- replicateM m B.getLine
    mapM_ print $ wrap n line query

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Control.Monad
import Control.Monad.ST.Safe
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  getLine >>= \ns -> C.getLine >>= \bs -> let [f1,f2] = map read $ words ns in (mapM_ print).(solve f1 bs) =<< (forM [1..f2] $ \ i ->C.getLine>>= \js -> let [a,b] = C.words js in return $ (fst $ fromJust $ C.readInt a,C.head b) )
solve n xs1 xs2 = map (snd) $ tail $ scanl f (ms,s) xs2
  where
  ms=Map.fromList $ [(0,'a')] ++ (zip [1..] $ C.unpack xs1) ++ [(n+1,'a')]
  s=sum $ map (\a -> C.length a -1 ) $ C.groupBy (\a b -> a==b && a=='.') xs1
  f (b1,b2) (a1,a2) | a2=='.' && b1 Map.! (a1-1)=='.' &&  b1 Map.! (a1+1)=='.'     = (Map.insert a1 a2 b1, b2+2)
                    | a2/='.' && b1 Map.! (a1-1)=='.' &&  b1 Map.! (a1+1)=='.'     = (Map.insert a1 a2 b1, b2-2)
                    | a2=='.' && (b1 Map.! (a1-1)=='.' ||  b1 Map.! (a1+1)=='.')   = (Map.insert a1 a2 b1, b2+1)
                    | a2/='.' && (b1 Map.! (a1-1)=='.' ||  b1 Map.! (a1+1)=='.')   = (Map.insert a1 a2 b1, b2-1)
                    | otherwise                                                    = (Map.insert a1 a2 b1, b2)

{-# LANGUAGE OverloadedStrings #-}
import Data.Maybe (fromJust)
import Control.Applicative ((<$>))
import Control.Monad (replicateM, forM)
import Control.Arrow (second)
import Data.List (group)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

import Data.Array.Unboxed (UArray, listArray)
import Control.Monad.ST.Strict (ST, runST)
import Data.Array.ST (STUArray,readArray, writeArray, thaw)
import Data.STRef (newSTRef, readSTRef, writeSTRef)

update :: Int -> Bool -> (Bool, Bool, Bool) -> Int
update val t (x, y, z)
    | t == y    = val
    | t         = val + inc
    | otherwise = val - inc
    where inc = (if x then 1 else 0) + if z then 1 else 0

solve :: Int -> UArray Int Bool -> [(Int, Bool)] -> [Int]
solve val' arr' query = runST $ do
    arr <- thaw arr' :: ST s (STUArray s Int Bool)
    val <- newSTRef val'

    forM query $ \(i, t) -> do
        x <- readArray arr $ pred i
        y <- readArray arr i
        z <- readArray arr $ succ i
        cur <- readSTRef val

        writeSTRef val $ update cur t (x, y, z)
        writeArray arr i t
        readSTRef val

wrap :: Int -> ByteString -> [ByteString] -> [Int]
wrap n line query = solve val arr mut
    where
    mut = second (== " .") . fromJust . C.readInt <$> query
    arr = listArray (0, n + 1) run
    run = False: C.foldr (\i acc -> (i == '.'):acc) [False] line
    val = sum . map (pred . length) . filter head . group $ run

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = do
    [n, m] <- parse <$> B.getLine
    line   <- B.getLine
    query  <- replicateM m B.getLine
    mapM_ print $ wrap n line query


Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the end of the game. If boys have the same number of points, the game finishes with a draw.At some point, Valera lost his count, and so he can not say exactly what the score is at the end of the game. But there are things he remembers for sure. He remembers that the entire game Vasya got heads at least a times, and Petya got heads at least b times. Moreover, he knows that the winner of the game was Vasya. Valera wants to use this information to know every possible outcome of the game, which do not contradict his memories.

The single line contains four integers x, y, a, b (1 ≤ a ≤ x ≤ 100, 1 ≤ b ≤ y ≤ 100). The numbers on the line are separated by a space.

In the first line print integer n — the number of possible outcomes of the game. Then on n lines print the outcomes. On the i-th line print a space-separated pair of integers ci, di — the number of heads Vasya and Petya got in the i-th outcome of the game, correspondingly. Print pairs of integers (ci, di) in the strictly increasing order. Let us remind you that the pair of numbers (p1, q1) is less than the pair of numbers (p2, q2), if p1 < p2, or p1 = p2 and also q1 < q2.

solve :: [Int] -> [String]
solve [x, y, a, b] =
  let variants = [[i, j] | i <- [a .. x], j <- [b .. y], i > j]
  in (show $ length variants):(map (unwords . map show) variants)

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

import Data.List

main = do
    [x,y,a,b] <- fmap (map read . words) getLine
    let pairs = solve [x,y,a,b]
    print $ length pairs
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) pairs

solve :: [Integer] -> [(Integer,Integer)]
solve [x,y,a,b] = sort [(f,g) | f <- [a..x], g <- [b..y], f > g]

main = do
  [x,y,a,b] <- fmap (map read.words) getLine
  let ans = [unwords$map show[sv,sp]|sv<-[a..x],sp<-[b..y],sv>sp+0]
  print $ length ans
  putStrLn $ unlines ans

main = interact $ unlines . map (unwords . map show) . solve . map read . words
solve [x, y, a, b] = [length out] : out
  where out = [[c, d] | c <- [a..x], d <- [b..y], c > d]

import Data.List
main = solve.map read.words =<< getLine
solve :: [Int] -> IO ()
solve [x,y,a,b] = do
    let s = sln a b x y
    print $ length s
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) s
sln a b x y = concatMap f [a..x]
    where f n = [(n,d) | d <- takeWhile (\x' -> x' <= y) [b..], d < n]

main = do
  [x, y, a, b] <- fmap (map read . words) getLine
  let z = [[i, j] | i <- [a .. x], j <- [b .. y], i > j] :: [[Int]]
  print $ length $ z
  putStr $ unlines $ map (unwords . map show) z

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

solve [x, y, a, b] = [length outcomes] : outcomes
  where
  outcomes = [[c, d] | c <- [a..x], d <- [b..y], c > d]

main = do
	x <- getLine
	putStrLn $ show $ length $ res x
	putStrLn $ unlines $ map (\(a,b) -> unwords [show a, show b]) $ res x
	where
		res = f . map (\a -> read a::Int) . words

f :: [Int] -> [(Int, Int)]
f [a,b,c,d] = [(x,y) | x <- [c..a], y<-[d..b], x>y]

import Control.Monad (liftM)

solve :: [Int] -> [(Int, Int)]
solve [x, y, a, b]  =  [(i, j) | i <- [a .. x], j <- [b .. y], i > j]

prints :: (Show a, Show b) => [(a, b)] -> IO ()
prints xs  =  print (length xs) >> mapM_ prints' xs
  where
    prints' (a, b)  =  putStrLn $ show a ++ " " ++ show b

main :: IO ()
main  =  liftM (map read . words) getLine >>= prints . solve

import Data.List
main = solve.map read.words =<< getLine
solve [x,y,a,b] = do
    let s = sln a b x y
    print $ length s
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) s
sln a b x y = concatMap f [(min (b+1) a) .. x]
    where f n = [(n,d) | d <- takeWhile (\x' -> x' <= y) [b..], d < n]

import Data.List
main = solve.map read.words =<< getLine
solve [x,y,a,b] = do
    let s = sln a b x y
    print $ length s
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) s
sln a b x y = concatMap f [(min (b+1) a) .. x]
    where f n = [(n,d) | d <- takeWhile (\x' -> x' <= y && x' < n) [b..], d < n]

import Data.List
main = solve.map read.words =<< getLine
solve [x,y,a,b] = do
    let s = sln a b x y
    print $ length s
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) s
sln a b x y = concatMap f [(min (b+1) a) .. x]
    where f n = [(n,d) | d <- takeWhile (\x' -> x' <= y && x' < n+1) [b..], d < n]

import Data.List
main = solve.map read.words =<< getLine
solve [x,y,a,b] = do
    let s = sln a b x y
    print $ length s
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) s
sln a b x y = concatMap f [(min (b+1) a) .. x]
    where f n = [(n,d) | d <- takeWhile (\x' -> x' <= y && x' < n-1) [b..], d < n]

import Control.Monad (liftM)

solve :: [Int] -> [(Int, Int)]
solve [x, y, a, b]  =  [(i, j) | i <- [a .. x], j <- [b .. y], i > j]

prints :: (Show a, Show b) => [(a, b)] -> IO ()
prints xs  =  mapM_ prints' xs
  where
    prints' (a, b)  =  putStrLn $ show a ++ " " ++ show b

main :: IO ()
main  =  liftM (map read . words) getLine >>= prints . solve


Ivan wants to have a good dinner. A good dinner should consist of a first course, a second course, a drink, and a dessert.There are $$$n_1$$$ different types of first courses Ivan can buy (the $$$i$$$-th of them costs $$$a_i$$$ coins), $$$n_2$$$ different types of second courses (the $$$i$$$-th of them costs $$$b_i$$$ coins), $$$n_3$$$ different types of drinks (the $$$i$$$-th of them costs $$$c_i$$$ coins) and $$$n_4$$$ different types of desserts (the $$$i$$$-th of them costs $$$d_i$$$ coins).Some dishes don't go well with each other. There are $$$m_1$$$ pairs of first courses and second courses that don't go well with each other, $$$m_2$$$ pairs of second courses and drinks, and $$$m_3$$$ pairs of drinks and desserts that don't go well with each other.Ivan wants to buy exactly one first course, one second course, one drink, and one dessert so that they go well with each other, and the total cost of the dinner is the minimum possible. Help him to find the cheapest dinner option!

The first line contains four integers $$$n_1$$$, $$$n_2$$$, $$$n_3$$$ and $$$n_4$$$ ($$$1 \le n_i \le 150000$$$) — the number of types of first courses, second courses, drinks and desserts, respectively. Then four lines follow. The first line contains $$$n_1$$$ integers $$$a_1, a_2, \dots, a_{n_1}$$$ ($$$1 \le a_i \le 10^8$$$), where $$$a_i$$$ is the cost of the $$$i$$$-th type of first course. Three next lines denote the costs of second courses, drinks, and desserts in the same way ($$$1 \le b_i, c_i, d_i \le 10^8$$$). The next line contains one integer $$$m_1$$$ ($$$0 \le m_1 \le 200000$$$) — the number of pairs of first and second courses that don't go well with each other. Each of the next $$$m_1$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i \le n_1$$$; $$$1 \le y_i \le n_2$$$) denoting that the first course number $$$x_i$$$ doesn't go well with the second course number $$$y_i$$$. All these pairs are different. The block of pairs of second dishes and drinks that don't go well with each other is given in the same format. The same for pairs of drinks and desserts that don't go well with each other ($$$0 \le m_2, m_3 \le 200000$$$).

If it's impossible to choose a first course, a second course, a drink, and a dessert so that they go well with each other, print $$$-1$$$. Otherwise, print one integer — the minimum total cost of the dinner.

NoteThe best option in the first example is to take the first course $$$2$$$, the second course $$$1$$$, the drink $$$2$$$ and the dessert $$$1$$$.In the second example, the only pair of the first course and the second course is bad, so it's impossible to have dinner.

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.Array.Unboxed
import qualified Data.IntMap.Strict as Map

type SIO = StateT P.ByteString IO

sentinel :: Int
sentinel = 5 * 10 ^ (8 :: Int)

step :: UArray Int Int -> [(Int, Int)] -> UArray Int Int -> UArray Int Int
step prevCosts excls currCosts = let
  initMap = Map.fromListWith (+) $ zip (sentinel : elems prevCosts) (repeat 1)
  updateFun 1 = Nothing
  updateFun v = Just (v - 1)
  remove = flip $ Map.update updateFun
  exclusionResults :: Array Int (Map.IntMap Int)
  exclusionResults = accumArray remove initMap (bounds currCosts)
    $ [(yi, prevCosts ! xi) | (xi, yi) <- excls]
  in  array (bounds currCosts) $ do
  (i, v) <- assocs currCosts
  let  nv = v + fst (Map.findMin $ exclusionResults ! i)
  pure (i, min sentinel nv)

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  ns <- readInts
  [a, b, c, d] <- forM ns $ \ni -> listArray (1, ni) <$> readInts
  [excl1, excl2, excl3] <- replicateM 3 $ do
    [mi] <- readInts
    replicateM mi $ do
      [xi, yi] <- readInts
      pure (xi, yi)
  let
    s2 = step a excl1 b
    s3 = step s2 excl2 c
    s4 = step s3 excl3 d
    ans = case  foldl' min sentinel $ elems s4  of
      v | v == sentinel -> 0-1
        | otherwise -> v
  putInts [ans]

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

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

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

main :: IO ()
main = do
  _ <- C.getLine
  (as : ass) <- replicateM 4 (fmap (zip [1..]) getInts)
  let
    cmp (_, c1) (_, c2) = compare c1 c2
    trans pres edges nexts (j, cost) =
      case filter (\(i, _) -> S.notMember (i, j) edges) pres of
        ((_, c) : _) -> (j, c + cost) : nexts
        _ -> nexts
    acc pres ys = do
      [m] <- getInts
      edges <- S.fromList <$> replicateM m (getInts >>= \[i, j] -> return (i, j))
      return $ sortBy cmp $ foldl' (trans pres edges) [] ys
  results <- foldM acc (sortBy cmp as) ass
  putStrLn $ if null results then "-1" else show $ snd $ head results

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

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Array
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
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.Traversable
import System.IO

------

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 :: MonadHopper r m => m r
popJust = fromJust <$> pop

------

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

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

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

popIntegers :: 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
  ~[n1, n2, n3, n4] <- popInts
  a <- popInts
  b <- popInts
  c <- popInts
  d <- popInts
  ab <- popPairs n1
  bc <- popPairs n2
  cd <- popPairs n3
  return $ bshow (solve n1 n2 n3 n4 a b c d ab bc cd) <> "\n"

  where
    popPairs n = do
      m <- popInt
      buildPairs n <$> replicateM m ((\ ~[x, y] -> (x - 1, y - 1)) <$> popInts)

    buildPairs n ps = IntSet.fromList <$> accumArray (flip (:)) [] (0, n - 1) ps

inf = (maxBound :: Int)

third (_, _, x) = x

solve :: Int -> Int -> Int -> Int -> [Int] -> [Int] -> [Int] -> [Int] ->
         Array Int IntSet -> Array Int IntSet -> Array Int IntSet -> Int
solve n1 n2 n3 n4 a b c d ab bc cd =
  case sortOn snd $ id' of
    [] -> -1
    ((_, v):_) -> v

  where
    ia :: [(Int, Int)]
    ia = sortOn snd $ zip [0..] a

    ib :: [(Int, Int)]
    ib = makeI ia n2 b ab

    ic :: [(Int, Int)]
    ic = makeI ib n3 c bc

    id' :: [(Int, Int)]
    id' = makeI ic n4 d cd

    makeI :: [(Int, Int)] -> Int -> [Int] -> Array Int IntSet -> [(Int, Int)]
    makeI is jn jv bans =
      sortOn snd $
      map (\(i, x, y) -> (i, x + y)) $
      filter ((/= inf) . third) $
      zip3 [0..] jv $
      make bans is [0 .. jn - 1]

    make :: Array Int IntSet -> [(Int, Int)] -> [Int] -> [Int]
    make bans is js = map snd $ sort $ makeV [] bans is js

    makeV :: [(Int, Int)] -> Array Int IntSet -> [(Int, Int)] -> [Int] ->
             [(Int, Int)]
    makeV acc _ [] js = (zip js $ repeat inf) ++ acc
    makeV acc _ _ [] = acc
    makeV acc bans ((i, x) : is) js = makeV' acc bans i x is js []

    makeV' :: [(Int, Int)] -> Array Int IntSet -> Int -> Int -> [(Int, Int)] ->
              [Int] -> [Int] -> [(Int, Int)]
    makeV' acc bans i x is [] js' = makeV acc bans is js'
    makeV' acc bans i x is (j : js) js'
      | IntSet.member j (bans ! i) = makeV' acc bans i x is js (j : js')
      | otherwise = makeV' ((j, x) : acc) bans i x is js js'


An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it either to the beginning of the train, or to the end of the train, at his desire. What is the minimum number of actions David Blaine needs to perform in order to sort the train?

The first line of the input contains integer n (1 ≤ n ≤ 100 000) — the number of cars in the train.  The second line contains n integers pi (1 ≤ pi ≤ n, pi ≠ pj if i ≠ j) — the sequence of the numbers of the cars in the train.

Print a single integer — the minimum number of actions needed to sort the railway cars.

NoteIn the first sample you need first to teleport the 4-th car, and then the 5-th car to the end of the train.

import Data.List.Split (splitOn)
import Data.List

longestsubsequence :: [(Int, Int)] -> (Int, Int) -> Int -> Int -> Int

longestsubsequence [] prev count maxi   = maxi
longestsubsequence (x:xs) prev count maxi
    | snd prev < snd x                  = longestsubsequence xs x (count+1) thus
    | snd prev > snd x && count > maxi  = longestsubsequence xs x 1 count
    | otherwise                         = longestsubsequence xs x 1 maxi
        where thus = if (count+1) > maxi then count+1 else maxi
main = do
    asd <- getLine
    dsa <- getLine
    let amount = read asd :: Int
    let sequence = [read x :: Int | x <- splitOn " " dsa]
    let sortedlist = sort (zip sequence [0..])
    putStrLn (show (amount - longestsubsequence (tail sortedlist) (head sortedlist) 1 1))

{-
Codeforces Round #335

Problem 606 C. Sorting Railway

@author yamaton
@date 2015-12-11
-}

import Control.Applicative
import Control.Monad
-- import Text.Printf (printf)
import qualified Data.List as L
-- import qualified Data.Map.Strict as M
-- import qualified Data.Set as S
-- import qualified Data.Foldable as F
-- import qualified Data.Traversable as T

-- Longest contiguous increasing sequence length
lcis :: Ord a => [a] -> Int
lcis []     = 0
lcis (x:xs) = helper 1 1 x xs
  where
    helper :: Ord a => Int -> Int -> a -> [a] -> Int
    helper best _    _ []    = best
    helper best curr p (q:qs)
      | p <= q    = helper (max best curr_p1) curr_p1 q qs
      | otherwise = helper best               1       q qs
      where curr_p1 = curr + 1

invPerm :: [Int] -> [Int]
invPerm xs = map snd . L.sort $ zip xs [1..]

solve :: [Int] -> Int -> Int
solve xs n = n - lcis (invPerm xs)

main :: IO ()
main = do
    n <- readLn :: IO Int
    xs <- (map read . words) <$> getLine :: IO [Int]
    let result = solve xs n
    print result

    -- IO.hPutStrLn IO.stderr $ printf "xs = %s" (show xs)
    -- IO.hPutStrLn IO.stderr $ printf "result = %d" result

{-# 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 Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
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

groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy' _   []                        = []
groupBy' _   [x]                       = [[x]]
groupBy' cmp (x:xs@(x':_)) | cmp x x'  = (x:y):ys
                           | otherwise = [x]:r
                           where r@(y:ys) = groupBy' cmp xs

main = do
  n <- readLn
  xs <- getInts :: IO [Int]

  print $ minimum $ map (\x -> n-x) $ map length $ groupBy' (<=) $ elems $ array (1, n) $ zip xs [1..]

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Monoid
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.Base
import Data.Function(on)
import Data.Tuple(swap)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

solve :: [Int] -> [(Int,Int)]
solve [] = []
solve [p] = [(p,p+1)]
solve ps = merge (solve ps1) (solve ps2) where
    n = length ps
    (ps1,ps2) = splitAt (div n 2) ps

merge :: [(Int,Int)] -> [(Int,Int)] -> [(Int,Int)]
merge l1 l2 = go (M.fromList l2) l1 where
    go m [] = M.toList m
    go m ((a,b):l) =
        case M.lookup b m of
            Just c -> (a,c) : go (M.delete b m) l
            Nothing -> (a,b) : go m l

main :: IO ()
main = do
    n <- readLn
    ps <- readInts
    let l = solve ps
    print $ n - maximum [ b - a | (a,b) <- l ]

-- IO
readInt :: B.ByteString -> Int
readInt = fromJust . fmap fst . B.readInt
readInts :: IO [Int]
readInts = map readInt . B.words <$> B.getLine
readIntPair :: IO (Int,Int)
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readAllInts :: IO [[Int]]
readAllInts = map (map readInt . B.words) . B.lines <$> B.getContents
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine

-- Utilities
l2p :: [a] -> (a,a)
l2p (a:b:_) = (a,b)
l2p _ = error "l2p: the input list is too short"
p2l :: (a,a) -> [a]
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
inf :: Int
inf = maxBound `div` 2

-- Monad
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i0 judge incr step = sub i0 where
    sub i | judge i = step i >> sub (incr i)
          | otherwise = return ()
rep_ :: Monad m => Int -> (Int -> m ()) -> m ()
rep_ n = stepM_ 0 (<n) (+1)
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
memoize :: (Monad m) => (k -> m (Maybe v)) -> (k -> v -> m ()) -> k -> m v -> m v
memoize getter setter key action = do
    mv <- getter key
    case mv of
        Just v -> return v
        Nothing -> action >>= thru (setter key)

-- Array
newUArray :: (MArray (STUArray s) e (ST s),Ix i) =>
             (i,i) -> e -> ST s (STUArray s i e)
newUArray = newArray
newBArray :: (Ix i) => (i,i) -> e -> ST s (STArray s i e)
newBArray = newArray
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
fromEdges :: Ix i => (i,i) -> [(i,e)] -> Array i [e]
fromEdges = accumArray (flip (:)) []

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Monoid
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.Base
import Data.Function(on)
import Data.Tuple(swap)
import qualified Data.Map as M
import qualified Data.IntMap as IM
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

solve :: Int -> [Int] -> IM.IntMap Int
solve 0 _ = IM.empty
solve 1 (p:_) = IM.singleton p (p+1)
solve n ps = merge (solve n1 ps) (solve n2 (drop n1 ps)) where
    n1 = div n 2
    n2 = n - n1

merge :: IM.IntMap Int -> IM.IntMap Int -> IM.IntMap Int
merge l1 l2 = uncurry IM.union $ go ((,) l2 (IM.empty)) l1 where
    go = IM.foldlWithKey' $ \(!m,!acc) a b ->
        case IM.lookup b m of
            Just c  -> (,) (IM.delete b m) (IM.insert a c acc)
            Nothing -> (,) m (IM.insert a b acc)

main :: IO ()
main = do
    n <- readLn
    ps <- readInts
    let l = solve n ps
    let d = IM.foldlWithKey' (\acc a b -> max acc (b - a)) 0 l
    print $ n - d

-- IO
readInt :: B.ByteString -> Int
readInt = fromJust . fmap fst . B.readInt
readInts :: IO [Int]
readInts = map readInt . B.words <$> B.getLine
readIntPair :: IO (Int,Int)
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readAllInts :: IO [[Int]]
readAllInts = map (map readInt . B.words) . B.lines <$> B.getContents
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine

-- Utilities
l2p :: [a] -> (a,a)
l2p (a:b:_) = (a,b)
l2p _ = error "l2p: the input list is too short"
p2l :: (a,a) -> [a]
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
inf :: Int
inf = maxBound `div` 2

-- Monad
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i0 judge incr step = sub i0 where
    sub i | judge i = step i >> sub (incr i)
          | otherwise = return ()
rep_ :: Monad m => Int -> (Int -> m ()) -> m ()
rep_ n = stepM_ 0 (<n) (+1)
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
memoize :: (Monad m) => (k -> m (Maybe v)) -> (k -> v -> m ()) -> k -> m v -> m v
memoize getter setter key action = do
    mv <- getter key
    case mv of
        Just v -> return v
        Nothing -> action >>= thru (setter key)

-- Array
newUArray :: (MArray (STUArray s) e (ST s),Ix i) =>
             (i,i) -> e -> ST s (STUArray s i e)
newUArray = newArray
newBArray :: (Ix i) => (i,i) -> e -> ST s (STArray s i e)
newBArray = newArray
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
fromEdges :: Ix i => (i,i) -> [(i,e)] -> Array i [e]
fromEdges = accumArray (flip (:)) []

import Data.List.Split (splitOn)
import Data.List

longestsubsequence :: [(Int, Int)] -> (Int, Int) -> Int -> Int -> Int

longestsubsequence [] prev count maxi   = maxi
longestsubsequence (x:xs) prev count maxi
    | snd prev < snd x                  = longestsubsequence xs x (count+1) maxi
    | snd prev > snd x && count > maxi  = longestsubsequence xs x 1 count
    | otherwise                         = longestsubsequence xs x 1 maxi

main = do
    asd <- getLine
    dsa <- getLine
    let amount = read asd :: Int
    let sequence = [read x :: Int | x <- splitOn " " dsa]
    let sortedlist = sort (zip sequence [0..])
    putStrLn (show (amount - longestsubsequence (tail sortedlist) (head sortedlist) 1 1))

import Data.List.Split (splitOn)
import Data.List

longestsubsequence :: [(Int, Int)] -> (Int, Int) -> Int -> Int -> Int

longestsubsequence [] prev count maxi   = maxi
longestsubsequence (x:xs) prev count maxi
    | snd prev < snd x                  = longestsubsequence xs x (count+1) maxi
    | snd prev > snd x && count > maxi  = longestsubsequence xs x 1 count
    | otherwise                         = longestsubsequence xs x 1 maxi

main = do
    asd <- getLine
    dsa <- getLine
    let amount = read asd :: Int
    let sequence = [read x :: Int | x <- splitOn " " dsa]
    let sortedlist = sort (zip sequence [0..])
    putStrLn (show (amount - longestsubsequence (tail sortedlist) (head sortedlist) 1 0))

{-# 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 Data.Function
-- import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
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

groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy' _   []                        = []
groupBy' _   [x]                       = [[x]]
groupBy' cmp (x:xs@(x':_)) | cmp x x'  = (x:y):ys
                           | otherwise = [x]:r
                           where r@(y:ys) = groupBy' cmp xs

main = do
  n <- readLn
  xs <- getInts :: IO [Int]

  print $ minimum $ map (\x -> n-x) $ map length $ groupBy (<=) $ elems $ array (1, n) $ zip xs [1..]


Polycarp has found a table having an infinite number of rows and columns. The rows are numbered from $$$1$$$, starting from the topmost one. The columns are numbered from $$$1$$$, starting from the leftmost one.Initially, the table hasn't been filled and Polycarp wants to fix it. He writes integers from $$$1$$$ and so on to the table as follows.  The figure shows the placement of the numbers from $$$1$$$ to $$$10$$$. The following actions are denoted by the arrows. The leftmost topmost cell of the table is filled with the number $$$1$$$. Then he writes in the table all positive integers beginning from $$$2$$$ sequentially using the following algorithm.First, Polycarp selects the leftmost non-filled cell in the first row and fills it. Then, while the left neighbor of the last filled cell is filled, he goes down and fills the next cell. So he goes down until the last filled cell has a non-filled neighbor to the left (look at the vertical arrow going down in the figure above).After that, he fills the cells from the right to the left until he stops at the first column (look at the horizontal row in the figure above). Then Polycarp selects the leftmost non-filled cell in the first row, goes down, and so on.A friend of Polycarp has a favorite number $$$k$$$. He wants to know which cell will contain the number. Help him to find the indices of the row and the column, such that the intersection of the row and the column is the cell containing the number $$$k$$$.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of one line containing one integer $$$k$$$ ($$$1 \le k \le 10^9$$$) which location must be found.

For each test case, output in a separate line two integers $$$r$$$ and $$$c$$$ ($$$r, c \ge 1$$$) separated by spaces — the indices of the row and the column containing the cell filled by the number $$$k$$$, respectively.

import Control.Monad

getCellPosByIndex :: Integer -> (Integer, Integer)
getCellPosByIndex cell_index = (x, y)
    where
        wave_index = floorSqrt cell_index
        local_index = cell_index - wave_index ^ 2
        x = min wave_index (2 * wave_index - local_index)
        y = min wave_index local_index

floorSqrt :: Integer -> Integer
floorSqrt x = binarySearch 0 x
    where
        binarySearch l r
            | l == r = mid
            | mid ^ 2 <= x = binarySearch mid r
            | otherwise    = binarySearch l (mid-1)
            where mid = (l + r + 1) `div` 2

processTest :: String -> String
processTest input = output
    where
        k = read input
        (x, y) = getCellPosByIndex (k - 1)
        output = show (y+1) ++ " " ++ show (x+1)

main :: IO()
main = do
    tests_n <- read <$> getLine
    tests_inputs <- replicateM tests_n getLine
    let outputs = map processTest tests_inputs
    mapM_ putStrLn outputs

import Control.Monad

getCellPosByIndex :: Integer -> (Integer, Integer)
getCellPosByIndex cell_index = (x, y)
    where
    wave_index = floorSqrt cell_index
    local_index = cell_index - wave_index ^ 2
    x = min wave_index (2 * wave_index - local_index)
    y = min wave_index local_index

floorSqrt :: Integer -> Integer
floorSqrt x = binarySearch 0 x
    where
    binarySearch l r
        | l == r = mid
        | mid ^ 2 <= x = binarySearch mid r
        | otherwise    = binarySearch l (mid-1)
        where mid = (l + r + 1) `div` 2

process_test :: String -> String
process_test input = output
    where
    k = read input
    (x, y) = getCellPosByIndex (k - 1)
    output = show (y+1) ++ " " ++ show (x+1)

main :: IO()
main = do
    tests_n <- read <$> getLine
    tests_inputs <- replicateM tests_n getLine
    let outputs = map process_test tests_inputs
    mapM_ putStrLn outputs

import Control.Monad

getCellPosByIndex :: Integer -> (Integer, Integer)
getCellPosByIndex cell_index = (x, y)
    where
        wave_index = floorSqrt cell_index
        local_index = cell_index - wave_index ^ 2
        x = min wave_index (2 * wave_index - local_index)
        y = min wave_index local_index

floorSqrt :: Integer -> Integer
floorSqrt x = binary_search 0 x
    where binary_search l r
              | l == r = mid
              | mid ^ 2 <= x = binary_search mid r
              | otherwise    = binary_search l (mid-1)
              where mid = (l + r + 1) `div` 2

process_test :: String -> String
process_test input = output
    where
        k = read input
        (x, y) = getCellPosByIndex (k - 1)
        output = show (y+1) ++ " " ++ show (x+1)

main :: IO()
main = do
    tests_n <- read <$> getLine
    tests_inputs <- replicateM tests_n getLine
    let outputs = map process_test tests_inputs
    mapM_ putStrLn outputs

import Control.Monad

getCellPosByIndex :: Integer -> (Integer, Integer)
getCellPosByIndex cell_index = (x, y)
    where i_wave = floorSqrt cell_index
          local_index = cell_index - i_wave ^ 2
          x = min (2*i_wave - local_index) i_wave
          y = min local_index i_wave

floorSqrt :: Integer -> Integer
floorSqrt i = fromIntegral $ length $ takeWhile (<= i) positive_squares
    where positive_squares = map (^2) [1..]

process_test :: String -> String
process_test input = output
    where k = read input
          (x, y) = getCellPosByIndex (k - 1)
          output = show (y+1) ++ " " ++ show (x+1)

main :: IO()
main = do
    tests_n <- read <$> getLine
    tests_inputs <- replicateM tests_n getLine
    let outputs = map process_test tests_inputs
    mapM_ putStrLn outputs

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

a002522_list = scanl (+) 1 [1, 3..] :: [Int64]

calc :: Int64 -> [Int64]
calc 1 = [1,1]
calc 2 = [1,2]
calc x =
  let first = dropWhile (\(i,an) -> an <= x) $ zip [1..] a002522_list
      ((m,an1):_) = first
      n = m-1
      an = (n-1)*(n-1)+1
  in
    if (x-an) <= ((an1-an) `div` 2) then
      [x-an+1, n]
    else
      [n, an1-x]

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let k = read line :: Int64
    putStrLn $ unwords $ map show $ calc k

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out > tmp.txt  &&  diff -sdu -- output.txt tmp.txt  &&  cat -- tmp.txt)

import Prelude
import Control.Monad

main :: IO ()
main = do
    t <- readLn
    tcs <- replicateM t readLn :: IO [Integer]

    (putStr . unlines . map (showP . solve)) tcs

solve k | (b     <= k && k <= b+i-1  ) = (k-b+1, i        )
        | (b+i-1 <  k && k <  b+2*i-1) = (i,     b+2*i-1-k)
        | otherwise                    = error "bad b calculation?"
  where
    i = (floor.sqrt) (fromIntegral (k-1) :: Double) + 1
    b = (i-1)*(i-1) + 1

showP (a,b) = show a ++ " " ++ show b

position :: Int -> (Int, Int)
position n = let
  p | steps == 0 = (sqrtN, 1)
    | steps <= (sqrtN + 1) = (steps, sqrtN + 1)
    | otherwise = (sqrtN + 1, sqrtN * 2 + 2 - steps)
  in p
  where
    sqrtN = (floor . sqrt . fromIntegral) n
    steps = n - sqrtN ^ 2

loop :: Int -> IO()
loop 0 = return ()
loop n = do
    nth <- readLn :: IO Int
    let (r, c) = position nth
    putStrLn $ concat [show r, " ", show c]
    loop $ n - 1

main :: IO()
main = do
    input <- getLine
    let n = read input :: Int
    loop n

import Data.Function ((&))

main = do
    t <- read <$> getLine :: IO Int
    mapM_ main' [1..t]

main':: Int -> IO ()
main' _ = do
    k <- read <$> getLine :: IO Int
    solve k & show' & putStrLn

show' :: (Int, Int) -> String
show' (a, b) = show a ++ " " ++ show b

solve :: Int -> (Int, Int)
solve k
    | row == 0      = (l, 1)
    | row <= l + 1  = (row, l + 1)
    | otherwise     = (l + 1, col)
    where
        l = k & fromIntegral & sqrt & floor :: Int
        row = k - l * l
        col = (l + 1) * (l + 1) - k + 1

module Main where

import           Control.Monad (replicateM_)

main = do
  t <- read <$> getLine
  replicateM_ t
    $ do
      getLine
        >>= (\(x, y) -> putStrLn (show x ++ " " ++ show y)) . solve . read

solve :: Int -> (Int, Int)
solve k = (ij - max (diag - k) 0, ij - max (k - diag) 0)
  where
    ij = contSq k

    diag = ij ^ 2 - ij + 1

contSq :: Int -> Int
contSq x = until ((x <=) . (^ 2)) (+ 1) 1
{-
>>>contSq 100000000
10000

>>>solve 100000000
(10000,1)

(2,4)
-}

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

printResult = do
    k <- readLn :: IO Integer
    let n =  ceiling $ sqrt $ fromInteger k
        a = n*n - k
        r = if a <= n - 1 then n else  n - (a - (n-1))
        c = if a <= n - 1 then a + 1 else n
    putStrLn . unwords . map show $ [r,c]

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


AquaMoon has two binary sequences $$$a$$$ and $$$b$$$, which contain only $$$0$$$ and $$$1$$$. AquaMoon can perform the following two operations any number of times ($$$a_1$$$ is the first element of $$$a$$$, $$$a_2$$$ is the second element of $$$a$$$, and so on): Operation 1: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\operatorname{min}(a_1,a_2)$$$, and remove the first element of $$$a$$$. Operation 2: if $$$a$$$ contains at least two elements, change $$$a_2$$$ to $$$\operatorname{max}(a_1,a_2)$$$, and remove the first element of $$$a$$$.Note that after a removal of the first element of $$$a$$$, the former $$$a_2$$$ becomes the first element of $$$a$$$, the former $$$a_3$$$ becomes the second element of $$$a$$$ and so on, and the length of $$$a$$$ reduces by one.Determine if AquaMoon can make $$$a$$$ equal to $$$b$$$ by using these operations.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 2\,000$$$) — the number of test cases. Description of test cases follows. The first line of each test case contains two integers $$$n$$$, $$$m$$$ ($$$1 \leq n,m \leq 50$$$, $$$m \leq n$$$) — the lengths of $$$a$$$ and $$$b$$$ respectively. The second line of each test case contains a string $$$a$$$ of length $$$n$$$, consisting only $$$0$$$ and $$$1$$$. The third line of each test case contains a string $$$b$$$ of length $$$m$$$, consisting only $$$0$$$ and $$$1$$$.

For each test case, output "YES" if AquaMoon can change $$$a$$$ to $$$b$$$ by using these options; otherwise, output "NO". You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as a positive answer).

NoteIn the first test case, you can use Operation 2 four times to make $$$a$$$ equals to $$$b$$$.In the second test case, you can use Operation 1 four times to make $$$a$$$ equals to $$$b$$$.In the third test case, it can be proved that no matter how we use the operations, it is impossible to make $$$a$$$ equal to $$$b$$$.In the fourth test case, it can be proved that no matter how we use the operations, it is impossible to make $$$a$$$ equal to $$$b$$$.In the fifth test case, you can use Operation 2 three times to make $$$a$$$ become $$$10101$$$, so the first element of $$$a$$$ equals to the first element of $$$b$$$, but it can be proved that no matter how to operate, the second to the fifth elements of $$$a$$$ can't be the same as $$$b$$$.

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