Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split!Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).The little walrus's text looks in the following manner: TEXT ::= SENTENCE | SENTENCE SPACE TEXTSENTENCE ::= WORD SPACE SENTENCE | WORD ENDEND ::= {'.', '?', '!'}WORD ::= LETTER | LETTER WORDLETTER ::= {'a'..'z', 'A'..'Z'}SPACE ::= ' 'SPACE stands for the symbol of a space.So, how many messages did Fangy send?

The first line contains an integer n, which is the size of one message (2 ≤ n ≤ 255). The second line contains the text. The length of the text does not exceed 104 characters. It is guaranteed that the text satisfies the above described format. Specifically, this implies that the text is not empty.

On the first and only line print the number of text messages Fangy will need. If it is impossible to split the text, print "Impossible" without the quotes.

NoteLet's take a look at the third sample. The text will be split into three messages: "Hello!", "Do you like fish?" and "Why?".

module Main where

import Control.Monad
import Data.List

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

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

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

        res = packMessage sentenceSize 0

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

main = interact(solve.take 2.lines)

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

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

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

module Main where

import Control.Monad
import Data.List

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

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

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

        res = packMessage sentenceSize 0

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


The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help.A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers b1, b2, ..., bm (m ≤ n). All numbers from the message and from the key belong to the interval from 0 to c - 1, inclusive, and all the calculations are performed modulo c.Encryption is performed in n - m + 1 steps. On the first step we add to each number a1, a2, ..., am a corresponding number b1, b2, ..., bm. On the second step we add to each number a2, a3, ..., am + 1 (changed on the previous step) a corresponding number b1, b2, ..., bm. And so on: on step number i we add to each number ai, ai + 1, ..., ai + m - 1 a corresponding number b1, b2, ..., bm. The result of the encryption is the sequence a1, a2, ..., an after n - m + 1 steps.Help the Beaver to write a program that will encrypt messages in the described manner.

The first input line contains three integers n, m and c, separated by single spaces.  The second input line contains n integers ai (0 ≤ ai < c), separated by single spaces — the original message.  The third input line contains m integers bi (0 ≤ bi < c), separated by single spaces — the encryption key. The input limitations for getting 30 points are:    1 ≤ m ≤ n ≤ 103  1 ≤ c ≤ 103  The input limitations for getting 100 points are:    1 ≤ m ≤ n ≤ 105  1 ≤ c ≤ 103

Print n space-separated integers — the result of encrypting the original message.

NoteIn the first sample the encryption is performed in two steps: after the first step a = (0, 0, 0, 1) (remember that the calculations are performed modulo 2), after the second step a = (0, 1, 1, 0), and that is the answer.

import Control.Applicative
import Data.Array

readWords = map read . words <$> getLine

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

		sums = scanl1 (+.) bs

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

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

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

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

		sums = scanl1 (+.) bs

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

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

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

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

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

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

import Control.Applicative
import Data.Array

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

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

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

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

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

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

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

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

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

import Control.Applicative
import Data.Array

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

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

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


There is a prison that can be represented as a rectangular matrix with $$$n$$$ rows and $$$m$$$ columns. Therefore, there are $$$n \cdot m$$$ prison cells. There are also $$$n \cdot m$$$ prisoners, one in each prison cell. Let's denote the cell in the $$$i$$$-th row and the $$$j$$$-th column as $$$(i, j)$$$.There's a secret tunnel in the cell $$$(r, c)$$$, that the prisoners will use to escape! However, to avoid the risk of getting caught, they will escape at night.Before the night, every prisoner is in his own cell. When night comes, they can start moving to adjacent cells. Formally, in one second, a prisoner located in cell $$$(i, j)$$$ can move to cells $$$( i - 1 , j )$$$ , $$$( i + 1 , j )$$$ , $$$( i , j - 1 )$$$ , or $$$( i , j + 1 )$$$, as long as the target cell is inside the prison. They can also choose to stay in cell $$$(i, j)$$$.The prisoners want to know the minimum number of seconds needed so that every prisoner can arrive to cell $$$( r , c )$$$ if they move optimally. Note that there can be any number of prisoners in the same cell at the same time.

The first line contains an integer $$$t$$$ $$$(1 \le t \le 10^4)$$$, the number of test cases. Each of the next $$$t$$$ lines contains four space-separated integers $$$n$$$, $$$m$$$, $$$r$$$, $$$c$$$ ($$$1 \le r \le n \le 10^9$$$, $$$1 \le c \le m \le 10^9$$$).

Print $$$t$$$ lines, the answers for each test case.

import Control.Arrow ((>>>))

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

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

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

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

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

main = readInt >>= flip replicateM solve

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

import Control.Monad

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

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

module Main where

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

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

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

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

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

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

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

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

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

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

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

module Main where

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

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

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

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

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

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

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

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

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

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

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

module Main where

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

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

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

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

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

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

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

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

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

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

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

module Main where

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

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

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

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

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

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

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

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

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

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


Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.Sasha and Masha are about to buy some coconuts which are sold at price $$$z$$$ chizhiks per coconut. Sasha has $$$x$$$ chizhiks, Masha has $$$y$$$ chizhiks. Each girl will buy as many coconuts as she can using only her money. This way each girl will buy an integer non-negative number of coconuts.The girls discussed their plans and found that the total number of coconuts they buy can increase (or decrease) if one of them gives several chizhiks to the other girl. The chizhiks can't be split in parts, so the girls can only exchange with integer number of chizhiks.Consider the following example. Suppose Sasha has $$$5$$$ chizhiks, Masha has $$$4$$$ chizhiks, and the price for one coconut be $$$3$$$ chizhiks. If the girls don't exchange with chizhiks, they will buy $$$1 + 1 = 2$$$ coconuts. However, if, for example, Masha gives Sasha one chizhik, then Sasha will have $$$6$$$ chizhiks, Masha will have $$$3$$$ chizhiks, and the girls will buy $$$2 + 1 = 3$$$ coconuts. It is not that easy to live on the island now, so Sasha and Mash want to exchange with chizhiks in such a way that they will buy the maximum possible number of coconuts. Nobody wants to have a debt, so among all possible ways to buy the maximum possible number of coconuts find such a way that minimizes the number of chizhiks one girl gives to the other (it is not important who will be the person giving the chizhiks).

The first line contains three integers $$$x$$$, $$$y$$$ and $$$z$$$ ($$$0 \le x, y \le 10^{18}$$$, $$$1 \le z \le 10^{18}$$$) — the number of chizhics Sasha has, the number of chizhics Masha has and the price of a coconut.

Print two integers: the maximum possible number of coconuts the girls can buy and the minimum number of chizhiks one girl has to give to the other.

NoteThe first example is described in the statement. In the second example the optimal solution is to dot exchange any chizhiks. The girls will buy $$$3 + 4 = 7$$$ coconuts.

trade :: (Integer, Integer, Integer) -> (Integer, Integer)
trade (sasha, masha, price) = (buy, trans)
                                where
                                    buy = (sasha + masha) `div` price
                                    trans = case sasha `div` price + masha `div` price - buy of
                                        0 -> 0
                                        _ -> let
                                                choice1 = [sasha `mod` price, masha `mod` price]
                                                choice2 = map (price - ) choice1
                                             in minimum $ choice1 ++ choice2

main :: IO ()
main = do
    rawinput <- getLine
    let [s, m, p] = map read $ words rawinput :: [Integer]
    let (buy, trans) = trade (s, m, p)
    putStrLn $ (show buy) ++ " " ++ (show trans)

trade :: (Integer, Integer, Integer) -> (Integer, Integer)
trade (sasha, masha, price) = (buy, trans)
                                where
                                    buy = (sasha + masha) `div` price
                                    spend = buy * price
                                    choice1 = [sasha `mod` price, masha `mod` price]
                                    choice2 = map (price - ) choice1
                                    trans = minimum $ choice1 ++ choice2

main :: IO ()
main = do
    rawinput <- getLine
    let [s, m, p] = map read $ words rawinput :: [Integer]
    let (buy, trans) = trade (s, m, p)
    putStrLn $ (show buy) ++ " " ++ (show trans)


Once upon a time Mike and Mike decided to come up with an outstanding problem for some stage of ROI (rare olympiad in informatics). One of them came up with a problem prototype but another stole the idea and proposed that problem for another stage of the same olympiad. Since then the first Mike has been waiting for an opportunity to propose the original idea for some other contest... Mike waited until this moment!You are given an array $$$a$$$ of $$$n$$$ integers. You are also given $$$q$$$ queries of two types:  Replace $$$i$$$-th element in the array with integer $$$x$$$.  Replace each element in the array with integer $$$x$$$. After performing each query you have to calculate the sum of all elements in the array.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n, q \le 2 \cdot 10^5$$$) — the number of elements in the array and the number of queries, respectively. The second line contains $$$n$$$ integers $$$a_1, \ldots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — elements of the array $$$a$$$. Each of the following $$$q$$$ lines contains a description of the corresponding query. Description begins with integer $$$t$$$ ($$$t \in \{1, 2\}$$$) which denotes a type of the query:   If $$$t = 1$$$, then two integers $$$i$$$ and $$$x$$$ are following ($$$1 \le i \le n$$$, $$$1 \le x \le 10^9$$$) — position of replaced element and it's new value.  If $$$t = 2$$$, then integer $$$x$$$ is following ($$$1 \le x \le 10^9$$$) — new value of each element in the array.

Print $$$q$$$ integers, each on a separate line. In the $$$i$$$-th line print the sum of all elements in the array after performing the first $$$i$$$ queries.

NoteConsider array from the example and the result of performing each query:  Initial array is $$$[1, 2, 3, 4, 5]$$$.  After performing the first query, array equals to $$$[5, 2, 3, 4, 5]$$$. The sum of all elements is $$$19$$$.  After performing the second query, array equals to $$$[10, 10, 10, 10, 10]$$$. The sum of all elements is $$$50$$$.  After performing the third query, array equals to $$$[10, 10, 10, 10, 11$$$]. The sum of all elements is $$$51$$$.  After performing the fourth query, array equals to $$$[10, 10, 10, 1, 11]$$$. The sum of all elements is $$$42$$$.  After performing the fifth query, array equals to $$$[1, 1, 1, 1, 1]$$$. The sum of all elements is $$$5$$$.

{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE DatatypeContexts #-}

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

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

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

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Maybe (fromJust, fromMaybe, isJust)

import qualified Data.IntMap as IM
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S

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

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

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

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

data Num a => Structure a = Structure {
        values :: IM.IntMap a,
        defaultValue :: a,
        size :: Int,
        currentSum :: a
    }

structureFromList :: (Num a) => Int -> [a] -> Structure a
structureFromList size tValues  = Structure {
        values = IM.fromAscList (zip [1 ..] tValues),
        defaultValue = 0,
        size = size,
        currentSum = sum tValues
    }

structureUpdateElement :: (Monad m, Num a) => Int -> a -> S.StateT (Structure a) m ()
structureUpdateElement i newValue = do
    S.modify (\structure ->
        let mValues = values structure in
            structure { values = IM.insert i newValue mValues,
                        currentSum = currentSum structure - IM.findWithDefault (defaultValue structure) i mValues + newValue
                        })

structureUpdateElements :: (Monad m, Num a) => a -> S.StateT (Structure a) m ()
structureUpdateElements newValue = do
    S.modify (\structure ->
        structure { values = IM.empty,
                    defaultValue = newValue,
                    currentSum = fromIntegral (size structure) * newValue })

main :: IO ()
main = do
    [n, q] <- B8.getLine <&> readIntB8s
    values <- B8.getLine <&> readIntB8s
    let
        doQuery :: S.StateT (Structure Int64) IO ()
        doQuery = do
            query <- liftIO (B8.getLine <&> readIntB8s)
            case query of
                [1, i, v] -> structureUpdateElement i (fromIntegral v)
                [2, v] -> structureUpdateElements (fromIntegral v)
            structure <- S.get
            liftIO . printf "%lld\n" $ currentSum structure

        forEachQuery :: S.StateT (Structure Int64) IO ()
        forEachQuery = do
            forM_ [1 .. q] $ \_ -> doQuery

    (flip S.evalStateT) (structureFromList n (map (fromIntegral :: Int -> Int64) values)) forEachQuery


Ilya is sitting in a waiting area of Metropolis airport and is bored of looking at time table that shows again and again that his plane is delayed. So he took out a sheet of paper and decided to solve some problems.First Ilya has drawn a grid of size n × n and marked n squares on it, such that no two marked squares share the same row or the same column. He calls a rectangle on a grid with sides parallel to grid sides beautiful if exactly two of its corner squares are marked. There are exactly n·(n - 1) / 2 beautiful rectangles.Ilya has chosen q query rectangles on a grid with sides parallel to grid sides (not necessarily beautiful ones), and for each of those rectangles he wants to find its beauty degree. Beauty degree of a rectangle is the number of beautiful rectangles that share at least one square with the given one.Now Ilya thinks that he might not have enough time to solve the problem till the departure of his flight. You are given the description of marked cells and the query rectangles, help Ilya find the beauty degree of each of the query rectangles.

The first line of input contains two integers n and q (2 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the size of the grid and the number of query rectangles. The second line contains n integers p1, p2, ..., pn, separated by spaces (1 ≤ pi ≤ n, all pi are different), they specify grid squares marked by Ilya: in column i he has marked a square at row pi, rows are numbered from 1 to n, bottom to top, columns are numbered from 1 to n, left to right. The following q lines describe query rectangles. Each rectangle is described by four integers: l, d, r, u (1 ≤ l ≤ r ≤ n, 1 ≤ d ≤ u ≤ n), here l and r are the leftmost and the rightmost columns of the rectangle, d and u the bottommost and the topmost rows of the rectangle.

For each query rectangle output its beauty degree on a separate line.

NoteThe first sample test has one beautiful rectangle that occupies the whole grid, therefore the answer to any query is 1.In the second sample test the first query rectangle intersects 3 beautiful rectangles, as shown on the picture below:  There are 5 beautiful rectangles that intersect the second query rectangle, as shown on the following picture:

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

import qualified Data.ByteString as B (getLine)
import qualified Data.ByteString.Char8 as C (readInt, words)
import qualified Data.Maybe as M (fromJust)
import qualified Data.Array.IO.Safe as IO (IOArray, IOUArray)
import Data.IORef (newIORef, modifyIORef, readIORef)
import qualified Data.Array.MArray.Safe as A (newArray, newListArray, readArray, writeArray, getElems)
import Data.Bits (testBit)
import qualified Control.Monad as M (forM_)
import Data.Int (Int64)

readInt = fst . M.fromJust . C.readInt

-- Binary Indexed Tree (BIT)
bitL = 18 :: Int
data BIT = Empty | Node {-# UNPACK #-} !Int !BIT !BIT
create :: BIT
create = cre bitL where
    cre 0 = Empty
    cre k = let crp = cre (k - 1) in Node 0 crp crp
insert :: Int -> BIT -> BIT
insert i bit = ins bit (bitL - 1) where
    ins Empty _ = Empty
    ins (Node y l r) j | i `testBit` j = Node y (ins l (j - 1)) r
                       | otherwise = Node (y + 1) l (ins r (j - 1))
query :: Int -> BIT -> Int64
query i bit = que bit (bitL - 1) 0 where
    que Empty _ x = x
    que (Node y l r) !j !x | i `testBit` j = que l (j - 1) (x + fromIntegral y)
                           | otherwise = que r (j - 1) x

f !x = (x - 1) * x `div` 2
ff = f . fromIntegral

main = do
    (map readInt . C.words -> [n@(ff -> ntot), q]) <- B.getLine
    (map readInt . C.words -> ps) <- B.getLine
    ql <- A.newArray (1, n) [] :: IO (IO.IOArray Int [(Int, Int, Int)])
    qr <- A.newArray (1, n) [] :: IO (IO.IOArray Int [(Int, Int, Int)])
    parr <- A.newListArray (1, n) ps :: IO (IO.IOUArray Int Int)
    qans <- A.newArray (1, q) ntot :: IO (IO.IOUArray Int Int64)
    treel <- newIORef create
    treer <- newIORef create
    M.forM_ [1..q] $ \i -> do
        (map readInt . C.words -> [l, d, r, u]) <- B.getLine
        A.readArray ql l >>= A.writeArray ql l . ((d, u, i):)
        A.readArray qr r >>= A.writeArray qr r . ((d, u, i):)
        A.readArray qans i >>= A.writeArray qans i . ($ (sum $ map ff [l - 1, d - 1, n - r, n - u])) . (-)
    M.forM_ [2..n] $ \i@(fromIntegral . pred -> !ix) -> do
        A.readArray parr (i - 1) >>= modifyIORef treel . insert
        A.readArray parr (n - i + 2) >>= modifyIORef treer . insert
        !trl <- readIORef treel
        !trr <- readIORef treer
        (A.readArray ql i >>=) . mapM_ $ \(d, u, ii) ->
            A.readArray qans ii >>= A.writeArray qans ii . (+ (f (query d trl) + f (ix - query (u + 1) trl)))
        (A.readArray qr (n + 1 - i) >>=) . mapM_ $ \(d, u, ii) ->
            A.readArray qans ii >>= A.writeArray qans ii . (+ (f (query d trr) + f (ix - query (u + 1) trr)))
    A.getElems qans >>= putStr . unlines . map show


Andryusha is an orderly boy and likes to keep things in their place.Today he faced a problem to put his socks in the wardrobe. He has n distinct pairs of socks which are initially in a bag. The pairs are numbered from 1 to n. Andryusha wants to put paired socks together and put them in the wardrobe. He takes the socks one by one from the bag, and for each sock he looks whether the pair of this sock has been already took out of the bag, or not. If not (that means the pair of this sock is still in the bag), he puts the current socks on the table in front of him. Otherwise, he puts both socks from the pair to the wardrobe.Andryusha remembers the order in which he took the socks from the bag. Can you tell him what is the maximum number of socks that were on the table at the same time?

The first line contains the single integer n (1 ≤ n ≤ 105) — the number of sock pairs. The second line contains 2n integers x1, x2, ..., x2n (1 ≤ xi ≤ n), which describe the order in which Andryusha took the socks from the bag. More precisely, xi means that the i-th sock Andryusha took out was from pair xi. It is guaranteed that Andryusha took exactly two socks of each pair.

Print single integer — the maximum number of socks that were on the table at the same time.

NoteIn the first example Andryusha took a sock from the first pair and put it on the table. Then he took the next sock which is from the first pair as well, so he immediately puts both socks to the wardrobe. Thus, at most one sock was on the table at the same time.In the second example Andryusha behaved as follows:   Initially the table was empty, he took out a sock from pair 2 and put it on the table.  Sock (2) was on the table. Andryusha took out a sock from pair 1 and put it on the table.  Socks (1, 2) were on the table. Andryusha took out a sock from pair 1, and put this pair into the wardrobe.  Sock (2) was on the table. Andryusha took out a sock from pair 3 and put it on the table.  Socks (2, 3) were on the table. Andryusha took out a sock from pair 2, and put this pair into the wardrobe.  Sock (3) was on the table. Andryusha took out a sock from pair 3 and put this pair into the wardrobe.  Thus, at most two socks were on the table at the same time.

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

import Control.Monad
import qualified Data.Set as Set

getInt = read `fmap` getLine :: IO Int

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

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

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

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

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

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

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

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

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

import System.IO
import Data.Set

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

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

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

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

    print . maximum $ pick 0 empty socks_

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

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

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

import qualified Data.Set as Set
import Data.List

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

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

import qualified Data.Set as Set
import Data.List

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

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

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

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

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

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

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

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

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

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


This problem is a simplified version of D2, but it has significant differences, so read the whole statement.Polycarp has an array of $$$n$$$ ($$$n$$$ is even) integers $$$a_1, a_2, \dots, a_n$$$. Polycarp conceived of a positive integer $$$k$$$. After that, Polycarp began performing the following operations on the array: take an index $$$i$$$ ($$$1 \le i \le n$$$) and reduce the number $$$a_i$$$ by $$$k$$$.After Polycarp performed some (possibly zero) number of such operations, it turned out that all numbers in the array became the same. Find the maximum $$$k$$$ at which such a situation is possible, or print $$$-1$$$ if such a number can be arbitrarily large.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of two lines. The first line contains an even integer $$$n$$$ ($$$4 \le n \le 40$$$) ($$$n$$$ is even). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots a_n$$$ ($$$-10^6 \le a_i \le 10^6$$$). It is guaranteed that the sum of all $$$n$$$ specified in the given test cases does not exceed $$$100$$$.

For each test case output on a separate line an integer $$$k$$$ ($$$k \ge 1$$$) — the maximum possible number that Polycarp used in operations on the array, or $$$-1$$$, if such a number can be arbitrarily large.

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

-- code --

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

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

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

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

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

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

-- //// --

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

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

readInt :: String -> Int
readInt = read

readBigInt :: String -> Integer
readBigInt = read

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

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

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

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

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

main = interact solve

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

-- code --

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

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

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

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

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

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

-- //// --

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

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

readInt :: String -> Int
readInt = read

readBigInt :: String -> Integer
readBigInt = read

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

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

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

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

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

main = interact solve

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

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

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

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

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

output = showB

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

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

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

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

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

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

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

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

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

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

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

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

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

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

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

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

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

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

    (putStr . unlines . map solve) tcs

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

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

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

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

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

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

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

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

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

output = showB

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

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

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

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

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

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

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

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

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

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

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

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

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

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


You have $$$n$$$ students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the $$$i$$$-th student skill is denoted by an integer $$$a_i$$$ (different students can have the same skills).So, about the teams. Firstly, these two teams should have the same size. Two more constraints:  The first team should consist of students with distinct skills (i.e. all skills in the first team are unique).  The second team should consist of students with the same skills (i.e. all skills in the second team are equal). Note that it is permissible that some student of the first team has the same skill as a student of the second team.Consider some examples (skills are given):  $$$[1, 2, 3]$$$, $$$[4, 4]$$$ is not a good pair of teams because sizes should be the same;  $$$[1, 1, 2]$$$, $$$[3, 3, 3]$$$ is not a good pair of teams because the first team should not contain students with the same skills;  $$$[1, 2, 3]$$$, $$$[3, 4, 4]$$$ is not a good pair of teams because the second team should contain students with the same skills;  $$$[1, 2, 3]$$$, $$$[3, 3, 3]$$$ is a good pair of teams;  $$$[5]$$$, $$$[6]$$$ is a good pair of teams. Your task is to find the maximum possible size $$$x$$$ for which it is possible to compose a valid pair of teams, where each team size is $$$x$$$ (skills in the first team needed to be unique, skills in the second team should be the same between them). A student cannot be part of more than one team.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of students. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le n$$$), where $$$a_i$$$ is the skill of the $$$i$$$-th student. Different students can have the same skills. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$).

For each test case, print the answer — the maximum possible size $$$x$$$ for which it is possible to compose a valid pair of teams, where each team size is $$$x$$$.

NoteIn the first test case of the example, it is possible to construct two teams of size $$$3$$$: the first team is $$$[1, 2, 4]$$$ and the second team is $$$[4, 4, 4]$$$. Note, that there are some other ways to construct two valid teams of size $$$3$$$.

module Main where

import Control.Monad
import Data.List

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

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

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

module Main where

import Control.Monad
import Data.List

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

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

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

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

import           Data.List

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

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

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

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

import Control.Monad
import Data.List

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

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

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

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

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

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

import Data.List

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

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

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

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

import Data.List

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

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

module Main where

import Control.Monad
import Data.List

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

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

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

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

import           Data.List

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

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

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

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


On the way to school, Karen became fixated on the puzzle game on her phone!  The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.One move consists of choosing one row or column, and adding 1 to all of the cells in that row or column.To win the level, after all the moves, the number in the cell at the i-th row and j-th column should be equal to gi, j.Karen is stuck on one level, and wants to know a way to beat this level using the minimum number of moves. Please, help her with this task!

The first line of input contains two integers, n and m (1 ≤ n, m ≤ 100), the number of rows and the number of columns in the grid, respectively. The next n lines each contain m integers. In particular, the j-th integer in the i-th of these rows contains gi, j (0 ≤ gi, j ≤ 500).

If there is an error and it is actually not possible to beat the level, output a single integer -1. Otherwise, on the first line, output a single integer k, the minimum number of moves necessary to beat the level. The next k lines should each contain one of the following, describing the moves in the order they must be done:   row x, (1 ≤ x ≤ n) describing a move of the form "choose the x-th row".  col x, (1 ≤ x ≤ m) describing a move of the form "choose the x-th column".  If there are multiple optimal solutions, output any one of them.

NoteIn the first test case, Karen has a grid with 3 rows and 5 columns. She can perform the following 4 moves to beat the level:  In the second test case, Karen has a grid with 3 rows and 3 columns. It is clear that it is impossible to beat the level; performing any move will create three 1s on the grid, but it is required to only have one 1 in the center.In the third test case, Karen has a grid with 3 rows and 3 columns. She can perform the following 3 moves to beat the level:  Note that this is not the only solution; another solution, among others, is col 1, col 2, col 3.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

data Op = Row Int | Col Int

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


User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible.Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≤ k ≤ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak < bk all holds.As known, permutation p is so sensitive that it could be only modified by swapping two distinct elements. But swapping two elements is harder than you think. Given an n × n binary matrix A, user ainta can swap the values of pi and pj (1 ≤ i, j ≤ n, i ≠ j) if and only if Ai, j = 1.Given the permutation p and the matrix A, user ainta wants to know the prettiest permutation that he can obtain.

The first line contains an integer n (1 ≤ n ≤ 300) — the size of the permutation p. The second line contains n space-separated integers p1, p2, ..., pn — the permutation p that user ainta has. Each integer between 1 and n occurs exactly once in the given permutation. Next n lines describe the matrix A. The i-th line contains n characters '0' or '1' and describes the i-th row of A. The j-th character of the i-th line Ai, j is the element on the intersection of the i-th row and the j-th column of A. It is guaranteed that, for all integers i, j where 1 ≤ i < j ≤ n, Ai, j = Aj, i holds. Also, for all integers i where 1 ≤ i ≤ n, Ai, i = 0 holds.

In the first and only line, print n space-separated integers, describing the prettiest permutation that can be obtained.

NoteIn the first sample, the swap needed to obtain the prettiest permutation is: (p1, p7).In the second sample, the swaps needed to obtain the prettiest permutation is (p1, p3), (p4, p5), (p3, p4).   A permutation p is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. The i-th element of the permutation p is denoted as pi. The size of the permutation p is denoted as n.

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

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

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

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

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

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

  putStrLn $ unwords $ map show p'

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

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

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

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

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

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

import qualified Data.Map as Map

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

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

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

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

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

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

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

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

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

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

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

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

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


Petya loves hockey very much. One day, as he was watching a hockey match, he fell asleep. Petya dreamt of being appointed to change a hockey team's name. Thus, Petya was given the original team name w and the collection of forbidden substrings s1, s2, ..., sn. All those strings consist of uppercase and lowercase Latin letters. String w has the length of |w|, its characters are numbered from 1 to |w|.First Petya should find all the occurrences of forbidden substrings in the w string. During the search of substrings the case of letter shouldn't be taken into consideration. That is, strings "aBC" and "ABc" are considered equal.After that Petya should perform the replacement of all letters covered by the occurrences. More formally: a letter in the position i should be replaced by any other one if for position i in string w there exist pair of indices l, r (1 ≤ l ≤ i ≤ r ≤ |w|) such that substring w[l ... r] is contained in the collection s1, s2, ..., sn, when using case insensitive comparison. During the replacement the letter's case should remain the same. Petya is not allowed to replace the letters that aren't covered by any forbidden substring.Letter letter (uppercase or lowercase) is considered lucky for the hockey players. That's why Petya should perform the changes so that the letter occurred in the resulting string as many times as possible. Help Petya to find such resulting string. If there are several such strings, find the one that comes first lexicographically.Note that the process of replacements is not repeated, it occurs only once. That is, if after Petya's replacements the string started to contain new occurrences of bad substrings, Petya pays no attention to them.

The first line contains the only integer n (1 ≤ n ≤ 100) — the number of forbidden substrings in the collection. Next n lines contain these substrings. The next line contains string w. All those n + 1 lines are non-empty strings consisting of uppercase and lowercase Latin letters whose length does not exceed 100. The last line contains a lowercase letter letter.

Output the only line — Petya's resulting string with the maximum number of letters letter. If there are several answers then output the one that comes first lexicographically. The lexicographical comparison is performed by the standard < operator in modern programming languages. The line a is lexicographically smaller than the line b, if a is a prefix of b, or there exists such an i (1 ≤ i ≤ |a|), that ai < bi, and for any j (1 ≤ j < i) aj = bj. |a| stands for the length of string a.

4
hello
party
abefglghjdhfgj
IVan
petrsmatchwin
a

module Main where

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

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

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

    putStrLn finalStr

    return ()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

state = State

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

import Data.Char

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

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

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

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

main = interact f

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

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

import Data.Char

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

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

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

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

main = interact f