{-# 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 Data.Array.Base
import qualified Data.ByteString.Char8 as B

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

get :: State s s
get = State $ id &&& id
put :: s -> State s ()
put = State . const . ((),)
modify :: (s -> s) -> State s ()
modify = State . (.) ((,) ())
evalState :: State s a -> s -> a
evalState = (.) fst . runState
execState :: State s a -> s -> s
execState = (.) snd . runState

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
    sn:l <- B.lines <$> B.getContents
    let n = readInt sn
    let (_es,sq:l') = splitAt (n-1) l
    let es = map (map readInt . B.words) _es
    let q = readInt sq
    let qs = map (map readInt . B.words) l'
    putStr $ unlines $ map (printf "%.6f") $ solve n es q qs

solve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]
solve n es q qs = runST doit where
    n' :: Integer
    n' = fromIntegral n
    edges = buildTree n es
    ws = [ fromIntegral w | [_,_,w] <- es ]
    doit :: ST s [Double]
    doit = do
        edgeLength <- newListArray (0,n-2) ws :: ST s (STUArray s Int Int64)
        let cost0 = sum $ zipWith (*) ws (elems edges)
        go cost0 edgeLength qs
    go :: Int64 -> (STUArray s Int Int64) -> [[Int]] -> ST s [Double]
    go _ _ [] = return []
    go !cost edgeLength ([ri,wi]:qs) = do
        wi' <- unsafeRead edgeLength (ri-1)
        let e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)
            r = unsafeAt edges (ri-1)
            cost' = cost + fromIntegral (fromIntegral wi - wi') * r
        unsafeWrite edgeLength (ri-1) (fromIntegral wi)
        (e:) <$> go cost' edgeLength qs

buildTree :: Int -> [[Int]] -> UArray Int Int64
buildTree n es = doit where
    g :: Array Int [(Int,Int)]
    g = accumArray (flip (:)) [] (1,n) $ do
        (i,[a,b,w]) <- zip [1..] es
        [(a,(b,i)),(b,(a,i))]
    n' = fromIntegral n
    doit = runSTUArray $ do
        a <- newArray_ (0,n-2)
        let dfs pv v = do
            let us = [ (u,i-1) | (u,i) <- g ! v, u /= pv ]
            fmap ((+1).sum) $ forM us $ \(u,i) -> do
                ci <- dfs v u
                unsafeWrite a i (ci * (n'- ci))
                return ci
        dfs (-1) 1
        return a

{-# 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
import qualified Data.IntMap as IM

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

get :: State s s
get = State $ id &&& id
put :: s -> State s ()
put = State . const . ((),)
modify :: (s -> s) -> State s ()
modify = State . (.) ((,) ())
evalState :: State s a -> s -> a
evalState = (.) fst . runState
execState :: State s a -> s -> s
execState = (.) snd . runState

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
    sn:l <- B.lines <$> B.getContents
    let n = readInt sn
    let (_es,sq:l') = splitAt (n-1) l
    let es = map (map readInt . B.words) _es
    let q = readInt sq
    let qs = map (map readInt . B.words) l'
    putStr $ unlines $ map (printf "%.6f") $ solve n es q qs

solve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]
solve n es q qs = runST doit where
    n' :: Integer
    n' = fromIntegral n
    doit = do
        edges <- buildTree n es
        cost0 <- do
            es <- getElems edges
            return $ sum $ [ fromIntegral w * l * (n'-l) | (w,l) <- es ]
        go cost0 edges qs
    go _ _ [] = return []
    go !cost edges ([ri,wi]:qs) = do
        (wi',l) <- readArray edges ri
        let e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)
            cost' = cost + fromIntegral (wi - wi') * l * (n'-l)
        writeArray edges ri (wi,l)
        (e:) <$> go cost' edges qs

buildTree :: Int -> [[Int]] -> ST s (STArray s Int (Int,Integer))
buildTree n es = doit where
    g :: Array Int [(Int,Int,Int)]
    g = accumArray (flip (:)) [] (1,n) $ do
        (i,[a,b,w]) <- zip [1..] es
        [(a,(b,w,i)),(b,(a,w,i))]
    doit = do
        a <- newArray_ (1,n-1)
        let dfs pv v = do
            let us = [ (u,w,i) | (u,w,i) <- g ! v, u /= pv]
            fmap ((+1).sum) $ forM us $ \(u,w,i) -> do
                ci <- dfs v u
                writeArray a i (w,ci)
                return ci
        dfs (-1) 1
        return a

{-# 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
import qualified Data.IntMap as IM

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

get :: State s s
get = State $ id &&& id
put :: s -> State s ()
put = State . const . ((),)
modify :: (s -> s) -> State s ()
modify = State . (.) ((,) ())
evalState :: State s a -> s -> a
evalState = (.) fst . runState
execState :: State s a -> s -> s
execState = (.) snd . runState

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
    sn:l <- B.lines <$> B.getContents
    let n = readInt sn
    let (_es,sq:l') = splitAt (n-1) l
    let es = map (map readInt . B.words) _es
    let q = readInt sq
    let qs = map (map readInt . B.words) l'
    putStr $ unlines $ map (printf "%.6f") $ solve n es q qs

solve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]
solve n es q qs = go cost0 edges0 qs where
    n' :: Integer
    n' = fromIntegral n
    go _ _ [] = []
    go !cost !edges ([ri,wi]:qs) = e : go cost' edges' qs where
        (wi',l) = edges IM.! ri
        e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)
        cost' = cost + fromIntegral (wi - wi') * l * (n'-l)
        edges' = IM.insert ri (wi,l) edges
    cost0 = sum $ [ fromIntegral w * l * (n'-l) | (w,l) <- IM.elems edges0 ]
    edges0 = buildTree n es

buildTree :: Int -> [[Int]] -> IM.IntMap (Int,Integer)
buildTree n es = execState doit IM.empty where
    g :: Array Int [(Int,Int,Int)]
    g = accumArray (flip (:)) [] (1,n) $ do
        (i,[a,b,w]) <- zip [1..] es
        [(a,(b,w,i)),(b,(a,w,i))]
    doit = void $ dfs (-1) 1
    dfs pv v = do
        let us = [ (u,w,i) | (u,w,i) <- g ! v, u /= pv]
        fmap ((+1).sum) $ forM us $ \(u,w,i) -> do
            ci <- dfs v u
            modify (IM.insert i (w,ci))
            return ci

import qualified Data.ByteString.Char8 as B
import Data.IntMap hiding (map, foldl)
import qualified Data.IntMap as M
fuck = maybe 0 fst . B.readInt
main = B.interact $ B.unlines . map (B.pack . show) . f . map fuck . B.words
f (n:x) = map (6/z/(z-1)*) $ g s m r where
  z = fromIntegral n
  (p, (q:r)) = splitAt (3*n-3) x
  m = M.map (\(k,l) -> (k*(z-k),l)) $ h p
  s = M.foldl (\a (k,l) -> a+k*fromIntegral l) 0 m
g _ _ [] = []
g s m (r:w:q) = t:g t u q where
  (k,l) = m!r
  t = s-k*fromIntegral(l-w)
  u = adjust (\(k,l) -> (k,w)) r m
h x = fromList . snd $ i [] 0 1 where
  m = j 1 x
  i s u v = foldl f (1,s) $ m!v where
    f x (b,_,_) | b == u = x
    f (x,y) (b,k,l) = let (p,q) = i y v b in (x+p,(k,(fromIntegral p,l)):q)
j _ [] = empty
j k (a:b:l:s) = unionWith (++) (fromList [(a,[(b,k,l)]),(b,[(a,k,l)])]) $ j (k+1) s

{-# 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
import qualified Data.IntMap as IM

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

get :: State s s
get = State $ id &&& id
put :: s -> State s ()
put = State . const . ((),)
modify :: (s -> s) -> State s ()
modify = State . (.) ((,) ())
evalState :: State s a -> s -> a
evalState = (.) fst . runState
execState :: State s a -> s -> s
execState = (.) snd . runState

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
    sn:l <- B.lines <$> B.getContents
    let n = readInt sn
    let (_es,sq:l') = splitAt (n-1) l
    let es = map (map readInt . B.words) _es
    let q = readInt sq
    let qs = map (map readInt . B.words) l'
    putStr $ unlines $ map (printf "%.6f") $ solve n es q qs

solve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]
solve n es q qs = runST doit where
    n' :: Integer
    n' = fromIntegral n
    edges = buildTree n es
    ws = [ fromIntegral w | [_,_,w] <- es ]
    doit :: ST s [Double]
    doit = do
        edgeLength <- newListArray (1,n-1) ws :: ST s (STUArray s Int Int64)
        let cost0 = sum $ zipWith (*) ws (elems edges)
        go cost0 edgeLength qs
    go :: Int64 -> (STUArray s Int Int64) -> [[Int]] -> ST s [Double]
    go _ _ [] = return []
    go !cost edgeLength ([ri,wi]:qs) = do
        wi' <- readArray edgeLength ri
        let e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)
            r = edges ! ri
            cost' = cost + fromIntegral (fromIntegral wi - wi') * r
        writeArray edgeLength ri (fromIntegral wi)
        (e:) <$> go cost' edgeLength qs

buildTree :: Int -> [[Int]] -> UArray Int Int64
buildTree n es = doit where
    g :: Array Int [(Int,Int)]
    g = accumArray (flip (:)) [] (1,n) $ do
        (i,[a,b,w]) <- zip [1..] es
        [(a,(b,i)),(b,(a,i))]
    n' = fromIntegral n
    doit = runSTUArray $ do
        a <- newArray_ (1,n-1)
        let dfs pv v = do
            let us = [ (u,i) | (u,i) <- g ! v, u /= pv]
            fmap ((+1).sum) $ forM us $ \(u,i) -> do
                ci <- dfs v u
                writeArray a i (ci * (n'- ci))
                return ci
        dfs (-1) 1
        return a

import Data.IntMap hiding (foldl)
import qualified Data.IntMap as M
main = interact $ unlines . fmap show . f . fmap read . words
f (n:x) = fmap ((* t) . fromIntegral) $ g s m r where
  (p, (q:r)) = splitAt (3*n-3) x
  m = M.map (\(k,l) -> (k*(toInteger n-k),l)) $ h p
  s = M.foldl (\a (k,l) -> a+k*toInteger l) 0 m
  t = 6.0 / (fromIntegral $ n*(n-1))
g _ _ [] = []
g s m (r:w:q) = t:g t u q where
  (k,l) = m!r
  t = s-k*toInteger(l-w)
  u = adjust (\(k,l) -> (k,w)) r m
h x = fromList . snd $ i 0 1 where
  m = j 1 x
  i u v = foldl f (1,[]) $ m!v where
    f x (b,_,_) | b == u = x
    f (x,y) (b,k,l) = let (p,q) = i v b in (x+p,(k,(p,l)):y++q)
j _ [] = empty
j k (a:b:l:s) = unionWith (++) (fromList [(a,[(b,k,l)]),(b,[(a,k,l)])]) $ j (k+1) s


import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.State
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as P
import Data.List
import Data.Semigroup
import System.IO

-- Throws exception if not found
findNext :: S.ByteString -> Char -> Int -> Int
findNext s c i = if S.index s i == c then i else findNext s c (i + 1)

firstBeautifulSequence :: S.ByteString -> String -> [Int]
firstBeautifulSequence s t = tail $ scanl (\i c -> findNext s c (i + 1)) (-1) t

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n, m] <- readInts
  s <- P.toStrict <$> readLine
  t <- P.unpack <$> readLine
  let dpFwd = firstBeautifulSequence s t
      dpRev = reverse (map ((S.length s - 1) -) $ firstBeautifulSequence (S.reverse s) (reverse t))
      answer = maximum $ zipWith (-) (tail dpRev) dpFwd
  putInts [answer]

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

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

import Control.Applicative
import Control.Exception (assert)
import Control.Monad
import Control.Monad.State
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Bits
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.Int
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.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
  ~[n, m] <- popInts
  s <- B.unpack <$> popJust
  t <- B.unpack <$> popJust
  return $ bshow (solve n m s t) <> "\n"

solve n m s t = maximum $ map (\((a, _), (_, b)) -> b - a) $ adjlist $ zip fi bi
  where
    makeIndex s t = makeIndex' 0 s t

    makeIndex' _ _ [] = []
    makeIndex' i (s : ss) ts@(t : ts')
      | s == t = i : makeIndex' (i + 1) ss ts'
      | otherwise = makeIndex' (i + 1) ss ts

    fi = makeIndex s t

    bi = map ((n - 1 -)) $ reverse $ makeIndex (reverse s) (reverse t)

adjlist as@(_ : as') = zip as as'
adjlist _ = []

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Char8 as S
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
  [n, m] <- readInts
  s <- P.toStrict <$> readLine
  t <- P.unpack <$> readLine
  let
    sfwd c i = if  S.index s i == c  then  i  else  sfwd c (i+1)
    srev c i = if  S.index s i == c  then  i  else  srev c (i-1)
    istart = sfwd (head t) 0
    is = scanl (\i c -> sfwd c (i+1)) istart (tail t)
    trev = reverse t
    jstart = srev (head trev) (n-1)
    js = reverse $ scanl (\j c -> srev c (j-1)) jstart (tail trev)
  putInts [maximum $ zipWith (-) (tail js) is]

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


main = do
  (n:as) <- fmap (map read . words) getContents
  let e = length $ filter even as
  let o = n - e
  print $ if o < e then o else (e + (o-e) `div` 3)

main = do
    (n : as) <- fmap (map read . words) getContents
    let even = length . filter (\x -> x `mod` 2 == 0) $ as
    let odd = length . filter (\x -> x `mod` 2 == 1) $ as
    if even >= odd
    then print $ odd
    else print $ even + ((odd - even) `quot` 3)

--ghc 7.10

evenCount :: [Integer] -> Integer
evenCount [] = 0
evenCount (x:xs)
    | x `mod` 2 == 0 = 1 + evenCount xs
    | otherwise = evenCount xs

oddCount :: [Integer] -> Integer
oddCount [] = 0
oddCount (x:xs)
    | x `mod` 2 == 1 = 1 + oddCount xs
    | otherwise = oddCount xs

main :: IO()
main = do
    str <- getLine
    let n = read str :: Integer
    str <- getLine
    let a = fmap (\as -> read as :: Integer) (words str)
    let ecnt = evenCount a
    let ocnt = oddCount a
    let ans = min ecnt ocnt
    let e1 = ecnt - ans
    let o1 = ocnt - ans
    let a1 = ans + (o1 `div` 3)
    print(a1)

main = do
    (n:as) <- fmap (map read . words) getContents
    print $ (let cnt1 = toInteger $ length $ filter odd as
             in if cnt1 <= (quot n 2) then cnt1
                                       else ((n - cnt1) + (quot (cnt1 - (n - cnt1))) 3))

import System.IO -- импорт  модуля IO
import Data.List
f :: [[Char]] -> Int
f [] = 0
f (x:xs) = if (mod (read x :: Int) 2 == 1) then (1 + (f xs))
    else (f xs)
split :: Char -> String -> [[Char]]
split _ [] = []
split d l = uncurry (:) . fmap (split d . drop 1) . break (==d) $ l
del :: Int -> Int -> Int
del n m = div n m
main :: IO ()
main = do
	n <- getLine
	m <- getLine
	let nech = length [x | (x,y)<- zip (split ' ' m) [1..],(mod (read x :: Int) 2) == 1];ch = length [x | (x,y)<- zip (split ' ' m) [1..], (mod (read x :: Int) 2) == 0];ans = min ch nech + w;w = h (nech - ch)
	print (ans)
    where
        h n = if n < 1 then 0
            else del n 3
	--putStrLn $ show $ (read sx1 :: Int) + (read sx2 :: Int) -- печатаем сумму (преобразовав строки в Int)
	--putStrLn $ show $ n

import Data.List (sort)
main = do
  (n:as) <- fmap (map read . words) getContents
  let oddcnt = length (filter (odd) as)
  print (if oddcnt <= (n - oddcnt) then (oddcnt) else (n - oddcnt + (div (oddcnt - n + oddcnt) 3)))

main = do
  (n:as) <- fmap (map read . words) getContents
  let e = length $ filter even as
  let o = n - e
  print $ if o < e then o else (e + (o-e) `div` 2)

--ghc 7.10

evenCount :: [Integer] -> Integer
evenCount [] = 0
evenCount (x:xs)
    | x `mod` 2 == 0 = 1 + evenCount xs
    | otherwise = evenCount xs

oddCount :: [Integer] -> Integer
oddCount [] = 0
oddCount (x:xs)
    | x `mod` 2 == 1 = 1 + oddCount xs
    | otherwise = oddCount xs

main :: IO()
main = do
    str <- getLine
    let n = read str :: Integer
    str <- getLine
    let a = fmap (\as -> read as :: Integer) (words str)
    let ecnt = evenCount a
    let ocnt = oddCount a
    let ans = ecnt + ((ocnt - ecnt) `div` 3)
    print(ans)

--ghc 7.10

evenCount :: [Integer] -> Integer
evenCount [] = 0
evenCount (x:xs)
    | x `mod` 2 == 0 = 1 + evenCount xs
    | otherwise = evenCount xs

oddCount :: [Integer] -> Integer
oddCount [] = 0
oddCount (x:xs)
    | x `mod` 2 == 1 = 1 + oddCount xs
    | otherwise = oddCount xs

main :: IO()
main = do
    str <- getLine
    let n = read str :: Integer
    str <- getLine
    let a = fmap (\as -> read as :: Integer) (words str)
    let ecnt = evenCount a
    let ocnt = oddCount a
    print(min ecnt ocnt)


import Control.Applicative
import Data.Char
import qualified Data.ByteString.Char8 as C

--process::String->Int->Int->Bool
--process [] a b =   a*b==1
--process [_] a b =   a*b==1
--process (x1:x2:xs) a b | a*b==1 = True
--	               | a==0 && x1=='A' && x2=='B' = or [process xs 1 b,process (x2:xs) a b]
--                       | b==0 && x1=='B' && x2=='A' = or [process xs a 1,process (x2:xs) a b]
--		       | otherwise = process (x2:xs) a b

process x | (all C.null [x3,x4])  = False
	  | otherwise = True
	where x1 = snd $ C.breakSubstring (C.pack "AB") x
              x2 = snd $ C.breakSubstring (C.pack "BA") x
	      x3 = snd $ C.breakSubstring (C.pack "BA") $ C.drop 2 x1
	      x4 = snd $ C.breakSubstring (C.pack "AB") $ C.drop 2 x2

main= do
	x<- C.getLine
	putStrLn $ if process x   then "YES" else "NO"

import Control.Arrow ((&&&))
import Data.Functor ((<$>))
import Data.List (isPrefixOf)

main :: IO ()
main = putStrLn <$> yesno =<< solve <$> getLine

solve :: String -> Bool
solve = faraway 2 . (listIndices 0 "AB" &&& listIndices 0 "BA")

listIndices :: Eq a => Int -> [a] -> [a] -> [Int]
listIndices _ _ [] = []
listIndices n xs yss@(_:ys) | xs `isPrefixOf` yss = n : listIndices (n + 1) xs ys
                            | otherwise = listIndices (n + 1) xs ys

faraway :: Int -> ([Int], [Int]) -> Bool
faraway n (xs, ys) = not (null xs) && not (null ys) && (n <= abs (head xs - last ys) || n <= abs (last xs - head ys))

yesno :: Bool -> String
yesno True = "YES"
yesno _ = "NO"

import Control.Applicative
main = interact $ merge Nothing Nothing Nothing Nothing . solve 0
solve i ('A':cs@('B':_)) = Left  i : solve (i+1) cs
solve i ('B':cs@('A':_)) = Right i : solve (i+1) cs
solve i (c:cs) = solve (i+1) cs
solve _ _ = []
merge fa la fb lb (Left  i:is) = merge (fa <|> Just i) (Just i) fb lb is
merge fa la fb lb (Right i:is) = merge fa la (fb <|> Just i) (Just i) is
merge fa la fb lb _ | liftA2 ((abs .) . (-)) fa lb > Just 1 = "YES"
                    | liftA2 ((abs .) . (-)) la fb > Just 1 = "YES"
                    | otherwise = "NO"

import Data.List (isPrefixOf)

check' :: String -> [String] -> Bool
check' _ [] = True
check' [] _ = False
check' s both@(p:ps)
  | p `isPrefixOf` s = check' (drop 2 s) ps
  | otherwise = check' (tail s) both

{-check' s subs-}
  {-| null subs = True-}
  {-| length s < 2 = False-}
  {-| (head subs) `isPrefixOf` s = check' (drop 2 s) (tail subs)-}
  {-| otherwise = check' (tail s) subs-}

check :: String -> String
check s
  | check' s ["AB", "BA"] || check' s ["BA", "AB"] = "YES"
  | otherwise = "NO"

main = do
  ans <- fmap check getLine
  putStrLn ans

import Data.List (isPrefixOf)

check' :: String -> [String] -> Bool
check' s subs
  | null subs = True
  | null s = False
  | (head subs) `isPrefixOf` s = check' (drop 2 s) (tail subs)
  | otherwise = check' (tail s) subs

{-check' _ [] = True-}
{-check' [] _ = False-}
{-check' s both@(p:ps)-}
  {-| p `isPrefixOf` s = check' (drop 2 s) ps-}
  {-| otherwise = check' (tail s) both-}

check :: String -> String
check s
  | check' s ["AB", "BA"] || check' s ["BA", "AB"] = "YES"
  | otherwise = "NO"

main = do
  ans <- fmap check getLine
  putStrLn ans

main = interact $ p . (\inp -> solve 'A' 'B' inp False || solve 'B' 'A' inp False)

p b = if b then "YES" else "NO"

solve :: Char -> Char -> [Char] -> Bool -> Bool
solve a b (x:y:xs) m
  | (m && x == b && y == a) = True
  | (not m && x == a && y == b) = solve a b xs (not m)
  | otherwise = solve a b (y : xs) m
solve _ _ _ _ = False

main = do
    inp <- getLine
    putStrLn $ ans inp

ans inp = if findFirst inp "AB" "BA" || findFirst inp "BA" "AB"
            then "YES"
            else "NO"

findFirst (x:y:xs) str1 str2 = if [x,y] == str1
                                    then findSecond xs str2
                                    else findFirst (y:xs) str1 str2
findFirst _ _ _ = False

findSecond (b:a:bs) str = if [b,a] == str
                            then True
                            else findSecond (a:bs) str
findSecond _ _ = False

import Control.Applicative
import Control.Monad
import Data.List
import qualified Data.Text as T

ab= T.pack "AB"
ba= T.pack "BA"
nu= T.pack ""

check n | (snd $ T.breakOn ba $ T.drop 2$ snd $ T.breakOn ab n) /=nu = True
	| (snd $ T.breakOn ab $ T.drop 2$ snd $ T.breakOn ba n) /=nu = True
	| otherwise = False

main = do

	n<-   getLine
	putStrLn $ if check (T.pack n) then "YES" else "NO"

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

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

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

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

main = do
	s <- getLine
	putStrLn $ which "YES" "NO" $ solve s [ "AB", "BA" ] || solve s [ "BA", "AB" ]

solve _ [] = True
solve [] _ = False
solve [a] _ = False
solve s tt@(t:ts)
	| t `isPrefixOf` s = solve ( drop 2 s ) ts
	| otherwise = solve ( drop 1 s ) tt

f :: String -> Bool
f s =
  let chars = zip [0 ..] (zip s (tail s))
      l1   = [ i | (i, ('A', 'B')) <- chars ]
      l2   = [ i | (i, ('B', 'A')) <- chars ]
  in  (not . null) [ (i, j) | i <- l1, j <- l2, abs (i-j) > 1 ]

main = interact $ \x -> if f x then "YES" else "NO"

import Data.List (isPrefixOf)

check :: String -> Bool
check s = recur ["AB", "BA"] s || recur ["BA", "AB"] s
          where recur [] _  = True
                recur _  [] = False
                recur (p : ps) s
                    | p `isPrefixOf` s = recur      ps  (drop (length p) s)
                    | otherwise        = recur (p : ps) (tail s)

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

main :: IO ()
main = putStrLn . format . check =<< getLine

import Data.List (isInfixOf)

solve :: String -> Bool
solve ('A':'B':'A':cs) = isInfixOf "AB" cs || isInfixOf "BA" cs
solve ('B':'A':'B':cs) = isInfixOf "AB" cs || isInfixOf "BA" cs
solve ('A':'B':cs) = isInfixOf "BA" cs
solve ('B':'A':cs) = isInfixOf "AB" cs
solve (_:cs) = solve cs
solve [] = False

displ :: Bool -> String
displ True = "YES\n"
displ False = "NO\n"

main :: IO ()
main = interact (displ . solve)

main :: IO()
main = putStrLn . solve =<< getLine

solve :: String -> String
solve s | solve' s False False = "YES"
        | otherwise = "NO"
    where
        solve' :: String -> Bool -> Bool -> Bool
        solve' _ True True = True
        solve' "" a b = a && b
        solve' ('A':'B':'A':ss) a b = (solve' ('A':ss) True b) || (solve' ss a True)
        solve' ('B':'A':'B':ss) a b = (solve' ('B':ss) a True) || (solve' ss True b)
        solve' ('A':'B':ss) a b = solve' ss True b
        solve' ('B':'A':ss) a b = solve' ss a True
        solve' (s:ss) a b = solve' ss a b

main :: IO()
main = do
    a <- getLine
    let l1 = solveAB 1 a
        l2 = solveBA 1 a
        l3 = [ x-y | x<-l1 , y<-l2 , abs (x-y) >1]
    if l3 == []
        then putStrLn "NO"
        else putStrLn "YES"

solveAB _ (_:[]) = []
solveAB l (a:b:xs) = if and[a=='A',b=='B'] then l:solveAB (l+1) (b:xs) else solveAB (l+1) (b:xs)

solveBA _ (_:[]) = []
solveBA l (a:b:xs) = if and[a=='B',b=='A'] then l:solveBA (l+1) (b:xs) else solveBA (l+1) (b:xs)

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}
{-# 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
  s <- B.getLine

  let
    b1 = "BA" `B.isInfixOf` s && ("AB" `B.isInfixOf` a || "AB" `B.isInfixOf` (B.drop 2 b))
      where
        (a, b) = B.breakSubstring "BA" s

    b2 = "AB" `B.isInfixOf` s && ("BA" `B.isInfixOf` a || "BA" `B.isInfixOf` (B.drop 2 b))
      where
        (a, b) = B.breakSubstring "AB" s

  putStrLn $ if b1 || b2 then "YES" else "NO"

answer s t 4 = True
answer [] t n =False
answer (s:ss) t 0 | s == (t !! 0) = answer ss t 1
                  | otherwise = answer ss t 0
answer (s:ss) t 1 | s == (t !! 1) = answer ss t 2
                  | s == (t !! 0) = answer ss t 1
                  | otherwise = answer ss t 0
answer (s:ss) t 2 | s == (t !! 2) = answer ss t 3
                  | otherwise = answer ss t 2
answer (s:ss) t 3 | s == (t !! 3) = answer ss t 4
                  | s == (t !! 2) = answer ss t 3
                  | otherwise = answer ss t 2
main = do
  s <- getLine
  putStrLn $ if (answer s "ABBA" 0) || (answer s "BAAB" 0) then "YES" else "NO"

import Data.List
import Data.Maybe
import Data.Char
import Data.Array
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.head. lines
solve :: String->String
solve xs = if r1+r2>=2 && r1>0 && r2>0 then "YES" else "NO"
    where
    ([r1,r2],r3)=slv1 $ zip zp $ tail zp
    zp =zipWith (\a b->a:b:[]) ('Z':xs) $ tail ('Z':xs)
slv1 []=([0,0],1)
slv1 xss = foldr (f) ([0,0],1) xss where
  f (a1,a2) ([b1,b2],b0) | b0>0 && ((a1,a2) == ("AB","BA") || (a1,a2) == ("BA","AB")) = ([b1+0.5,b2+0.5],-1)
                         | b0>0 && a2 == "AB" = ([b1+1,b2],0)
                         | b0>0 && a2 == "BA" = ([b1,b2+1],0)
                         | otherwise = ([b1,b2],b0+1)

import Control.Arrow ((&&&))
import Data.Functor ((<$>))
import Data.List (isPrefixOf)

main :: IO ()
main = putStrLn <$> yesno =<< solve <$> getLine

solve :: String -> Bool
solve = not . nearBy 2 . (listIndices 0 "AB" &&& listIndices 0 "BA")

listIndices :: Eq a => Int -> [a] -> [a] -> [Int]
listIndices _ _ [] = []
listIndices n xs yss@(_:ys) | xs `isPrefixOf` yss = n : listIndices (n + 1) xs ys
                            | otherwise = listIndices (n + 1) xs ys

nearBy :: Int -> ([Int], [Int]) -> Bool
nearBy n (xs, ys) = null xs || null ys || n > abs (head xs - last ys) || n > abs (last xs - head ys)

yesno :: Bool -> String
yesno True = "YES"
yesno _ = "NO"

import Data.List

check' :: String -> Int -> String -> Bool
check' s idx sub
  | idx + 1 >= length s = False
  | sub `isInfixOf` fst && (reverse sub) `isInfixOf` snd = True
  | otherwise = False
      where (fst, snd) = splitAt idx s

check :: String -> String
check s
  | check' s 2 "AB" || check' s 2 "BA" = "YES"
  | otherwise = "NO"

main = do
  ans <- fmap check getLine
  putStrLn ans

import Data.List (isPrefixOf)

check' :: String -> Int -> String -> Bool
check' s idx sub
  | idx + 1 >= length s = False
  | sub `isPrefixOf` fst && (reverse sub) `isPrefixOf` snd = True
  | otherwise = check' s (idx + 1) sub
      where (fst, snd) = splitAt idx s

check :: String -> String
check s
  | check' s 2 "AB" || check' s 2 "BA" = "YES"
  | otherwise = "NO"

main = do
  ans <- fmap check getLine
  putStrLn ans

import Control.Monad
import Data.List
xor :: Bool -> Bool -> Bool
xor a b = a /= b

t = (zip `ap` tail)
isSubStr = (`elem` [('A','B'), ('B','A')])
solve = check . t . map isSubStr . t

check l = not ((True, True) `elem` l) &&
               (False, True) `elem` l &&
               (True, False) `elem` l

p True = "YES"
p False = "NO"
main = interact $ p . solve

import Control.Monad
solve = foldr (&&) True . map (uncurry (&&)) . (zip `ap` tail) . map (`elem` [('A','B'), ('B','A')]) . (zip `ap` tail)

p True = "YES"
p False = "NO"
main = interact $ p . solve

import Control.Monad
import Data.List
import Data.Char
t = (zip `ap` tail)
isSubStr = (`elem` [('A','B'), ('B','A')])
solve = check . t . map isSubStr . t

check :: [(Bool, Bool)] -> Bool
check l = (case elemIndex (False, True) l of
             Just _ -> case elemIndex (True, False) l of
                         Just _ -> True
                         Nothing -> False
             Nothing -> False)
          || any (> 1) ((zipWith (\a b -> (abs (a - b))) `ap` tail)
             (elemIndices (True, True) l))

p True = "YES"
p False = "NO"
main = interact $ p . solve

import Control.Monad
solve = not . foldr (||) False . map (uncurry (&&)) . (zip `ap` tail) . map (`elem` [('A','B'), ('B','A')]) . (zip `ap` tail)

p True = "YES"
p False = "NO"
main = interact $ p . solve

import Control.Monad
solve = any (uncurry (&&)) . (zip `ap` tail) . map (`elem` [('A','B'), ('B','A')]) . (zip `ap` tail)

p True = "YES"
p False = "NO"
main = interact $ p . solve

import Control.Applicative
import Data.Char

process [] a b = if a*b==1 then "YES" else "NO"
process [_] a b = if a*b==1 then "YES" else "NO"
process (x1:x2:xs) a b | a*b==1 = "YES"
	               | x1=='A' && x2=='B' = process xs 1 b
                       | x1=='B' && x2=='A' = process xs a 1
		       | otherwise = process (x2:xs) a b

main= do
	x<-getLine
	putStrLn $ process x 0 0

main :: IO ()
main = interact (format . solve)

newtype State = State Int
                deriving (Show, Eq)

step :: State -> Char -> State
step (State 0) 'A' = State 1
step (State 0)  _  = State 0
step (State 1) 'B' = State 2
step (State 1)  _  = State 0
step (State 2) 'B' = State 3
step (State 2)  _  = State 2
step (State 3) 'A' = State 4
step (State 3)  _  = State 2
step (State 4)  _  = State 4

step' :: State -> Char -> State
step' (State 0) 'B' = State 1
step' (State 0)  _  = State 0
step' (State 1) 'A' = State 2
step' (State 1)  _  = State 0
step' (State 2) 'A' = State 3
step' (State 2)  _  = State 2
step' (State 3) 'B' = State 4
step' (State 3)  _  = State 2
step' (State 4)  _  = State 4

run :: (State -> Char -> State) -> String -> State
run step = foldl step (State 0)

solve :: String -> Bool
solve s = (run step s) == (State 4) || (run step' s) == (State 4)

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

main = do
	a <- getLine
	if solve a == 2
		then putStrLn "YES"
		else putStrLn "NO"

solve "" = 0
solve ('A':'B':xs) = 1 + solve xs
solve ('B':'A':xs) = 1 + solve xs
solve (x:xs) = solve xs

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

  let
    f [] = []
    f ('A':'B':s) = s
    f (c:s) = c:(f s)

    g [] = []
    g ('B':'A':s) = s
    g (c:s) = c:(f s)

    b = "AB" `isInfixOf` s && "BA" `isInfixOf` (f s) || "BA" `isInfixOf` s && "AB" `isInfixOf` (g s)

  putStrLn $ if b then "YES" else "NO"

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

  let
    f [] = []
    f ('A':'B':s) = s
    f (c:s) = c:(f s)

    b = "AB" `isInfixOf` s && "BA" `isInfixOf` (f s)

  putStrLn $ if b then "YES" else "NO"

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}
{-# 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
  s <- B.getLine

  let
    b1 = "AB" `B.isInfixOf` a || "AB" `B.isInfixOf` (B.drop 2 b)
      where
        (a, b) = B.breakSubstring "BA" s

    b2 = "BA" `B.isInfixOf` a || "BA" `B.isInfixOf` (B.drop 2 b)
      where
        (a, b) = B.breakSubstring "AB" s

  putStrLn $ if b1 || b2 then "YES" else "NO"

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

  let
    f [] = []
    f ('A':'B':s) = s
    f (c:s) = c:(f s)

    g [] = []
    g ('B':'A':s) = s
    g (c:s) = c:(g s)

    b = "AB" `isInfixOf` s && "BA" `isInfixOf` (f s) || "BA" `isInfixOf` s && "AB" `isInfixOf` (g s)

  putStrLn $ if b then "YES" else "NO"

answer::String -> String
answer a = btos ((smatch "BA" a)-(ematch "AB" a) >= 2  || (smatch "AB" a)-(ematch "BA" a) > 2)
smatch::String -> String -> Int
smatch a b= smatch0 a b 0
smatch0::String -> String -> Int -> Int
smatch0 a b index | lb < la = -1
                  | (take la b) == a = index
                  | otherwise = smatch0 a (tail b) (index + 1)
                  where la = length a
                        lb = length b
ematch::String -> String -> Int
ematch a b | lb < la = -1
           | (drop (lb-la) b) == a = (lb - la)
           | otherwise = ematch a (init b)
           where la = length a
                 lb = length b
btos::Bool -> String
btos True = "YES"
btos False = "NO"
main = do
  w <- getLine
  putStrLn $ answer w

answer s t 4 = True
answer [] t n =False
answer (s:ss) t 0 | s == (t !! 0) = answer ss t 1
                  | otherwise = answer ss t 0
answer (s:ss) t 1 | s == (t !! 1) = answer ss t 2
                  | otherwise = answer ss t 0
answer (s:ss) t 2 | s == (t !! 2) = answer ss t 3
                  | otherwise = answer ss t 2
answer (s:ss) t 3 | s == (t !! 3) = answer ss t 4
                  | otherwise = answer ss t 2
main = do
  s <- getLine
  putStrLn $ if (answer s "ABBA" 0) || (answer s "BAAB" 0) then "YES" else "NO"

import Data.List
import Data.Maybe
import Data.Char
import Data.Array
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.head. lines
solve :: String->String
solve xs = if r1+r2>=2 && r1>0 && r3>0 then "YES" else "NO" where
    ([r1,r2],r3)=slv1 $ zip zp $ tail zp
    zp =zipWith (\a b->a:b:[]) xs $ tail xs
slv1 xss = foldr (f) ([0,0],1) xss where
  f (a1,a2) ([b1,b2],b0) | b0==1 && ((a1,a2) == ("AB","BA") || (a1,a2) == ("BA","AB")) = ([b1+0.5,b2+0.5],0)
                         | b0==1 && a1 == "AB" = ([b1+1,b2],1)
                         | b0==1 && a2 == "AB" = ([b1+1,b2],0)
                         | b0==1 && a1 == "BA" = ([b1,b2+1],1)
                         | b0==1 && a2 == "BA" = ([b1,b2+1],0)
                         | otherwise = ([b1,b2],1)

import Data.List
import Data.Maybe
import Data.Char
import Data.Array
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.head. lines
solve :: String->String
solve xs = if r1+r2>=2 && r1>0 && r2>0 then "YES" else "NO"
    where
    ([r1,r2],r3)=slv1 $ zip zp $ tail zp
    zp =zipWith (\a b->a:b:[]) ('Z':xs) $ tail ('Z':xs)
slv1 []=([0,0],1)
slv1 xss = foldr (f) ([0,0],1) xss where
  f (a1,a2) ([b1,b2],b0) | b0==1 && ((a1,a2) == ("AB","BA") || (a1,a2) == ("BA","AB")) = ([b1+0.5,b2+0.5],0)
                         | b0==1 && a2 == "AB" = ([b1+1,b2],0)
                         | b0==1 && a2 == "BA" = ([b1,b2+1],0)
                         | otherwise = ([b1,b2],1)

import Data.List
import Data.Maybe
import Data.Char
import Data.Array
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ solve.head. lines
solve :: String->String
solve xs = if r1+r2>=2 && r1>0 && r2>0 then "YES" else "NO"
    where
    ([r1,r2],r3)=slv1 $ zip zp $ tail zp
    zp =zipWith (\a b->a:b:[]) xs $ tail xs
slv1 []=([0,0],1)
slv1 xss = foldr (f) ([0,0],1) xss where
  f (a1,a2) ([b1,b2],b0) | b0==1 && ((a1,a2) == ("AB","BA") || (a1,a2) == ("BA","AB")) = ([b1+0.5,b2+0.5],0)
                         | b0==1 && a1 == "AB" = ([b1+1,b2],0)
                         | b0==1 && a2 == "AB" = ([b1+1,b2],1)
                         | b0==1 && a1 == "BA" = ([b1,b2+1],0)
                         | b0==1 && a2 == "BA" = ([b1,b2+1],1)
                         | otherwise = ([b1,b2],1)


{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}
{-# 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

numLoop :: (Num a, Ord a, Monad m) => a -> a -> (a -> m ()) -> m ()
numLoop start end f = if start <= end then go start else return ()
  where
    go !x | x == end  = f x
          | otherwise = f x >> go (x+1)

{-# INLINE numLoop #-}

numLoopState :: (Num a, Eq a, Monad m) => a -> a -> b -> (b -> a -> m b) -> m b
numLoopState start end initState f = go start initState
  where
    go !x !state | x == end  = f state x
                 | otherwise = f state x >>= go (x+1)

{-# INLINE numLoopState #-}

main = do
  n <- readLn

  inp <- unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getContents
  let
    (a, vs) = splitAt (n*n) inp
    a' = listArray ((1, 1), (n, n)) a :: UArray (Int, Int) Int
    vs' = listArray (1, n) vs :: UArray Int Int

  b :: IOUArray (Int) Int <- newArray_ (0, n*n-1)

  numLoop 1 n $ \i -> numLoop 1 n $ \j ->
    writeArray b ((i-1)*n + j-1) $ a'!(vs'!(n-i+1), vs'!(n-j+1))

  rs <- numLoopState 0 (n-1) [] $ \rs w -> do
    numLoop 0 (n-1) $ \u -> do
      d1 <- readArray b (u*n + w)
      numLoop 0 (n-1) $ \v -> do
        d <- readArray b (u*n + v)
        d2 <- readArray b (w*n + v)
        let d' = d1+d2

        when (d' < d) $ writeArray b (u*n + v) d'

    r <- numLoopState 0 w 0 $ \s i -> do
      v <- numLoopState 0 w 0 $ \s j -> do
        v <- readArray b (i*n + j)
        return $ s + fromIntegral v
      return $ s + v

    return $ r:rs

  putStrLn $ unwords $ map show $ rs

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}
{-# OPTIONS_GHC -O #-}

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

foldM' :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m a
foldM' _ z [] = return z
foldM' f z (x:xs) = do
  z' <- f z x
  z' `seq` foldM' f z' xs
main = do
  n <- readLn

  inp <- unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getContents
  let
    (a, vs) = splitAt (n*n) inp
    a' = listArray ((1, 1), (n, n)) a :: UArray (Int, Int) Int
    vs' = listArray (1, n) vs :: UArray Int Int

  b :: IOUArray (Int, Int) Int <- newArray_ ((1, 1), (n, n))
  forM_ [1..n] $ \i -> forM_ [1..n] $ \j ->
    writeArray b (i, j) $ a'!(vs'!(n-i+1), vs'!(n-j+1))

  let
    {-# INLINE total #-}
    total k = f 1 0
      where
        f i !s
          | i > k = return s
          | otherwise = do
            let
              g j !s
                | j > k = return s
                | otherwise = readArray b (i, j) >>= \v -> g (j+1) (s + fromIntegral v)

            g 1 0 >>= \v -> f (i+1) (s+v)

    loop1 w rs
      | w > n = return rs
      | otherwise = do
        let
          loop2 u
            | u > n = return ()
            | otherwise = do
              d1 <- readArray b (u, w)
              let
                loop3 v
                  | v > n = return ()
                  | otherwise = do
                    d <- readArray b (u, v)

                    d2 <- readArray b (w, v)
                    let d' = d1+d2

                    when (d' < d) $ writeArray b (u, v) d'

                    loop3 (v+1)

              loop3 1
              loop2 (u+1)

        loop2 1
        r <- total w
        loop1 (w+1) (r:rs)

  rs <- loop1 1 []

  putStrLn $ unwords $ map show $ rs


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

import Control.Monad
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.List
import Data.Maybe
import Data.Monoid

------

mapFst :: (a -> c) -> (a, b) -> (c, b)
mapFst f (x, y) = (f x, y)

mapSnd :: (b -> c) -> (a, b) -> (a, c)
mapSnd f (x, y) = (x, f y)

------

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

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

popJust :: MonadState [r] m => m r
popJust = fromJust <$> pop

------

popInt :: MonadState [B.ByteString] m => m Int
popInt = fst . fromJust . B.readInt <$> popJust

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

dropBackWhile :: (Char -> Bool) -> B.ByteString -> B.ByteString
dropBackWhile p = B.reverse . B.dropWhile p . B.reverse

main = B.interact go
  where
    go :: B.ByteString -> B.ByteString
    go = evalHopper run . map (dropBackWhile isSpace) . B.lines

run :: Hopper B.ByteString B.ByteString
run = do
  n <- popInt
  B.unlines <$> replicateM n solve

solve :: Hopper B.ByteString B.ByteString
solve = B.pack . map f . zip (cycle [True, False]) . B.unpack <$> popJust
  where
    f (True, 'a') = 'b'
    f (True, _) = 'a'
    f (False, 'z') = 'y'
    f (False, _) = 'z'

process :: Bool -> String -> String
process _     []      = []
process True  (h : t) = (if h == 'a' then 'b' else 'a') : process False t
process False (h : t) = (if h == 'z' then 'y' else 'z') : process True t

main :: IO ()
main = interact (unlines . map (process True) . tail . lines)

module Main where

solve :: String -> String
solve = map f . zip [0..]
        where f (i,l) | even i = if l == 'a' then 'b' else 'a'
                      | odd  i = if l == 'z' then 'y' else 'z'

main = interact $ unlines . map solve . tail . lines

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

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

func :: Bool -> String -> String
func _ [] = []
func _ ['\r'] = []
func True ('a' : cs) = 'b' : func False cs
func True (c : cs) = 'a' : func False cs
func False ('z' : cs) = 'y' : func True cs
func False (c : cs) = 'z' : func True cs

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    s <- C.unpack <$> C.getLine
    C.putStrLn $ C.pack $ func True s

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

best :: P.ByteString
best = P.cycle $ P.pack "az"

step :: Char -> Char -> Char
step x y
  | x /= y  = x
  | x == 'a' = 'b'
  | otherwise = 'y'

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ readLine >>= (lift . putStrLn . P.zipWith step best)

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]

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

import Control.Monad
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.List
import Data.Maybe
import Data.Monoid

------

mapFst :: (a -> c) -> (a, b) -> (c, b)
mapFst f (x, y) = (f x, y)

mapSnd :: (b -> c) -> (a, b) -> (a, c)
mapSnd f (x, y) = (x, f y)

------

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

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

popJust :: MonadState [r] m => m r
popJust = fromJust <$> pop

------

popInt :: MonadState [B.ByteString] m => m Int
popInt = fst . fromJust . B.readInt <$> popJust

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

main = B.interact go
  where
    go :: B.ByteString -> B.ByteString
    go = evalHopper run . map (B.dropWhile isSpace) . B.lines

run :: Hopper B.ByteString B.ByteString
run = do
  n <- popInt
  B.unlines <$> replicateM n solve

solve :: Hopper B.ByteString B.ByteString
solve = B.pack . map f . zip (cycle [True, False]) . B.unpack <$> popJust
  where
    f (True, 'a') = 'b'
    f (True, _) = 'a'
    f (False, 'z') = 'y'
    f (False, _) = 'z'

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

import Control.Monad
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as B
import Data.List
import Data.Maybe
import Data.Monoid

------

mapFst :: (a -> c) -> (a, b) -> (c, b)
mapFst f (x, y) = (f x, y)

mapSnd :: (b -> c) -> (a, b) -> (a, c)
mapSnd f (x, y) = (x, f y)

------

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

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

popJust :: MonadState [r] m => m r
popJust = fromJust <$> pop

------

popInt :: MonadState [B.ByteString] m => m Int
popInt = fst . fromJust . B.readInt <$> popJust

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

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

run :: Hopper B.ByteString B.ByteString
run = do
  n <- popInt
  B.unlines <$> replicateM n solve

solve :: Hopper B.ByteString B.ByteString
solve = B.pack . map f . zip (cycle [True, False]) . B.unpack <$> popJust
  where
    f (True, 'a') = 'b'
    f (True, _) = 'a'
    f (False, 'z') = 'y'
    f (False, _) = 'z'

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

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

func :: Bool -> String -> String
func _ [] = []
func True ('a' : cs) = 'b' : func False cs
func True (c : cs) = 'a' : func False cs
func False ('z' : cs) = 'y' : func True cs
func False (c : cs) = 'z' : func True cs

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    s <- C.unpack <$> C.getLine
    C.putStrLn $ C.pack $ func True s


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

main = getLine >>= test.read
test 0 = return ()
test n = getLine >> getLine >>= print.solve.map read.words >> test (n - 1)

solve as
  | any (== 0) as = (length $ filter (== 0) as) + (solve $ map (\x -> if x == 0 then 1 else x) as)
  | sum as == 0 = 1
  | otherwise = 0

import Data.Ord
import Data.Int
import qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>), take)
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Prelude hiding (showList)
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if DSeq.null s then
                aux s
            else
                return $ toList s
        else
            aux $ s DSeq.|> x
    in aux DSeq.Empty

type EIO a = ExceptT String IO a

get :: Read a => EIO a
get = ExceptT $ liftM readEither getToken
gets :: EIO String
gets = ExceptT $ liftM Right getToken
puts :: String -> EIO ()
puts = lift . putStr
putsln :: String -> EIO ()
putsln = lift . putStrLn
put :: Show a => a -> EIO ()
put = putsln . show
putln :: Show a => a -> EIO ()
putln = putsln . show
showList :: Show a => [a] -> String
showList [] = []
showList (x : l) = shows x $ showChar ' ' $ showList l

main :: IO ()
main = do
    o <- runExceptT main_
    case o of
        Right () -> return ()
        Left s -> putStrLn s

main_ :: EIO ()
main_ = do
    t <- get
    replicateM_ t f1

f1 :: EIO ()
f1 = do
    n <- get
    a <- replicateM n get
    putln $ f2 a n

f2 :: [Int] -> Int -> Int
f2 a n =    let asum = foldl (+) 0 a
            in
            let a0count = foldl (\s c -> if c == 0 then s + 1 else s) 0 a
            in
            let amcount = foldl (\s c -> if c == -1 then s + 1 else s) 0 a
            in
            if asum + a0count == 0 then
                if amcount == n then
                    a0count + 2
                else
                    a0count + 1
            else
                a0count

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

onecase= do
		getLine
		s<- map read <$> words <$> getLine ::IO [Int]
		let z = length $ filter (==0) s
		let su = sum s
		print $ if su +z ==0 then z+1 else z

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

--ghc 7.10

import Data.List(groupBy)

nonZero :: [Int] -> Int
nonZero a =
    if (n + sum a) == 0
        then n+1
        else n
    where n = length . filter (==0) $ a

process :: Int -> IO ()
process 0 = return ()
process t = do
    line1 <- getLine
    line2 <- getLine
    let a = map read . words $ line2
    print $ nonZero a
    process (t-1)

main = do
    tStr <- getLine
    let t = read tStr :: Int
    process t

import Data.List as L

solve :: [Int] -> Int
solve xs = stepsToRemoveZero + if sumAfterZeroRemoval == 0 then 1 else 0
  where stepsToRemoveZero = length $ filter (== 0) xs
        sumAfterZeroRemoval = (sum xs) + stepsToRemoveZero

groupByTwo :: [String] -> [(String, String)]
groupByTwo [] = []
groupByTwo (n:as:others) = [(n, as)] ++ groupByTwo others

parse :: (String, String) -> String
parse (_, as) = show $ solve as'
  where as' = map (\x -> read x :: Int) $ words as

main :: IO ()
main = interact (unlines . map parse . groupByTwo . tail . lines)

import Control.Monad
main :: IO ()
main = do
  n <- readLn
  replicateM_ n routine
routine :: IO ()
routine = do
  _ <- getLine
  as <- (map read. words) <$> getLine
  print $ solve as

solve :: [Int] -> Int
solve xs = if nsum ==0 then nuller +1 else nuller
  where
    nsum = summe + nuller
    (summe,nuller) = foldr bin acc xs
    bin x (sm,zs) = if x==0 then (sm,zs+1) else (sm+x,zs)
    acc = (0,0)


-- Codeforces 549A

import Data.List (sort)

main :: IO ()
main = do
    [n, m] <- fmap (map read . words) getLine
    getContents >>= print . solve [(i, j) | i <- [0..n-2], j <- [0..m-2]] . lines -- enumerate all positions.

solve :: [(Int, Int)] -> [String] -> Int
solve [] _ = 0
solve ((i,j):xs) mat = check + (solve xs mat) where check = if sort [mat!!i!!j, mat!!i!!(j+1), mat!!(i+1)!!j, mat!!(i+1)!!(j+1)] == "acef" then 1 else 0

import Data.List

main :: IO()
main = print . solve . tail . lines =<< getContents

solve :: [String] -> Int
solve (a:b:s) = (count (zips a b)) + (solve (b:s))
solve _       = 0

zips :: String -> String -> String
zips ""     ""     = ""
zips (a:as) (b:bs) = (a:b:(zips as bs))

count :: String -> Int
count (a:b:c:d:s) | sort [a,b,c,d] == sort "face" = 1 + (count (c:d:s))
                  | otherwise = count (c:d:s)
count _           = 0

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns, OverloadedStrings #-}
{-# 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, m] <- map read . words <$> getLine
  a <- replicateM n getLine

  let check (a, b) (c, d) = sort [a, b, c, d] == "acef"

  print $ length $ filter id $ [check p q | [x, y] <- map (take 2) (init (init (tails a))), [p, q] <- map (take 2) (init (init (tails (zip x y))))]

import Data.List

detect i [] _ = i
detect i _ [] = i
detect i [_] _ = i
detect i _ [_] = i
detect i (a:b:as) (c:d:cs) = detect (i + if sort [a,b,c,d] == "acef" then 1 else 0) (b:as) (d:cs)

solve i [a] = i
solve i (a:b:as) = solve (i + detect 0 a b) (b:as)

main = interact $ show . solve 0 . tail . lines

import Data.List

main :: IO ()
main =
  interact $ show . solve . tail . lines

solve :: [String] -> Int
solve lst =
  let n = length lst
      m = length $ head lst
      getSquare :: Int -> Int -> String
      getSquare i j =
        [(lst !! k) !! l | k <- [i, min (i+1) (n-1)], l <- [j, min (j+1) (m-1)]]
      isSquare :: String -> Bool
      isSquare str =
        sort str == "acef"
  in length $ filter isSquare $ [getSquare i j | i <- [0..n-1], j <- [0..m-1]]

import Control.Arrow ((&&&), (***))
import Data.Functor ((<$>))
import Data.List (sort)

main :: IO ()
main = print =<< solve <$> (tail <$> lines <$> getContents)

solve :: [String] -> Int
solve xs = length . filter (=="acef") . concatMap (map (sort . uncurry (++) . (unTuple *** unTuple))
        . uncurry zip . (uncurry zip . (id &&& tail) *** uncurry zip . (id &&& tail))) $ zip xs (tail xs)

unTuple :: (a, a) -> [a]
unTuple (a, b) = [a, b]

import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.Array as Arr
import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import Data.List
import Control.Applicative
import Control.Monad
import Data.Function

solve1 ((a,b) : (c,d) : _) = if sort [a,b,c,d] == sort "face" then 1 else 0
solve1 _ = 0

solver (x:y:_) = sum $ map solve1 (tails (zip x y))
solver _ = 0

solve :: [String] -> Integer
solve l = sum $ map solver (tails l)

main = interact $ unlines . return . show . solve . tail . lines

import Data.List (sort)

type Face = ((Char, Char), (Char, Char))

parse :: String -> [String]
parse = tail . lines

isFace :: Face -> Bool
isFace ((a, b), (c, d)) = (sort [a, b, c, d]) == "acef"

mkFaces :: [String] -> [Face]
mkFaces = concat . pairWith zip . map (pairWith (,))
          where pairWith f a = zipWith f a (tail a)

solve :: [String] -> Int
solve = length . filter isFace . mkFaces

main :: IO ()
main = print . solve . parse =<< getContents


import Control.Monad ( guard, replicateM_, forM_, when )
import Data.Bits ( Bits(xor) )
import Data.IORef ( newIORef, readIORef, writeIORef )
import Data.List ( unfoldr )
import Data.Maybe ( fromJust )
import System.IO ( hFlush, stdout )
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    [n, k] <- readInts
    done <- newIORef False
    forM_ [0..n - 1] $ \i -> do
        done' <- readIORef done
        if done' then return ()
        else do
            let j = if i == 0 then i else i `xor` (i - 1)
            print j
            hFlush stdout
            r <- readInt
            guard (r /= -1)
            when (r == 1) $ writeIORef done True
    readIORef done >>= guard

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

readInts :: IO [Int]
readInts = unfoldr (C.readInt . C.dropWhile (== ' ')) <$> C.getLine

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

import Control.Monad ( guard, replicateM_, forM_, when )
import Data.Bits ( Bits(xor) )
import Data.IORef ( newIORef, readIORef, writeIORef )
import Data.Maybe ( fromJust )
import System.IO ( hFlush, stdout )
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    [n, k] <- readInts
    done <- newIORef False
    forM_ [0..n - 1] $ \i -> do
        done' <- readIORef done
        if done' then return ()
        else do
            let j = if i == 0 then i else i `xor` (i - 1)
            C.putStrLn $ C.pack $ show j
            hFlush stdout
            r <- readInt
            guard (r /= -1)
            when (r == 1) $ writeIORef done True
    readIORef done >>= guard

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

readInt :: IO Int
readInt = parseInt <$> C.getLine

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

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

import Control.Monad ( replicateM_, guard, when )
import Data.Bits ( Bits(xor) )
import System.IO ( hFlush, stdout )

solve :: IO ()
solve = do
    [n, k] <- readMany :: IO [Int]
    let go :: Int -> IO ()
        go i = do
            let j = i `xor` (i - 1)
            print j
            hFlush stdout
            r <- readLn :: IO Int
            guard (r /= -1)
            when (r == 0) $ go (i + 1)
    go 1

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

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


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

main = readInt >>= flip replicateM solve >>= mapM_ print

solve = do
	n <- readInt
	ss <- replicateM n getLine
	let
		ls = map length ss
		zeros = length $ filter ( == '0' ) $ concat ss
		ones = sum ls - zeros
		pairs = ( zeros `div` 2 ) + ( ones `div` 2 )
	return $ length $ takeWhile ( <= pairs ) $ scanl1 (+) $ sort $ map ( `div` 2 ) ls

import           Data.List
import           Numeric

(|>) = flip (.)

int :: String -> Int
int x = fst $ readDec x !! 0

ints :: String -> [Int]
ints = map int . words

main = interact $
  lines
  |> solverLoop
  |> map show
  |> unlines

solverLoop :: [String] -> [Int]
solverLoop (ts:xs) = go t xs
    where
      t = int ts
      go 0 _ = []
      go t (nStr:xs) =
          solve (take n xs) : go (t - 1) (drop n xs)
          where
            n = int nStr

solve :: [String] -> Int
solve xs = go lengths counts1 counts0
  where
    counts1 = sum $ map (count '1') xs
    counts0 = sum $ map (count '0') xs
    lengths = sort $ map length xs
    go [] _ _ = 0
    go (x:xs) c1 c0
      | x `mod` 2 == 0
        && ec1 + ec0 >= x
        = 1 + go xs
          (c1 - (min ec1 x))
          (c0 - (min ec0 (x - (min ec1 x))))
      | x `mod` 2 == 1
        && c1 + c0 >= x
        = 1 + if c1 `mod` 2 == 1
            then go xs (c1 - (min c1 x)) (c0 - (x - (min c1 x)))
            else go xs (c1 - (min c1 (x-1))) (c0 - (x - (min c1 (x-1))))
      | otherwise = 0
      where
        ec1 = (c1 - c1 `mod` 2)
        ec0 = (c0 - c0 `mod` 2)

count x = length . filter (== x)

import           Data.List
import           Numeric

(|>) = flip (.)

int :: String -> Int
int x = fst $ readDec x !! 0

ints :: String -> [Int]
ints = map int . words

main = interact $
  lines
  |> solverLoop
  |> map show
  |> unlines

solverLoop :: [String] -> [Int]
solverLoop (ts:xs) = go t xs
    where
      t = int ts
      go 0 _ = []
      go t (nStr:xs) =
          solve (take n xs) : go (t - 1) (drop n xs)
          where
            n = int nStr

solve :: [String] -> Int
solve xs = length
  $ takeWhile (<= (counts1 `div` 2 + counts0 `div` 2))
  $ scanl1 (+)
  $ sort $ map ((`div` 2) . length) xs
  where
    counts1 = sum $ map (count '1') xs
    counts0 = sum $ map (count '0') xs

count x = length . filter (== x)


import Text.Printf
import Data.List
import Data.Functor
import Control.Applicative
import Prelude
import Control.Monad
import Data.Maybe
import Data.Function
import Data.Array
import qualified Data.ByteString.Char8 as B8

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

type DpState = (Maybe Int, Maybe Int, Maybe Int, Maybe Int)

maybeMaximum :: [Maybe Int] -> Maybe Int
maybeMaximum = foldr max Nothing

dpStateStep :: DpState -> Char -> DpState
dpStateStep (a0, a1, a2, a3) '[' = (maybeMaximum [a0, Just 1], a1, a2, a3)
dpStateStep (a0, a1, a2, a3) ':' = (a0, maybeMaximum [(+1) <$> a0, a1], maybeMaximum [(+1) <$> a1, a2], a3)
dpStateStep (a0, a1, a2, a3) '|' = (a0, (+1) <$> a1, a2, a3)
dpStateStep (a0, a1, a2, a3) ']' = (a0, a1, a2, maybeMaximum [(+1) <$> a2, a3])
dpStateStep dpState _ = dpState

solve :: B8.ByteString -> Int
solve str = fromMaybe (-1) answer
    where
        (_, _, _, answer) = B8.foldl' dpStateStep (Nothing, Nothing, Nothing, Nothing) str

main :: IO ()
main = do
    str <- B8.getLine
    printf "%d" $ solve str

main = interact f

f s = (case f0 s of
    Just i -> show (i + 4)
    Nothing -> "-1") ++ "\n"

f0 ('[':s) = f1 s
f0 (_:s) = f0 s
f0 [] = Nothing

f1 (':':s) = f2 s
f1 (_:s) = f1 s
f1 [] = Nothing

f2 s = f3 Nothing 0 s

f3 prev score ('|':s) = f3 prev (score + 1) s
f3 prev score (':':s) = case f4 score s of
    Just (i, j, s) -> f3 (Just i) j s
    Nothing -> prev
f3 prev score (_:s) = f3 prev score s
f3 prev _ [] = prev

f4 score s = f5 score score s

f5 i j ('|':s) = f5 i (j + 1) s
f5 i j (']':s) = Just (i, j, s)
f5 i j (':':s) = f5 j j s
f5 i j (_:s) = f5 i j s
f5 _ _ [] = Nothing

{-# LANGUAGE BangPatterns #-}
import System.IO
import Control.Applicative
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Function (fix)
import Data.Array (Array, array, (!))
import Data.ByteString.Lazy.Builder
import Data.ByteString.Lazy.Builder.ASCII
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

construct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]
construct reader str
    | BS.null str = []
    | isSpace (BS8.head str) = construct reader (BS8.tail str)
    | otherwise = let Just (i, other) = reader str in i : construct reader other

getInts :: IO [Int]
getInts = construct BS8.readInt <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = construct BS8.readInteger <$> BS.getLine

printInts :: [Int] -> IO ()
printInts = putStrLn . intercalate " " . map show

solve [] = -1
solve ('[':s) = solve2 $ s
solve (x:s) = solve s

solve2 [] = -1
solve2 (':':s) = solve3 $ reverse s
solve2 (x:s) = solve2 s

solve3 [] = -1
solve3 (']':s) = solve4 s
solve3 (x:s) = solve3 s

solve4 [] = -1
solve4 (':':s) = solve5 s
solve4 (x:s) = solve4 s

solve5 [] = 4
solve5 ('|':s) = 1 + solve5 s
solve5 (x:s) = solve5 s

main = do
    s <- getLine
    print $ solve s

-- Educational Codeforces Round #58 (B), Contest 1101, Problem set ?.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function

main :: IO ()
main = do
  s <- BS.getLine
  print $ fromMaybe (-1) $ query s

query :: BS.ByteString -> Maybe Int
query xs0 = do
  let xs1 = BS.dropWhile (/='[') xs0
      xs2 = BS.dropWhile (/=':') xs1
  guard $ not $ BS.null xs2
  let (xs3,_) = BS.spanEnd (/= ']') $ BS.tail xs2
      (xs4,_) = BS.spanEnd (/=':') $ xs3
  guard $ not $ BS.null xs4
  let xs5 = BS.init xs4
  return $ (4+) $ length $ BS.elemIndices '|' xs5

-- Educational Codeforces Round #58 (B), Contest 1101, Problem set ?.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections#-}
{-# LANGUAGE ExplicitForAll #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST.Safe
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function

main :: IO ()
main = do
  s <- BS.getLine
  print $ fromMaybe (-1) $ query s

query :: BS.ByteString -> Maybe Int
query xs0 = do
  let xs1 = BS.dropWhile (/='[') xs0
      xs2 = BS.dropWhile (/=':') xs1
  guard $ not $ BS.null xs2
  let (xs3,_) = BS.spanEnd (/= ']') $ BS.tail xs2
      (xs4,_) = BS.spanEnd (/=':') $ xs3
  guard $ not $ BS.null xs4
  let xs5 = BS.tail xs4
  return $ (4+) $ length $ BS.elemIndices '|' xs5

main = interact f

f s = (case f0 s of
    Just i -> show (i + 4)
    Nothing -> "-1") ++ "\n"

f0 ('[':s) = f1 s
f0 (_:s) = f0 s
f0 [] = Nothing

f1 (':':s) = f2 s
f1 (_:s) = f1 s
f1 [] = Nothing

f2 s = f3 Nothing 0 s

f3 prev score ('|':s) = f3 prev (score + 1) s
f3 prev score (':':s) = case f4 s of
    Just (i, s) -> f3 (Just score) (score + i) s
    Nothing -> prev
f3 prev score (_:s) = f3 prev score s
f3 prev _ [] = prev

f4 s = f5 0 s

f5 i ('|':s) = f5 (i + 1) s
f5 i (']':s) = Just (i, s)
f5 i (_:s) = f5 i s
f5 _ [] = Nothing


import qualified Data.Array as A
import qualified Data.List as L
import Data.Ix
import Control.Monad

main :: IO ()
main = do [na,ma] <- (getLine >>= return . map read . words)
          la      <- foldM (\e x -> nextChar >>= (\c -> return ((x,c):e))) [] [(x,y) | x <- [1..na],y <- [1..ma]]
          getLine
          [nb,mb] <- (getLine >>= return . map read . words)
          lb      <- foldM (\e x -> nextChar >>= (\c -> return ((x,c):e))) [] [(x,y) | x <- [1..nb],y <- [1..mb]]
          putStrLn . unwords . map show $ solve (na,ma) la (nb,mb) lb
    where
          nextChar = do c <- getChar
                        case c of
                            '\n' -> nextChar
                            '0'  -> return 0
                            '1'  -> return 1

solve :: (Int,Int) -> [((Int,Int),Int)] -> (Int,Int) -> [((Int,Int),Int)] -> [Int]
solve (na,ma) la (nb,mb) lb = snd $ maximum [ (overlap x y,[x,y]) | x <- [-50..50], y <- [-50..50]]
    where mat_a = A.array ((1,1),(na,ma)) la
          mat_b = A.array ((1,1),(nb,mb)) lb
          overlap :: Int -> Int -> Int
          overlap x y = L.foldl' (+) 0 [(mat_a A.! (i,j)) * (mat_b A.! (i+x,j+y)) | i <- [max 1 (1-x)..min na (nb-x)],j <- [max 1 (1-y)..min ma (mb-y)]]

import Array
import Data.List (foldl')
import Monad (liftM)

solve :: Array (Int, Int) Int -> Array (Int, Int) Int -> (Int, Int)
solve a b  =  (m, n)
  where
    (m, n, fa)  =  foldl' getMax (undefined, undefined, -1)
                    [(x, y) | x <- [1 - na .. nb - 1], y <- [1 - ma .. mb - 1]]
    (na, ma)  =  snd $ bounds a
    (nb, mb)  =  snd $ bounds b
    getMax a@(_, _, fa) b@(b1, b2)
      | fa > fb    =   a
      | otherwise  =  (b1, b2, fb)
      where
        fb  =  f b
    f (x, y)  =  foldl' (+) 0 [a ! (i,j) * b ! (i+x, j+y)
                  | i <- [max 1 (1 - x) .. min na (nb - x)],
                    j <- [max 1 (1 - y) .. min ma (mb - y)]]

main :: IO ()
main  =  do
    ls  <-  liftM lines getContents
    let [na, ma]  =  map read . words . head $ ls
    let a  =  listArray ((1,1), (na, ma)) . map read . concatMap (map (\c -> [c])) . take na . tail $ ls
    let [nb, mb]  =  map read . words . head . drop na . drop 1 $ ls
    let b  =  listArray ((1,1), (nb, mb)) . map read . concatMap (map (\c -> [c])) . take nb . drop 1 . drop na . drop 1 $ ls
    let (x,y)  = solve a b
    putStrLn $ concat [show x, " ", show y]


import Data.Ord
import Data.Int
import Data.Char
import qualified Data.Sequence as DSeq (null, Seq( Empty ), (|>))
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Prelude hiding (showList)
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if DSeq.null s then
                aux s
            else
                return $ toList s
        else
            aux $ s DSeq.|> x
    in aux DSeq.Empty

type EIO a = ExceptT String IO a

get :: Read a => EIO a
get = ExceptT $ liftM readEither getToken
gets :: EIO String
gets = ExceptT $ liftM Right getToken
puts :: String -> EIO ()
puts = lift . putStr
putsln :: String -> EIO ()
putsln = lift . putStrLn
put :: Show a => a -> EIO ()
put = putsln . show
putln :: Show a => a -> EIO ()
putln = putsln . show
showList :: Show a => [a] -> String
showList [] = []
showList (x : l) = shows x $ showChar ' ' $ showList l

main :: IO ()
main = do
    o <- runExceptT main_
    case o of
        Right () -> return ()
        Left s -> putStrLn s

main_ :: EIO ()
main_ = do
    t <- get :: EIO Int
    replicateM_ t f1

f1 :: EIO ()
f1 = do
    get :: EIO Int
    s <- gets
    case f2 s of
        Nothing -> putsln("-1")
        Just (i, j) -> putsln(i : j : [])

f2 :: String -> Maybe (Char, Char)
f2 s =  let aux (c : rest) (x, y) = if (mod ((ord c) - (ord '0')) 2) == 1 then aux rest (y, c) else aux rest (x, y)
            aux [] (x, y) = (x, y)
        in
        let (x, y) = aux s ('x', 'x') in
            if x == 'x' || y == 'x' then
                Nothing
            else Just (x, y)

import Data.Maybe (fromMaybe)

main = readLn >>= go where
    go 0 = return ()
    go n = getLine >> readLn >>= print . fromMaybe (-1) . solve >> go (n-1)

solve :: Integer -> Maybe Int
solve n = let
    a = map read (map (:[]) $ show n) :: [Int]
    odds = filter odd a
    in if length odds < 2 then Nothing else Just $ 10 * (odds !! 0) + odds !! 1

import Data.Char

toEbne :: [Integer] -> [Integer]
toEbne number = take 2 $ filter odd number

groupByTwo :: [String] -> [(String, String)]
groupByTwo [] = []
groupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest

toString :: [Integer] -> String
toString [] = "-1"
toString [_] = "-1"
toString number = foldl (\acc n -> acc ++ show n) "" number

solve :: (String, String) -> String
solve (_, xs) = toString $ toEbne number
  where number = map (\n -> toInteger $ n - (ord '0')) $ map ord xs

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

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

main = getLine >>= test.read
test 0 = return ()
test a = getLine >> getLine >>= putStrLn.solve.take 2.filter (\d -> odd $ read [d]) >> test (a - 1)

solve a | length a == 2 = a | otherwise = "-1"

import Data.Char

toEbne :: [Integer] -> [Integer]
toEbne number = take 2 $ filter odd number

groupByTwo :: [String] -> [(String, String)]
groupByTwo [] = []
groupByTwo [_, _] = []
groupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest

toString :: [Integer] -> String
toString [] = "-1"
toString number = foldl (\acc n -> acc ++ show n) "" number

solve :: (String, String) -> String
solve (_, xs) = toString $ toEbne number
  where number = map (\n -> toInteger $ n - (ord '0')) $ map ord xs

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

import Data.Char

toEbne :: [Integer] -> [Integer]
toEbne number = take 2 $ filter odd number

groupByTwo :: [String] -> [(String, String)]
groupByTwo [] = []
groupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest

toString :: [Integer] -> String
toString [] = "-1"
toString number = foldl (\acc n -> acc ++ show n) "" number

solve :: (String, String) -> String
solve (_, xs) = toString $ toEbne number
  where number = map (\n -> toInteger $ n - (ord '0')) $ map ord xs

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

import Data.Char

toEbne :: [Integer] -> [Integer]
toEbne number
  | null oddVersion = []
  | even currSum = oddVersion
  | otherwise    = (takeWhile even oddVersion) ++ (tail (dropWhile even oddVersion))
  where oddVersion = reverse $ dropWhile even $ reverse number
        currSum = sum oddVersion

groupByTwo :: [String] -> [(String, String)]
groupByTwo [] = []
groupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest

toString :: [Integer] -> String
toString [] = "-1"
toString number = foldl (\acc n -> acc ++ show n) "" number

solve :: (String, String) -> String
solve (_, xs) = toString $ toEbne number
  where number = map (\n -> toInteger $ n - (ord '0')) $ map ord xs

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

import Data.Char

toEbne :: [Integer] -> [Integer]
toEbne number = take 2 $ filter odd number

groupByTwo :: [String] -> [(String, String)]
groupByTwo [] = []
groupByTwo [_] = []
groupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest

toString :: [Integer] -> String
toString [] = "-1"
toString number = foldl (\acc n -> acc ++ show n) "" number

solve :: (String, String) -> String
solve (_, xs) = toString $ toEbne number
  where number = map (\n -> toInteger $ n - (ord '0')) $ map ord xs

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

import Data.Char

toEbne :: [Int] -> [Int]
toEbne number
  | null oddVersion = []
  | even currSum = oddVersion
  | otherwise    = (takeWhile even oddVersion) ++ (tail (dropWhile even oddVersion))
  where oddVersion = reverse $ dropWhile even $ reverse number
        currSum = sum oddVersion

groupByTwo :: [String] -> [(String, String)]
groupByTwo [] = []
groupByTwo (n:s:rest) = [(n, s)] ++ groupByTwo rest

toString :: [Int] -> String
toString [] = "-1"
toString number = foldl (\acc n -> acc ++ show n) "" number

solve :: (String, String) -> String
solve (_, xs) = toString $ toEbne number
  where number = map (\n -> n - (ord '0')) $ map ord xs

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


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

solve :: [Int] -> [Int]
solve [n, k]
  | n == k  =  [-1]
  | n == k + 1  =  [1..n]
  | otherwise  =  n : [2 .. k+1] ++ 1 : [k+2 .. n-1]

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

  where

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

    readPair :: Num a => IO (a, a)
    readPair  =  do
        [a, b]  <-  reads
        return (a, b)

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

module Main where
import Control.Applicative
main :: IO ()
main = do
  [n,k] <- map read . words <$> getLine :: IO [Int]
  let ans = [n] ++ [2..k+1] ++ [1] ++ [k+2..n-1]
  case undefined of
    _ | n == k -> print $ -1
    _ | n == k+1 -> putStrLn $ unwords $ map show [1..n]
    _ | otherwise -> putStrLn $ unwords $ map show ans

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

solve :: [Int] -> [Int]
solve [n, k]
  | n == k  =  [-1]
  | otherwise  =  take n ([1..k+1] ++ repeat 1)

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

  where

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

    readPair :: Num a => IO (a, a)
    readPair  =  do
        [a, b]  <-  reads
        return (a, b)

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

module Main where
import Control.Applicative
main :: IO ()
main = do
  [n,k] <- map read . words <$> getLine :: IO [Int]
  let ans = [n] ++ [2..k+1] ++ [1] ++ [k+2..n-1]
  if n == k
    then print $ -1
    else putStrLn $ unwords $ map show ans