import Control.Monad (replicateM_)
import Data.List

solve :: IO ()
solve = do
  m <- read <$> getLine
  bs <- getLine
  let
    m0 = length $ filter (=='0') bs
    cs = replicate m0 '0' ++ replicate (m-m0) '1'
    ds = zip [1..] $ zipWith (/=) bs cs
    es = [i | (i,j)<-ds, j==True]
  print $ if null es then 0 else 1
  if null es then return () else putStrLn $ intercalate " " $ fmap show $ (length es) : es

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n 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
import Data.Bool

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

data TC = TC { n :: Int, s :: String }

input :: Scanner TC
input = do
  n <- int
  s <- str
  return TC {..}

type Output = [[Int]]

output :: Output -> C.ByteString
output ops = C.pack . unlines $ show (length ops) : map showl ops
  where
    showl xs = unwords . map show $ length xs : xs

solve :: TC -> Output
solve TC {..}
  | null bs0 = []
  | otherwise = [bs1 ++ bs0]
  where
    c0 = count '0' s
    bs0 = [i | (c, i) <- zip s [1..], c == '0', i > c0]
    bs1 = [i | (c, i) <- zip s [1..], c == '1', i <= c0]

-------------------------- 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
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Char8 as C

solve :: IO ()
solve = do
    ~[n] <- readInts
    s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine
    let cnt0 = length $ filter (=='0') s
        ans = [i | (i, x, y) <- zip3 [1..] s $ replicate cnt0 '0' ++ repeat '1', x /= y]
    if null ans
        then print 0
        else print 1 >> putStrLn (unwords $ map show $ length ans : ans)

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

main :: IO ()
main = flip replicateM_ solve . head =<< readInts

import Control.Monad (replicateM_)
import Data.List

solve :: IO ()
solve = do
  m <- read <$> getLine
  bs <- getLine
  let
    m0 = length $ filter (=='0') bs
    cs = replicate m0 '0' ++ replicate (m-m0) '1'
    ds = zip [1..] $ zipWith (/=) bs cs
    es = [i | (i,j)<-ds, j==True]
  print $ if null es then 0 else 1
  putStrLn $ intercalate " " $ fmap show $ (length es) : es

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n solve

import Control.Monad (replicateM_)
import Data.List

solve :: IO ()
solve = do
  m <- read <$> getLine
  bs <- getLine
  let
    m0 = length $ filter (=='0') bs
    cs = replicate m0 '0' ++ replicate (m-m0) '1'
    ds = zip [1..] $ zipWith (/=) bs cs
    es = [i | (i,j)<-ds, j==True]
  print $ if null es then 0 else 1
  print $ intercalate " " $ fmap show $ (length es) : es

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n solve

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

solve :: IO ()
solve = do
    ~[n] <- readInts
    s <- takeWhile (not . isSpace) . C.unpack <$> C.getLine
    let cnt0 = length $ filter (=='0') s
        ans = [i | (i, x, y) <- zip3 [1..] s $ replicate cnt0 '0' ++ repeat '1', x /= y]
    if null ans
        then print 0
        else print 1 >> putStrLn (unwords $ map show ans)

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

main :: IO ()
main = flip replicateM_ solve . head =<< readInts


import Control.Monad
import Data.List

readIntLine :: IO [Int]
readIntLine = fmap (map read.words) getLine

solve = do
    s <- getLine
    s <- getLine
    let t = sort s
    print $ sum $ zipWith (\x y -> if x /= y then 1 else 0) t s

main = do
    [t] <- readIntLine
    replicateM t solve
    return ()

import Control.Monad
import Data.List

solve :: IO ()
solve = do
    n <- readLn :: IO Int
    s <- getLine
    print $ length $ filter id $ zipWith (/=) s (sort s)

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

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

-- main :: IO [()]
main = do
    n <- read <$> getLine
    replicateM n $ do
        y <- read <$> getLine
        x <- getLine
        print $ y - solve x

solve :: [Char] -> Int
solve x = foldr (\(i,j) acc -> if i == j then acc + 1 else acc) 0 (zip x (sort x))

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P

import Data.Word (Word8)
import Data.Int (Int64)
import qualified Data.Bits as Bits
import qualified Data.Char as Char
import qualified Data.Ratio as Rat

import Data.List as L
import qualified Data.Set as Set
import qualified Data.Map as Map

import qualified Data.ByteString as Bs
import qualified System.IO as Io
--import Data.IntSet

solve :: IO ()
solve = do
  n <- readLn :: IO Int
  s <- getLine
  let res = zipWith (\a b -> a == b) s $ sort s
      sol = length $ filter (==False) res
    in print sol

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

----------------------------------------------------------------------------------------
readrows :: (Integral b) => b -> IO [String]
readrows 0 = return []
readrows n = do
  row <- getLine
  l <- readrows $ n-1
  return (row : l)

readintrows :: (Integral a, Integral b) => b -> IO [[a]]
readintrows 0 = return []
readintrows n = do
  row <- readInts
  l <- readintrows $ n-1
  return (row : l)

parseInt :: (Integral a) => Bs.ByteString -> a
parseInt xs = snd $ Bs.foldr (\y (pow, acc) -> (pow*10, acc + pow*(fromIntegral (y-48)))) (1, 0) xs

readInts :: (Integral a) => IO [a]
readInts =  map parseInt . filter (/=Bs.empty) . Bs.splitWith (==32) . fuckingWindowsCRLF <$> Bs.getLine
  where fuckingWindowsCRLF bs = if Bs.last bs == 13 then Bs.init bs else bs

import Control.Monad
import Data.List

printResult = do
    n <- getLine
    s <- getLine
    let ss = sort s
    print $ sum $ zipWith (\x y->if x /= y then 1 else 0) ss s

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

import Control.Arrow ((>>>))
import Data.List (sort)

main :: IO ()
main = interact $ words >>> drop 1 >>> chunksOf 2 >>> map (last >>> solve >>> show) >>> unlines

solve :: String -> Int
solve s = length . filter not $ zipWith (==) s (sort s)

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

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

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

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [_n] <- readInts
    s <- P.unpack <$> readLine
    putInts [length [() | (c, v) <- zip s (sort s), c /= v]]

type SIO = StateT P.ByteString IO

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

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

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


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

import Data.List
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

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

solve :: [Int] -> String
solve xs =
    let ds = sort $ zipWith (-) (tail xs) xs
        h = head ds
        len = length $ takeWhile (== h) ds
    in  unwords $ map show [h, len]

main = do
    (sort . tail . map nextInt . C.words -> xs) <- B.getContents
    putStrLn $ solve xs

import Data.List
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

main :: IO ()
main = putStrLn . unwords . map show . solve . tail . map (fst . fromJust . C.readInt) . C.words =<< B.getContents

solve :: [Int] -> [Int]
solve a = solve' [maxBound :: Int, 0] (sort a)

solve' :: [Int] -> [Int] -> [Int]
solve' result [] = result
solve' result [a] = result
solve' [d, c] (a:b:x) | b - a < d = solve' [b - a, 1] (b:x)
                      | b - a == d = solve' [d, c + 1] (b:x)
                      | otherwise = solve' [d, c] (b:x)

{-# LANGUAGE ViewPatterns, ScopedTypeVariables #-}

import Data.List
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

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

solve :: [Int] -> String
solve xs =
    let ds = sort $ zipWith (-) (tail xs) xs
        h = head ds
        len = length $ takeWhile (== h) ds
    in  show h ++ " " ++ show len

main = do
    (sort . tail . map nextInt . C.words -> xs) <- B.getContents
    putStrLn $ solve xs

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

import Control.Monad (forM_, forM)
import Data.List (sort)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Data.Maybe (fromJust)

readint = fst. fromJust . C.readInt

main = do
    (readint -> n) <- B.getLine
    (sort . map readint . C.words -> xs) <- B.getLine
    let ds = sort $ zipWith (-) (tail xs) xs
    putStrLn $ show (head ds) ++ " " ++ show (length $ takeWhile (== (head ds)) ds)


{-# LANGUAGE BangPatterns #-}

import Control.Applicative

main = getLine >> do
  ps <- map read.words <$> getLine :: IO [Integer]
  [a,b,c,d,e] <- map read.words <$> getLine :: IO [Integer]
  let solve !point !cnts [] = do
         putStrLn.unwords $ map show cnts
         print point
      solve !point !cnts (x:xs) = solve ra (zipWith (+) cnts [da,db,dc,dd,de]) xs
       where
         (de,re) = (point+x)`divMod`e
         (dd,rd) = re`divMod`d
         (dc,rc) = rd`divMod`c
         (db,rb) = rc`divMod`b
         (da,ra) = rb`divMod`a
  solve 0 [0,0,0,0,0] ps

main = do
  getLine
  p <- fmap (map read . words) getLine
  q <- fmap (reverse . map read . words) getLine
  let (x, y) = foldl (gao q) (repeat 0, 0) p
  putStrLn $ unwords $ map show $ reverse x ++ [y]

gao q (c, s) t = let (x, y) = go q c [] (s+t) in (reverse x, y)

go [] _ x y = (x, y)
go (a:as) (b:bs) x y = let c = y `div` a in go as bs (b+c:x) (y `mod` a)

import Prelude hiding (Int ())

type Int  =  Integer
type Fiver  =  (Int, Int, Int, Int, Int)

solve :: Fiver -> [Int] -> (Fiver, Int)
solve (a,b,c,d,e) xs  =  solve' xs ((0, 0, 0, 0, 0), 0)
  where
    solve' [] acc  =  acc
    solve' (x:xs) ((a',b',c',d',e'), y)
      | xy >= e  =  solve' ((xy `mod` e) : xs) ((a', b', c', d', e' + xy `div` e), 0)
      | xy >= d  =  solve' ((xy `mod` d) : xs) ((a', b', c', d' + xy `div` d, e'), 0)
      | xy >= c  =  solve' ((xy `mod` c) : xs) ((a', b', c' + xy `div` c, d', e'), 0)
      | xy >= b  =  solve' ((xy `mod` b) : xs) ((a', b' + xy `div` b, c', d', e'), 0)
      | xy >= a  =  solve' ((xy `mod` a) : xs) ((a' + xy `div` a, b', c', d', e'), 0)
      | otherwise  =  solve' xs ((a',b',c',d',e'), xy)
      where
        xy  =  x + y

printAns :: (Fiver, Int) -> IO ()
printAns ((a, b, c, d, e), x)  =  putStrLn (unwords (map show [a,b,c,d,e])) >> print x

main :: IO()
main  =  do
    getLine
    xs  <-  getLine >>= return . map read . words
    [a,b,c,d,e]  <-  getLine >>= return . map read . words
    printAns $ solve (a,b,c,d,e) xs

buy money [] = (money, [])
buy money (p:ps) =
    let (nokori, buyed ) = buy money ps
    in (mod nokori p, div nokori p:buyed)

next ps (money, gift) addp =
     let (nokori, ngift) = buy (money+addp) ps
     in (nokori, zipWith (\x y->x+y) gift ngift )

cal getPoints ps = foldl (next ps) (0, [0,0,0,0,0]) getPoints

join c (x:[]) = x
join c (x:xs) = x++(c:join c xs)

main = do
     _ <- getLine
     s <- getLine
     let getPoints = map read $ words s
     s2 <- getLine
     let ps = map read $ words s2
     let (remMoney, gifts) = cal getPoints ps
     putStrLn $ join ' ' $ map show gifts
     print remMoney

import Control.Monad

readInt :: String -> Integer
readInt = read

buyItems cash [] = (cash,[])
buyItems cash (c:cs) = (cash',cnt:bought)
  where cnt = cash `div` c
        (cash',bought) = buyItems (cash-cnt*c) cs

addList xs ys = map (\(a,b)->a+b) $ zip xs ys

main = do
  n <- liftM readInt $ getLine
  ps <- liftM (map readInt . words) $ getLine
  cs <- liftM (reverse . map readInt . words) $ getLine
  let (cash, bt) = foldl (f cs) (0,repeat 0) ps
  putStrLn . unwords . map show . reverse $ bt
  putStrLn . show $ cash
  where f cs (cash,bought) p = (cash',addList bt bought)
          where (cash',bt) = (buyItems (cash+p) cs)

import Control.Monad

solve (a,b,c,d,e) xs = solve' 0 [0,0,0,0,0] xs
  where
    costs = [e,d,c,b,a]
    solve' n ys (x:xs) =
      let
        (l, r) = spend (n+x) costs
      in
        solve' l (zipWith (+) r ys) xs
      where
        spend p [] = (p, [])
        spend p (x:xs) =
          let
            cnt = p `div` x
            rem = p - cnt * x
            (l, r) = spend rem xs
          in
            (l, cnt : r)
    solve' n ys [] = (n, ys)

main = do
  n <- liftM read getLine
  xs <- getLine >>= (return.map read.take n.words)
  [a,b,c,d,e] <- getLine >>= (return.map read.take 5.words)
  let (l, r) = solve (a,b,c,d,e) xs :: (Integer, [Integer])
  putStrLn (unwords $ reverse $ map show r)
  putStrLn (show l)


main :: IO ()
main = do
  [n, r] <- map (read :: String -> Double) . words <$> getLine
  print $ r / (sqrt (2 / (1 - cos (2 * pi / n))) - 1)

-- Codeforces Round #532 (C), Contest 1100, Problem set ?.
-- UNDONE

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

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

main :: IO ()
main = do
  [n,r] <- map read . words <$> getLine :: IO [Double]
  print $ r * sin(pi/n) / (1 - sin (pi/n))

import Text.Printf
import Data.List
import Data.Functor
import Control.Applicative
import Prelude
import Control.Monad
import Data.Maybe
import Data.Function
import qualified Data.ByteString.Char8 as B8
import Data.Foldable (foldr')
import Data.Bits
import Data.IORef

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

readB8Int :: B8.ByteString -> Int
readB8Int = fst . fromJust . B8.readInt

solve :: Double -> Double -> Double
solve n r = r / (1 / sin (2 * pi / (2 * n)) - 1)

main :: IO ()
main = do
    [n, r] <- (map (read :: String -> Double) . words) <$> getLine
    let answer = solve n r
    printf "%.10f" $ answer


main = (read `fmap` getLine) >>= \n ->
    (if even n then mapM_ (putStrLn . take n . concat . repeat) ["aabb", "ccdd"] >>
        mapM_ (\x -> putStrLn $ "e" ++ (take (n - 2) $ concat $ repeat x) ++ "h")
            ["ffgg", "aabb"]
    else mapM_ (\x -> putStrLn $ "a" ++ (take (n - 1) $ concat $ repeat x))
            ["bbcc", "ddee"] >>
        mapM_ (\x -> putStrLn $ (take (n - 1) $ concat $ repeat x)++"g")
            ["bbcc", "ddee"])

import Control.Applicative
import Data.Monoid
import Control.Monad
import qualified Data.Map as Map
import Data.Map(Map)
import Data.Maybe

type Ending = [IsHorisEnd]

data State s v = State { runState :: (s -> (s, v)) }
type StateMap a b = State (Map a b) b

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

instance Monad (State a) where
    return x = State $ \m -> (m, x)
    a >>= f = joinState $ f <$> a

joinState s = State $ \m -> let (m', s') = runState s m in runState s' m'

get = State $ \m -> (m, m)
put m' = State $ \m -> (m', ())
evalState s m = snd $ (runState s) m

memoizeM :: (Show a, Show b, Ord a) =>
            ((a -> StateMap a b) -> (a -> StateMap a b)) -> (a -> b)
memoizeM t x = evalState (f x) Map.empty where
  g x = do
    y <- t f x
    m <- get
    put $ Map.insert x y m
    newM <- get
    return $ y
  f x = get >>= \m -> maybe (g x) return (Map.lookup x m)

type IsHorisEnd = Bool
type IsVertStart = Bool

getContinuations :: Ending -> [[(IsHorisEnd, IsVertStart)]]
getContinuations = go
    where
        go :: [Bool] -> [[(IsHorisEnd, IsVertStart)]]
        go [] = [[]]
        go (False : False : t) = let aug l = [(True, False) : (True, False) : l, (False, True) : (False, False) : l] in go t >>= aug
        go (b : t) = map ((not b, False) :) $ go t

getHor :: Int -> Int -> Char
getHor n i = toEnum $ fromEnum 'a' + (i `mod` 2) + 2 * (n `mod` 3)
getVert :: Int -> Int -> Char
getVert n i = toEnum $ fromEnum 'p' + (n `mod` 2) + 2 * (i `mod` 3)

solve :: (Functor m, Monad m) => ((Ending, Int) -> m (Maybe [String])) -> (Ending, Int) -> m (Maybe [String])
solve rec (ed, 0) = return $ do
    guard (not $ or ed)
    (return ["","","",""]) :: Maybe [String]
solve rec (ed, n) = getFirst . mconcat . map First <$> (solveAll $ getContinuations ed)
    where
        solveAll = mapM solve
        solve cont | (not $ isGood (map fst cont)) = return Nothing
        solve cont = do
            res <- rec (map fst cont, n-1)
            return (appendThis cont <$> (res :: Maybe [String]) :: Maybe [String])
        isGood | n==1 = not . or
               | n>1 = or
        appendThis :: [(IsHorisEnd, IsVertStart)] -> [String] -> [String]
        appendThis cont res = zipWith (:) (getThis cont) res
        getChar True (False, False) i = getHor (n+1) i
        getChar False (True, False) i = getHor n i
        getChar False (False, True) i = getVert n i
        getChar False (False, False) i = getVert n (i-1)
        getThis cont = zipWith3 getChar ed cont [1..]

main = interact $ unlines . fromMaybe ["-1"] . memoizeM solve . (\n -> (replicate 4 False, n)) . read

module Main where

import Control.Monad

main = do
    n <- read `liftM` getLine
    putStr $ board n

board n =
    if even n
    then
        take n (cycle "aabb") ++ "\n" ++
        "i" ++ take (n-2) (cycle "ccdd") ++ "j\n" ++
        "i" ++ take (n-2) (cycle "eeff") ++ "j\n" ++
        take n (cycle "gghh") ++ "\n"
    else
        take (n-1) (cycle "aabb") ++ "i\n" ++
        take (n-1) (cycle "ccdd") ++ "i\n" ++
        "j" ++ take (n-1) (cycle "eeff") ++ "\n" ++
        "j" ++ take (n-1) (cycle "gghh") ++ "\n"

myPrint :: Int -> Int -> String
myPrint 1 n
    | mod n 2 == 0 = take n (cycle "aabb")
    | otherwise = take (n - 1) (cycle "aabb") ++ "z"
myPrint 2 n
    | mod n 2 == 0 = take n (cycle "ccdd")
    | otherwise = take (n - 1) (cycle "ccdd") ++ "z"
myPrint 3 n
    | mod n 2 == 0 = 'q' : (take (n - 2) (cycle "aabb") ++ "z")
    | otherwise = 'q' : (take (n - 1) (cycle "aabb"))
myPrint 4 n
    | mod n 2 == 0 = 'q' : (take (n - 2) (cycle "ccdd") ++ "z")
    | otherwise = 'q' : (take (n - 1) (cycle "ccdd"))

main = do
    n <- readLn::IO Int
    putStrLn (myPrint 1 n)
    putStrLn (myPrint 2 n)
    putStrLn (myPrint 3 n)
    putStrLn (myPrint 4 n)

{-# 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
    return n
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

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

solve :: Int -> ByteString
solve n = BS.unlines . map BS.pack $ answer
  where
    answer
      | even n    = [r2 0 False, r121 1 False, r121 2 True, r2 3 False]
      | otherwise = [r21 0 False, r21 1 True, r12 2 False, r12 3 True]

    n2 = n `div` 2

    r2 = color (replicate n2 2)
    r121 = color ([1] ++ replicate (n2 - 1) 2 ++ [1])
    r21 = color (replicate n2 2 ++ [1])
    r12 = color ([1] ++ replicate n2 2)

    color :: [Int] -> Int -> Bool -> String
    color a row bool = concatMap go $ zip (cycle [0..4]) a
      where
        go (id, num) = replicate num (chr $ ord 'a' + row' * 5 + id)
          where
            row' = if num == 1 && bool then row - 1 else row -- vertical

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

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

main = (read `fmap` getLine) >>= \n ->
    (if even n then mapM_ (putStrLn . take n . concat . repeat) ["aabb", "ccdd"] >>
        mapM_ (\x -> putStrLn $ "e" ++ (take (n - 2) $ concat $ repeat x) ++ "e")
            ["ffgg", "aabb"]
    else mapM_ (\x -> putStrLn $ "a" ++ (take (n - 1) $ concat $ repeat x))
            ["bbcc", "ddee"] >>
        mapM_ (\x -> putStrLn $ (take (n - 1) $ concat $ repeat x)++"a")
            ["bbcc", "ddee"])

main = (read `fmap` getLine) >>= \n ->
    (if even n then mapM_ (putStrLn . take n . concat . repeat) ["aabb", "ccdd"] >>
        mapM_ (\x -> putStrLn $ "e" ++ (take (n - 2) $ concat $ repeat x) ++ "h")
            ["ffgg", "aabb"]
    else mapM_ (\x -> putStrLn $ "a" ++ (take (n - 1) $ concat $ repeat x))
            ["bbcc", "ddee"] >>
        mapM_ (\x -> putStrLn $ (take (n - 1) $ concat $ repeat x)++"a")
            ["bbcc", "ddee"])


import Data.IntMap (elems, empty, insertWith, unionWith)
import Monad (liftM)

solve :: Int -> [(Int, Int)] -> Int
solve n xs
  | res == maxBound  =  -1
  | otherwise  =  res
  where
    res  =  minimum $ map f $ elems $ unionWith add mapA mapB
    halfN  =  div n 2 + mod n 2
    mapA  =  foldl (\map x -> insertWith add x (1,0) map) empty (map fst xs)
    mapB  =  foldl (\map x -> insertWith add x (0,1) map) empty (map snd . filter notEq $ xs)
    notEq (x, y)  =  x /= y
    add (a, b) (c, d)  =  (a+c, b+d)
    f (a,b)
      | a + b >= halfN  =  max 0 (halfN - a)
      | otherwise  =  maxBound

parse :: String -> (Int, Int)
parse line  =  case words line of
    [s1, s2]  ->  (read s1, read s2)

main :: IO ()
main  =  do
    n   <-  readLn
    xs  <-  liftM (take n . map parse . lines) getContents
    print $ solve n xs

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

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

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

main = do
  n <- readLn
  ps <- replicateM n $ getInts

  let
    a = map (\g -> (head g, length g)) . group . sort $ map (!! 0) ps
    b = map (\g -> (head g, length g)) . group . sort $ map (!! 1) $ filter (\[a, b] -> a /= b) ps

    max' m (c1, c2)
      | c1 + c2 >= (n+1)`div`2 = min m $ max 0 $ (n+1)`div`2 - c1
      | otherwise = m

    merge [] [] m = m
    merge ((_, c1):as) [] m = merge as [] $ max' m (c1, 0)

    merge [] ((_, c2):bs) m = merge [] bs $ max' m (0, c2)

    merge as@((a, c1):as') bs@((b, c2):bs') m
      | a < b = merge as' bs $ max' m (c1, 0)
      | a > b = merge as bs' $ max' m (0, c2)
      | otherwise = merge as' bs' $ max' m (c1, c2)

    r :: Int = merge a b maxBound

  print $ if r == maxBound then -1 else r

import Data.List
import qualified Data.IntMap as IM
import qualified Data.ByteString.Char8 as B
import Control.Applicative

readInt s = let Just (n,_) = B.readInt s in n

toPairs [] = []
toPairs (x:y:xys) = (x,y):toPairs xys

ins imap (x,y)
  | x==y = IM.insertWith (\_ (f,b)->(f+1,b)) x (1,0) imap
  | otherwise = IM.insertWith (\_ (f,b)->(f+1,b)) x (1,0) $
                  IM.insertWith (\_ (f,b)->(f,b+1)) y (0,1) imap

main = do
  n <- readLn
  let m = (n+1)`div`2
  gr <- IM.elems.foldl' ins IM.empty.toPairs.map readInt.B.words<$> B.getContents
  case filter (\(f,b)->f+b>=m) gr of
    [] -> print $ -1
    xs -> print $ minimum $ map (\(f,b)-> max 0 $ m-f) xs

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

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

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

main = do
  n <- readLn
  ps <- replicateM n $ getInts

  let
    a = map (\g -> (head g, length g)) . group . sort $ map (!! 0) ps
    b = map (\g -> (head g, length g)) . group . sort $ map (!! 1) $ filter (\[a, b] -> a /= b) ps

    max' m (c1, c2)
      | c1 + c2 > n`div`2 = min m $ max 0 $ n`div`2 + 1 - c1
      | otherwise = maxBound

    merge [] [] m = m
    merge ((_, c1):as) [] m = merge as [] $ max' m (c1, 0)
    merge [] ((_, c2):bs) m = merge [] bs $ max' m (0, c2)
    merge as@((a, c1):as') bs@((b, c2):bs') m
      | a < b = merge as' bs $ max' m (c1, 0)
      | a > b = merge as bs' $ max' m (0, c2)
      | otherwise = merge as' bs' $ max' m (c1, c2)

    r :: Int = merge a b maxBound

  print $ if r == maxBound then -1 else r

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

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

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

main = do
  n <- readLn
  ps <- replicateM n $ getInts

  let
    a = map (\g -> (head g, length g)) . group . sort $ map (!! 0) ps
    b = map (\g -> (head g, length g)) . group . sort $ map (!! 1) $ filter (\[a, b] -> a /= b) ps

    merge [] _ m = m
    merge _ [] m = m
    merge as@((a, c1):as') bs@((b, c2):bs') m
      | a < b = merge as' bs m
      | a > b = merge as bs' m
      | c1 + c2 > n `div` 2 = merge as' bs' $ min m $ max 0 $ n`div`2 + 1 - c1
      | otherwise = merge as' bs' m

    r = merge a b maxBound

  print $ if r == maxBound then -1 else r

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

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

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

main = do
  n <- readLn
  ps <- replicateM n $ getInts

  let
    a = map (\g -> (head g, length g)) . group . sort $ map (!! 0) ps
    b = map (\g -> (head g, length g)) . group . sort $ map (!! 1) $ filter (\[a, b] -> a /= b) ps

    max' m (c1, c2)
      | c1 + c2 > n`div`2 = min m $ max 0 $ n`div`2 + 1 - c1
      | otherwise = m

    merge [] [] m = m
    merge ((_, c1):as) [] m = merge as [] $ max' m (c1, 0)

    merge [] ((_, c2):bs) m = merge [] bs $ max' m (0, c2)

    merge as@((a, c1):as') bs@((b, c2):bs') m
      | a < b = merge as' bs $ max' m (c1, 0)
      | a > b = merge as bs' $ max' m (0, c2)
      | otherwise = merge as' bs' $ max' m (c1, c2)

    r :: Int = merge a b maxBound

  print $ if r == maxBound then -1 else r


import System.IO
import Array

emptyStrings = "":emptyStrings

main :: IO()
main = do
  s <- readFile "input.txt"
  let list = lines s
  let [h, w, n] = map (\x -> read x :: Int) $ words $ head list
  let arr = array (0, w*h-1) $ zip [0..(w*h-1)] emptyStrings
  let commands = map words $ tail list
  let result = foldl (f w h) (arr, []) commands
--  mapM_ (\s -> putStrLn s) $ reverse $ snd result
  writeFile "output.txt" $ unlines $ foldr (:) [] $ reverse $ snd result

f w h (arr, actions) ["+1", i', j', name]
  | loc < 0 = (arr, actions)
  | otherwise = (arr // [(loc, name)], actions)
    where
      n = i*w + j
      loc = locate arr n n
      i = -1 + (read i' :: Int)
      j = -1 + (read j' :: Int)
f w h (arr, actions) ["-1", name]
  | loc < 0 = (arr, ("-1 -1":actions))
  | otherwise = (arr // [(loc, "")], ((parse w h loc):actions))
    where
      loc = find name arr 0

parse w h n = show i ++ " " ++ show j
  where
    i = 1 + n `div` w
    j = 1 + n `mod` w

find name arr n
  | n > r = -1
  | otherwise = if arr!n == name then n else find name arr (n+1)
    where (_, r) = bounds arr

locate arr n n0
--  | n == (n0-1) = -1
--  | n > r = locate arr 0 n0
  | n > r = -1
  | otherwise = if arr!n == "" then n else locate arr (n+1) n0
    where (_, r) = bounds arr

{-# LANGUAGE ForeignFunctionInterface #-}

import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.ByteString as SB
import Data.ByteString.Internal (inlinePerformIO)
import Foreign.C.String (CString)
import Foreign.C (CDouble)
import Data.Maybe
import Data.List (foldl')
import Data.Array
import qualified Data.Map as M
import qualified Data.IntMap as IM
import Debug.Trace

foreign import ccall unsafe "stdlib.h atof" c_atof :: CString -> IO Double
unsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof
{-# INLINE unsafeReadDouble #-}
readDouble = unsafeReadDouble . SB.concat . LB.toChunks
readInt = fst . fromJust . LB.readInt

debug :: Show a => a -> b -> b
--debug = trace . show
debug _ = id

main = readFile "input.txt" >>= (writeFile "output.txt" . output . solve . parse . lines)

output = unlines . map (\(x, y) -> show x ++ " " ++ show y)

parse :: [String] -> (Int, Int, [([Int], String)])
parse (nmk:rest) =
  let [n, m, k] = map read . words $ nmk
      lst = map (f . words) . take k $ rest
      f wds = (rfix (head wds) : map read (tail (init wds)), last wds)
      rfix ('+':s) = 1
      rfix ('-':s) = -1
  in (n, m, lst)

solve (n, m, lst) =
  let (_, _, responses) = foldl' process (startingState, M.empty, []) lst
      startingState = IM.fromDistinctAscList $ zip [1..n]
             (repeat (IM.fromDistinctAscList $ zip [1..m] (repeat "")))

      process (state, idx, responses) (nums, name) =
        case head nums of
            1 -> processAdd state idx responses (tail nums) name
            _ -> processRemove state idx responses name

      processRemove state idx responses name =
        case M.lookup name idx of
          Nothing -> (state, idx, (-1, -1) : responses)
          Just (x,y) -> (newState, newIdx, (x,y) : responses)
            where newIdx = M.delete name idx
                  newState = IM.insert x (IM.insert y "" oldArray) state
                  Just oldArray = IM.lookup x state

      processAdd state idx responses [x,y] name =
        case findFree state x y of
          Nothing -> debug "miss" (state, idx, responses)
          Just (i, j) -> debug (i,j) $ (newState, newIdx, responses)
            where newState = IM.insert i (IM.insert j name oldArray) state
                  Just oldArray = IM.lookup i state
                  newIdx = M.insert name (i,j) idx

      findFree state x y | y == m+1 = findFree state (x+1) 1
                         | x == n+1 = Nothing
      findFree state x y =
        case IM.lookup y arr of
          Just "" -> Just (x,y)
          Just s  -> debug s $ findFree state x (y+1)
        where Just arr = IM.lookup x state

  in reverse responses

import Prelude
import List
import Char

main = fileInteract q "input.txt" "output.txt"

q = func.map words.lines

func::[[String]]->String
func (a:xs) = solve'$solve m n xs (take (m*n)$repeat "")
              where
                b = map toInt a
                m = b!!0
                n = b!!1
func _      = ""

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve' a = case elem '#' a of
             True -> ""
             False->a

ins a b c = (take a c) ++ [b] ++ (drop (a+1) c)

solve m n (a:xs) b | a!!0 == "-1"  = case elemIndex (a!!1) b of
                                       Just c -> (toString (c`div`n+1))++" "++
                                                 (toString (c`mod`n+1))++"\n"++
                                                 solve m n xs (ins c "" b)
                                       Nothing ->"-1 -1\n"++
                                                 solve m n xs b
                   | a!!3 `elem` b = "#"
                   | b!!ind == ""  =  solve m n xs (ins ind (a!!3) b)
                   | otherwise     =  case elemIndex "" (drop (ind) b) of
                                        Just c -> solve m n xs (ins (c+ind) (a!!3) b)
                                        Nothing ->solve m n xs b
                                    where
                                      l = length b
                                      ind = (toInt (a!!1) -1)*n + (toInt (a!!2)-1)
solve _ _ [] _ = ""

import System.IO
import Array

emptyStrings = "":emptyStrings

main :: IO()
main = do
  s <- readFile "input.txt"
  let list = lines s
  let [w, h, n] = map (\x -> read x :: Int) $ words $ head list
  let arr = array (1, w*h) $ zip [1..(w*h)] emptyStrings
  let commands = map words $ tail list
  let result = foldl (f w h) (arr, []) commands
--  mapM_ (\s -> putStrLn s) $ reverse $ snd result
  writeFile "output.txt" $ unlines $ foldr (:) [] $ reverse $ snd result

f w h (arr, actions) ["+1", i', j', name]
  | loc < 0 = (arr, actions)
  | otherwise = (arr // [(loc, name)], actions)
    where
      n = (i-1)*(j-1)+1
      loc = locate arr n
      i = read i' :: Int
      j = read j' :: Int
f w h (arr, actions) ["-1", name]
  | loc < 0 = (arr, ("-1 -1":actions))
  | otherwise = (arr // [(loc, "")], ((parse w h loc):actions))
    where
      loc = find name arr 1

parse w h n = show i ++ " " ++ show j
  where
    i = 1 + ((n-1) `div` w)
    j = 1 + ((n-1) `mod` w)

find name arr n
  | n > r = -1
  | otherwise = if arr!n == name then n else find name arr (n+1)
    where (_, r) = bounds arr

locate arr n
  | n > r = -1
  | otherwise = if arr!n == "" then n else locate arr (n+1)
    where (_, r) = bounds arr

import System.IO
import Array

emptyStrings = "":emptyStrings

main :: IO()
main = do
  s <- readFile "input.txt"
  let list = lines s
  let [w, h, n] = map (\x -> read x :: Int) $ words $ head list
  let arr = array (0, w*h-1) $ zip [0..(w*h-1)] emptyStrings
  let commands = map words $ tail list
  let result = foldl (f w h) (arr, []) commands
--  mapM_ (\s -> putStrLn s) $ reverse $ snd result
  writeFile "output.txt" $ unlines $ foldr (:) [] $ reverse $ snd result

f w h (arr, actions) ["+1", i', j', name]
  | loc < 0 = (arr, actions)
  | otherwise = (arr // [(loc, name)], actions)
    where
      n = i*w + j
      loc = locate arr n n
      i = -1 + (read i' :: Int)
      j = -1 + (read j' :: Int)
f w h (arr, actions) ["-1", name]
  | loc < 0 = (arr, ("-1 -1":actions))
  | otherwise = (arr // [(loc, "")], ((parse w h loc):actions))
    where
      loc = find name arr 0

parse w h n = show i ++ " " ++ show j
  where
    i = 1 + n `div` w
    j = 1 + n `mod` w

find name arr n
  | n > r = -1
  | otherwise = if arr!n == name then n else find name arr (n+1)
    where (_, r) = bounds arr

locate arr n n0
--  | n == (n0-1) = -1
--  | n > r = locate arr 0 n0
  | n > r = -1
  | otherwise = if arr!n == "" then n else locate arr (n+1) n0
    where (_, r) = bounds arr

import System.IO
import Array

emptyStrings = "":emptyStrings

main :: IO()
main = do
  s <- readFile "input.txt"
  let list = lines s
  let [w, h, n] = map (\x -> read x :: Int) $ words $ head list
  let arr = array (1, w*h) $ zip [1..(w*h)] emptyStrings
  let commands = map words $ tail list
  let result = foldl (f w h) (arr, []) commands
--  mapM_ (\s -> putStrLn s) $ reverse $ snd result
  writeFile "output.txt" $ unlines $ foldr (:) [] $ reverse $ snd result

f w h (arr, actions) ["+1", i', j', name]
  | loc < 0 = (arr, actions)
  | otherwise = (arr // [(loc, name)], actions)
    where
      n = (i-1)*w + j
      loc = locate arr n
      i = read i' :: Int
      j = read j' :: Int
f w h (arr, actions) ["-1", name]
  | loc < 0 = (arr, ("-1 -1":actions))
  | otherwise = (arr // [(loc, "")], ((parse w h loc):actions))
    where
      loc = find name arr 1

parse w h n = show i ++ " " ++ show j
  where
    i = 1 + ((n-1) `div` w)
    j = 1 + ((n-1) `mod` w)

find name arr n
  | n > r = -1
  | otherwise = if arr!n == name then n else find name arr (n+1)
    where (_, r) = bounds arr

locate arr n
  | n > r = -1
  | otherwise = if arr!n == "" then n else locate arr (n+1)
    where (_, r) = bounds arr

import System.IO
import Array

emptyStrings = "":emptyStrings

main :: IO()
main = do
  s <- readFile "input.txt"
  let list = lines s
  let [w, h, n] = map (\x -> read x :: Int) $ words $ head list
  let arr = array (1, w*h) $ zip [1..(w*h)] emptyStrings
  let commands = map words $ tail list
  let result = foldl f (arr, []) commands
--  mapM_ (\s -> putStrLn s) $ reverse $ snd result
  writeFile "output.txt" $ unlines $ foldr (:) [] $ reverse $ snd result

f (arr, actions) ["+1", i', j', name]
  | loc < 0 = (arr, actions)
  | otherwise = (arr // [(loc, name)], actions)
    where
      n = (i-1)*(j-1)+1
      loc = locate arr n
      i = read i' :: Int
      j = read j' :: Int
f (arr, actions) ["-1", name]
  | loc < 0 = (arr, ("-1 -1":actions))
  | otherwise = (arr // [(loc, "")], (("-1 " ++ arr!loc):actions))
    where
      loc = find name arr 1

find name arr n
  | n > r = -1
  | otherwise = if arr!n == name then n else find name arr (n+1)
    where (_, r) = bounds arr

locate arr n
  | n > r = -1
  | otherwise = if arr!n == "" then n else locate arr (n+1)
    where (_, r) = bounds arr

import System.IO
import Array

emptyStrings = "":emptyStrings

main :: IO()
main = do
  s <- readFile "input.txt"
  let list = lines s
  let [w, h, n] = map (\x -> read x :: Int) $ words $ head list
  let arr = array (1, w*h) $ zip [1..(w*h)] emptyStrings
  let commands = map words $ tail list
  let result = foldl (f w h) (arr, []) commands
--  mapM_ (\s -> putStrLn s) $ reverse $ snd result
  writeFile "output.txt" $ unlines $ foldr (:) [] $ reverse $ snd result

f w h (arr, actions) ["+1", i', j', name]
  | loc < 0 = (arr, actions)
  | otherwise = (arr // [(loc, name)], actions)
    where
      n = (i-1)*(j-1)+1
      loc = locate arr n n
      i = read i' :: Int
      j = read j' :: Int
f w h (arr, actions) ["-1", name]
  | loc < 0 = (arr, ("-1 -1":actions))
  | otherwise = (arr // [(loc, "")], ((parse w h loc):actions))
    where
      loc = find name arr 1

parse w h n = show i ++ " " ++ show j
  where
    i = 1 + ((n-1) `div` w)
    j = 1 + ((n-1) `mod` w)

find name arr n
  | n > r = -1
  | otherwise = if arr!n == name then n else find name arr (n+1)
    where (_, r) = bounds arr

locate arr n0 n
  | n == n0-1 = -1
  | n > r = locate arr n0 1
  | otherwise = if arr!n == "" then n else locate arr n0 (n+1)
    where (_, r) = bounds arr

import System.IO
import Array

emptyStrings = "":emptyStrings

main :: IO()
main = do
  s <- readFile "input.txt"
  let list = lines s
  let [w, h, n] = map (\x -> read x :: Int) $ words $ head list
  let arr = array (1, w*h) $ zip [1..(w*h)] emptyStrings
  let commands = map words $ tail list
  let result = foldl (f w h) (arr, []) commands
--  mapM_ (\s -> putStrLn s) $ reverse $ snd result
  writeFile "output.txt" $ unlines $ foldr (:) [] $ reverse $ snd result

f w h (arr, actions) ["+1", i', j', name]
  | loc < 0 = (arr, actions)
  | otherwise = (arr // [(loc, name)], actions)
    where
      n = (i-1)*w + j
      loc = locate arr n n
      i = read i' :: Int
      j = read j' :: Int
f w h (arr, actions) ["-1", name]
  | loc < 0 = (arr, ("-1 -1":actions))
  | otherwise = (arr // [(loc, "")], ((parse w h loc):actions))
    where
      loc = find name arr 1

parse w h n = show i ++ " " ++ show j
  where
    i = 1 + ((n-1) `div` w)
    j = 1 + ((n-1) `mod` w)

find name arr n
  | n > r = -1
  | otherwise = if arr!n == name then n else find name arr (n+1)
    where (_, r) = bounds arr

locate arr n n0
  | n == (n0-1) = -1
  | n > r = locate arr 1 n0
  | otherwise = if arr!n == "" then n else locate arr (n+1) n0
    where (_, r) = bounds arr

import Prelude
import List
import Char

main = fileInteract q "input.txt" "output.txt"

q = func.map words.lines

func::[[String]]->String
func (a:xs) = solve'$solve m n xs (take (m*n)$repeat "")
              where
                b = map toInt a
                m = b!!0
                n = b!!1
func _      = ""

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve' a = case elem '#' a of
             True -> ""
             False->a

ins a b c = (take a c) ++ [b] ++ (drop (a+1) c)

solve m n (a:xs) b | a!!0 == "-1" = case elemIndex (a!!1) (reverse b) of
                                      Just c -> (toString ((l-c-1)`div`n+1) )++" "++
                                                (toString ((l-c-1)`mod`n+1))++"\n"++
                                                solve m n xs (ins (l-c-1) "" b)
                                      Nothing ->"-1 -1\n"++
                                                solve m n xs b
                   | b!!(ind (a!!1) (a!!2)) == ""
                                  = solve m n xs (ins (ind (a!!1) (a!!2)) (a!!3) b)
                   | otherwise    = case elemIndex "" b of
                                      Just c -> solve m n xs (ins c (a!!3) b)
                                      Nothing ->"#"
                                    where
                                      l = length b
                                      ind a b = (toInt a -1)*n + (toInt b-1)
solve _ _ [] _ = ""

import Prelude
import List
import Char

main = fileInteract q "input.txt" "output.txt"

q = func.map words.lines

func::[[String]]->String
func (a:xs) = solve m n xs (take (m*n)$repeat "")
              where
                b = map toInt a
                m = b!!0
                n = b!!1
func _      = ""

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

ins a b c = (take a c) ++ [b] ++ (drop (a+1) c)

solve m n (a:xs) b | a!!0 == "-1" = case elemIndex (a!!1) (reverse b) of
                                      Just c -> (toString ((l-c-1)`div`n+1) )++" "++
                                                (toString ((l-c-1)`mod`n+1))++"\n"++
                                                solve m n xs (ins (l-c-1) "" b)
                                      Nothing ->"-1 -1\n"++
                                                solve m n xs b
                   | b!!(ind (a!!1) (a!!2)) == ""
                                  = solve m n xs (ins (ind (a!!1) (a!!2)) (a!!3) b)
                   | otherwise    = case elemIndex "" b of
                                      Just c -> solve m n xs (ins c (a!!3) b)
                                      Nothing ->undefined
                                    where
                                      l = length b
                                      ind a b = (toInt a -1)*n + (toInt b-1)
solve _ _ [] _ = ""

import Prelude
import List
import Char

main = fileInteract q "input.txt" "output.txt"

q = func.map words.lines

func::[[String]]->String
func (a:xs) = solve'$solve m n xs (take (m*n)$repeat "")
              where
                b = map toInt a
                m = b!!0
                n = b!!1
func _      = ""

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve' a = case elem '#' a of
             True -> ""
             False->a

ins a b c = (take a c) ++ [b] ++ (drop (a+1) c)

solve m n (a:xs) b | a!!0 == "-1"  = case elemIndex (a!!1) b of
                                       Just c -> (toString (c`div`n+1))++" "++
                                                 (toString (c`mod`n+1))++"\n"++
                                                 solve m n xs (ins c "" b)
                                       Nothing ->"-1 -1\n"++
                                                 solve m n xs b
                   | a!!3 `elem` b = "#"
                   | b!!ind == ""  =  solve m n xs (ins ind (a!!3) b)
                   | otherwise     =  case elemIndex "" (drop ind b) of
                                        Just c -> solve m n xs (ins c (a!!3) b)
                                        Nothing ->solve m n xs b
                                    where
                                      l = length b
                                      ind = (toInt (a!!1) -1)*n + (toInt (a!!2)-1)
solve _ _ [] _ = ""

import Prelude
import List
import Char

main = fileInteract q "input.txt" "output.txt"

q = func.map words.lines

func::[[String]]->String
func (a:xs) = solve'$solve m n xs (take (m*n)$repeat "")
              where
                b = map toInt a
                m = b!!0
                n = b!!1
func _      = ""

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve' a = case elem '#' a of
             True -> ""
             False->a

ins a b c = (take a c) ++ [b] ++ (drop (a+1) c)

solve m n (a:xs) b | a!!0 == "-1"  = case elemIndex (a!!1) (reverse b) of
                                       Just c -> (toString ((l-c-1)`div`n+1) )++" "++
                                                 (toString ((l-c-1)`mod`n+1))++"\n"++
                                                 solve m n xs (ins (l-c-1) "" b)
                                       Nothing ->"-1 -1\n"++
                                                 solve m n xs b
                   | a!!3 `elem` b = "#"
                   | b!!ind == ""  =  solve m n xs (ins ind (a!!3) b)
                   | otherwise     =  case elemIndex "" (drop ind b) of
                                      Just c -> solve m n xs (ins c (a!!3) b)
                                      Nothing ->"#"
                                    where
                                      l = length b
                                      ind = (toInt (a!!1) -1)*n + (toInt (a!!2)-1)
solve _ _ [] _ = ""

import Prelude
import List
import Char

main = fileInteract q "input.txt" "output.txt"

q = func.map words.lines

func::[[String]]->String
func (a:xs) = solve'$solve m n xs (take (m*n)$repeat "")
              where
                b = map toInt a
                m = b!!0
                n = b!!1
func _      = ""

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve' a = case elem '#' a of
             True -> ""
             False->a

ins a b c = (take a c) ++ [b] ++ (drop (a+1) c)

solve m n (a:xs) b | a!!0 == "-1"  = case elemIndex (a!!1) (reverse b) of
                                       Just c -> (toString ((l-c-1)`div`n+1) )++" "++
                                                 (toString ((l-c-1)`mod`n+1))++"\n"++
                                                 solve m n xs (ins (l-c-1) "" b)
                                       Nothing ->"-1 -1\n"++
                                                 solve m n xs b
                   | a!!3 `elem` b = "#"
                   | b!!(ind (a!!1) (a!!2)) == ""
                                   =  solve m n xs (ins (ind (a!!1) (a!!2)) (a!!3) b)
                   | otherwise     =  case elemIndex "" b of
                                      Just c -> solve m n xs (ins c (a!!3) b)
                                      Nothing ->"#"
                                    where
                                      l = length b
                                      ind a b = (toInt a -1)*n + (toInt b-1)
solve _ _ [] _ = ""

import Prelude
import List
import Char

main = fileInteract q "input.txt" "output.txt"

q = func.map words.lines

func::[[String]]->String
func (a:xs) = solve'$solve m n xs (take (m*n)$repeat "")
              where
                b = map toInt a
                m = b!!0
                n = b!!1
func _      = ""

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve' a = case elem '#' a of
             True -> ""
             False->a

ins a b c = (take a c) ++ [b] ++ (drop (a+1) c)

solve m n (a:xs) b | a!!0 == "-1"  = case elemIndex (a!!1) (reverse b) of
                                       Just c -> (toString ((l-c-1)`div`n+1))++" "++
                                                 (toString ((l-c-1)`mod`n+1))++"\n"++
                                                 solve m n xs (ins (l-c-1) "" b)
                                       Nothing ->"-1 -1\n"++
                                                 solve m n xs b
                   | a!!3 `elem` b = "#"
                   | b!!ind == ""  =  solve m n xs (ins ind (a!!3) b)
                   | otherwise     =  case elemIndex "" (drop ind b) of
                                        Just c -> solve m n xs (ins c (a!!3) b)
                                        Nothing ->solve m n xs b
                                    where
                                      l = length b
                                      ind = (toInt (a!!1) -1)*n + (toInt (a!!2)-1)
solve _ _ [] _ = ""


import Control.Monad
import Data.List

solve :: Int -> [Int] -> Int
solve k li = let
  tar = length . map head . group $ li
  in  if  tar == 1
  then  1
  else  if  k == 1
  then  -1
  else  div (tar - 1 + k - 2) (k - 1)

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [_n, k] <- map read . words <$> getLine
    a <- map read . words <$> getLine
    print $ solve k a

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

main :: IO ()
main = getLine >>= flip replicateM_ test . read

test :: IO ()
test = do
  [_, k] <- map read . words <$> getLine
  as <- map read . words <$> getLine
  print $ solve k as

solve :: Integer -> [Integer] -> Integer
solve 1 as
  | all (== head as) as = 1
  | otherwise = -1
solve k as = max 1 $ (fromIntegral (length $ filter (/= 0) $ zipWith (-) (tail as) as) - 1) `div` (k - 1) + 1

import Control.Monad (forM_)
import Data.Set (fromList, size)

solve :: Int -> [Int] -> Int
solve k as = if s < 1 then 1 else rez
  where s = fromIntegral . subtract k . size $ fromList as
        k' = fromIntegral $ k - 1
        rez = if k' < 1 then -1 else 1 + (ceiling $ s / k')

main :: IO ()
main = do
  t <- pure . read =<< getLine
  forM_ [1..t] $ \_ -> do
    [n, k] <- pure . map read . words =<< getLine
    getLine >>= pure . map read . words >>= putStrLn . show . solve k

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

main :: IO ()
main = getLine >>= flip replicateM_ test . read

test :: IO ()
test = do
  [_, k] <- map read . words <$> getLine
  as <- map read . words <$> getLine
  print $ solve k as

solve :: Integer -> [Integer] -> Integer
solve 1 as
  | all (== head as) as = 1
  | otherwise = -1
solve k as = max 1 $ (fromIntegral (length $ filter (/= 0) $ zipWith (-) (tail as) as) - 1) `div` k + 1

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

main :: IO ()
main = getLine >>= flip replicateM_ test . read

test :: IO ()
test = do
  [_, k] <- map read . words <$> getLine
  as <- map read . words <$> getLine
  print $ solve k as

solve :: Integer -> [Integer] -> Integer
solve 1 as
  | all (== head as) as = 1
  | otherwise = -1
solve k as = (fromIntegral (length $ filter (/= 0) $ zipWith (-) (tail as) as) - 1) `div` k + 1

import Control.Monad (forM_)
import Data.Set (fromList, size)

solve :: Int -> [Int] -> Int
solve k as = if k == 1 && s > 1 then -1 else ceiling $ s / (fromIntegral k)
  where s = fromIntegral . size $ fromList as

main :: IO ()
main = getLine >>= pure . read >>= \t -> forM_ [1..t] $ \_ -> do
         [n, k] <- pure . map read . words =<< getLine
         getLine >>= pure . map read . words >>= putStrLn . show . solve k

import Control.Monad (forM_)
import Data.Set (fromList, size)

solve :: Int -> [Int] -> Int
solve k as = if s > 0 && k == 1 then -1 else 1 + (ceiling $ s / k')
  where s = fromIntegral . subtract k . size $ fromList as
        k' = fromIntegral $ k - 1

main :: IO ()
main = do
  t <- pure . read =<< getLine
  forM_ [1..t] $ \_ -> do
    [n, k] <- pure . map read . words =<< getLine
    getLine >>= pure . map read . words >>= putStrLn . show . solve k

import Control.Monad (forM_)
import Data.Set (fromList, size)

solve :: Int -> [Int] -> Int
solve k as = if s > 0 && k == 1 then -1 else 1 + (ceiling (s / k'))
  where s = fromIntegral . subtract k . size $ fromList as
        k' = fromIntegral $ k - 1

main :: IO ()
main = do
  t <- pure . read =<< getLine
  forM_ [1..t] $ \_ -> do
    [n, k] <- pure . map read . words =<< getLine
    getLine >>= pure . map read . words >>= putStrLn . show . solve k


import Data.List
solve a n = case findIndex (==n) a of
  Just i -> i:(map (+(i+1)) $ solve (drop (i+1) a) (n+1))
  Nothing -> []

main = do
  n <- fmap read getLine
  a <- fmap (map read . take n . words) getLine
  let res = solve a 1
  print (length res)
  putStrLn . unwords . map (show . (+2001)) $ res

main = interact solve

solve s = unlines [show $ length g, unwords g]
  where
    g = map show $ map snd $ reverse $ init r
    r = foldl (\xs (k,y)->if k==1+(fst $ head xs) then (k,y):xs else xs) [(0,0)] $ zip (map (\s -> read s :: Int) $ words $ last $ lines s) [2001..]

solve :: [Int] -> [Int]
solve as  =  solve' 1 (zip as [2001..])
  where
    solve' _ []  =  []
    solve' k ((x,y):xs)
      | k == x  =  y : solve' (k+1) xs
      | otherwise  =  solve' k xs

prints :: Show a => [a] -> IO ()
prints xs  =  print (length xs) >> prints' xs
  where
    prints' []  =  return ()
    prints' [x]  =  print x
    prints' (x:xs)  =  putStr (show x ++ " ") >> prints' xs

main :: IO ()
main  =  do
    getLine
    as  <-  fmap (map read . words) getLine
    prints $ solve as


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

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

main :: IO ()
main =
  do letters <- read <$> getLine :: IO Word64
     print $ query letters

query :: Word64 -> Word64
query letters = go 1 0 1
  where
    go :: Word64 -> Word64 -> Word64 -> Word64
    go !k !acc !fact
      | k > letters = if acc + fact >= n then acc + fact - n else acc + fact
      | otherwise = go (k+1)
                       (mod ((acc+fact-1) * k) n)
                       (mod (fact * k) n)

{-# INLINE n #-}
n :: (Integral i) => i
n = 998244353

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

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

main :: IO ()
main =
  do letters <- read <$> getLine :: IO Word32
     print $ query letters

query :: Word32 -> Word32
query letters = fromMon $ go 1 rep1 0 1
  where
    rep1 = monRep 1
    go :: Word32 -> Montgomery -> Montgomery -> Montgomery -> Montgomery
    go !k !kRep !acc !fact
      | k > letters = acc + fact
      | otherwise = go (k+1) (kRep + rep1)
                       ((acc+fact-rep1) * kRep) (fact * kRep)

{-# INLINE n #-}
n :: (Integral i) => i
n = 998244353

{-# INLINE nprime #-}
nprime :: Word64
nprime = 998244351

{-# INLINE rsq #-}
rsq :: Word64
rsq = 932051910

newtype Montgomery = Mon {unMon :: Word32}
  deriving (Eq, Show)

instance Num Montgomery where
  {-# INLINE (+) #-}
  (+) = monAdd
  {-# INLINE (*) #-}
  (*) = monMult
  {-# INLINE negate #-}
  negate (Mon x) = Mon (n - x)
  {-# INLINE fromInteger #-}
  fromInteger = monRep . fromInteger
  {-# INLINE signum #-}
  signum x | x == Mon 0 = Mon 0
           | otherwise  = monRep 1
  {-# INLINE abs #-}
  abs = id

{-# INLINE monMult #-}
monMult :: Montgomery -> Montgomery -> Montgomery
monMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y

{-# INLINE monAdd #-}
monAdd :: Montgomery -> Montgomery -> Montgomery
monAdd (Mon x) (Mon y)
  | xpy >= n  = Mon $ xpy - n
  | otherwise = Mon $ xpy
  where
    xpy = x+y

{-# INLINE monRep #-}
monRep :: Word32 -> Montgomery
monRep x = Mon $ monRed $ rsq * fromIntegral x

{-# INLINE fromMon #-}
fromMon :: Montgomery -> Word32
fromMon (Mon x) = monRed $ fromIntegral x

{-# INLINE monRed #-}
monRed :: Word64 -> Word32
monRed x = fromIntegral $ if t >= n then t - n else t
  where t = (x + ((x*nprime) .&. mask32) * n) `shiftR` 32

{-# INLINE mask32 #-}
mask32 :: Word64
mask32 = bit 32 - 1

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

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

main :: IO ()
main =
  do letters <- read <$> getLine :: IO Word32
     print $ query letters

query :: Word32 -> Word32
query letters = fromMon $ go 1 0 1
  where
    go :: Word32 -> Montgomery -> Montgomery -> Montgomery
    go !k !acc !fact
      | k > letters = acc + fact
      | otherwise = go (k+1) ((acc+fact-1) * kRep) newFact
      where
        kRep = monRep k
        newFact = kRep * fact

n :: (Integral i) => i
n = 998244353

nprime :: Word64
nprime = 998244351

rsq :: Word64
rsq = 932051910

newtype Montgomery = Mon {unMon :: Word32}
  deriving (Eq, Show)

instance Num Montgomery where
  (+) = monAdd
  (*) = monMult
  negate (Mon x) = Mon (n - x)
  fromInteger = monRep . fromInteger
  signum x | x == Mon 0 = Mon 0
           | otherwise  = 1
  abs = id

monMult :: Montgomery -> Montgomery -> Montgomery
monMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y

monAdd :: Montgomery -> Montgomery -> Montgomery
monAdd (Mon x) (Mon y)
  | xpy >= n  = Mon $ xpy - n
  | otherwise = Mon $ xpy
  where
    xpy = x+y

monRep :: Word32 -> Montgomery
monRep = Mon . monRed . (rsq*) . fromIntegral

fromMon :: Montgomery -> Word32
fromMon = monRed . fromIntegral . unMon

monRed :: Word64 -> Word32
monRed x = fromIntegral $ if t >= n then t - n else t
  where t = (x + ((x*nprime) .&. mask32) * n) `shiftR` 32

mask32 :: Word64
mask32 = bit 32 - 1

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

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

main :: IO ()
main =
  do letters <- read <$> getLine :: IO Word32
     print $ query letters

query :: Word32 -> Word32
query letters = fromMon $ go 1 rep1 0 1
  where
    rep1 = monRep 1
    go :: Word32 -> Montgomery -> Montgomery -> Montgomery -> Montgomery
    go !k !kRep !acc !fact
      | k > letters = acc + fact
      | otherwise = go (k+1) (kRep + rep1)
                       ((acc+fact-rep1) * kRep) (fact * kRep)

{-# INLINE n #-}
n :: (Integral i) => i
n = 998244353

{-# INLINE nprime #-}
nprime :: Word64
nprime = 998244351

{-# INLINE rsq #-}
rsq :: Word64
rsq = 932051910

newtype Montgomery = Mon {unMon :: Word32}
  deriving (Eq, Show)

instance Num Montgomery where
  {-# INLINE (+) #-}
  (+) = monAdd
  {-# INLINE (*) #-}
  (*) = monMult
  {-# INLINE (-) #-}
  (-) = monSub
  {-# INLINE negate #-}
  negate (Mon x) = Mon (n - x)
  {-# INLINE fromInteger #-}
  fromInteger = monRep . fromInteger
  {-# INLINE signum #-}
  signum x | x == Mon 0 = Mon 0
           | otherwise  = monRep 1
  {-# INLINE abs #-}
  abs = id

{-# INLINE monMult #-}
monMult :: Montgomery -> Montgomery -> Montgomery
monMult (Mon x) (Mon y) = Mon $ monRed $ fromIntegral x * fromIntegral y

{-# INLINE monAdd #-}
monAdd :: Montgomery -> Montgomery -> Montgomery
monAdd (Mon x) (Mon y) = Mon $ x+y - if x >= n-y then n else 0

{-# INLINE monSub #-}
monSub :: Montgomery -> Montgomery -> Montgomery
monSub (Mon x) (Mon y) = Mon $ x-y + if x < y then n else 0

{-# INLINE monRep #-}
monRep :: Word32 -> Montgomery
monRep x = Mon $ monRed $ rsq * fromIntegral x

{-# INLINE fromMon #-}
fromMon :: Montgomery -> Word32
fromMon (Mon x) = monRed $ fromIntegral x

{-# INLINE monRed #-}
monRed :: Word64 -> Word32
monRed x = t - if t >= n then n else 0
  where t = fromIntegral $ (x + ((x*nprime) .&. mask32) * n) `shiftR` 32

{-# INLINE mask32 #-}
mask32 :: Word64
mask32 = bit 32 - 1

{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import Data.Ord
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray hiding ((!))
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet

import Data.Int
import Data.Ratio
import Data.Ix

getWords  = words <$> getLine :: IO [String]
getInts   = map read <$> getWords :: IO [Int]
getDoubles = map read <$> getWords :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()

data ModInt = ModInt Int64 deriving (Eq, Ord, Read)

modulo = 998244353 :: Int64
toModInt n = ModInt (n `mod` modulo)
emi = error "ModInt"
unaryOp f (ModInt x) = ModInt (f x)
binaryOp f (ModInt x) (ModInt y) = ModInt (f x y)
binaryOp' f (ModInt x) (ModInt y) = toModInt (f x y)

instance Bounded ModInt where
    maxBound = ModInt modulo
    minBound = ModInt (-modulo)
instance Enum ModInt where
    succ x
        | x /= maxBound = x + 1
        | otherwise = emi
    pred x
        | x /= minBound = x - 1
        | otherwise = emi
    toEnum i = toModInt (fromIntegral i)
    fromEnum (ModInt x) = (fromIntegral x)
instance Integral ModInt where
    quot = binaryOp quot
    rem = binaryOp rem
    div = binaryOp div
    mod = binaryOp mod
    quotRem (ModInt x) (ModInt y) = let  (q, r) = x `quotRem` y in (ModInt q, ModInt r)
    divMod (ModInt x) (ModInt y) = let  (d, m) = x `divMod` y in (ModInt d, ModInt m)
    toInteger (ModInt x) = toInteger x
instance Num ModInt where
    (+) = binaryOp' (+)
    (-) = binaryOp' (-)
    (*) = binaryOp' (*)
    negate = unaryOp negate
    abs = unaryOp abs
    signum = unaryOp signum
    fromInteger i = toModInt (fromInteger i)
instance Real ModInt where
    toRational (ModInt x) = toInteger x % 1
instance Show ModInt where
    show (ModInt x) = show x
instance Ix ModInt where
    range (ModInt m, ModInt n) = map ModInt [m..n]
    index (ModInt m, _) (ModInt i) = fromIntegral i - fromIntegral m
    inRange (ModInt m, ModInt n) (ModInt i) = m <= i && i <= n

---- Answer Code Section ----

process :: Int -> Int
process (fromIntegral -> n :: ModInt) = if n == 1 then 1 else fromIntegral answer where
    facScans = scanl (*) n [ n-1, n-2 .. ]     -- f(n) = [n, n(n-1), n(n-1)(n-2)..]
    foldFn s (k, fn, fn1) = s + k * (fn - fn1) -- S(n+1) = S(n) + k(f(n) - f(n-1))
    answer = foldl' foldFn 0 $ zip3 [1..n-1] facScans (0 : facScans)

main = do
    n <- getInt
    print $ process n

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

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

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

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

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

m :: Integer
m = 998244353

facto :: Integer -> Integer
facto n = foldl (\acc x -> (acc * x) `mod` m) 1 [1..n]

rfacto :: Integer -> [Integer]
rfacto n = scanl (\acc x -> (acc * x) `mod` m) n [n-1,n-2..1]

solve n = (f * (n-1) `mod` m + m - msum) `mod` m
    where f = facto n
          r = rfacto n
          msum = foldl (\acc x -> (acc + x) `mod` m) 0 $ take (fromIntegral $ n-2) r

main = do
    [n] <- getIntegers
    if n == 1
    then print 1
    else print $ solve n

solve n = m $ (n+1) * last p - sum p
  where m = (`mod` 998244353)
        p = scanl1 ((.) m . (*)) [n, n-1..1]
main = interact $ show . solve . read

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

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

main :: IO ()
main =
  do letters <- read <$> getLine :: IO Word64
     print $ query letters

query :: Word64 -> Word64
query letters = go 1 0 1
  where
    go :: Word64 -> Word64 -> Word64 -> Word64
    go !k !acc !fact
      | k > letters = acc + fact
      | otherwise = go (k+1)
                       (mod ((acc+fact-1) * k) n)
                       (mod (fact * k) n)

{-# INLINE n #-}
n :: (Integral i) => i
n = 998244353

{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import Data.Ord
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray hiding ((!))
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet

import Data.Int
import Data.Ratio
import Data.Ix

getWords  = words <$> getLine :: IO [String]
getInts   = map read <$> getWords :: IO [Int]
getDoubles = map read <$> getWords :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()

data ModInt = ModInt Int64 deriving (Eq, Ord, Read)

modulo = 998244353 :: Int64
toModInt n = ModInt (n `rem` modulo)
emi = error "ModInt"
unaryOp f (ModInt x) = ModInt (f x)
binaryOp f (ModInt x) (ModInt y) = ModInt (f x y)
binaryOp' f (ModInt x) (ModInt y) = toModInt (f x y)

instance Bounded ModInt where
    maxBound = ModInt modulo
    minBound = ModInt (-modulo)
instance Enum ModInt where
    succ x
        | x /= maxBound = x + 1
        | otherwise = emi
    pred x
        | x /= minBound = x - 1
        | otherwise = emi
    toEnum i = toModInt (fromIntegral i)
    fromEnum (ModInt x) = (fromIntegral x)
instance Integral ModInt where
    quot = binaryOp quot
    rem = binaryOp rem
    div = binaryOp div
    mod = binaryOp mod
    quotRem (ModInt x) (ModInt y) = let  (q, r) = x `quotRem` y in (ModInt q, ModInt r)
    divMod (ModInt x) (ModInt y) = let  (d, m) = x `divMod` y in (ModInt d, ModInt m)
    toInteger (ModInt x) = toInteger x
instance Num ModInt where
    (+) = binaryOp' (+)
    (-) = binaryOp' (-)
    (*) = binaryOp' (*)
    negate = unaryOp negate
    abs = unaryOp abs
    signum = unaryOp signum
    fromInteger i = toModInt (fromInteger i)
instance Real ModInt where
    toRational (ModInt x) = toInteger x % 1
instance Show ModInt where
    show (ModInt x) = show x
instance Ix ModInt where
    range (ModInt m, ModInt n) = map ModInt [m..n]
    index (ModInt m, _) (ModInt i) = fromIntegral i - fromIntegral m
    inRange (ModInt m, ModInt n) (ModInt i) = m <= i && i <= n

---- Answer Code Section ----

process :: Int -> Int
process (fromIntegral -> n :: ModInt) = if n == 1 then 1 else fromIntegral answer where
    facScans = scanl (*) n [ n-1, n-2 .. ]     -- f(n) = [n, n(n-1), n(n-1)(n-2)..]
    foldFn s (k, fn, fn1) = s + k * (fn - fn1) -- S(n+1) = S(n) + k(f(n) - f(n-1))
    answer = foldl foldFn 0 $ zip3 [1..n-1] facScans (0 : facScans)

main = do
    n <- getInt
    print $ process n


{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array.ST
import Data.Bits
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Control.Applicative
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Function as F
import Debug.Trace

import qualified Numeric as N

readInt :: String -> Int
readInt ('-':s) = case N.readDec s of [(n, "")] -> -n
readInt s = case N.readDec s of [(n, "")] -> n

readFloat :: String -> Double
readFloat ('-':s) = case N.readFloat s of [(x, "")] -> -x
readFloat s = case N.readFloat s of [(x, "")] -> x

getInts :: IO [Int]
getInts = map readInt . words <$> getLine

solve :: [(Integer, Integer)] -> Integer -> Maybe Integer
solve xs@((t, h):_) m = loop ((max `F.on` snd) first end) ([first] ++ xs ++ [end])
  where
    first = (1, t + h - 1)
    end = (m, m - t' + h')
    (t', h') = last xs

-- loop acc xs
--   | trace (show acc ++ " " ++ show (xs)) False = undefined
loop acc [(t1, h1), (t2, h2)] =
  if abs (h2 - h1) <= t2 - t1 then Just acc else Nothing
loop acc ((t1, h1):(xs@((t2, h2):_))) =
  if abs (h2 - h1) <= t2 - t1
  then loop (maximum [h1, h2, acc, fff t1 t2 h1 h2]) xs
  else Nothing

fff t1 t2 h1 h2 = (max h1 h2) + ((t2 - t1) - abs (h2 - h1)) `div` 2

main :: IO ()
main = do
  [n, m] <- map toInteger <$> getInts
  diary <- forM [1..m] $ \_ -> do
    [a, b] <- getInts
    return (toInteger a, toInteger b)
  putStrLn $ case solve (L.sort diary) n of
    Nothing -> "IMPOSSIBLE"
    Just x -> show x

import Control.Monad
import Data.List
isOk (i0,h0) (i1,h1) | h1 < h0 = isOk (i0,h1) (i1,h0)
                     | otherwise = (i1-i0) >= (h1-h0)
getMaxHeight (i0,h0) (i1,h1) | h1 < h0 = getMaxHeight (i0,h1) (i1,h0)
                             | h0 < h1 = getMaxHeight (i0+d,h0+d) (i1,h1)
                             | otherwise = h0 + (s `div` 2)
                             where d = h1-h0
                                   s = i1-i0

mapPair::(a -> a-> b)->[a] -> [b]
mapPair f (a0:ts) | null ts = []
                 | otherwise = ((f a0 a1):(mapPair f ts))
                          where a1 = head ts
getMax1Height (i0,h0) = h0+i0-1
getMaxNHeight n (i0,h0) = h0+(n-i0)
readInput 0 = return []
readInput m = do
  w0 <- getLine
  let w = words w0
  next <- readInput (m-1)
  let h = (read (w !! 0)::Int,read (w !! 1)::Int)
  return (h:next)
toTup a = ((w !! 0),(w !! 1))
  where w = [read n::Int| n <-(words a)]
main = do
  w <- getLine
  let w0 = words w
  let n = read (w0 !! 0)::Int
  let m = read (w0 !! 1)::Int
  contents <- getContents
  let s = lines contents
  let route = map toTup s
  if not $ all id $ mapPair isOk route
  then putStrLn "IMPOSSIBLE"
  else do
  print $ maximum $ (getMax1Height (head route)):(getMaxNHeight n (last route)):(mapPair getMaxHeight route)

isOk (i0,h0) (i1,h1) | h1 < h0 = isOk (i0,h1) (i1,h0)
                     | otherwise = (i1-i0) >= (h1-h0)
getMaxHeight (i0,h0) (i1,h1) | h1 < h0 = getMaxHeight (i0,h1) (i1,h0)
                             | h0 > h1 = getMaxHeight (i0+d,h0+d) (i1,h1)
                             | otherwise = h0 + (s `div` 2)
                             where d = h1-h0
                                   s = i1-i0
mapPair::(a -> a-> b)->[a] -> [b]
mapPair f a | (length a) == 1 = []
            | otherwise = ((f a0 a1):(mapPair f ta))
                          where a0 = head a
                                ta = tail a
                                a1 = head ta
getMax1Height (i0,h0) = h0+i0-1
getMaxNHeight n (i0,h0) = h0+(n-i0)
readInput 0 = return []
readInput m = do
  w0 <- getLine
  let w = words w0
  next <- readInput (m-1)
  let h = (read (w !! 0)::Int,read (w !! 1)::Int)
  return (h:next)
main = do
  w <- getLine
  let w0 = words w
  let n = read (w0 !! 0)::Int
  let m = read (w0 !! 1)::Int
  route <- readInput m
  if not $ all id $ mapPair isOk route
  then putStrLn "IMPOSSIBLE"
  else do
  print $ maximum $ (getMax1Height (head route)):(getMaxNHeight n (last route)):(mapPair getMaxHeight route)

isOk (i0,h0) (i1,h1) | h1 < h0 = isOk (i0,h1) (i1,h0)
                     | otherwise = (i1-i0) >= (h1-h0)
getMaxHeight (i0,h0) (i1,h1) | h1 < h0 = getMaxHeight (i0,h1) (i1,h0)
                             | h0 > h1 = getMaxHeight (i0+d,h0+d) (i1,h1)
                             | otherwise = h0 + (s `div` 2)
                             where d = h1-h0
                                   s = i1-i0
mapPair::(a -> a-> b)->[a] -> [b]
mapPair f a | (length a) == 1 = []
            | otherwise = ((f a0 a1):(mapPair f ta))
                          where a0 = head a
                                ta = tail a
                                a1 = head ta
getMax0Height (i0,h0) = h0+i0
getMaxNHeight n (i0,h0) = h0+(n-i0)
readInput 0 = return []
readInput m = do
  w0 <- getLine
  let w = words w0
  next <- readInput (m-1)
  let h = (read (w !! 0)::Int,read (w !! 1)::Int)
  return (h:next)
main = do
  w <- getLine
  let w0 = words w
  let n = read (w0 !! 0)::Int
  let m = read (w0 !! 1)::Int
  route <- readInput m
  if not $ all id $ mapPair isOk route
  then putStrLn "IMPOSSIBLE"
  else do
    print $ maximum $ (getMax0Height (head route)):(getMaxNHeight n (last route)):(mapPair getMaxHeight route)

{-# OPTIONS_GHC -rtsopts -O2 #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array.ST
import Data.Bits
import Data.STRef
import Control.Monad.ST
import Control.Monad
import Control.Applicative
import qualified Data.List as L
import qualified Data.Set as S
import qualified Data.Map as M
import qualified Data.Function as F
import Debug.Trace

import qualified Numeric as N

readInt :: String -> Int
readInt ('-':s) = case N.readDec s of [(n, "")] -> -n
readInt s = case N.readDec s of [(n, "")] -> n

readFloat :: String -> Double
readFloat ('-':s) = case N.readFloat s of [(x, "")] -> -x
readFloat s = case N.readFloat s of [(x, "")] -> x

getInts :: IO [Int]
getInts = map readInt . words <$> getLine

solve :: [(Integer, Integer)] -> Integer -> Maybe Integer
solve xs@((t, h):_) m = loop ((max `F.on` snd) first end) ([first] ++ xs ++ [end])
  where
    first = (0, t + h)
    end = (m - 1, m - 1 - t' + h')
    (t', h') = last xs

-- loop acc xs
--  | trace (show acc ++ " " ++ show (xs)) False = undefined
loop acc [(t1, h1), (t2, h2)] =
  if abs (h2 - h1) <= t2 - t1 then Just acc else Nothing
loop acc ((t1, h1):(xs@((t2, h2):_))) =
  if abs (h2 - h1) <= t2 - t1
  then loop (maximum [h1, h2, acc, fff t1 t2 h1 h2]) xs
  else Nothing

fff t1 t2 h1 h2 = (max h1 h2) + ((t2 - t1) - abs (h2 - h1)) `div` 2

main :: IO ()
main = do
  [n, m] <- map toInteger <$> getInts
  diary <- forM [1..m] $ \_ -> do
    [a, b] <- getInts
    return (toInteger a, toInteger b)
  putStrLn $ case solve (L.sort diary) n of
    Nothing -> "IMPOSSIBLE"
    Just x -> show x