import qualified Data.Map as M
import qualified Data.ByteString.Char8 as B

main = mapM_ putStrLn . solve . map (map (maybe 0 fst . B.readInt) . B.words) . B.lines =<< B.getContents

solve :: [[Int]] -> [String]
solve ([n, m] : as : qs) = map (judge vs) qs
  where
  vs = M.fromList $ findV [] $ zip [1..] as

judge :: M.Map Int Int -> [Int] -> String
judge vs [l, r] = case M.lookupGE l vs of
  Just (i, j)  -> if j <= r then "No" else "Yes"
  Nothing -> "Yes"

findV :: [Int] -> [(Int, Int)] -> [(Int, Int)]
findV  _  ((i, a) : x@(_, b) : xs) | a > b = findV [i] (x : xs)
findV [i] ((_, b) : x@(j, c) : xs) | b < c = (i, j) : findV [] (x : xs)
findV is (x : xs) = findV is xs
findV _ _ = []

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Data.Array.Base
import qualified Data.ByteString.Char8 as B
import Data.List

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

main = do
  [n,m] <- map read.words <$> getLine
  xs <- map readInt.B.words <$> B.getLine
  qs <- map readInt.B.words <$> B.getContents
  putStr.unlines.map (\flg -> if flg then "Yes" else "No") $ solve n xs qs

solve :: Int -> [Int] -> [Int] -> [Bool]
solve n _ qs | n<=2 = replicate (length qs `div` 2) True
solve n xs qs = go qs
   where
     !arr = listArray (0,n-2) $ zipWith (-) (tail xs) xs :: UArray Int Int
     !segtree = mkSegTree 0 (n-2) arr
     go (l:r:rest) = query (l-1) (r-2) segtree : go rest
     go _ = []

data SegTree = Node !Bool !Int !Int !Int !Int !SegTree !SegTree
             | Leaf !Bool !Int !Int

getMin :: SegTree -> Int
getMin (Node _ _ _ val _ _ _) = val
getMin (Leaf _ _ val )        = val

getMax :: SegTree -> Int
getMax (Node _ _ _ _ val _ _) = val
getMax (Leaf _ _ val )        = val

getFlg :: SegTree -> Bool
getFlg (Node flg _ _ _ _ _ _) = flg
getFlg (Leaf flg _ _ ) = flg

mkSegTree :: Int -> Int -> UArray Int Int -> SegTree
mkSegTree l r arr
  | l/=r = do
      let !m = (l+r) `quot` 2
          lt = mkSegTree l m arr
          rt = mkSegTree (m+1) r arr
      Node (getFlg lt && getFlg rt && (getMin lt >= 0 || getMax rt <= 0) ) l r
           (min (getMin lt) (getMin rt)) (max (getMax lt) (getMax rt)) lt rt
  | otherwise = Leaf True l (unsafeAt arr l)

query :: Int -> Int -> SegTree -> Bool
query kl kr segtree = if kl>=kr then True else go segtree
   where
     go (Node flg l r _ _ lt rt)
       | r<kl  || kr<l  = True
       | kl<=l && r<=kr = flg
       | otherwise = go lt && go rt && (queryMin kl kr lt >= 0 || queryMax kl kr rt <= 0)
     go (Leaf _ _ _ ) = True

queryMin :: Int -> Int -> SegTree -> Int
queryMin kl kr segtree = go segtree
   where
     go (Node flg l r v _ lt rt)
       | r<kl  || kr<l  = maxBound
       | kl<=l && r<=kr = v
       | otherwise = go lt `min` go rt
     go (Leaf _ k v )
       | kl<=k && k<=kr = v
       | otherwise = maxBound

queryMax :: Int -> Int -> SegTree -> Int
queryMax kl kr segtree = go segtree
   where
     go (Node flg l r _ v lt rt)
       | r<kl  || kr<l  = minBound
       | kl<=l && r<=kr = v
       | otherwise = go lt `max` go rt
     go (Leaf _ k v )
       | kl<=k && k<=kr = v
       | otherwise = minBound

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Data.Array.Base
import qualified Data.ByteString.Char8 as B
import Data.List

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

main = do
  [n,m] <- map read.words <$> getLine
  xs <- map readInt.B.words <$> B.getLine
  qs <- map readInt.B.words <$> B.getContents
  putStr.unlines.map (\flg -> if flg then "Yes" else "No") $ solve n xs qs

solve :: Int -> [Int] -> [Int] -> [Bool]
solve n _ qs | n<=2 = replicate (length qs `div` 2) True
solve n xs qs = go qs
   where
     !arr = listArray (0,n-2) $ zipWith (-) (tail xs) xs :: UArray Int Int
     !segtree = mkSegTree 0 (n-2) arr
     go (l:r:rest) = query (l-1) (r-2) segtree : go rest
     go _ = []

data SegTree = Node !Bool !Int !Int !Int !Int !SegTree !SegTree
             | Leaf !Bool !Int !Int

getMin :: SegTree -> Int
getMin (Node _ _ _ val _ _ _) = val
getMin (Leaf _ _ val )        = val

getMax :: SegTree -> Int
getMax (Node _ _ _ _ val _ _) = val
getMax (Leaf _ _ val )        = val

getFlg :: SegTree -> Bool
getFlg (Node flg _ _ _ _ _ _) = flg
getFlg (Leaf flg _ _ ) = flg

mkSegTree :: Int -> Int -> UArray Int Int -> SegTree
mkSegTree l r arr
  | l/=r = do
      let !m = (l+r) `quot` 2
          lt = mkSegTree l m arr
          rt = mkSegTree (m+1) r arr
      if getFlg lt && getFlg rt
         then if getMin lt < 0 && 0 < getMax rt
                 then Node False l r (min (getMin lt) (getMin rt)) (max (getMax lt) (getMax rt)) lt rt
                 else Node True  l r (min (getMin lt) (getMin rt)) (max (getMax lt) (getMax rt)) lt rt
         else Node False l r (min (getMin lt) (getMin rt)) (max (getMax lt) (getMax rt)) lt rt
  | otherwise = Leaf True l (unsafeAt arr l)

query :: Int -> Int -> SegTree -> Bool
query kl kr segtree = if kl>=kr then True else go segtree
   where
     go (Node flg l r v _ lt rt)
       | r<kl  || kr<l  = True
       | kl<=l && r<=kr = flg
       | otherwise = (queryMin kl kr lt >= 0 || queryMax kl kr rt <= 0) && go lt && go rt
     go (Leaf _ _ _ ) = True

queryMin :: Int -> Int -> SegTree -> Int
queryMin kl kr segtree = go segtree
   where
     go (Node flg l r v _ lt rt)
       | r<kl  || kr<l  = maxBound
       | kl<=l && r<=kr = v
       | otherwise = go lt `min` go rt
     go (Leaf _ _ v ) = v

queryMax :: Int -> Int -> SegTree -> Int
queryMax kl kr segtree = go segtree
   where
     go (Node flg l r _ v lt rt)
       | r<kl  || kr<l  = minBound
       | kl<=l && r<=kr = v
       | otherwise = go lt `max` go rt
     go (Leaf _ _ v ) = v


main = interact $ f . read
f n = unlines $ map (g $ div (n + 1) 2) [1..n]
g x y = star ++ diam ++ star
  where star = replicate ns '*'
        diam = replicate (x * 2 - 1 - 2 * ns) 'D'
        ns = abs $ x - y

import Data.List
mkLine n m = replicate m '*' ++ replicate (n-2*m) 'D' ++ replicate m '*'
mkAns n = map (mkLine n) ([n`div`2,n`div`2-1..0] ++ [1..n`div`2])
main = readLn >>= mapM_ putStrLn . mkAns

solve :: Int -> [String]
solve n  =  [getLine i | i <- [1..n]]
  where
    getLine i  =  [getChar i j | j <- [1..n]]
    getChar i j
      | abs (m - i) + abs (m - j) < m  =  'D'
      | otherwise  =  '*'
    m  =  n `div` 2 + 1

main :: IO()
main  =  readLn >>= mapM_ putStrLn . solve

s m = replicate m '*'
main = do
  n <- read `fmap` getLine
  let xs = [1,3..n] ++ [n-2,n-4..1]
      sol= [concat [s m,replicate i 'D',s m] | i <- xs
           , let m = (n-i)`div`2]
  putStr . unlines $ sol

import Data.List

rowSizes :: Int -> [Int]
rowSizes n = gradient ++ [n] ++ (reverse gradient)
    where gradient = takeWhile (/=n) $ iterate (+2) 1

renderRow :: Int -> Int -> String
renderRow n s = padding ++ (replicate s 'D') ++ padding
    where t = (n - s) `div` 2
          padding = replicate t '*'

solve :: Int -> String
solve n = unlines $ map (renderRow n) $ rowSizes n

main = interact $ solve . read

main = do
    n <- readLn :: IO Int
    putStr $ unlines $ map (gen n) ([1, 3 .. n] ++ [n - 2, n - 4 .. 1])
    where
        gen :: Int -> Int -> [Char]
        gen n x = out ++ (replicate x 'D') ++ out
            where out = replicate ((n - x) `div` 2) '*'

main :: IO ()
main = readLn >>= mapM_ putStrLn . solve

solve :: Int -> [String]
solve n = [ replicate (m - i) '*' ++ replicate (2 * i + 1) 'D'
         ++ replicate (m - i) '*' | i <- [0..m] ++ [m-1, m-2 .. 0] ]
  where m = n `div` 2

import Control.Monad (liftM2)
main = interact $ unlines . liftM2 map row peak . read
peak n = [1 .. h+1] ++ [h,h-1..1] where h = n `div` 2
row n k = g ++ replicate (2*k-1) 'D' ++ g
  where g = replicate ((n-2*k+1) `div` 2) '*'

s n=[[if abs(i-(n`div`2+1))+abs(j-(n`div`2+1))>n`div`2 then '*' else 'D'|j<-[1..n]]|i<-[1..n]]
main=interact$unlines.s.read

import Control.Applicative
import Data.List

process n = (reverse k) ++ [(replicate n 'D')] ++ k
	where k = [ replicate i '*' ++ replicate j 'D' ++ replicate i '*'| i<-[1..div n 2], let j = n-2*i]

main= do
	n<-  read  <$>getLine::IO Int
	putStrLn $ intercalate "\n" $ process n

process :: Int -> [[Char]]
process n
    | even n = undefined
    | otherwise = [[if n'-i' <= j && j <= n'+i' then 'D' else '*' | j <- [0..(n-1)]] | i <- [0..(n-1)], let i' = min i (n-1-i)]
    where n' = n `div` 2

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    putStrLn . unlines $ process n

main = do
    n <- fmap read getLine :: IO Int
    putStrLn $ f n n
f 0 n = ""
f m n = x ++ y ++ x ++ "\n" ++ (f (m - 1) n) where
    k = if 2*m-1<=n then 2*m-1 else 2*(n-m)+1
    x = [1..div (n-k) 2]>>"*"
    y = [1..k]>>"D"

f :: Int -> Int -> String
f s l | l <= s `quot` 2    = (replicate ((s `quot` 2) - l+1) '*') ++ (replicate (2*(l) -1) 'D') ++ (replicate ((s `quot` 2) - l+1) '*')
      | l == s `quot` 2 +1 = replicate s 'D'
      | otherwise          = f s (s-l+1)

main = do
  line <- getLine
  let num = read line :: Int
      lst = map (f num) [1..num]
  mapM putStrLn lst

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O2 -optc-O2 #-}

main :: IO ()
main = interact $ unlines . solve . read

solve :: Int -> [String]
solve n = [l | x <- [1..n], let l = out x n]

out :: Int -> Int -> String
out i n
        | i*2-1 > n = out (n+1-i) n
        | otherwise =
            let
              p = i*2-1
              q = (n-p) `div` 2
            in
              replicate q '*' ++ replicate p 'D' ++ replicate q '*'

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O2 -optc-O2 #-}

main :: IO ()
main = interact $ unlines . solve . read

solve :: Int -> [String]
solve n = [out i n | i <- [1..n]]

out :: Int -> Int -> String
out i n
        | i*2-1 > n = out (n+1-i) n
        | otherwise =
            let
              p = i*2-1
              q = (n-p) `div` 2
            in
              replicate q '*' ++ replicate p 'D' ++ replicate q '*'

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O2 -optc-O2 #-}
import qualified Data.List as L
import qualified Data.ByteString.Lazy.Char8 as LC

main :: IO ()
main = do
  (line:_) <- fmap LC.words LC.getContents
  let n = readInt line
  putStr $ unlines $ out 1 (n `div` 2 + 1) n

out :: Int -> Int -> Int -> [String]
out _ _ 0 = []
out i n k =
          let
            j = if i < k then i+1 else i-1
          in
            (replicate (n-i) '*' ++ replicate (i*2-1) 'D' ++ replicate (n-i) '*') : out j n (k-1)

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

readInt :: LC.ByteString -> Int
readInt = LC.foldl' (\x c -> 10 * x + fromEnum c - 48) 0

main = do
	n<-getLine
	let res1 = solve (read n) 1
	let res2 = init $ unlines $reverse $ init $ lines res1
	putStr $ res1
	putStrLn res2

solve n l | l <=n = spaces ((n-l)) ++ printer (generator l) ++ spaces ((n-l))++ "\n" ++ solve n (l+2)
          | otherwise = ""

generator n =  replicate (n) "D"

spaces n = replicate (div n 2) '*'

printer s =  concat $  map (\x->  x ++ "") s

import Data.List

main = putStrLn . unlines . solve . read =<< getLine

solve :: Int -> [String]
solve n = solve' 1 True
    where solve' :: Int -> Bool -> [String]
          solve' x inc | x < 0 = []
                       | x > n = solve' (x - 4) False
                       | otherwise = let f = div (n - x) 2
                                         s = (replicate f '*') ++ (replicate x 'D') ++ (replicate f '*')
                                     in if inc
                                        then s:solve' (x + 2) inc
                                        else s:solve' (x - 2) inc

import Data.List
import Data.Function
import Data.Char

main = interact $ unlines . getAns . read

getAns :: Int -> [String]
getAns n = do
	x <- [1..n]
	return (getL x n)

getL :: Int -> Int -> String
getL x n
	| x * 2 - 1 > n = getL (n + 1 - x) n
	| otherwise = let a = x * 2 - 1; b = (n - a) `div` 2
				  in replicate b '*' ++ replicate a 'D' ++ replicate b '*'

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

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

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

main = do
  n <- readLn

  let
    s = [[f i j | j <- [1..n]] | i <- [1..n]]
    f i j = if abs (i-c) + abs (j-c) <= n`div`2 then 'D' else '*'
      where
        c = n`div`2+1

  putStr $ unlines s


import Control.Monad

solve :: IO ()
solve = do
    n <- readLn :: IO Int
    a <- readMany :: IO [Int]
    let go [] 0     = 1
        go [] _     = 0
        go (x:xs) s = go xs s + go xs (s + x) + go xs (s - x)
    putStrLn $ if go a 0 > 1 then "YES" else "NO"

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

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

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

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [_n] <- readInts
    a <- map abs <$> readInts
    let  opts = sort $ map (foldl' (+) 0) $ subsequences a
    --forM_ (subsequences a) putInts
    lift $ putStrLn $ if  any (uncurry (==)) $ zip opts $ tail opts
      then  "YES"
      else  "NO"

type SIO = StateT P.ByteString IO

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

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

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

import Control.Arrow ((>>>))
import Control.Monad (filterM)
import Data.Bool (bool)
import Data.List (group, sort)

main :: IO ()
main =
  interact $
    lines
      >>> drop 1
      >>> chunksOf 2
      >>> map (last >>> words >>> map read >>> solve >>> bool "No" "Yes")
      >>> unlines

solve :: [Int] -> Bool
solve =
  any ((> 1) . length) -- does any sum occur more than once?
    . group
    . sort
    . map sum -- subsequence sums
    . filterM (const [False, True]) -- all subsequences
    . sort
    . map abs

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

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE Strict #-}

import Control.Applicative (liftA2)
import Control.Monad (filterM, guard, replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.List (group, sort, delete)
import Data.Maybe (fromJust, fromMaybe)
import Debug.Trace (trace)

main :: IO ()
main = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))

testCase :: Scanner String
testCase = maybe "Yes" (const "No") . solve <$> numberOf int

-- Nothing -> Yes, Just () -> No
solve :: [Int] -> Maybe ()
solve xs = do
  xs <- pure $ sort (map abs xs)
  yesIf $ 0 `elem` xs
  yesIf $ any ((> 1) . length) $ group xs
  yesIf $ any ((> 1) . length) . group . sort $ subsums xs
  where
    yesIf = guard . not
    subseq = filterM (const [False, True])
    subsums = map sum . subseq

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

debug a = trace (show a) a

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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


ans :: IO String
ans = do
 n <- readLn :: IO Int
 sInput <- getLine
 fInput <- getLine
 let s = [read x :: Int | x <- words sInput]
 let f = [read x :: Int | x <- words fInput]
 let maxs = [max (fst x) (snd x) | x <- zip (tail s) f]
 let results = (head f - head s) : [(fst x) - (snd x) | x <- zip (tail f) maxs]
 return $ unwords [show x | x <- results]

main :: IO ()
main = do
 t <- readLn :: IO Int
 results <- sequence $ replicate t ans
 putStrLn $ unlines results

module Main where

import Data.List
import Data.Maybe
import qualified Data.Map.Strict as Map

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

sep (_:x:y:xs) = (x,y):(sep xs)

parse (x,y) = (phi x, phi y)
  where phi = (map read) . words

format = unwords . map show

solve (ss,fs) = solve' 0 ss fs

solve' _ [] [] = []
solve' f0 (s:ss) (f:fs) = (f - max s f0):(solve' f ss fs)

-- boilerplate {{{1
-- vim: foldmethod=marker
-- pragmas {{{2
{-# LANGUAGE BangPatterns        #-}
{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE DeriveFoldable      #-}
{-# LANGUAGE DeriveTraversable   #-}
{-# LANGUAGE FlexibleContexts    #-}
{-# LANGUAGE LambdaCase          #-}
{-# LANGUAGE MultiWayIf          #-}
{-# LANGUAGE RankNTypes          #-}
{-# LANGUAGE StandaloneDeriving  #-}
{-# LANGUAGE TupleSections       #-}
{-# LANGUAGE TypeApplications    #-}

module Main where -- {{{2

import Control.Applicative
import Control.Arrow ( (|||), (&&&) )
import Control.Monad
import Control.Monad.ST
import Data.Array.IArray
import Data.Array.IO
import Data.Array.ST
import Data.Array.Unboxed
import Data.Bifunctor
import Data.Bits
import Data.Bool
import Data.Char
import Data.Foldable hiding ( sum, product )
import Data.Function
import Data.Functor
import Data.IntMap ( IntMap )
import Data.IntSet ( IntSet )
import Data.List hiding ( sum, product )
import Data.Map ( Map )
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Semigroup ( Min(..), Max(..) )
import Data.Sequence ( Seq )
import Data.Set ( Set )
import Data.Text ( Text )
import Data.Traversable
import Data.Tuple
import Debug.Trace
import Prelude hiding ( sum, product )
import System.IO
-- import System.Random
import Text.Printf
import qualified Data.ByteString.Char8 as C
import qualified Data.IntMap           as IM
import qualified Data.IntSet           as IS
import qualified Data.Map              as LM
import qualified Data.Map.Strict       as M
import qualified Data.Sequence         as Q
import qualified Data.Set              as S
import qualified Data.Text             as T
import qualified Data.Text.IO          as T

-- utilites {{{2
readInt s = let Just (i,_) = C.readInt s in i :: Int
getInt = readInt <$> C.getLine
getInts = map readInt . C.words <$> C.getLine
putShows :: Show a => [a] -> IO ()
putShows = putStrLn . unwords . map show
ynq = putStrLn . bool "NO" "YES"
gcount g@(x:_) = (x, length g)
modulus = 10^9 + 7 :: Int
mod' x = rem x modulus
tri n = quot (n * n + n) 2
sum t     = foldl' (+) 0 t
product t = foldl' (*) 1 t
mprint :: Show a => String -> Maybe a -> IO ()
mprint s = maybe (putStrLn s) print
ifM :: Monad m => m Bool -> m a -> m a -> m a
ifM b t e = b >>= bool e t
whenM :: Monad m => m Bool -> m () -> m ()
whenM b t = ifM b t (pure ())

-- }}}1

main = getInt >>= flip replicateM_ docase

docase = do
    [n] <- getInts
    aa  <- getInts
    bb  <- getInts

    let f a z b = b - max a z
    let dd = zipWith3 f aa (0:bb) bb
    putShows dd

import Data.Int

ans :: IO String
ans = do
 n <- readLn :: IO Int
 input <- getLine
 let s = [read x :: Int32 | x <- words input]
 input <- getLine
 let f = [read x :: Int32 | x <- words input]
 let maxs = [max (fst x) (snd x) | x <- zip (tail s) f]
 let results = (head f - head s) : [(fst x) - (snd x) | x <- zip (tail f) maxs]
 return $ unwords [show x | x <- results]

main :: IO ()
main = do
 t <- readLn :: IO Int
 results <- sequence $ replicate t ans
 putStrLn $ unlines results

ans :: IO String
ans = do
 n <- readLn :: IO Int
 input <- getLine
 let s = [read x :: Int | x <- words input]
 input <- getLine
 let f = [read x :: Int | x <- words input]
 let maxs = [max (fst x) (snd x) | x <- zip (tail s) f]
 let results = (head f - head s) : [(fst x) - (snd x) | x <- zip (tail f) maxs]
 return $ unwords [show x | x <- results]

main :: IO ()
main = do
 t <- readLn :: IO Int
 results <- sequence $ replicate t ans
 putStrLn $ unlines results

calc' :: [Int] -> [Int] -> Int -> [Int]
calc' [] [y] later = [y - later]
calc' (x : xs) (y : ys) later = [y - later] ++ calc' xs ys (max y x)

calc :: [Int] -> [Int] -> [Int]
calc [x] [y] = [y - x]
calc (x0 : x1 : xs) (y : ys) = [y - x0] ++ calc' xs ys (max y x1)

ans :: IO String
ans = do
 n <- readLn :: IO Int
 sInput <- getLine
 fInput <- getLine
 let s = [read x :: Int | x <- words sInput]
 let f = [read x :: Int | x <- words fInput]
 let results = calc s f
 return $ unwords [show x | x <- results]

main :: IO ()
main = do
 t <- readLn :: IO Int
 results <- sequence $ replicate t ans
 putStrLn $ unlines results

calc' :: [Int] -> [Int] -> Int -> [Int]
calc' [_] [y] later = [y - later]
calc' (_ : x : xs) (y : ys) later = [y - later] ++ calc' (x : xs) ys (max y x)

calc :: [Int] -> [Int] -> [Int]
calc [x] [y] = [y - x]
calc (x : xs) (y : ys) = [y - x] ++ calc' xs ys (max y $ head xs)

ans :: IO String
ans = do
 n <- readLn :: IO Int
 sInput <- getLine
 fInput <- getLine
 let s = [read x :: Int | x <- words sInput]
 let f = [read x :: Int | x <- words fInput]
 let results = calc s f
 return $ unwords [show x | x <- results]

main :: IO ()
main = do
 t <- readLn :: IO Int
 results <- sequence $ replicate t ans
 putStrLn $ unlines results


module Main where

import Control.Monad
import Data.List

main = do
    n <- read `liftM` getLine :: IO Int
    str <- getLine

    let sentenceSize = snd $ mapAccumL (\last this -> (this, this - last - 1)) (0-2) $
            findIndices (\a -> a == '.' || a == '?' || a == '!') str

        packMessage [] _ = return 0
        packMessage (s:ss) r =
            if s <= r
            then packMessage ss (r-s-1)
            else if s <= n
            then packMessage ss (n-s-1) >>= return . (1+)
            else fail ""

        res = packMessage sentenceSize 0

    putStrLn $ case res of
        Just n -> show n
        Nothing -> "Impossible"

main = interact(solve.take 2.lines)

solve (sn:cs:[]) = if count>0 then show count else "Impossible" where
    n = read sn
    count = cnt n cs
    cnt n cs = cnt' cs 0 where
        cnt' []       acc  = acc
        cnt' (' ':cs) acc  = cnt' cs acc
        cnt' cs       acc  = if l>0 then cnt' (drop l cs) (acc+1) else 0 where
            l = length $ dropWhile (`notElem` ".!?") $ reverse (take n cs)

solve :: Int -> String -> Maybe Int
solve n text
  | any (> n) ls  =  Nothing
  | otherwise  =  Just $ length $ groups ls
  where
    is  =  map fst $ filter (flip elem ".?!" . snd) $ zip [1..] text
    ls  =  head is : zipWith (\i j -> j - i - 1) is (tail is)
    groups []  =  []
    groups ls  =  (take k ls) : groups (drop k ls)
      where
        k  =  length $ tail $ takeWhile (<= n) $ scanl (\s i -> s + i + 1) (-1) ls

main :: IO ()
main  =  do
    n  <-  readLn
    s  <-  getLine
    putStrLn $ maybe "Impossible" show $ solve n s

module Main where

import Control.Monad
import Data.List

main = do
    n <- read `liftM` getLine :: IO Int
    str <- getLine

    let sentenceSize = tail $ scanl (\last this -> this - last) 0 $
            findIndices (\a -> a == '.' || a == '?' || a == '!') (' ':str)

        packMessage [] _ = return 0
        packMessage (s:ss) r =
            if s <= r
            then packMessage ss (r-s-1)
            else if s <= n
            then packMessage ss (n-s-1) >>= return . (1+)
            else fail ""

        res = packMessage sentenceSize 0

    putStrLn $ case res of
        Just n -> show n
        Nothing -> "Impossible"


import Control.Applicative
import Data.Array

readWords = map read . words <$> getLine

solve n m c as bs =
		zipWith (+.) as $ zipWith (-.) (sums ++ replicate (n-m) (last sums)) (replicate (n-m+1) 0 ++ sums)
	where
		a +. b = (a + b) `mod` c
		a -. b = (a - b) `mod` c

		sums = scanl1 (+.) bs

main = do
		[n, m, c] <- readWords
		as <- readWords
		bs <- readWords
		putStrLn $ unwords $ map show $ solve n m c as bs

main :: IO ()
main =
    do cs <- getContents
       (putStr.showSolve.solve.parseIn) cs

solve :: (Int,Int,Int,[Int],[Int])->[Int]
solve (n,m,c,as,bs) = map (\x->mod x c) $ foldl (zipWith (+)) as adds
    where
      adds = encryptB (n-m+1) n bs

showSolve::[Int]->String
showSolve [] = ""
showSolve [i] = show i
showSolve (i:is) = show i ++ " " ++ showSolve is

parseIn :: String->(Int,Int,Int,[Int],[Int])
parseIn s = (n,m,c,as,bs)
            where
              [l1,la,lb] = lines s
              [n,m,c] = map read $ words l1
              as = take n $ map read $ words la
              bs = take m $ map read $ words lb

encryptB::Int->Int->[Int]->[[Int]]
encryptB 1 _ x = [x]
encryptB k n x = (listFill n x) : (encryptB (k-1) n (0:x))

listFill::Int->[Int]->[Int]
listFill n l = l++(take (n-(length l)) [0,0..])

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

-- readWords = map read . words <$> getLine
readWords =  map (fst . fromJust . B.readInt) . B.words <$> B.getLine

solve n m c as bs =
		zipWith (+.) as $ zipWith (-.) (sums ++ replicate (n-m) (last sums)) (replicate (n-m+1) 0 ++ sums)
	where
		a +. b = (a + b) `mod` c
		a -. b = (a - b) `mod` c

		sums = scanl1 (+.) bs

main = do
		[n, m, c] <- readWords
		as <- readWords
		bs <- readWords
		putStrLn $ unwords $ map show $ solve n m c as bs

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

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

solve n m c as bs =
		zipWith (+.) as sums
	where
		a +. b = (a + b) `mod` c
		a -. b = (a - b) `mod` c

		starts = scanl1 (+.) bs
		sums = zipWith (-.) (starts ++ replicate (n-m) (last starts)) (replicate (n-m+1) 0 ++ starts)

main = do
		[n, m, c] <- readWords
		as <- readWords
		bs <- readWords
		putStrLn $ unwords $ map show $ solve n m c as bs

import Control.Applicative
import Data.Array

main = do
		[n, m, c] <- readWords
		as <- readWords
		bs <- readWords
		putStrLn $ unwords $ map show $ solve n m c as bs
	where
		readWords = map read . words <$> getLine

		solve n m c as bs =
				zipWith (+.) as $ [(sums ! (min i m)) -. (sums ! ((max (i+m-n) 1) - 1)) | i <- [1..n]]
			where
				a +. b = (a + b) `mod` c
				a -. b = (a - b) `mod` c

				sums = listArray (0, m) $ scanl (+.) 0 bs

import Control.Applicative
import Data.Array

main = do
		[n, m, c] <- readWords
		as <- readWords
		bs <- readWords
		putStrLn $ unwords $ map show $ solve n m c as bs
	where
		readWords = map read . words <$> getLine

		solve n m c as bs =
				zipWith (+.) as $ [(sums ! (min i m)) -. (sums ! (max (i+m-n) 1)) - 1 | i <- [1..n]]
			where
				a +. b = (a + b) `mod` c
				a -. b = (a - b) `mod` c

				sums = listArray (0, m) $ scanl (+.) 0 bs


-- {-# LANGUAGE
--     BangPatterns
--   , BlockArguments
--   , DataKinds
--   , DeriveGeneric
--   , DerivingStrategies
--   , DerivingVia
--   , FlexibleContexts
--   , FlexibleInstances
--   , GADTs
--   , GeneralizedNewtypeDeriving
--   , KindSignatures
--   , LambdaCase
--   , MultiParamTypeClasses
--   , MultiWayIf
--   , NPlusKPatterns
--   , NegativeLiterals
--   , OverloadedLabels
--   , OverloadedStrings
--   , ParallelListComp
--   , PolyKinds
--   , RankNTypes
--   , ScopedTypeVariables
--   , StrictData
--   , TupleSections
--   , TypeApplications
--   , TypeFamilies
--   , TypeOperators
--   , UndecidableInstances
--   , ViewPatterns
--   #-}

module Main where

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Control.Monad.ST
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.Foldable
import           Data.Functor
import           Data.Int
import           Data.List
import           Data.Maybe
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup                 ( Max(..)
                                                , Min(..)
                                                , All(..)
                                                , Arg(..)
                                                )
import           Data.Ratio
-- import           Data.Vector.Unboxing.Mutable   ( Unboxable )
-- import qualified Data.Vector.Unboxing.Mutable  as V
-- import           System.IO
-- import           Data.Proxy
-- import           GHC.TypeLits
-- import           GHC.Generics                   ( Generic )
-- import           GHC.Exts
-- import           Control.Monad.Primitive        ( PrimMonad(PrimState) )
-- import           Control.Monad.Trans.Class      ( MonadTrans(lift) )

-- {-# ANN module ("Hlint: ignore Unused LANGUAGE pragma" :: String) #-}
-- {-# ANN module ("Hlint: ignore Reduce duplication" :: String) #-}

twice :: (a -> a -> b) -> a -> b
twice f x = f x x

both :: Arrow a => a b c -> a (b, b) (c, c)
both = twice (***)

readsLn :: Read a => IO [a]
readsLn = mapM readIO . words =<< getLine

getInt :: IO Int
getInt = fst . fromJust . BS.readInt <$> BS.getLine

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

getInteger :: IO Integer
getInteger = fst . fromJust . BS.readInteger <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine

main = do
  t <- getInt
  replicateM_ t $ do
    [n, m, r, c] <- getInts
    print $ maximum [n - r + m - c, r - 1 + m - c, n - r + c - 1, r - 1 + c - 1]

import Control.Arrow ((>>>))

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

solve :: [Int] -> Int
solve [n, m, r, c] = max (r - 1) (n - r) + max (c - 1) (m - c)

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

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

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

import Data.Array.ST.Safe
import Data.STRef

-- import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInteger = readLn :: IO Integer
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine

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

modifyArray a i f = writeArray a i =<< f <$> readArray a i

printList [a] = print a
printList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as

main = readInt >>= flip replicateM solve

solve = do
	[ n, m, r, c ] <- readInts
	print $ max ( r - 1 ) ( n - r ) + max ( c - 1 ) ( m - c )

import Control.Monad

main = do
  cases <- read <$> getLine
  replicateM_ cases $ do
    [n, m, r, c] <- (map read . words) <$> getLine :: IO [Int]
    putStrLn $ show $ (max (abs $ 1 - r) (abs $ n - r)) + (max (abs $ 1 - c) (m - c))

{-# LANGUAGE
    BangPatterns
  , BlockArguments
  , DataKinds
  , DeriveGeneric
  , DerivingStrategies
  , DerivingVia
  , FlexibleContexts
  , FlexibleInstances
  , GADTs
  , GeneralizedNewtypeDeriving
  , KindSignatures
  , LambdaCase
  , MultiParamTypeClasses
  , MultiWayIf
  , NPlusKPatterns
  , NegativeLiterals
  , OverloadedLabels
  , OverloadedStrings
  , ParallelListComp
  , PolyKinds
  , RankNTypes
  , ScopedTypeVariables
  , StrictData
  , TupleSections
  , TypeApplications
  , TypeFamilies
  , TypeOperators
  , UndecidableInstances
  , ViewPatterns
  #-}

module Main where

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Control.Monad.ST
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.Foldable
import           Data.Functor
import           Data.Int
import           Data.List
import           Data.Maybe
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup                 ( Max(..)
                                                , Min(..)
                                                , All(..)
                                                , Arg(..)
                                                )
import           Data.Ratio
-- import           Data.Vector.Unboxing.Mutable   ( Unboxable )
-- import qualified Data.Vector.Unboxing.Mutable  as V
import           System.IO
import           Data.Proxy
import           GHC.TypeLits
import           GHC.Generics                   ( Generic )
-- import           Control.Monad.Primitive        ( PrimMonad(PrimState) )
import           Control.Monad.Trans.Class      ( MonadTrans(lift) )
import           Control.Monad.Cont
import           Text.Parsec.ByteString

-- #if defined(LOCAL_ZER0STAR)
-- {-# ANN module ("Hlint: ignore Unused LANGUAGE pragma" :: String) #-}
-- {-# ANN module ("Hlint: ignore Reduce duplication" :: String) #-}
-- #endif

twice :: (a -> a -> b) -> a -> b
twice f x = f x x

both :: Arrow a => a b c -> a (b, b) (c, c)
both = twice (***)

readsLn :: Read a => IO [a]
readsLn = mapM readIO . words =<< getLine

getInt :: IO Int
getInt = fst . fromJust . BS.readInt <$> BS.getLine

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

getInteger :: IO Integer
getInteger = fst . fromJust . BS.readInteger <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine

main = do
  t <- getInt
  replicateM_
    t
    do
      [x, y, r, c] <- getInts
      print $ max (r - 1) (x - r) + max (c - 1) (y - c)

{-# LANGUAGE
    BangPatterns
  , BlockArguments
  , DataKinds
  , DeriveGeneric
  , DerivingStrategies
  , DerivingVia
  , FlexibleContexts
  , FlexibleInstances
  , GADTs
  , GeneralizedNewtypeDeriving
  , KindSignatures
  , LambdaCase
  , MultiParamTypeClasses
  , MultiWayIf
  , NPlusKPatterns
  , NegativeLiterals
  , OverloadedLabels
  , OverloadedStrings
  , ParallelListComp
  , PolyKinds
  , RankNTypes
  , ScopedTypeVariables
  , StrictData
  , TupleSections
  , TypeApplications
  , TypeFamilies
  , TypeOperators
  , UndecidableInstances
  , ViewPatterns
  #-}

module Main where

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Control.Monad.ST
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.Foldable
import           Data.Functor
import           Data.Int
import           Data.List
import           Data.Maybe
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup                 ( Max(..)
                                                , Min(..)
                                                , All(..)
                                                , Arg(..)
                                                )
import           Data.Ratio
-- import           Data.Vector.Unboxing.Mutable   ( Unboxable )
-- import qualified Data.Vector.Unboxing.Mutable  as V
-- import           System.IO
-- import           Data.Proxy
-- import           GHC.TypeLits
-- import           GHC.Generics                   ( Generic )
-- import           GHC.Exts
-- import           Control.Monad.Primitive        ( PrimMonad(PrimState) )
-- import           Control.Monad.Trans.Class      ( MonadTrans(lift) )

-- #if defined(LOCAL_ZER0STAR)
-- {-# ANN module ("Hlint: ignore Unused LANGUAGE pragma" :: String) #-}
-- {-# ANN module ("Hlint: ignore Reduce duplication" :: String) #-}
-- #endif

twice :: (a -> a -> b) -> a -> b
twice f x = f x x

both :: Arrow a => a b c -> a (b, b) (c, c)
both = twice (***)

readsLn :: Read a => IO [a]
readsLn = mapM readIO . words =<< getLine

getInt :: IO Int
getInt = fst . fromJust . BS.readInt <$> BS.getLine

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

getInteger :: IO Integer
getInteger = fst . fromJust . BS.readInteger <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine

main = do
  t <- getInt
  replicateM_
    t
    do
      [x, y, r, c] <- getInts
      print $ max (r - 1) (x - r) + max (c - 1) (y - c)

{-# LANGUAGE
    BangPatterns
  , BlockArguments
  , DataKinds
  , DeriveGeneric
  , DerivingStrategies
  , DerivingVia
  , FlexibleContexts
  , FlexibleInstances
  , GADTs
  , GeneralizedNewtypeDeriving
  , KindSignatures
  , LambdaCase
  , MultiParamTypeClasses
  , MultiWayIf
  , NPlusKPatterns
  , NegativeLiterals
  , OverloadedLabels
  , OverloadedStrings
  , ParallelListComp
  , PolyKinds
  , RankNTypes
  , ScopedTypeVariables
  , StrictData
  , TupleSections
  , TypeApplications
  , TypeFamilies
  , TypeOperators
  , UndecidableInstances
  , ViewPatterns
  #-}

module Main where

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Control.Monad.ST
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.Foldable
import           Data.Functor
import           Data.Int
import           Data.List
import           Data.Maybe
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup                 ( Max(..)
                                                , Min(..)
                                                , All(..)
                                                , Arg(..)
                                                )
import           Data.Ratio
-- import           Data.Vector.Unboxing.Mutable   ( Unboxable )
-- import qualified Data.Vector.Unboxing.Mutable  as V
import           System.IO
import           Data.Proxy
import           GHC.TypeLits
import           GHC.Generics                   ( Generic )
-- import           GHC.Exts
-- import           Control.Monad.Primitive        ( PrimMonad(PrimState) )
import           Control.Monad.Trans.Class      ( MonadTrans(lift) )

-- #if defined(LOCAL_ZER0STAR)
-- {-# ANN module ("Hlint: ignore Unused LANGUAGE pragma" :: String) #-}
-- {-# ANN module ("Hlint: ignore Reduce duplication" :: String) #-}
-- #endif

twice :: (a -> a -> b) -> a -> b
twice f x = f x x

both :: Arrow a => a b c -> a (b, b) (c, c)
both = twice (***)

readsLn :: Read a => IO [a]
readsLn = mapM readIO . words =<< getLine

getInt :: IO Int
getInt = fst . fromJust . BS.readInt <$> BS.getLine

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

getInteger :: IO Integer
getInteger = fst . fromJust . BS.readInteger <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine

main = do
  t <- getInt
  replicateM_
    t
    do
      [x, y, r, c] <- getInts
      print $ max (r - 1) (x - r) + max (c - 1) (y - c)


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

process m n se [] = max m n
process m n se (a:as) | S.member a se = process (max m n) (n-1) se as
		      | otherwise = process m (n+1) (S.insert a se) as

main = do
		n<- read<$> getLine ::IO Int
		a<- map read <$> words <$> getLine ::IO [Int]
		print $ process 0 0 S.empty a

-- Codeforces Round #403 (Div. 2)
-- A. Andryusha and Socks
-- http://codeforces.com/contest/782/problem/A

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

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

type State = (Set.Set Int, Int, Int)

main = do
    n <- getInt
    socks <- getInts
    let (_, _, answer) = foldl pick (Set.empty, 0, 0) socks
    print answer

pick (table, curr, answer) sock
    | sock `Set.member` table = (table, curr - 1, answer)
    | otherwise = (sock `Set.insert` table, curr + 1, max answer (curr + 1))

import System.IO
import Data.Set

solve :: [Int] -> Set Int -> Int -> Int
solve [] table res = res
solve (x:xs) table res
  | x `member` table = solve xs (delete x table) res
  | otherwise = solve xs (insert x table) maxLength
  where currLength = size table
        nextLength = currLength + 1
        maxLength = max res nextLength

main = do
  n <- readLn :: IO Int
  a <- fmap (Prelude.map read . words) getLine :: IO [Int]
  print (solve a empty 0)

import Control.Applicative( (<$>))
import Data.IntSet( insert, delete, member, empty)
main = do
    n_ <- readLn::IO Int
    socks_ <- map read . words <$> getLine  ::IO [Int]
    let
	pick _ _ [] = [0]
	pick n table (s:socks)
	  | s `member` table = let
		    n' = n-1
		    recur = pick n' table' socks
		      where
			table' = delete s table
		in
		    n':recur

	  | otherwise	= let
		    n' = n+1
		    recur = pick n' table' socks
		      where
			table' = insert s table
		in
		    n':recur

    print . maximum $ pick 0 empty socks_

import Data.Set (Set)
import qualified Data.Set as Set

main = do
    _ <- getLine
    ns <- getLineValues
    let doCount (currT, maxT, s) curr
            | curr `Set.member` s = (currT - 1, maxT, Set.delete curr s)
            | otherwise = (currT + 1, maxT `max` (currT + 1), Set.insert curr s)
        (_, maxT, _) = foldl doCount (0, 0, Set.empty) ns
    print maxT

getLineValues :: IO [Int]
getLineValues = getLine >>= return . map read . words

import qualified Data.Set as Set
import Data.List

main = do
    _ <- getLine
    ns <- getLineValues
    let doCount (currT, maxT, s) curr
            | curr `Set.member` s = (currT - 1, maxT, Set.delete curr s)
            | otherwise = (currT + 1, maxT `max` (currT + 1), Set.insert curr s)
        (_, maxT, _) = foldl' doCount (0, 0, Set.empty) ns
    print maxT

getLineValues :: IO [Int]
getLineValues = getLine >>= return . map read . words

import qualified Data.Set as Set
import Data.List

main = do
    _ <- getLine
    ns <- getLineValues
    let doCount (currT, maxT, s) curr
            | curr `Set.member` s = (currT - 1, maxT, Set.delete curr s)
            | otherwise = (currT + 1, maxT `max` (currT + 1), curr `Set.insert` s)
        (_, maxT, _) = foldl' doCount (0, 0, Set.empty) ns
    print maxT

getLineValues :: IO [Int]
getLineValues = getLine >>= return . map read . words

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as B
main = print . solve . map readI . tail . B.words =<< B.getContents
solve = maximum . snd . mapAccumL f (0 :: Integer)
f s i | testBit s i = (clearBit s i,popCount s)
      | otherwise = (setBit s i,popCount s)
readI b = i where Just (i,_) = B.readInt b

{-# OPTIONS_GHC -O3 #-}
{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}

import Control.Monad (forM_, forM)
import qualified Data.Set as S (empty, delete, insert, member, size)
import Data.List (delete)

fll (x:xs) l m | x `S.member` l = fll xs (S.delete x l) m
               | otherwise  = fll xs (S.insert x l) (max m (S.size l + 1))
fll [] _ m = m

main = do
    (read -> n) <- getLine
    (map (read :: String -> Int) . words -> xs) <- getLine
    let x = take (2 * n) xs
    putStrLn $ show $ fll x S.empty 0

-- Codeforces Round #403 (Div. 2)
-- A. Andryusha and Socks
-- http://codeforces.com/contest/782/problem/A

import Control.Monad
import qualified Data.Set as Set

getInt = read `fmap` getLine :: IO Int

type State = (Set.Set Int, Int, Int)

main = do
    n <- getInt
    socks <- (map read . words) `fmap` getLine :: IO [Int]
    let (_, _, answer) = foldl pick (Set.empty, 0, 0) socks
    print answer

pick (table, curr, answer) sock
    | sock `Set.member` table = (table, curr - 1, answer)
    | otherwise = (sock `Set.insert` table, curr + 1, max answer (curr + 1))


import Data.Function (on)
import Data.List
import qualified Data.Set as S

-- code --

data Task = Task { nums :: [Int]
                 } deriving (Show)

data Answer = Answer { num :: Int
                     } deriving (Show)

biteTask :: String -> (Task, String)
biteTask str = let line1:line2:_ = lines str
                   nums = map read $ words line2
                   in (Task {nums=nums}, dropLines 2 str)

showAns :: Answer -> String
showAns Answer {num = ans} = show ans

solve_task :: Task -> Answer
solve_task Task { nums=nums
                } = let setNums = S.fromList nums
                        minnum = minimum setNums
                        shiftnums = S.delete 0 $ S.map (-minnum+) setNums
                        numsdivs = S.map (S.fromList . allDivisors) shiftnums

                        in Answer { num = if null shiftnums then -1 else maximum $ foldr1 S.intersection numsdivs }

-- //// --

allDivisors :: (Integral a) => a -> [a]
allDivisors num = check'emAll 1 num where
                  check'emAll n num | n2 > num         = []
                                    | n2 == num        = [n]
                                    | num `mod` n == 0 = n : check'emAll (n+1) num ++ [num `div` n]
                                    | otherwise        = check'emAll (n+1) num where
                                        n2 = n^2

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

readInt :: String -> Int
readInt = read

readBigInt :: String -> Integer
readBigInt = read

dropLines _ ""        = ""
dropLines 0 text      = text
dropLines n ('\n':xs) = dropLines (n-1) xs
dropLines n (x:xs)    = dropLines n xs

type Tasks = [Task]
type Answers = [Answer]

readTasks :: String -> Tasks
readTasks ""    = []
readTasks input = let (task, input') = biteTask input
                      in task : readTasks input'

showAnswers :: Answers -> String
showAnswers [] = ""
showAnswers (ans : anss) = showAns ans ++ "\n" ++ showAnswers anss

solve :: String -> String
solve = showAnswers . map solve_task . readTasks . dropLines 1

main = interact solve

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

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

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

data TC = TC {xs :: [Int]}

input :: Scanner TC
input = do
  xs <- numberOf int
  return TC {..}

output = showB

solve :: TC -> Int
solve TC {..} = check . foldl1 gcd . map (abs . (head xs - )) $ tail xs
  where
    check 0 = -1
    check x = x

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

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

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

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

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

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

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

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

import Control.Monad (replicateM_, forM_, forM)
import Data.List (sort)

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

go :: [Int] -> Int -> Int
go [] _ = 0
go (a : as) x = if a > x then 0 else go as (x - a) + 1

solve = do
    [n] <- nextList
    a <- nextList
    let b = [abs (x - y) | x <- a,  y <- a]
    print $ if foldr gcd 0 b == 0 then -1 else foldr gcd 0 b

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

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

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

import Prelude
import Control.Monad
-- import Data.List

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

    (putStr . unlines . map solve) tcs

readTC = do
    _n <- readLn  :: IO Int
    readListLn

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

solve xs = show . solveGCD . filter (/=0) . map (flip (-) (minimum xs)) $ xs

solveGCD [] = -1
solveGCD [x] = x
solveGCD (x:y:zs) = solveGCD (gcd x y : zs)

import Data.Function (on)
import Data.List
import qualified Data.Set as S

-- code --

data Task = Task { nums :: [Int]
                 } deriving (Show)

data Answer = Answer { num :: Int
                     } deriving (Show)

biteTask :: String -> (Task, String)
biteTask str = let line1:line2:_ = lines str
                   nums = map read $ words line2
                   in (Task {nums=nums}, dropLines 2 str)

showAns :: Answer -> String
showAns Answer {num = ans} = show ans

solve_task :: Task -> Answer
solve_task Task { nums=nums
                } = let minnum = minimum nums
                        shiftnums = filter (/=0) $ map (-minnum+) nums
                        numsdivs = map (S.fromList . allDivisors) shiftnums

                        in Answer { num = if null shiftnums then -1 else maximum $ foldr1 S.intersection numsdivs }

-- //// --

allDivisors :: (Integral a) => a -> [a]
allDivisors num = check'emAll 1 num where
                  check'emAll n num | n2 > num         = []
                                    | n2 == num        = [n]
                                    | num `mod` n == 0 = n : check'emAll (n+1) num ++ [num `div` n]
                                    | otherwise        = check'emAll (n+1) num where
                                        n2 = n^2

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

readInt :: String -> Int
readInt = read

readBigInt :: String -> Integer
readBigInt = read

dropLines _ ""        = ""
dropLines 0 text      = text
dropLines n ('\n':xs) = dropLines (n-1) xs
dropLines n (x:xs)    = dropLines n xs

type Tasks = [Task]
type Answers = [Answer]

readTasks :: String -> Tasks
readTasks ""    = []
readTasks input = let (task, input') = biteTask input
                      in task : readTasks input'

showAnswers :: Answers -> String
showAnswers [] = ""
showAnswers (ans : anss) = showAns ans ++ "\n" ++ showAnswers anss

solve :: String -> String
solve = showAnswers . map solve_task . readTasks . dropLines 1

main = interact solve

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

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

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

data TC = TC {xs :: [Int]}

input :: Scanner TC
input = do
  xs <- numberOf int
  return TC {..}

output = showB

solve :: TC -> Int
solve TC {..} = foldl1 gcd . map (abs . (head xs - )) $ tail xs

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

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

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

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

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

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

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

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

import Control.Monad (replicateM_, forM_, forM)
import Data.List (sort)

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

go :: [Int] -> Int -> Int
go [] _ = 0
go (a : as) x = if a > x then 0 else go as (x - a) + 1

solve = do
    [n] <- nextList
    a <- nextList
    let b = [abs (x - y) | x <- a,  y <- a]
    print $ foldr gcd 0 b

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


import           Data.List

count_ l = sort $ map (\g -> (length g, head g)) $ group (sort l)

everyOther []           = []
everyOther (a : b : xs) = b : everyOther xs

f l =
  let (nSame, _) = last $ count_ l
      nUnique    = length $ map head $ group (sort l)
  in  max (min nSame (nUnique - 1)) (min (nSame - 1) nUnique)

main = interact $ unlines . map (show . f . words) . everyOther . tail . lines

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

solve xs = res where
	sorted = sort xs
	sizes = go sorted 0 where
		go (x:y:xs) acc
			| x == y = go (y:xs) (acc+1)
			| otherwise = (acc+1) : go (y:xs) 0
		go [x] acc = [acc + 1]
		go [] 0 = []

	m = maximum sizes
	len = length sizes
	res = max (min m (len-1)) (min (m-1) len)

main = do
	t <- fmap read getLine
	forM_ [1..t] $ \i -> do
		n <- fmap read getLine :: IO Int
		xs <- fmap (map read.words) getLine :: IO [Int]
		print (solve xs)

import Data.List

solve :: [Int] -> Int
solve as = if m == d then m-1 else min m d
    where
        grouping = group $ sort as
        d = length grouping
        m = maximum $ map length grouping

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    _ <- readInts
    as <- readInts
    print $ solve as
    testCases (t-1)

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

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

import Data.List

main :: IO ()
main = do
    getLine
    answers <- map (solve . map read . words . snd) <$> filter (even . fst) <$> zip[1..] <$> lines <$> getContents
    mapM_ print answers

solve :: [Int] -> Int
solve xs = let groupLengths = sort . map length . group . sort $ xs
            in max (min (length groupLengths - 1) (last groupLengths)) (min (length groupLengths) (last groupLengths - 1))

module Main where

import Control.Monad
import Data.List

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

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

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        getLine
        a <- sort <$> getIntList
        let b = group a
            max_size = maximum . map length $ b
            diff = length b
        print $ if diff > max_size then max_size else if max_size - 1 >= diff then diff else diff - 1

module Main where

import Control.Monad
import Data.List

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

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

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        n <- readLn
        a <- sort <$> getIntList
        print $ f n a

f :: Int -> [Int] -> Int
f n a =
    let {
        b = group a;
        max_size = maximum . map length $ b;
        diff = length b
    } in
    if diff > max_size then max_size else if max_size - 1 >= diff then diff else diff - 1

import Control.Monad
import Data.List

solve :: [Int] -> Int
solve xs = max u v
  where
    counts = map length $ group $ sort xs
    mc = maximum counts
    mt = length counts
    u = min mc (mt-1)
    v = min mt (mc-1)

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

module Main where

import Control.Monad
import Data.List

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

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

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        n <- readLn
        a <- sort <$> getIntList
        print $ f n a

f :: Int -> [Int] -> Int
f n a =
    let {
        b = group a;
        max_size = maximum . map length $ b;
        diff = length b
    } in
    if diff > max_size
        then max_size
        else if diff == max_size && n == diff * 2 - 1
                then max_size - 1
                else diff

import           Data.List

count_ l = sort $ map (\g -> (length g, head g)) $ group (sort l)

everyOther []           = []
everyOther (a : b : xs) = b : everyOther xs

f l =
  let (nSame, _) = last $ count_ l
      nUnique    = length $ map (head . group) (sort l)
  in  max (min nSame (nUnique - 1)) (min (nSame - 1) nUnique)

main = interact $ unlines . map (show . f . words) . everyOther . tail . lines


{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.State.Lazy

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

data Step = Row Int | Col Int
instance Show Step where
  show (Row r) = "row " ++ show r
  show (Col c) = "col " ++ show c

gr p b = zipWithM go (zip [1..] b) $ map minimum b
  where
    go :: (Int, [Int]) -> Int -> State [Step] [Int]
    go (i, r) m
      | m <= 0 = return r
      | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)

solve' r c b = if all (== 0) $ concat b' then Just lg else Nothing
  where
    (b', lg) = runState (gr r b >>= gr c . transpose) []

solve b = case (solve' Row Col b, solve' Col Row (transpose b)) of
  (Just l, Just r) -> Just $ if length l < length r then l else r
  (l, r) -> l <|> r

main = do
  n:_ <- fmap readInts B.getLine
  b <- replicateM n (fmap readInts B.getLine)
  B.putStr $ maybe "-1" (\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve b

{-# LANGUAGE BangPatterns #-}
import           Control.Applicative
import           Data.List

main = do
  _ <- getLine
  css <- map (map read.words).lines <$> getContents
  let res = solve css
  case res of
      Just (len, ops) -> do
          print len
          putStr.unlines.map show $ ops
      Nothing -> print $ - 1

solve :: [[Int]] -> Maybe (Int, [Op])
solve xss | not $ isValid xss = Nothing
solve xss = Just $ solve' xss `min` fmap (map trans) (solve' (transpose xss))
solve' xss = (length $ rows ++ cols, map Row rows ++ map Col cols)
  where
    rows = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum xss
    cols = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum.transpose $ map step xss

isValid :: [[Int]] -> Bool
isValid xss = all(0==).concat.map step.transpose $ map step xss

step xs = map (subtract m) xs
  where
    !m = minimum xs

data Op = Row Int | Col Int deriving (Eq, Ord)

instance Show Op where
    show (Row x) = "row " ++ show x
    show (Col x) = "col " ++ show x

trans (Row x) = Col x
trans (Col x) = Row x

{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.State.Strict

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

data Step = Row Int | Col Int
instance Show Step where
  show (Row r) = "row " ++ show r
  show (Col c) = "col " ++ show c

gr p b = zipWithM go (zip [1..] b) $ map minimum b
  where
    go :: (Int, [Int]) -> Int -> State [Step] [Int]
    go (i, r) m
      | m <= 0 = return r
      | otherwise = modify (replicate m (p i) ++) *> return (map (subtract m) r)

solve' r c b = if all (== 0) $ concat b' then Just lg else Nothing
  where
    (b', lg) = runState (gr r b >>= gr c . transpose) []

solve b = case (solve' Row Col b, solve' Col Row (transpose b)) of
  (Just l, Just r) -> Just $ if length l < length r then l else r
  (l, r) -> l <|> r

main = do
  n:_ <- fmap readInts B.getLine
  b <- replicateM n (fmap readInts B.getLine)
  B.putStr $ maybe "-1" (\lg -> B.unlines $ ((showB $ length lg):) $ map showB $ reverse lg) $ solve b

{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.State.Strict

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

data Step = Row Int | Col Int
instance Show Step where
  show (Row r) = "row " ++ show r
  show (Col c) = "col " ++ show c

gr p b = zipWithM go (zip [1..] b) $ map minimum b
  where
    go :: (Int, [Int]) -> Int -> State [Step] [Int]
    go (i, r) m
      | m <= 0 = return r
      | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)

solve' r c b = if all (== 0) $ concat b' then Just lg else Nothing
  where
    (b', lg) = runState (gr r b >>= gr c . transpose) []

solve b = case (solve' Row Col b, solve' Col Row (transpose b)) of
  (Just l, Just r) -> Just $ if length l < length r then l else r
  (l, r) -> l <|> r

main = do
  n:_ <- fmap readInts B.getLine
  b <- replicateM n (fmap readInts B.getLine)
  B.putStr $ maybe "-1" (\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve b

import Data.List as L
import Data.Text as T
import Data.Char
import Control.Arrow

readInput :: String -> [Int]
readInput = pack >>> (split isSpace) >>> (L.filter (/= pack "")) >>> (fmap (unpack >>> read))

grp (x:y:xs) = gr y xs
  where gr _ [] = []
        gr y xs = L.take y xs : (gr y $ L.drop y xs)

l = L.map (\s -> L.map (subtract $ L.minimum s) s)
r a = L.map L.minimum a

l' x = L.transpose $l (L.transpose x)
r' a = r $L.transpose a

a = ((l &&& r) >>> (\ (x,y) -> (l' x,(y,(r' x))) ))
aa = ((l' &&& r') >>> (\ (x,y) -> (l x,((r x),y)) ))

a' x = if comp (a x) (aa x)
       then a x
       else aa x
  where comp (_,(a,b)) (_,(c,d)) = sum a + sum b < sum c + sum d

b (x,(a,b)) = if (0 < L.maximum (L.map L.maximum x))
          then "-1"
          else ((flip (++)$"\n"). show . L.length &&& L.foldr (++) "") >>> uncurry (++) $(c "row " a)++(c "col " b)
c s n =  L.filter ((/=0).snd) >>> L.map (\(i, t)-> L.take (fromIntegral t) $repeat $s ++ show i++"\n") >>>L.foldr (++) [] $z n
z = L.zipWith(,)[1..]
main = do
  lines <- getContents
  putStr$ (b.a') (grp $readInput lines)

import Data.List as L
import Data.Text as T
import Data.Char
import Control.Arrow

readInput :: String -> [Int]
readInput = pack >>> (split isSpace) >>> (L.filter (/= pack "")) >>> (fmap (unpack >>> read))

grp (x:y:xs) = gr y xs
  where gr _ [] = []
        gr y xs = L.take y xs : (gr y $ L.drop y xs)

l = L.map (\s -> L.map (subtract $ L.minimum s) s)
r a = L.map L.minimum a

l' x = L.transpose $l (L.transpose x)
r' a = r $L.transpose a

a = ((l &&& r) >>> (\ (x,y) -> (l' x,(y,(r' x))) ))
b (x,(a,b)) = if (0 < L.maximum (L.map L.maximum x))
          then "-1"
          else ((flip (++)$"\n"). show . L.length &&& L.foldr (++) "") >>> uncurry (++) $(c "row " a)++(c "col " b)
c s n =  L.filter ((/=0).snd) >>> L.map (\(i, t)-> L.take (fromIntegral t) $repeat $s ++ show i++"\n") >>>L.foldr (++) [] $z n
z = L.zipWith(,)[1..]
main = do
  lines <- getContents
  putStr$ (b.a) (grp $readInput lines)

{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.State.Lazy

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

data Step = Row Int | Col Int
instance Show Step where
  show (Row r) = "row " ++ show r
  show (Col c) = "col " ++ show c

gr p b = zipWithM go (zip [1..] b) $ map minimum b
  where
    go :: (Int, [Int]) -> Int -> State [Step] [Int]
    go (i, r) m
      | m <= 0 = return r
      | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)

solve b = if all (== 0) $ concat b' then Just lg else Nothing
   where
     (b', lg) = runState (gr Row b >>= gr Col . transpose) []

main = do
  n:m:_ <- fmap readInts B.getLine
  b <- replicateM n (fmap readInts B.getLine)
  B.putStr $ maybe "-1" (\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve b

{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.State.Lazy

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

data Step = Row Int | Col Int
instance Show Step where
  show (Row r) = "row " ++ show r
  show (Col c) = "col " ++ show c

gr p b = zipWithM go (zip [1..] b) $ map minimum b
  where
    go :: (Int, [Int]) -> Int -> State [Step] [Int]
    go (i, r) m
      | m <= 0 = return r
      | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)

solve n m b = if all (== 0) $ concat b' then Just lg else Nothing
  where
    (s1, s2)
      | n <= m = (Row, Col)
      | otherwise = (Col, Row)
    (b', lg) = runState (gr s1 b >>= gr s2 . transpose) []

main = do
  n:m:_ <- fmap readInts B.getLine
  b <- replicateM n (fmap readInts B.getLine)
  B.putStr $ maybe "-1" (\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve n m b

{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.State.Lazy

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

data Step = Row Int | Col Int
instance Show Step where
  show (Row r) = "row " ++ show r
  show (Col c) = "col " ++ show c

gr p b = zipWithM go (zip [1..] b) $ map minimum b
  where
    go :: (Int, [Int]) -> Int -> State [Step] [Int]
    go (i, r) m
      | m <= 0 = return r
      | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)

solve n m b = if all (== 0) $ concat b' then Just lg else Nothing
  where
    r = gr Row
    c = gr Col . transpose
    (b', lg) = runState ((if n < m then r >=> c else c >=> r) b) []

main = do
  n:m:_ <- fmap readInts B.getLine
  b <- replicateM n (fmap readInts B.getLine)
  B.putStr $ maybe "-1" (\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve n m b

{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Control.Monad.State.Lazy

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

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

data Step = Row Int | Col Int
instance Show Step where
  show (Row r) = "row " ++ show r
  show (Col c) = "col " ++ show c

gr p b = zipWithM go (zip [1..] b) $ map minimum b
  where
    go :: (Int, [Int]) -> Int -> State [Step] [Int]
    go (i, r) m
      | m <= 0 = return r
      | otherwise = modify (++ replicate m (p i)) *> return (map (subtract m) r)

solve n m b = if all (== 0) $ concat b' then Just lg else Nothing
  where
    r = gr Row
    c = gr Col . transpose
    (b', lg) = runState ((if n <= m then r >=> c else c >=> r) b) []

main = do
  n:m:_ <- fmap readInts B.getLine
  b <- replicateM n (fmap readInts B.getLine)
  B.putStr $ maybe "-1" (\lg -> B.unlines $ ((showB $ length lg):) $ map showB lg) $ solve n m b

{-# LANGUAGE BangPatterns #-}
import           Control.Applicative
import           Data.List

main = do
  _ <- getLine
  css <- map (map read.words).lines <$> getContents
  let res = solve css
  case res of
      Just (len, ops) -> do
          print len
          putStr.unlines.map show $ ops
      Nothing -> print $ - 1

solve :: [[Int]] -> Maybe (Int, [Op])
solve xss | not $ isValid xss = Nothing
solve xss = Just $ solve' xss `min` solve' (transpose xss)
solve' xss = (length $ rows ++ cols, map Row rows ++ map Col cols)
  where
    rows = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum xss
    cols = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum.transpose $ map step xss

isValid :: [[Int]] -> Bool
isValid xss = all(0==).concat.map step.transpose $ map step xss

step xs = map (subtract m) xs
  where
    !m = minimum xs

data Op = Row Int | Col Int deriving (Eq, Ord)

instance Show Op where
    show (Row x) = "row " ++ show x
    show (Col x) = "col " ++ show x

{-# LANGUAGE BangPatterns #-}
import           Control.Applicative
import           Data.List

main = do
  _ <- getLine
  css <- map (map read.words).lines <$> getContents
  let res = solve css
  case res of
      Just ops -> do
          print $ length ops
          putStr.unlines.map show $ ops
      Nothing -> print $ -1

solve :: [[Int]] -> Maybe [Op]
solve xss | not $ isValid xss = Nothing
solve xss = Just $ map Row rows ++ map Col cols
  where
    rows = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum xss
    cols = concatMap(uncurry$flip replicate).filter((>0).snd).zip[1..] $ map minimum.transpose $ map step xss

isValid :: [[Int]] -> Bool
isValid xss = all(0==).concat.map step.transpose $ map step xss

step xs = map (subtract m) xs
  where
    !m = minimum xs

data Op = Row Int | Col Int

instance Show Op where
    show (Row x) = "row " ++ show x
    show (Col x) = "col " ++ show x


{-# 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.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
inf = maxBound `div` 2 :: Int

main = do
    n  <- readLn
    ps <- readInts
    a  <- listArray ((1,1),(n,n)) . concat <$> replicateM n getLine
    let a' = expand n a
    let qs = solve n ps a'
    {-
    stepM_ 1 (<=n) (+1) $ \i -> do
        stepM_ 1 (<=n) (+1) $ \j -> putChar (a' ! (i,j))
        putChar '\n'
        -}
    putStrLn $ unwords $ map show qs

expand :: Int -> UArray (Int,Int) Char -> UArray (Int,Int) Char
expand n mat = runSTUArray $ do
    res <- newArray ((1,1),(n,n)) '0'
    stepM_ 1 (<=n) (+1) $ \s -> do
        let dfs v pv = do
            m <- readArray res (s,v)
            when (m == '0') $ do
                writeArray res (s,v) '1'
                stepM_ 1 (<=n) (+1) $ \w ->
                    when (mat ! (v,w) == '1' && w /= pv) (dfs w v)
        dfs s (-1)
    return res

solve :: Int -> [Int] -> UArray (Int,Int) Char -> [Int]
solve n ps arr = go 1 ps where
    go _ [] = []
    go i (a:as) =
        let cands = [(aj,j) | (j,aj) <- zip [i+1..] as,
                              arr ! (i,j) == '1',
                              aj < a ]
        in
        if null cands then
            a:go (i+1) as
        else
            let (b,j) = minimum cands in
            b:go (i+1) (g (j-i-1) a as)
    g 0 a (_:l) = a:l
    g j a (b:bs) = b:g (j-1) a bs

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

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

getInts = fmap (map read . words) getLine :: IO [Int]
-- getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  n <- readLn
  p <- getInts
  g <- replicateM n $ map (== '1') <$> getLine

  let
    g' = buildG (1, n) $ map fst $ filter snd $ zip [(i, j) | i <- [1..n], j <- [1..n]] $ concat g
    cs = map flatten $ components g'

    p' = map snd $ sort $ concat $ map f cs
      where
        f xs = zip (sort xs) $ sort $ map (\i -> p!!(i-1)) xs

  putStrLn $ unwords $ map show p'

import qualified Data.Map as Map

main :: IO ()
main = do
  nLine <- getLine
  seqLine <- getLine

  let n = read nLine :: Int
      sequ = strToInts seqLine

  sets <- readNeighbors n 0 $ initSets n
  printSlots n 0 sets sequ []

readNeighbors :: Int -> Int -> Map.Map Int Int -> IO (Map.Map Int Int)
readNeighbors n i sets = do
  if n == 0
     then return sets
     else do
        line <- getLine
        readNeighbors (n-1) (i+1) (unionNeighbors sets i line 0)

printSlots :: Int -> Int -> Map.Map Int Int -> [Int] -> [Int] -> IO ()
printSlots n i sets sequ used = do
  if n == 0
     then do
          putStr "\n"
          return ()
     else do
          let (sets2, num, newUsed) = getSlot sets i sequ used
          putStr . show $ num
          putStr " "
          printSlots (n-1) (i+1) sets2 sequ newUsed

strToInts :: String -> [Int]
strToInts = map read . words

initSets :: Int -> Map.Map Int Int
initSets n = Map.fromList $ zip [0..n-1] [0..n-1]

findSet :: Map.Map Int Int -> Int -> (Map.Map Int Int, Int)
findSet sets i
  | pset == i   = (sets, i)
  | otherwise   =
      let (sets2, setNum) = findSet sets pset
      in (Map.insert i setNum sets2, setNum)
  where (Just pset) = Map.lookup i sets

isSameSet :: Map.Map Int Int -> Int -> Int -> (Map.Map Int Int, Bool)
isSameSet sets i j =
  let (sets2, seti) = findSet sets i
      (sets3, setj) = findSet sets2 j
  in (sets3, seti == setj)

unionSet :: Map.Map Int Int -> Int -> Int -> Map.Map Int Int
unionSet sets i j =
  let (sets2, seti) = findSet sets i
      (sets3, setj) = findSet sets2 j
  in Map.insert seti setj sets3

unionNeighbors :: Map.Map Int Int -> Int -> String -> Int -> Map.Map Int Int
unionNeighbors sets _ [] _ = sets
unionNeighbors sets i (x:xs) curr
  | x == '1'  = unionNeighbors (unionSet sets i curr) i xs (curr+1)
  | otherwise = unionNeighbors sets i xs (curr+1)

component :: Map.Map Int Int -> Int -> Int -> [Int] -> (Map.Map Int Int, [Int])
component sets _ (-1) acc = (sets, acc)
component sets i curr acc
  | sameSet   = component sets2 i (curr-1) (curr:acc)
  | otherwise = component sets2 i (curr-1) acc
  where (sets2, sameSet) = isSameSet sets i curr

getSlot :: Map.Map Int Int -> Int -> [Int] -> [Int] -> (Map.Map Int Int, Int, [Int])
getSlot sets i sequ used =
  let maxIdx = (length sequ)-1
      (sets2, comp) = component sets i maxIdx []
      num = minimum $ filter (\x -> not $ elem x used) $ map (sequ !!) comp
  in (sets2, num, num:used)


import Data.Char

f s = do
  let l1 = lines s
  let s1 = tail $ l1
  let n  = read $ head l1
  let pat = take n s1
  let str = s1 !! n
  let lck = head $ s1 !! (n+1)
  doit str pat lck 0 ++ "\n"

repl s l = do
  let r = if toLower l == toLower s then if toLower l == 'a' then 'b' else 'a' else l
  if isUpper s then toUpper r else toLower r

doit [] _ _ _ = []
doit (s:ss) p l r = do
  let z = maximum $ map (\x -> if prefix x ([s]++ss) then length x else 0) p
  let r' = max r z
  (if r' > 0 then [repl s l] else [s]) ++ doit ss p l (r'-1)

prefix [] _  = True
prefix _  [] = False
prefix (p:ps) (s:ss) = if toLower p == toLower s then prefix ps ss else False

main = interact f

module Main where

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

main = do
    n <- read `liftM` getLine
    forbidden <- replicateM n getLine
    initStr <- getLine
    letter <- head `liftM` getLine

    let finalStr = foldl' (\str forbidden ->
                let occur = strstrs initStr forbidden
                    len = length forbidden
                    str' = zipWith3 (\i ch ich ->
                            if ch /= ich || not ( any (\s -> s <= i && i < s + len) occur )
                            then ch
                            else chooseLetter ch
                        ) [0..] str initStr
                in str'
            ) initStr forbidden
        chooseLetter ch =
            let ch' = toLower ch
                letter' = if ch' == letter
                    then if ch' == 'a'
                        then 'b'
                        else 'a'
                    else letter
            in ( if isUpper ch then toUpper else toLower ) letter'

    putStrLn finalStr

    return ()

strstrs :: [Char] -> [Char] -> [Int]
strstrs whole' part' =
    if length whole' < length part'
    then []
    else let
        whole = map toLower whole'
        part = map toLower part'
        len = length part
        crc = sum $ map fromEnum part
        (firstPart, later) = splitAt len whole
        crc0 = sum $ map fromEnum firstPart
        strstrs' _ _ [] _ = []
        strstrs' i (w:ws) (c:cs) crc0 =
            let crc0' = crc0 - fromEnum w + fromEnum c
                laterResult = strstrs' (i+1) ws cs crc0'
            in if crc == crc0' && part == take len ws
            then i : laterResult
            else laterResult
        laterResult = strstrs' 1 whole later crc0
    in if crc == crc0 && part == firstPart
    then 0 : laterResult
    else laterResult

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

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

parseInput = do
    n <- readInt
    patterns <- replicateM n readString
    string <- readString
    letter <- head . BS.unpack <$> readString
    return (patterns, string, letter)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

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

solve (patterns, string, letter) = string'
  where
    intervals = [ (startPos, startPos + len - 1)
                | pattern <- patterns
                , let len = BS.length pattern
                , startPos <- BS.findSubstrings (BS.map toLower pattern) (BS.map toLower string)
                ]

    string' = [ if toChange then targetCase else ch
              | (i, ch) <- zip [0..] (BS.unpack string)
              , let toChange = not . null $ filter (flip inRange i) intervals
              , let lowerCh = toLower ch
              , let target = if lowerCh == letter then head (delete lowerCh $ delete letter ['a'..'z']) else letter
              , let targetCase = if isLower ch then target else toUpper target
              ]

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

class (Monad m) => MonadState s m | m -> s where
	get :: m s
	put :: s -> m ()

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

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

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

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

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

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

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

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

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

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

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

state = State

import Control.Arrow
import Char
o n f=uncurry(++).f.splitAt n
w=toLower
u p|p=toUpper|1>0=w
s([c]:q:f)=(zipWith u$map isUpper q)g
 where
 b|c>'a'='a'|1>0='b'
 j x n|n==0=x|x==c=b|1>0=c
 s=map w q
 r n b|take m(drop n s)==map w b=o n$second$o m$first$map$succ|1>0=id where m=length b
 g=zipWith j s$foldl1(.)((`map`f).r=<<[0..length s])(map(const 0)s)
main=interact$s.reverse.tail.lines

import Control.Arrow
import Char
o n f=uncurry(++).f.splitAt n
w=toLower
u p|p=toUpper|1>0=w
s([c]:q:f)=(zipWith u$map isUpper q)g
 where
 b|c>'a'='a'|1>0='b'
 j x|x==c=b|1>0=c
 s=map w q
 r n b|take m(drop n s)==map w b=o n$second$o m$first$map$j|1>0=id where m=length b
 g=foldl1(.)((`map`f).r=<<[0..length s])s
main=interact$s.reverse.tail.lines

import Control.Arrow
import Char
o n f=uncurry(++).f.splitAt n
w=toLower
u p|p=toUpper|1>0=w
s([c]:q:f)=(zipWith u$map isUpper q)g
 where
 s=map w q
 r n b|take m(drop n s)==map w b=o n$second$o m$first$map$const c|1>0=id where m=length b
 g=foldl1(.)((`map`f).r=<<[0..length s])s
main=interact$s.reverse.tail.lines

import Data.Char

f s = do
  let l1 = lines s
  let s1 = tail $ l1
  let n  = read $ head l1
  let pat = take n s1
  let str = s1 !! n
  let lck = head $ s1 !! (n+1)
  doit str pat lck 0 ++ "\n"

repl s l = do
  let r = if l == s then if l == 'a' then 'b' else 'a' else l
  if isUpper s then toUpper r else toLower r

doit [] _ _ _ = []
doit (s:ss) p l r = do
  let z = maximum $ map (\x -> if prefix x ([s]++ss) then length x else 0) p
  let r' = max r z
  (if r' > 0 then [repl s l] else [s]) ++ doit ss p l (r'-1)

prefix [] _  = True
prefix _  [] = False
prefix (p:ps) (s:ss) = if toLower p == toLower s then prefix ps ss else False

main = interact f