import System.IO (getChar)
import Control.Monad (liftM)
import Data.IntMap
import Data.Maybe (fromMaybe)
import Prelude hiding(lookup,null)
--import Control.Monad.Trans(lift)
--import Control.Monad.Trans.State
import Data.Array.IO

newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }

instance (Monad m) => Functor (StateT s m) where
	fmap f m = StateT $ \s -> do
		(x, s') <- runStateT m s
		return (f x, s')

instance (Monad m) => Monad (StateT s m) where
	return a = StateT $ \s -> return (a, s)
	m >>= k  = StateT $ \s -> do
		(a, s') <- runStateT m s
		runStateT (k a) s'
	fail str = StateT $ \_ -> fail str

evalStateT :: (Monad m) => StateT s m a -> s -> m a
evalStateT m s = do
	(a, _) <- runStateT m s
	return a

execStateT :: (Monad m) => StateT s m a -> s -> m s
execStateT m s = do
	(_, s') <- runStateT m s
	return s'

lift m = StateT $ \s -> do
		a <- m
		return (a, s)

get   = StateT $ \s -> return (s, s)
put s = StateT $ \_ -> return ((), s)

data Intv = Intv {getInf::Int,
                  getSup::Int
                 } deriving Show

data  Env = Env {
                 sizeLot::Int,
                 values:: IOArray Int Int,
                 eIntvs::IntMap (IntMap Intv),
                 bIntvs::IOArray Int (Maybe (Int,Intv))
                }

type LotState a = StateT Env IO a

data BIntv = BIntv (Int,Intv) | BNotFound

main :: IO ()
main = do
         nbS <- getNumbers 2
         let size = nbS !! 0
         let nbActs = nbS !! 1
         runManage size nbActs

printRes (x:xs) = print x >> printRes xs
printRes [] = return ()

getNumber =  do
              s <- getNumber'
              case s of
               [] -> return Nothing
               otherwise -> return $ Just (read $ s :: Int)

getNumber'  = do
                c <- catch getChar  (\err-> return ' ')
                case c of
                  ' ' ->  return ""
                  '\n' ->  return ""
                  otherwise -> do l <- getNumber'
                                  return (c:l)

getNumbers n | (n<=0) = return []
getNumbers n = do
                mbNum <- getNumber
                case mbNum of
                 Nothing -> return []
                 Just num -> (liftM (num:) (getNumbers(n-1)))

ins:: Int -> LotState Int
ins v = do
          pos <- takePos
          insertValue pos v >> return pos

insertValue pos v = do
                      s <- get
                      lift $ writeArray (values s) v pos

takeValue v = do
                   s <- get
                   let curValues = values s
                   pos <- lift $ readArray curValues v
                   return pos

deleteInEIntvs b e = do
                      env <- get
                      let curEIntvs = eIntvs env
                      let bInf = getInf b
                      let bSup = getSup b

                      lift $ writeArray (bIntvs env) bInf Nothing
                      lift $ writeArray (bIntvs env) bSup Nothing

                      let intvs = curEIntvs ! e
                      let newIntvs = delete bInf intvs
                      if (null newIntvs)
                        then put $ env {eIntvs = delete e curEIntvs}
                        else put $ env {eIntvs = insert e newIntvs curEIntvs}

insertEIntvs e v = do
                    s <- get
                    let curEIntvs = eIntvs s
                    put $ s {eIntvs = insert e v curEIntvs}

updateEIntvs m = do
                   s <- get
                   put $ s {eIntvs = m}

deleteBIntvs b = do
                   s <- get
                   lift $ writeArray (bIntvs s) b Nothing

insertBIntvs b v = do
                    s <- get
                    lift $ writeArray (bIntvs s) b (Just v)

takePos:: LotState Int
takePos = do
            s <- get
            let curEIntvs = eIntvs s
            let curBIntvs = bIntvs s

            let (e,maxIntvs) = findMax curEIntvs
            let (intv,newIntvs) = deleteFindMin maxIntvs
            let minBInf = getInf intv
            let minBSup = getSup intv

            deleteBIntvs minBInf
            deleteBIntvs minBSup

            let sz = sizeLot s
            let newEIntvs = if (null newIntvs)
                               then delete e curEIntvs
                               else insert e newIntvs curEIntvs

            updateEIntvs newEIntvs

            case intv of
             (Intv bInf bSup) | (bInf==bSup) ->  return bInf
             (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1  --ok
             (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1   --ok
             (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok
             (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok
             (Intv bInf bSup) -> do
                                   let pos = bInf+e
                                   let eFirst = calcEcart bInf (pos-1)
                                   let eSecond = calcEcart (pos+1) bSup
                                   insertIntv eFirst $ Intv bInf (pos-1)
                                   insertIntv eSecond $ Intv (pos+1) bSup
                                   return pos

            where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2
                  diff bInf bSup = fromIntegral $ bSup-bInf

insertIntv e v = do
                   s <- get
                   let bInf = getInf v
                   let bSup = getSup v
                   let curEIntvs = eIntvs s
                   insertBIntvs bInf (e,v)
                   insertBIntvs bSup (e,v)
                   case (lookup e curEIntvs) of
                     Just intvs -> insertEIntvs e (insert bInf v intvs)
                     Nothing -> insertEIntvs e (singleton bInf v)

insFusion bInf bSup = do
                        env <- get
                        let sz = sizeLot env
                        let  e = case (bInf,bSup) of
                                 (1,b) -> b-1
                                 (a,b) | (b==sz) -> sz-a
                                 (a,b) -> let diff = fromIntegral (b-a)
                                          in truncate $ diff / 2
                        insertIntv e (Intv bInf bSup)

remV v = do
          pos <- takeValue v
          remPos pos

remPos p = do
             env <- get
             let sz = sizeLot env
             let curBIntvs = bIntvs env

             mBinf <- if (p==1)
                        then return Nothing
                        else lift $ readArray curBIntvs (p-1)

             let bInf = fromMaybe BNotFound (mBinf >>= return.BIntv)

             mBintvSup <- if(p==sz)
                           then return Nothing
                           else lift $ readArray curBIntvs (p+1)

             let bSup = fromMaybe BNotFound (mBintvSup >>= return.BIntv)

             case (bInf,bSup) of
                (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do
                                                           deleteInEIntvs iInf eInf
                                                           deleteInEIntvs iSup eSup
                                                           insFusion (getInf iInf) (getSup iSup)

                (BIntv (eInf,iInf),_) -> do
                                           deleteInEIntvs iInf eInf
                                           insFusion (getInf iInf) p

                (_,BIntv (eSup,iSup)) -> do
                                           deleteInEIntvs iSup eSup
                                           insFusion p (getSup iSup)
                otherwise ->  insFusion p p

initEnv n = do
              values <- newArray (1,1000000) 0
              bIntvs <- newArray (1,n) Nothing
              writeArray bIntvs 1 $ Just ((n-1),(Intv 1 n))
              return $ Env {sizeLot=n,
                 values = values,
                 bIntvs = bIntvs,
                 eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))
                }

test [] = return []
test (action:xs) = do
                     let value = snd action
                     case (fst action ) of
                          1 -> do
                                pos <- ins value
                                liftM (pos:) $  test xs
                          2 -> remV value >> test xs

runManage n nbActs = do
                       env <- initEnv n
                       evalStateT (manage nbActs) env

manage 0 = return ()
manage nbActs= do
                  action <- lift $ getNumbers 2
                  let value = action !! 1
                  case (action !! 0) of

                          1 -> do
                                pos <- ins value
                                (lift $ print pos) >> manage (nbActs-1)
                          2 -> remV value >> manage (nbActs-1)

import System.IO (getChar)
import Control.Monad (liftM)
import Data.IntMap
import Data.Maybe (fromMaybe)
import Prelude hiding(lookup,null)
--import Control.Monad.Trans(lift)
--import Control.Monad.Trans.State
import Data.Array.IO
import Data.Array.Unboxed hiding ((!))

newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }

instance (Monad m) => Functor (StateT s m) where
	fmap f m = StateT $ \s -> do
		(x, s') <- runStateT m s
		return (f x, s')

instance (Monad m) => Monad (StateT s m) where
	return a = StateT $ \s -> return (a, s)
	m >>= k  = StateT $ \s -> do
		(a, s') <- runStateT m s
		runStateT (k a) s'
	fail str = StateT $ \_ -> fail str

evalStateT :: (Monad m) => StateT s m a -> s -> m a
evalStateT m s = do
	(a, _) <- runStateT m s
	return a

execStateT :: (Monad m) => StateT s m a -> s -> m s
execStateT m s = do
	(_, s') <- runStateT m s
	return s'

lift m = StateT $ \s -> do
		a <- m
		return (a, s)

get   = StateT $ \s -> return (s, s)
put s = StateT $ \_ -> return ((), s)

data Intv = Intv {getInf::Int,
                  getSup::Int
                 } deriving Show

data  Env = Env {
                 sizeLot:: Int,
                 values:: IOUArray Int Int,
                 eIntvs:: IntMap (IntMap Intv),
                 bInfs:: IOUArray Int Int,
                 bSups:: IOUArray Int Int
                }

type LotState a = StateT Env IO a

data BIntv = BIntv (Int,Intv) | BNotFound

main :: IO ()
main = do
         nbS <- getNumbers 2
         let size = nbS !! 0
         let nbActs = nbS !! 1
         runManage size nbActs

printRes (x:xs) = print x >> printRes xs
printRes [] = return ()

getNumber =  do
              s <- getNumber'
              case s of
               [] -> return Nothing
               otherwise -> return $ Just (read $ s :: Int)

getNumber'  = do
                c <- catch getChar  (\err-> return ' ')
                case c of
                  ' ' ->  return ""
                  '\n' ->  return ""
                  otherwise -> do l <- getNumber'
                                  return (c:l)

getNumbers n | (n<=0) = return []
getNumbers n = do
                mbNum <- getNumber
                case mbNum of
                 Nothing -> return []
                 Just num -> (liftM (num:) (getNumbers(n-1)))

ins:: Int -> LotState Int
ins v = do
          pos <- takePos
          insertValue pos v >> return pos

insertValue pos v = do
                      s <- get
                      lift $ writeArray (values s) v pos

takeValue v = do
                   s <- get
                   let curValues = values s
                   pos <- lift $ readArray curValues v
                   return pos

deleteInEIntvs b e = do
                      env <- get
                      let curEIntvs = eIntvs env
                      let bInf = getInf b
                      let bSup = getSup b

                      --lift $ writeArray (bIntvs env) bInf Nothing
                      --lift $ writeArray (bIntvs env) bSup Nothing

                      lift $ writeArray (bInfs env) bInf (-1)
                      lift $ writeArray (bSups env) bSup (-1)

                      let intvs = curEIntvs ! e
                      let newIntvs = delete bInf intvs
                      if (null newIntvs)
                        then put $ env {eIntvs = delete e curEIntvs}
                        else put $ env {eIntvs = insert e newIntvs curEIntvs}

insertEIntvs e v = do
                    s <- get
                    let curEIntvs = eIntvs s
                    put $ s {eIntvs = insert e v curEIntvs}

updateEIntvs m = do
                   s <- get
                   put $ s {eIntvs = m}

deleteBIntvs (Intv bInf bSup)= do
                   s <- get
                   lift $ writeArray (bInfs s) bInf (-1)
                   lift $ writeArray (bSups s) bSup (-1)

insertBIntvs (Intv bInf bSup) = do
                                s <- get
                                --lift $ writeArray (bIntvs s) b (Just v)
                                lift $ writeArray (bInfs s) bInf bSup
                                lift $ writeArray (bSups s) bSup bInf

takePos:: LotState Int
takePos = do
            s <- get
            let curEIntvs = eIntvs s
            --let curBIntvs = bIntvs s

            let (e,maxIntvs) = findMax curEIntvs
            let (intv,newIntvs) = deleteFindMin maxIntvs
            --let minBInf = getInf intv
            --let minBSup = getSup intv

            deleteBIntvs intv

            let sz = sizeLot s
            let newEIntvs = if (null newIntvs)
                               then delete e curEIntvs
                               else insert e newIntvs curEIntvs

            updateEIntvs newEIntvs

            case intv of
             (Intv bInf bSup) | (bInf==bSup) ->  return bInf
             (Intv 1 bSup) | (bSup==sz) -> insertIntv (sz-2) (Intv 2 sz) >> return 1  --ok
             (Intv 1 bSup) -> insertIntv (calcE 2 bSup) (Intv 2 bSup) >> return 1   --ok
             (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcE bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok
             (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok
             (Intv bInf bSup) -> do
                                   let pos = bInf+e
                                   let eFirst = calcE bInf (pos-1)
                                   let eSecond = calcE (pos+1) bSup
                                   insertIntv eFirst $ Intv bInf (pos-1)
                                   insertIntv eSecond $ Intv (pos+1) bSup
                                   return pos
            where calcE bInf bSup = truncate $ (diff bInf bSup) / 2
                  diff bInf bSup = fromIntegral $ bSup-bInf

calcEcart bInf bSup = do
                       s <- get
                       let sz = sizeLot s
                       case (bInf,bSup) of
                        (1,bS) | (bS==sz) -> return (sz)
                        (1,bS) -> return (bS-1)
                        (bI,bS) | (bS==sz) -> return (sz-bI)
                        (bI,bS) | (bI==bS) -> return 0
                        otherwise -> return $ truncate $ (diff bInf bSup) / 2
                       where diff bInf bSup = fromIntegral $ bSup-bInf

insertIntv e v = do
                   s <- get
                   let bInf = getInf v
                   let bSup = getSup v
                   let curEIntvs = eIntvs s
                   insertBIntvs v
                   insertBIntvs v
                   case (lookup e curEIntvs) of
                     Just intvs -> insertEIntvs e (insert bInf v intvs)
                     Nothing -> insertEIntvs e (singleton bInf v)

insFusion bInf bSup = do
                        env <- get
                        let sz = sizeLot env
                        let  e = case (bInf,bSup) of
                                 (1,b) | ( b==sz) -> b
                                 (1,b) -> b-1
                                 (a,b) | (b==sz) -> sz-a
                                 (a,b) -> let diff = fromIntegral (b-a)
                                          in truncate $ diff / 2
                        insertIntv e (Intv bInf bSup)

remV v = do
          pos <- takeValue v
          remPos pos

remPos p = do
             env <- get
             let sz = sizeLot env
             --let curBIntvs = bIntvs env
             let curBInfs = bInfs env
             let curBSups = bSups env

             mBinf <- if (p==1)
                        then return Nothing
                        else do
                               bInfinf <- lift $ readArray curBSups (p-1)
                               if (bInfinf<0)
                                then return Nothing
                                else do
                                      e <- calcEcart bInfinf (p-1)
                                      return $ Just $ BIntv (e,(Intv bInfinf (p-1)))

             let bInf = fromMaybe BNotFound mBinf -- >>= return.BIntv)

             mBintvSup <- if(p==sz)
                           then return Nothing
                           else do
                                 bSupsup <- lift $ readArray curBInfs (p+1)
                                 if (bSupsup<0)
                                  then return Nothing
                                  else do
                                        e <- calcEcart (p+1) bSupsup
                                        return $ Just $ BIntv (e, (Intv (p+1) bSupsup))

             let bSup = fromMaybe BNotFound mBintvSup -- >>= return.BIntv)

             case (bInf,bSup) of
                (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do
                                                           deleteInEIntvs iInf eInf
                                                           deleteInEIntvs iSup eSup
                                                           insFusion (getInf iInf) (getSup iSup)

                (BIntv (eInf,iInf),_) -> do
                                           deleteInEIntvs iInf eInf
                                           insFusion (getInf iInf) p

                (_,BIntv (eSup,iSup)) -> do
                                           deleteInEIntvs iSup eSup
                                           insFusion p (getSup iSup)
                otherwise ->  insFusion p p

initEnv n = do
              values <- newArray (1,1000000) 0
              --bIntvs <- newArray (1,n) Nothing
              bInfs <- newArray (1,n) (-1)
              bSups <- newArray (1,n) (-1)
              writeArray bInfs 1 n
              writeArray bSups n 1
              return $ Env {sizeLot=n,
                 values = values,
                 bInfs = bInfs,
                 bSups = bSups,
                 eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))
                }

test [] = return []
test (action:xs) = do
                     let value = snd action
                     case (fst action ) of
                          1 -> do
                                pos <- ins value
                                liftM (pos:) $  test xs
                          2 -> remV value >> test xs

runManage n nbActs = do
                       env <- initEnv n
                       evalStateT (manage nbActs) env

manage 0 = return ()
manage nbActs= do
                  action <- lift $ getNumbers 2
                  let value = action !! 1
                  case (action !! 0) of

                          1 -> do
                                pos <- ins value
                                (lift $ print pos) >> manage (nbActs-1)
                          2 -> remV value >> manage (nbActs-1)

import System.IO (getChar)
import Control.Monad (liftM)
import Data.IntMap
import Data.Maybe (fromMaybe)
import Prelude hiding(lookup,null)
--import Control.Monad.Trans(lift)
--import Control.Monad.Trans.State
import Data.Array.IO
import Data.Array.Unboxed hiding ((!))

newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }

instance (Monad m) => Functor (StateT s m) where
	fmap f m = StateT $ \s -> do
		(x, s') <- runStateT m s
		return (f x, s')

instance (Monad m) => Monad (StateT s m) where
	return a = StateT $ \s -> return (a, s)
	m >>= k  = StateT $ \s -> do
		(a, s') <- runStateT m s
		runStateT (k a) s'
	fail str = StateT $ \_ -> fail str

evalStateT :: (Monad m) => StateT s m a -> s -> m a
evalStateT m s = do
	(a, _) <- runStateT m s
	return a

execStateT :: (Monad m) => StateT s m a -> s -> m s
execStateT m s = do
	(_, s') <- runStateT m s
	return s'

lift m = StateT $ \s -> do
		a <- m
		return (a, s)

get   = StateT $ \s -> return (s, s)
put s = StateT $ \_ -> return ((), s)

data Intv = Intv {getInf::Int,
                  getSup::Int
                 } deriving Show

data  Env = Env {
                 sizeLot::Int,
                 values:: IOUArray Int Int,
                 eIntvs::IntMap (IntMap Intv),
                 bIntvs::IOArray Int (Maybe (Int,Intv))
                }

type LotState a = StateT Env IO a

data BIntv = BIntv (Int,Intv) | BNotFound

main :: IO ()
main = do
         nbS <- getNumbers 2
         let size = nbS !! 0
         let nbActs = nbS !! 1
         runManage size nbActs

printRes (x:xs) = print x >> printRes xs
printRes [] = return ()

getNumber =  do
              s <- getNumber'
              case s of
               [] -> return Nothing
               otherwise -> return $ Just (read $ s :: Int)

getNumber'  = do
                c <- catch getChar  (\err-> return ' ')
                case c of
                  ' ' ->  return ""
                  '\n' ->  return ""
                  otherwise -> do l <- getNumber'
                                  return (c:l)

getNumbers n | (n<=0) = return []
getNumbers n = do
                mbNum <- getNumber
                case mbNum of
                 Nothing -> return []
                 Just num -> (liftM (num:) (getNumbers(n-1)))

ins:: Int -> LotState Int
ins v = do
          pos <- takePos
          insertValue pos v >> return pos

insertValue pos v = do
                      s <- get
                      lift $ writeArray (values s) v pos

takeValue v = do
                   s <- get
                   let curValues = values s
                   pos <- lift $ readArray curValues v
                   return pos

deleteInEIntvs b e = do
                      env <- get
                      let curEIntvs = eIntvs env
                      let bInf = getInf b
                      let bSup = getSup b

                      lift $ writeArray (bIntvs env) bInf Nothing
                      lift $ writeArray (bIntvs env) bSup Nothing

                      let intvs = curEIntvs ! e
                      let newIntvs = delete bInf intvs
                      if (null newIntvs)
                        then put $ env {eIntvs = delete e curEIntvs}
                        else put $ env {eIntvs = insert e newIntvs curEIntvs}

insertEIntvs e v = do
                    s <- get
                    let curEIntvs = eIntvs s
                    put $ s {eIntvs = insert e v curEIntvs}

updateEIntvs m = do
                   s <- get
                   put $ s {eIntvs = m}

deleteBIntvs b = do
                   s <- get
                   lift $ writeArray (bIntvs s) b Nothing

insertBIntvs b v = do
                    s <- get
                    lift $ writeArray (bIntvs s) b (Just v)

takePos:: LotState Int
takePos = do
            s <- get
            let curEIntvs = eIntvs s
            let curBIntvs = bIntvs s

            let (e,maxIntvs) = findMax curEIntvs
            let (intv,newIntvs) = deleteFindMin maxIntvs
            let minBInf = getInf intv
            let minBSup = getSup intv

            deleteBIntvs minBInf
            deleteBIntvs minBSup

            let sz = sizeLot s
            let newEIntvs = if (null newIntvs)
                               then delete e curEIntvs
                               else insert e newIntvs curEIntvs

            updateEIntvs newEIntvs

            case intv of
             (Intv bInf bSup) | (bInf==bSup) ->  return bInf
             (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1  --ok
             (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1   --ok
             (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok
             (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok
             (Intv bInf bSup) -> do
                                   let pos = bInf+e
                                   let eFirst = calcEcart bInf (pos-1)
                                   let eSecond = calcEcart (pos+1) bSup
                                   insertIntv eFirst $ Intv bInf (pos-1)
                                   insertIntv eSecond $ Intv (pos+1) bSup
                                   return pos

            where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2
                  diff bInf bSup = fromIntegral $ bSup-bInf

insertIntv e v = do
                   s <- get
                   let bInf = getInf v
                   let bSup = getSup v
                   let curEIntvs = eIntvs s
                   insertBIntvs bInf (e,v)
                   insertBIntvs bSup (e,v)
                   case (lookup e curEIntvs) of
                     Just intvs -> insertEIntvs e (insert bInf v intvs)
                     Nothing -> insertEIntvs e (singleton bInf v)

insFusion bInf bSup = do
                        env <- get
                        let sz = sizeLot env
                        let  e = case (bInf,bSup) of
                                 (1,b) -> b-1
                                 (a,b) | (b==sz) -> sz-a
                                 (a,b) -> let diff = fromIntegral (b-a)
                                          in truncate $ diff / 2
                        insertIntv e (Intv bInf bSup)

remV v = do
          pos <- takeValue v
          remPos pos

remPos p = do
             env <- get
             let sz = sizeLot env
             let curBIntvs = bIntvs env

             mBinf <- if (p==1)
                        then return Nothing
                        else lift $ readArray curBIntvs (p-1)

             let bInf = fromMaybe BNotFound (mBinf >>= return.BIntv)

             mBintvSup <- if(p==sz)
                           then return Nothing
                           else lift $ readArray curBIntvs (p+1)

             let bSup = fromMaybe BNotFound (mBintvSup >>= return.BIntv)

             case (bInf,bSup) of
                (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do
                                                           deleteInEIntvs iInf eInf
                                                           deleteInEIntvs iSup eSup
                                                           insFusion (getInf iInf) (getSup iSup)

                (BIntv (eInf,iInf),_) -> do
                                           deleteInEIntvs iInf eInf
                                           insFusion (getInf iInf) p

                (_,BIntv (eSup,iSup)) -> do
                                           deleteInEIntvs iSup eSup
                                           insFusion p (getSup iSup)
                otherwise ->  insFusion p p

initEnv n = do
              values <- newArray (1,1000000) 0
              bIntvs <- newArray (1,n) Nothing
              writeArray bIntvs 1 $ Just ((n-1),(Intv 1 n))
              return $ Env {sizeLot=n,
                 values = values,
                 bIntvs = bIntvs,
                 eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))
                }

test [] = return []
test (action:xs) = do
                     let value = snd action
                     case (fst action ) of
                          1 -> do
                                pos <- ins value
                                liftM (pos:) $  test xs
                          2 -> remV value >> test xs

runManage n nbActs = do
                       env <- initEnv n
                       evalStateT (manage nbActs) env

manage 0 = return ()
manage nbActs= do
                  action <- lift $ getNumbers 2
                  let value = action !! 1
                  case (action !! 0) of

                          1 -> do
                                pos <- ins value
                                (lift $ print pos) >> manage (nbActs-1)
                          2 -> remV value >> manage (nbActs-1)

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
import Control.Monad
-- import Control.Monad.ST
-- import Data.Array.ST
import Data.Array.IO
import Data.Array.Unboxed
import Data.Maybe
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as C

data Interval = Interval {
    begin   :: !Int,
    end     :: !Int,
    spacing :: !Int
  }
  deriving (Show, Eq)

interval n (l, r) = Interval l r m
  where
    m = if l == 0 || r == n then r - l else (r - l + 1) `div` 2

instance Ord Interval where
  compare a b =
    case compare (spacing a) (spacing b) of
      LT  -> GT
      EQ  -> compare (begin a) (begin b)
      GT  -> LT

{-
data State s = State {
    size :: Int,
    free :: S.Set Interval,
    l2r  :: STUArray s Int Int,
    r2l  :: STUArray s Int Int,
    pos  :: STUArray s Int Int
  }
-}
data State = State {
    size :: Int,
    free :: S.Set Interval,
    l2r  :: IOUArray Int Int,
    r2l  :: IOUArray Int Int,
    pos  :: IOUArray Int Int
  }

top s = return (l, r, center)
  where
    (Interval l r m) = S.findMin $ free s
    center
      | l == 0      = l
      | r == size s = r - 1
      | otherwise   = (l + r - 1) `div` 2

empty n = do
  l2r <- newArray (0, n) $ -1 -- :: ST s (STUArray s Int Int)
  r2l <- newArray (0, n) $ -1
  pos <- newArray (0, 10^6) $ -1
  return $ State n S.empty l2r r2l pos

insert (l, r) s = do
  if l >= r
    then return s
    else do
      writeArray (l2r s) l r
      writeArray (r2l s) r l
      return s{free = S.insert (interval (size s) (l, r)) $ free s}

delete (l, r) s = do
  writeArray (l2r s) l $ -1
  writeArray (r2l s) r $ -1
  return s{free = S.delete (interval (size s) (l, r)) $ free s}

gao s [] =
  return []

gao s (1:k:q) = do
  (l, r, p) <- top s
  s <- delete (l, r) s
  s <- insert (l, p) s
  s <- insert (p + 1, r) s
  writeArray (pos s) k p
  ps <- gao s q
  return $ p: ps

gao s (2:k:q) = do
  p <- readArray (pos s) k
  l' <- readArray (r2l s) p
  (l, s) <-
    if l' == -1
      then return (p, s)
      else do
        s <- delete (l', p) s
        return (l', s)
  r' <- readArray (l2r s) (p + 1)
  (r, s) <-
    if r' == -1
      then return (p + 1, s)
      else do
        s <- delete (p + 1, r') s
        return (r', s)
  s <- insert (l, r) s
  writeArray (pos s) k $ -1
  gao s q

solve n q = do
  s <- empty n
  s <- insert (0, n) s
  gao s q

main = do
  (n:m:q) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents
  ans <- solve n q
  putStr $ unlines $ map (show . succ) $ ans {- runST $ solve n q -}

{-
IOUArray:
  watashi-laptop:
    ./E3 < E.in > E.out  1.09s user 0.04s system 92% cpu 1.226 total
  acm90:
    real	0m6.047s
    user	0m5.976s
    sys	0m0.072s
STUArray:
  watashi-laptop:
    ./E3 < E.in > E.out  1.79s user 0.08s system 90% cpu 2.057 total
  acm90:
    real	0m7.916s
    user	0m7.868s
    sys	0m0.040s
-}

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
import Control.Monad (replicateM)
import Data.Maybe (fromJust)
import qualified Data.Set as S
import qualified Data.IntMap as M
import qualified Data.ByteString.Char8 as C

data Interval = Interval {
    begin   :: !Int,
    end     :: !Int,
    spacing :: !Int
  }
  deriving (Show, Eq)

interval n (l, r) = Interval l r m
  where
    m = if l == 0 || r == n then r - l else (r - l + 1) `div` 2

instance Ord Interval where
  compare a b =
    case compare (spacing a) (spacing b) of
      LT  -> GT
      EQ  -> compare (begin a) (begin b)
      GT  -> LT

data State = State {
    size :: Int,
    free :: S.Set Interval,
    l2r  :: M.IntMap Int,
    r2l  :: M.IntMap Int,
    pos  :: M.IntMap Int
  }
  deriving (Show)

top s = (l, r, center)
  where
    (Interval l r m) = S.findMin $ free s
    center
      | l == 0      = l
      | r == size s = r - 1
      | otherwise   = (l + r - 1) `div` 2

findByL l s = M.findWithDefault (-1) l $ l2r s

findByR r s = M.findWithDefault (-1) r $ r2l s

findById k = fromJust . M.lookup k . pos

delete (l, r) s@(State n sf ml mr _) = s {
    free = S.delete (interval n (l, r)) sf,
    l2r  = M.delete l ml,
    r2l  = M.delete r mr
  }

insert (l, r) s@(State n sf ml mr _)
  | l >= r    = s
  | otherwise = s {
      free = S.insert (interval n (l, r)) sf,
      l2r  = M.insert l r ml,
      r2l  = M.insert r l mr
    }

gao s [] = []

gao s (1:k:q) = p: gao s'{ pos = M.insert k p $ pos s' } q
  where
    (l, r, p) = top s
    s' = insert (l, p) $ insert (p + 1, r) $ delete (l, r) $ s

gao s (2:k:q) = gao s'{ pos = M.delete k $ pos s' } q
  where
    p = findById k s
    (l, sl) =
      case findByR p s of
        -1  -> (p, s)
        l   -> (l, delete (l, p) s)
    (r, sr) =
      case findByL (p + 1) sl of
        -1  -> (p + 1, sl)
        r   -> (r, delete (p + 1, r) sl)
    s' = insert (l, r) sr

main = do
  (n:m:q) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents
  putStr $ unlines $ map (show . succ) $ gao (empty n) q
  where
    empty n = State {
        size = n,
        free = S.singleton $ interval n (0, n),
        l2r  = M.singleton 0 n,
        r2l  = M.singleton n 0,
        pos  = M.empty
      }

{-
watashi-laptop:
  ./E1 < E.in > E.out  2.60s user 0.08s system 87% cpu 3.053 total
acm90:
  real	0m5.263s
  user	0m5.200s
  sys	0m0.064s
-}

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
import Control.Monad (replicateM)
import Data.Maybe (fromJust)
import qualified Data.Set as S
import qualified Data.IntMap as M
import qualified Data.ByteString.Char8 as C

data Interval = Interval {
    begin   :: !Int,
    end     :: !Int,
    spacing :: !Int
  }
  deriving (Show, Eq)

interval n (l, r) = Interval l r m
  where
    m = if l == 0 || r == n then r - l else (r - l + 1) `div` 2

instance Ord Interval where
  compare a b =
    case compare (spacing a) (spacing b) of
      LT  -> GT
      EQ  -> compare (begin a) (begin b)
      GT  -> LT

data State = State {
    size :: Int,
    free :: S.Set Interval,
    l2r  :: M.IntMap Int,
    r2l  :: M.IntMap Int,
    pos  :: M.IntMap Int
  }
  deriving (Show)

top s = (l, r, center)
  where
    (Interval l r m) = S.findMin $ free s
    center
      | l == 0      = l
      | r == size s = r - 1
      | otherwise   = (l + r - 1) `div` 2

findByL l s = M.findWithDefault (-1) l $ l2r s

findByR r s = M.findWithDefault (-1) r $ r2l s

findById k = fromJust . M.lookup k . pos

delete (l, r) s@(State n sf ml mr _) = s {
    free = S.delete (interval n (l, r)) sf,
    l2r  = M.delete l ml,
    r2l  = M.delete r mr
  }

insert (l, r) s@(State n sf ml mr _)
  | l >= r    = s
  | otherwise = s {
      free = S.insert (interval n (l, r)) sf,
      l2r  = M.insert l r ml,
      r2l  = M.insert r l mr
    }

gao s [] = []

gao s ([1,k]:q) = p: gao s'{ pos = M.insert k p $ pos s' } q
  where
    (l, r, p) = top s
    s' = insert (l, p) $ insert (p + 1, r) $ delete (l, r) $ s

gao s ([2,k]:q) = gao s'{ pos = M.delete k $ pos s' } q
  where
    p = findById k s
    (l, sl) =
      case findByR p s of
        -1  -> (p, s)
        l   -> (l, delete (l, r) s)
    (r, sr) =
      case findByL (p + 1) sl of
        -1  -> (p + 1, sl)
        r   -> (r, delete (l, r) sl)
    s' = insert (l, r) sr

main = do
  [n, m] <- getArray
  q <- replicateM m getArray
  putStr $ unlines $ map (show . succ) $ gao (empty n) q
  where
    getArray = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine
    empty n = State {
        size = n,
        free = S.singleton $ interval n (0, n),
        l2r  = M.singleton 0 n,
        r2l  = M.singleton n 0,
        pos  = M.empty
      }

import Control.Monad (replicateM)
import Data.Maybe (fromJust)
import Data.Ord (comparing)
import qualified Data.Set as S
import qualified Data.IntMap as M
import qualified Data.ByteString.Char8 as C

data Interval = Interval {
    range   :: (Int, Int),
    spacing :: Int
  }
  deriving (Show, Eq)

interval n (l, r) = Interval (l, r) m
  where
    m = if l == 0 || r == n then r - l else (r - l + 1) `div` 2

center n (Interval (l, r) _)
  | l == 0    = l
  | r == n    = r - 1
  | otherwise = (l + r - 1) `div` 2

instance Ord Interval where
  compare = comparing (\i -> (negate $ spacing i, range i))

data State = State {
    size :: Int,
    free :: S.Set Interval,
    l2r  :: M.IntMap Int,
    r2l  :: M.IntMap Int,
    pos  :: M.IntMap Int
  }

top s = (range interval, center (size s) interval)
  where
    interval = S.findMin $ free s

findByL l s = do
  r <- M.lookup l $ l2r s
  return (l, r)

findByR r s = do
  l <- M.lookup r $ r2l s
  return (l, r)

findById k = fromJust . M.lookup k . pos

delete (l, r) s@(State n sf ml mr _) = s {
    free = S.delete (interval n (l, r)) sf,
    l2r  = M.delete l ml,
    r2l  = M.delete r mr
  }

insert (l, r) s@(State n sf ml mr _)
  | l >= r    = s
  | otherwise = s {
      free = S.insert (interval n (l, r)) sf,
      l2r  = M.insert l r ml,
      r2l  = M.insert r l mr
    }

gao s [] = []

gao s ([1,k]:q) = p: gao s'{ pos = M.insert k p $ pos s' } q
  where
    ((l, r), p) = top s
    s' = insert (l, p) $ insert (p + 1, r) $ delete (l, r) $ s

gao s ([2,k]:q) = gao s'{ pos = M.delete k $ pos s' } q
  where
    p = findById k s
    (l, sl) =
      case findByR p s of
        Just (l, r) -> (l, delete (l, r) s)
        Nothing     -> (p, s)
    (r, sr) =
      case findByL (p + 1) sl of
        Just (l, r) -> (r, delete (l, r) sl)
        Nothing     -> (p + 1, sl)
    s' = insert (l, r) s

main = do
  [n, m] <- getArray
  q <- replicateM m getArray
  putStr $ unlines $ map (show . succ) $ gao (empty n) q
  where
    getArray = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine
    empty n = State {
        size = n,
        free = S.singleton $ interval n (0, n),
        l2r  = M.singleton 0 n,
        r2l  = M.singleton n 0,
        pos  = M.empty
      }

import System.IO (getChar)
import Control.Monad (liftM)
import Data.IntMap
import Data.Maybe (fromMaybe)
import Prelude hiding(lookup,null)
--import Control.Monad.Trans(lift)
--import Control.Monad.Trans.State

newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }

instance (Monad m) => Functor (StateT s m) where
	fmap f m = StateT $ \s -> do
		(x, s') <- runStateT m s
		return (f x, s')

instance (Monad m) => Monad (StateT s m) where
	return a = StateT $ \s -> return (a, s)
	m >>= k  = StateT $ \s -> do
		(a, s') <- runStateT m s
		runStateT (k a) s'
	fail str = StateT $ \_ -> fail str

evalStateT :: (Monad m) => StateT s m a -> s -> m a
evalStateT m s = do
	(a, _) <- runStateT m s
	return a

execStateT :: (Monad m) => StateT s m a -> s -> m s
execStateT m s = do
	(_, s') <- runStateT m s
	return s'

lift m = StateT $ \s -> do
		a <- m
		return (a, s)

get   = StateT $ \s -> return (s, s)
put s = StateT $ \_ -> return ((), s)

data Intv = Intv {getInf::Int,
                  getSup::Int
                 } deriving Show

data  Env = Env {
                 sizeLot::Int,
                 values::IntMap Int,
                 eIntvs::IntMap (IntMap Intv),
                 bIntvs::IntMap (Int,Intv)
                }  deriving Show

type LotState a = StateT Env IO a

data Pos = Pos Int Int | None deriving Show

data BIntv = BIntv (Int,Intv) | BNotFound

main :: IO ()
main = do
         nbS <- getNumbers 2
         let size = nbS !! 0
         let nbActs = nbS !! 1
         runManage size nbActs >>= printRes

printRes (x:xs) = print x >> printRes xs
printRes [] = return ()

getNumber =  do
              s <- getNumber'
              case s of
               [] -> return Nothing
               otherwise -> return $ Just (read $ s :: Int)

getNumber'  = do
                c <- catch getChar  (\err-> return ' ')
                case c of
                  ' ' ->  return ""
                  '\n' ->  return ""
                  otherwise -> do l <- getNumber'
                                  return (c:l)

getNumbers n | (n<=0) = return []
getNumbers n = do
                mbNum <- getNumber
                case mbNum of
                 Nothing -> return []
                 Just num -> (liftM (num:) (getNumbers(n-1)))

ins:: Int -> LotState Int
ins v = do
          pos <- takePos
          insertValue pos v >> return pos

insertValue pos v = do
                      s <- get
                      put $ s {values = insert v pos $ values s}

takeValue v = do
                   s <- get
                   let curValues = values s
                   let pos = curValues ! v
                   --put $ s {values = delete v curValues}
                   return pos

deleteInEIntvs bInf e = do
                      env <- get
                      let curEIntvs = eIntvs env
                      let newBIntvs = delete bInf $ bIntvs env
                      let intvs = curEIntvs ! e
                      let newIntvs = delete bInf intvs
                      if (null newIntvs)
                        then put $ env {eIntvs = delete e curEIntvs,bIntvs=newBIntvs}
                        else put $ env {eIntvs = insert e newIntvs curEIntvs,bIntvs=newBIntvs}

updateEIntvs m = do
                   s <- get
                   put $ s {eIntvs = m}

insertEIntvs e v = do
                    s <- get
                    let curEIntvs = eIntvs s
                    put $ s {eIntvs = insert e v curEIntvs}

updateBIntvs m = do
                   s <- get
                   put $ s {bIntvs = m}

insertBIntvs bInf v = do
                        s <- get
                        put s {bIntvs = insert bInf v $ bIntvs s}

takePos:: LotState Int
takePos = do
            s <- get
            let curEIntvs = eIntvs s
            let curBIntvs = bIntvs s

            let (e,maxIntvs) = findMax curEIntvs
            let (minBInf,intv) = findMin maxIntvs

            let newBIntvs = delete minBInf curBIntvs
            updateBIntvs newBIntvs
            let sz = sizeLot s
            let newIntvs = delete minBInf maxIntvs
            let newEIntvs = if (null newIntvs)
                               then delete e curEIntvs
                               else insert e newIntvs curEIntvs

            updateEIntvs newEIntvs

            case intv of
             (Intv bInf bSup) | (bInf==bSup) ->  return bInf
             (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1  --ok
             (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1   --ok
             (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok
             (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok
             (Intv bInf bSup) -> do
                                   let pos = bInf+e
                                   let eFirst = calcEcart bInf (pos-1)
                                   let eSecond = calcEcart (pos+1) bSup
                                   insertIntv eFirst $ Intv bInf (pos-1)
                                   insertIntv eSecond $ Intv (pos+1) bSup
                                   return pos

            where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2
                  diff bInf bSup = fromIntegral $ bSup-bInf

insertIntv e v = do
                   s <- get
                   let bInf = getInf v
                   let curEIntvs = eIntvs s
                   insertBIntvs bInf (e,v)
                   case (lookup e curEIntvs) of
                     Just intvs -> insertEIntvs e (insert bInf v intvs)
                     Nothing -> insertEIntvs e (singleton bInf v)

insFusion bInf bSup = do
                        env <- get
                        let sz = sizeLot env
                        let  e = case (bInf,bSup) of
                                 (1,b) -> b-1
                                 (a,b) | (b==sz) -> sz-a
                                 (a,b) -> let diff = fromIntegral (b-a)
                                          in truncate $ diff / 2
                        insertIntv e (Intv bInf bSup)

remV v = do
          pos <- takeValue v
          remPos pos

remPos p = do
             env <- get
             let sz = sizeLot env
             let curBIntvs = bIntvs env
             let (mins,_) = split p curBIntvs
             let bInf = if (p==1)
                         then BNotFound
                         else if null mins
                               then BNotFound
                               else let (_,(e,i)) = (findMax mins)
                                    in if ((getSup i)==(p-1))
                                      then  BIntv (e,i)
                                      else BNotFound

             let bSup = if (p==sz)
                   then BNotFound
                   else fromMaybe BNotFound $ do
                            (e,i) <- lookup (p+1) curBIntvs
                            return $ BIntv (e,i)

             case (bInf,bSup) of
                (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do
                                                           deleteInEIntvs (getInf iInf) eInf
                                                           deleteInEIntvs (getInf iSup) eSup
                                                           insFusion (getInf iInf) (getSup iSup)

                (BIntv (eInf,iInf),_) -> do
                                           deleteInEIntvs (getInf iInf) eInf
                                           insFusion (getInf iInf) p

                (_,BIntv (eSup,iSup)) -> do
                                           deleteInEIntvs (getInf iSup) eSup
                                           insFusion p (getSup iSup)
                otherwise ->  insFusion p p

initEnv n = Env {sizeLot=n,
                 values = empty,
                 bIntvs = singleton 1 ((n-1),(Intv 1 n)),
                 eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))
                }

getState n xs = execStateT (test xs)  (initEnv n)
testState n xs = evalStateT (test xs)  (initEnv n)

test [] = return []
test (action:xs) = do
                     let value = snd action
                     case (fst action ) of
                          1 -> do
                                pos <- ins value
                                liftM (pos:) $  test xs
                          2 -> remV value >> test xs

runManage n nbActs = evalStateT (manage nbActs) (initEnv n)

manage 0 = return []
manage 100000 = return []
manage nbActs= do
                  action <- lift $ getNumbers 2
                  let value = action !! 1
                  case (action !! 0) of

                          1 -> do
                                pos <- ins value
                                liftM (pos:) $  manage (nbActs-1)
                          2 -> remV value >> manage (nbActs-1)

import System.IO (getChar)
import Control.Monad (liftM)
import Data.IntMap
import Data.Maybe (fromMaybe)
import Prelude hiding(lookup,null)
--import Control.Monad.Trans(lift)
--import Control.Monad.Trans.State

newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }

instance (Monad m) => Functor (StateT s m) where
	fmap f m = StateT $ \s -> do
		(x, s') <- runStateT m s
		return (f x, s')

instance (Monad m) => Monad (StateT s m) where
	return a = StateT $ \s -> return (a, s)
	m >>= k  = StateT $ \s -> do
		(a, s') <- runStateT m s
		runStateT (k a) s'
	fail str = StateT $ \_ -> fail str

evalStateT :: (Monad m) => StateT s m a -> s -> m a
evalStateT m s = do
	(a, _) <- runStateT m s
	return a

execStateT :: (Monad m) => StateT s m a -> s -> m s
execStateT m s = do
	(_, s') <- runStateT m s
	return s'

lift m = StateT $ \s -> do
		a <- m
		return (a, s)

get   = StateT $ \s -> return (s, s)
put s = StateT $ \_ -> return ((), s)

data Intv = Intv {getInf::Int,
                  getSup::Int
                 } deriving Show

data  Env = Env {
                 sizeLot::Int,
                 values::IntMap Int,
                 eIntvs::IntMap (IntMap Intv),
                 bIntvs::IntMap (Int,Intv)
                }  deriving Show

type LotState a = StateT Env IO a

data Pos = Pos Int Int | None deriving Show

data BIntv = BIntv (Int,Intv) | BNotFound

main :: IO ()
main = do
         nbS <- getNumbers 2
         let size = nbS !! 0
         let nbActs = nbS !! 1
         runManage size nbActs >>= printRes

printRes (x:xs) = print x >> printRes xs
printRes [] = return ()

getNumber =  do
              s <- getNumber'
              case s of
               [] -> return Nothing
               otherwise -> return $ Just (read $ s :: Int)

getNumber'  = do
                c <- catch getChar  (\err-> return ' ')
                case c of
                  ' ' ->  return ""
                  '\n' ->  return ""
                  otherwise -> do l <- getNumber'
                                  return (c:l)

getNumbers n | (n<=0) = return []
getNumbers n = do
                mbNum <- getNumber
                case mbNum of
                 Nothing -> return []
                 Just num -> (liftM (num:) (getNumbers(n-1)))

ins:: Int -> LotState Int
ins v = do
          pos <- takePos
          insertValue pos v >> return pos

insertValue pos v = do
                      s <- get
                      put $ s {values = insert v pos $ values s}

takeValue v = do
                   s <- get
                   let curValues = values s
                   let pos = curValues ! v
                   put $ s {values = delete v curValues}
                   return pos

deleteInEIntvs bInf e = do
                      env <- get
                      let curEIntvs = eIntvs env
                      let newBIntvs = delete bInf $ bIntvs env
                      let intvs = curEIntvs ! e
                      let newIntvs = delete bInf intvs
                      if (null newIntvs)
                        then put $ env {eIntvs = delete e curEIntvs,bIntvs=newBIntvs}
                        else put $ env {eIntvs = insert e newIntvs curEIntvs,bIntvs=newBIntvs}

updateEIntvs m = do
                   s <- get
                   put $ s {eIntvs = m}

insertEIntvs e v = do
                    s <- get
                    let curEIntvs = eIntvs s
                    put $ s {eIntvs = insert e v curEIntvs}

updateBIntvs m = do
                   s <- get
                   put $ s {bIntvs = m}

insertBIntvs bInf v = do
                        s <- get
                        put s {bIntvs = insert bInf v $ bIntvs s}

takePos:: LotState Int
takePos = do
            s <- get
            let curEIntvs = eIntvs s
            let curBIntvs = bIntvs s

            let (e,maxIntvs) = findMax curEIntvs
            let (minBInf,intv) = findMin maxIntvs

            let newBIntvs = delete minBInf curBIntvs
            updateBIntvs newBIntvs
            let sz = sizeLot s
            let newIntvs = delete minBInf maxIntvs
            let newEIntvs = if (null newIntvs)
                               then delete e curEIntvs
                               else insert e newIntvs curEIntvs

            updateEIntvs newEIntvs

            case intv of
             (Intv bInf bSup) | (bInf==bSup) ->  return bInf
             (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1  --ok
             (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1   --ok
             (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok
             (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok
             (Intv bInf bSup) -> do
                                   let pos = bInf+e
                                   let eFirst = calcEcart bInf (pos-1)
                                   let eSecond = calcEcart (pos+1) bSup
                                   insertIntv eFirst $ Intv bInf (pos-1)
                                   insertIntv eSecond $ Intv (pos+1) bSup
                                   return pos

            where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2
                  diff bInf bSup = fromIntegral $ bSup-bInf

insertIntv e v = do
                   s <- get
                   let bInf = getInf v
                   let curEIntvs = eIntvs s
                   insertBIntvs bInf (e,v)
                   case (lookup e curEIntvs) of
                     Just intvs -> insertEIntvs e (insert bInf v intvs)
                     Nothing -> insertEIntvs e (singleton bInf v)

insFusion bInf bSup = do
                        env <- get
                        let sz = sizeLot env
                        let  e = case (bInf,bSup) of
                                 (1,b) -> b-1
                                 (a,b) | (b==sz) -> sz-a
                                 (a,b) -> let diff = fromIntegral (b-a)
                                          in truncate $ diff / 2
                        insertIntv e (Intv bInf bSup)

remV v = do
          pos <-  takeValue v
          remPos pos

remPos p = do
             env <- get
             let sz = sizeLot env
             let curBIntvs = bIntvs env
             let (mins,_) = split p curBIntvs
             let bInf = if (p==1)
                         then BNotFound
                         else if null mins
                               then BNotFound
                               else let (_,(e,i)) = (findMax mins)
                                    in if ((getSup i)==(p-1))
                                      then  BIntv (e,i)
                                      else BNotFound

             let bSup = if (p==sz)
                   then BNotFound
                   else fromMaybe BNotFound $ do
                            (e,i) <- lookup (p+1) curBIntvs
                            return $ BIntv (e,i)

             case (bInf,bSup) of
                (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do
                                                           deleteInEIntvs (getInf iInf) eInf
                                                           deleteInEIntvs (getInf iSup) eSup
                                                           insFusion (getInf iInf) (getSup iSup)

                (BIntv (eInf,iInf),_) -> do
                                           deleteInEIntvs (getInf iInf) eInf
                                           insFusion (getInf iInf) p

                (_,BIntv (eSup,iSup)) -> do
                                           deleteInEIntvs (getInf iSup) eSup
                                           insFusion p (getSup iSup)
                otherwise ->  insFusion p p

initEnv n = Env {sizeLot=n,
                 values = empty,
                 bIntvs = singleton 1 ((n-1),(Intv 1 n)),
                 eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))
                }

getState n xs = execStateT (test xs)  (initEnv n)
testState n xs = evalStateT (test xs)  (initEnv n)

test [] = return []
test (action:xs) = do
                     let value = snd action
                     case (fst action ) of
                          1 -> do
                                pos <- ins value
                                liftM (pos:) $  test xs
                          2 -> remV value >> test xs

runManage n nbActs = evalStateT (manage nbActs) (initEnv n)

manage 0 = return []
manage 100000 = return []
manage nbActs= do
                  action <- lift $ getNumbers 2
                  let value = action !! 1
                  case (action !! 0) of

                          1 -> do
                                pos <- ins value
                                liftM (pos:) $  manage (nbActs-1)
                          2 -> remV value >> manage (nbActs-1)

import System.IO (getChar)
import Control.Monad (liftM)
import Data.IntMap
import Data.Maybe (fromMaybe)
import Prelude hiding(lookup,null)
--import Control.Monad.Trans(lift)
--import Control.Monad.Trans.State

newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }

instance (Monad m) => Functor (StateT s m) where
	fmap f m = StateT $ \s -> do
		(x, s') <- runStateT m s
		return (f x, s')

instance (Monad m) => Monad (StateT s m) where
	return a = StateT $ \s -> return (a, s)
	m >>= k  = StateT $ \s -> do
		(a, s') <- runStateT m s
		runStateT (k a) s'
	fail str = StateT $ \_ -> fail str

evalStateT :: (Monad m) => StateT s m a -> s -> m a
evalStateT m s = do
	(a, _) <- runStateT m s
	return a

execStateT :: (Monad m) => StateT s m a -> s -> m s
execStateT m s = do
	(_, s') <- runStateT m s
	return s'

lift m = StateT $ \s -> do
		a <- m
		return (a, s)

get   = StateT $ \s -> return (s, s)
put s = StateT $ \_ -> return ((), s)

data Intv = Intv {getInf::Int,
                  getSup::Int
                 } deriving Show

data  Env = Env {
                 sizeLot::Int,
                 values::IntMap Int,
                 eIntvs::IntMap (IntMap Intv),
                 bIntvs::IntMap (Int,Intv)
                }  deriving Show

type LotState a = StateT Env IO a

data Pos = Pos Int Int | None deriving Show

data BIntv = BIntv (Int,Intv) | BNotFound

main :: IO ()
main = do
         nbS <- getNumbers 2
         let size = nbS !! 0
         let nbActs = nbS !! 1
         runManage size nbActs >>= printRes

printRes (x:xs) = print x >> printRes xs
printRes [] = return ()

getNumber =  do
              s <- getNumber'
              case s of
               [] -> return Nothing
               otherwise -> return $ Just (read $ s :: Int)

getNumber'  = do
                c <- catch getChar  (\err-> return ' ')
                case c of
                  ' ' ->  return ""
                  '\n' ->  return ""
                  otherwise -> do l <- getNumber'
                                  return (c:l)

getNumbers n | (n<=0) = return []
getNumbers n = do
                mbNum <- getNumber
                case mbNum of
                 Nothing -> return []
                 Just num -> (liftM (num:) (getNumbers(n-1)))

ins:: Int -> LotState Int
ins v = do
          pos <- takePos
          insertValue pos v >> return pos

insertValue pos v = do
                      s <- get
                      put $ s {values = insert v pos $ values s}

takeValue v = do
                   s <- get
                   let curValues = values s
                   let pos = curValues ! v
                   --put $ s {values = delete v curValues}
                   return pos

deleteInEIntvs bInf e = do
                      env <- get
                      let curEIntvs = eIntvs env
                      let newBIntvs = delete bInf $ bIntvs env
                      put $ env {eIntvs = alter f e curEIntvs,bIntvs=newBIntvs}
                      --let intvs = curEIntvs ! e
                      --let newIntvs = delete bInf intvs
                      --if (null newIntvs)
                      --  then put $ env {eIntvs = delete e curEIntvs,bIntvs=newBIntvs}
                      --  else put $ env {eIntvs = insert e newIntvs curEIntvs,bIntvs=newBIntvs}
                      where
                        f Nothing =  Nothing
                        f (Just a) = let newIntvs = delete bInf a
                                     in if null newIntvs
                                         then Nothing
                                         else (Just newIntvs)

updateEIntvs m = do
                   s <- get
                   put $ s {eIntvs = m}

insertEIntvs e v = do
                    s <- get
                    let curEIntvs = eIntvs s
                    put $ s {eIntvs = insert e v curEIntvs}

updateBIntvs m = do
                   s <- get
                   put $ s {bIntvs = m}

insertBIntvs bInf v = do
                        s <- get
                        put s {bIntvs = insert bInf v $ bIntvs s}

takePos:: LotState Int
takePos = do
            s <- get
            let curEIntvs = eIntvs s
            let curBIntvs = bIntvs s

            let (e,maxIntvs) = findMax curEIntvs
            let (minBInf,intv) = findMin maxIntvs

            let newBIntvs = delete minBInf curBIntvs
            updateBIntvs newBIntvs
            let sz = sizeLot s
            let newIntvs = delete minBInf maxIntvs
            let newEIntvs = if (null newIntvs)
                               then delete e curEIntvs
                               else insert e newIntvs curEIntvs

            updateEIntvs newEIntvs

            case intv of
             (Intv bInf bSup) | (bInf==bSup) ->  return bInf
             (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1  --ok
             (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1   --ok
             (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok
             (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok
             (Intv bInf bSup) -> do
                                   let pos = bInf+e
                                   let eFirst = calcEcart bInf (pos-1)
                                   let eSecond = calcEcart (pos+1) bSup
                                   insertIntv eFirst $ Intv bInf (pos-1)
                                   insertIntv eSecond $ Intv (pos+1) bSup
                                   return pos

            where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2
                  diff bInf bSup = fromIntegral $ bSup-bInf

insertIntv e v = do
                   s <- get
                   let bInf = getInf v
                   let curEIntvs = eIntvs s
                   insertBIntvs bInf (e,v)
                   case (lookup e curEIntvs) of
                     Just intvs -> insertEIntvs e (insert bInf v intvs)
                     Nothing -> insertEIntvs e (singleton bInf v)

insFusion bInf bSup = do
                        env <- get
                        let sz = sizeLot env
                        let  e = case (bInf,bSup) of
                                 (1,b) -> b-1
                                 (a,b) | (b==sz) -> sz-a
                                 (a,b) -> let diff = fromIntegral (b-a)
                                          in truncate $ diff / 2
                        insertIntv e (Intv bInf bSup)

remV v = do
          pos <- takeValue v
          remPos pos

remPos p = do
             env <- get
             let sz = sizeLot env
             let curBIntvs = bIntvs env
             let (mins,_) = split p curBIntvs
             let bInf = if (p==1)
                         then BNotFound
                         else if null mins
                               then BNotFound
                               else let (_,(e,i)) = (findMax mins)
                                    in if ((getSup i)==(p-1))
                                      then  BIntv (e,i)
                                      else BNotFound

             let bSup = if (p==sz)
                   then BNotFound
                   else fromMaybe BNotFound $ do
                            (e,i) <- lookup (p+1) curBIntvs
                            return $ BIntv (e,i)

             case (bInf,bSup) of
                (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do
                                                           deleteInEIntvs (getInf iInf) eInf
                                                           deleteInEIntvs (getInf iSup) eSup
                                                           insFusion (getInf iInf) (getSup iSup)

                (BIntv (eInf,iInf),_) -> do
                                           deleteInEIntvs (getInf iInf) eInf
                                           insFusion (getInf iInf) p

                (_,BIntv (eSup,iSup)) -> do
                                           deleteInEIntvs (getInf iSup) eSup
                                           insFusion p (getSup iSup)
                otherwise ->  insFusion p p

initEnv n = Env {sizeLot=n,
                 values = empty,
                 bIntvs = singleton 1 ((n-1),(Intv 1 n)),
                 eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))
                }

getState n xs = execStateT (test xs)  (initEnv n)
testState n xs = evalStateT (test xs)  (initEnv n)

test [] = return []
test (action:xs) = do
                     let value = snd action
                     case (fst action ) of
                          1 -> do
                                pos <- ins value
                                liftM (pos:) $  test xs
                          2 -> remV value >> test xs

runManage n nbActs = evalStateT (manage nbActs) (initEnv n)

manage 0 = return []
manage 100000 = return []
manage nbActs= do
                  action <- lift $ getNumbers 2
                  let value = action !! 1
                  case (action !! 0) of

                          1 -> do
                                pos <- ins value
                                liftM (pos:) $  manage (nbActs-1)
                          2 -> remV value >> manage (nbActs-1)

import System.IO (getChar)
import Control.Monad (liftM)
import Data.IntMap

type  Env = (IntMap Int,IntMap [Intv])

data Pos = Pos Int Int | None deriving Show

data Intv = Intv {getInf::Int,
                  getSup::Int
                 }

main :: IO ()
main = do
         nbS <- getNumbers 2
         let size = nbS !! 0
         let nbActs = nbS !! 1
         manage size nbActs (empty, (insert (size-1) [(Intv 1 size)] $ empty))  >>= printRes

printRes (x:xs) = print x >> printRes xs
printRes [] = return ()

getNumber =  do
              s <- getNumber'
              case s of
               [] -> return Nothing
               otherwise -> return $ Just (read $ s :: Int)

getNumber'  = do
                c <- catch getChar  (\err-> return ' ')
                case c of
                  ' ' ->  return ""
                  '\n' ->  return ""
                  otherwise -> do l <- getNumber'
                                  return (c:l)

getNumbers n | (n<=0) = return []
getNumbers n = do
                mbNum <- getNumber
                case mbNum of
                 Nothing -> return []
                 Just num -> (liftM (num:) (getNumbers(n-1)))

ins:: Int -> Env -> Int -> (Int,Env)
ins n (values,intvs) v = let (pos,newIntvs) = takePos n intvs
                           in (pos,((insert v pos values),newIntvs))

remV:: Int -> Env -> Int -> Env
remV n (values,intvs) v = let pos = values ! v
                              newIntvs = remPos n pos intvs
                          in ((delete v values),newIntvs)

insFusion n bInf bSup intvs = let  e = case (bInf,bSup) of
                                     (1,b) -> b-1
                                     (a,b) | (b==n) -> n-a
                                     (a,b) -> let diff = fromIntegral (b-a)
                                              in truncate $ diff / 2
                           in insertIntv e [(Intv bInf bSup)] intvs

remPos:: Int -> Int -> (IntMap [Intv]) -> (IntMap [Intv])

remPos n p intvs = let lIntvs = toList intvs
                       (iS,nIntvs) = findBornes p (Nothing,Nothing) lIntvs intvs
                   in case iS of
                     (Just iInf,Just iSup) -> insFusion n (getInf iInf) (getSup iSup) nIntvs
                     (Just iInf,Nothing) ->  insFusion n (getInf iInf) p  nIntvs
                     (Nothing,Just iSup) -> insFusion n p (getSup iSup) nIntvs
                     otherwise ->  insFusion n p p nIntvs

findBornes::  Int -> (Maybe Intv,Maybe Intv) -> [(Int,[Intv])] -> (IntMap [Intv]) ->  ((Maybe Intv,Maybe Intv),(IntMap [Intv]))
findBornes _ bs [] intvs = (bs,intvs)
findBornes _ bs@(Just iInf, Just iSup) _ intvs  = (bs,intvs)
findBornes p iS ((e,xs):ys) intvs =  let (nIs,f,zs) =  findBornes' p False (Nothing,Nothing) xs []
                                         newIntvs = if f
                                           then case zs of
                                             [] -> delete e intvs
                                             otherwise -> insert e zs intvs
                                           else intvs
                                     in findBornes p nIs ys newIntvs

findBornes' _ f iS [] ys = (iS,f,[])
findBornes' p f (iInf,iSup) (intv@(Intv bInf bSup):xs) ys  = case (bInf,bSup) of
                     (i,s) | (p==(bSup+1)) -> findBornes' p True (Just intv,iSup) xs ys
                     (i,s) | (p==(bInf-1)) -> findBornes' p True (iInf,Just intv) xs ys
                     (i,s)  -> let (nIs,ff,ys) = findBornes' p f (iInf,iSup) xs ys
                               in (nIs,ff,intv:ys)

takePos:: Int -> (IntMap [Intv]) -> (Int,(IntMap [Intv]))
takePos n intvs = let (e,maxIntvs) = findMax intvs
                      (intv:xs) = maxIntvs
                      newIntvs = case xs of
                                  [] -> delete e intvs
                                  xs -> insert e xs intvs
                  in case intv of
                    (Intv bInf bSup) | (bInf==bSup) -> (bInf,newIntvs) --ok
                    (Intv 1 bSup) | (bSup==n) -> (1, insertIntv (e-1) [(Intv 2 n)] newIntvs)  --ok
                    (Intv 1 bSup) -> (1,insertIntv (calcEcart 2 bSup) [(Intv 2 bSup)] newIntvs)   --ok
                    (Intv bInf bSup) | (bSup==n) -> (n,insertIntv (calcEcart bInf (n-1)) [(Intv bInf (n-1))] newIntvs) --ok
                    (Intv bInf bSup) | e==0 -> (bInf,insertIntv 0 [(Intv bSup bSup)] newIntvs) --ok
                    (Intv bInf bSup) -> let pos = bInf+e
                                            eFirst = calcEcart bInf (pos-1)
                                            eSecond = calcEcart (pos+1) bSup
                                        in (pos,insertIntv eFirst  [(Intv bInf (pos-1))] $
                                                insertIntv eSecond [(Intv (pos+1) bSup)] newIntvs) --ok
                   where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2
                         diff bInf bSup = fromIntegral $ bSup-bInf

insertIntv k v m = insertWith insIntv k v m

insIntv:: [Intv] -> [Intv] -> [Intv]
insIntv [] ys = ys
insIntv xs [] = xs
insIntv (x:xs) (y:ys) = if ((getInf x) < (getInf y))
                         then x: (insIntv xs (y:ys))
                         else y: (insIntv (x:xs) (ys))

test size [] _ = return []
test size (action:xs) env = do
                         let value = snd action
                         case (fst action ) of
                          1 -> do
                                let (pos,newEnv) = ins size env value
                                liftM (pos:) $  test size xs newEnv
                          2 -> test size xs  $ remV size env value

manage size 0 _ = return []
manage size nbActs env = do
                         action <- getNumbers 2
                         let value = action !! 1
                         case (action !! 0) of
                          1 -> do
                                let (pos,newEnv) = ins size env value
                                liftM (pos:) $  manage size (nbActs-1) newEnv
                          2 -> manage size (nbActs-1) $ remV size env value

import System.IO (getChar)
import Control.Monad (liftM)

data Pos = Pos Int Int | None deriving Show

main :: IO ()
main = do
         nbS <- getNumbers 2
         let size = nbS !! 0
         let nbActs = nbS !! 1
         manage size nbActs [] >>= print

getNumber =  do
              s <- getNumber'
              case s of
               [] -> return Nothing
               otherwise -> return $ Just (read $ s :: Int)

getNumber'  = do
                c <- catch getChar  (\err-> return ' ')
                case c of
                  ' ' ->  return ""
                  '\n' ->  return ""
                  otherwise -> do l <- getNumber'
                                  return (c:l)

getNumbers n | (n<=0) = return []
getNumbers n = do
                mbNum <- getNumber
                case mbNum of
                 Nothing -> return []
                 Just num -> (liftM (num:) (getNumbers(n-1)))

getPos:: Int -> [(Int,Int)] -> (Int,Pos)
getPos n xs = case (foldl maxDist (0,None) xs) of
                (0,None) ->  (1,Pos (n) 1)
                (i,None) | (i==n) -> (0,None)
                (i,None) ->  (n,Pos (n-i) n)
                (i,Pos e ii) | (e==0) -> (0,None)
                (i,p) -> (i,p)

maxDist (0,_) (i,v) = (1,Pos (i-1) 1)

maxDist (l,None) (n,v) = case (eMin>0) of
                               True ->  (n,(Pos eMin (l+eMin)))
                               False -> (n,None)
                              where eMin = truncate $ diff / 2
                                    diff= fromIntegral $ n-l

maxDist (l,(Pos e i)) (n,v) = case (eMin>e) of
                               True ->  (n,(Pos eMin (l+eMin)))
                               False -> (n,(Pos e i))

                              where eMin = truncate $ diff / 2
                                    diff= fromIntegral $ n-l

getPos' n xs  = case (l,p) of
                 (i,None) -> case ((n-i)>0) of
                               True -> n
                               False -> 0
                 (_,(Pos e i)) -> case ((n-l)>e) of
                                True -> case (i==0) of
                                         True -> 0
                                         False -> n
                                False -> i
                where(l,p) = getPos n xs

manage size 0 _ = return []
manage size nbActs xs = do
                         action <- getNumbers 2
                         let value = action !! 1
                         case (action !! 0) of
                          1 -> do
                                let pos = getPos' size xs
                                liftM (pos:) $  manage size (nbActs-1) $ insert pos xs value

                          2 -> manage size (nbActs-1) $ remove value xs

insert:: Int -> [(Int,Int)] -> Int -> [(Int,Int)]
insert pos xs v = case (pos) of
                  0 -> []
                  otherwise -> ins v pos  xs
                where
                  ins val p ((pp,vv):ys) = case (pp>p) of
                              True -> (p,val):(pp,vv):ys
                              False -> (pp,vv):(ins val p ys)
                  ins val p ([]) = [(p,val)]

remove:: Int -> [(Int,Int)] -> [(Int,Int)]
remove v ((pp,vv):xs) = case (vv==v) of
                          True -> xs
                          False -> (pp,vv):(remove v xs)
remove v [] = []

import System.IO (getChar)
import Control.Monad (liftM)

data Pos = Pos Int Int | None deriving Show

main :: IO ()
main = do
         nbS <- getNumbers 2
         let size = nbS !! 0
         let nbActs = nbS !! 1
         manage size nbActs [] >>= printRes

printRes (x:xs) = print x >> printRes xs
printRes [] = return ()

getNumber =  do
              s <- getNumber'
              case s of
               [] -> return Nothing
               otherwise -> return $ Just (read $ s :: Int)

getNumber'  = do
                c <- catch getChar  (\err-> return ' ')
                case c of
                  ' ' ->  return ""
                  '\n' ->  return ""
                  otherwise -> do l <- getNumber'
                                  return (c:l)

getNumbers n | (n<=0) = return []
getNumbers n = do
                mbNum <- getNumber
                case mbNum of
                 Nothing -> return []
                 Just num -> (liftM (num:) (getNumbers(n-1)))

getPos:: Int -> [(Int,Int)] -> (Int,Pos)
getPos n xs = case (foldl maxDist (0,None) xs) of
                (0,None) ->  (1,Pos (n) 1)
                (i,None) | (i==n) -> (0,None)
                (i,None) ->  (n,Pos (n-i) n)
                (i,Pos e ii) | (e==0) -> (0,None)
                (i,p) -> (i,p)

maxDist (0,_) (i,v) = (1,Pos (i-1) 1)

maxDist (l,None) (n,v) = case (eMin>0) of
                               True ->  (n,(Pos eMin (l+eMin)))
                               False -> (n,None)
                              where eMin = truncate $ diff / 2
                                    diff= fromIntegral $ n-l

maxDist (l,(Pos e i)) (n,v) = case (eMin>e) of
                               True ->  (n,(Pos eMin (l+eMin)))
                               False -> (n,(Pos e i))

                              where eMin = truncate $ diff / 2
                                    diff= fromIntegral $ n-l

getPos' n xs  = case (l,p) of
                 (i,None) -> case ((n-i)>0) of
                               True -> n
                               False -> 0
                 (_,(Pos e i)) -> case ((n-l)>e) of
                                True -> case (i==0) of
                                         True -> 0
                                         False -> n
                                False -> i
                where(l,p) = getPos n xs

manage size 0 _ = return []
manage size nbActs xs = do
                         action <- getNumbers 2
                         let value = action !! 1
                         case (action !! 0) of
                          1 -> do
                                let pos = getPos' size xs
                                liftM (pos:) $  manage size (nbActs-1) $ insert pos xs value

                          2 -> manage size (nbActs-1) $ remove value xs

insert:: Int -> [(Int,Int)] -> Int -> [(Int,Int)]
insert pos xs v = case (pos) of
                  0 -> []
                  otherwise -> ins v pos  xs
                where
                  ins val p ((pp,vv):ys) = case (pp>p) of
                              True -> (p,val):(pp,vv):ys
                              False -> (pp,vv):(ins val p ys)
                  ins val p ([]) = [(p,val)]

remove:: Int -> [(Int,Int)] -> [(Int,Int)]
remove v ((pp,vv):xs) = case (vv==v) of
                          True -> xs
                          False -> (pp,vv):(remove v xs)
remove v [] = []

import System.IO (getChar)
import Control.Monad (liftM)

data Pos = Pos Int Int | None deriving Show

main :: IO ()
main = do
         nbS <- getNumbers 2
         let size = nbS !! 0
         let nbActs = nbS !! 1
         manage size nbActs [] >>= printRes

printRes (x:xs) = print x >> printRes xs
printRes [] = return ()

getNumber =  do
              s <- getNumber'
              case s of
               [] -> return Nothing
               otherwise -> return $ Just (read $ s :: Int)

getNumber'  = do
                c <- catch getChar  (\err-> return ' ')
                case c of
                  ' ' ->  return ""
                  '\n' ->  return ""
                  otherwise -> do l <- getNumber'
                                  return (c:l)

getNumbers n | (n<=0) = return []
getNumbers n = do
                mbNum <- getNumber
                case mbNum of
                 Nothing -> return []
                 Just num -> (liftM (num:) (getNumbers(n-1)))

getPos:: Int -> [(Int,Int)] -> (Int,Pos)
getPos n xs = case (foldl maxDist (0,None) xs) of
                (0,None) ->  (1,Pos (n) 1)
                (i,None) | (i==n) -> (0,None)
                (i,None) ->  (n,Pos (n-i) n)
                (i,Pos e ii) | (e==0) -> (0,None)
                (i,p) -> (i,p)

maxDist (0,_) (i,v) = case (i==1) of
                       True -> (1,None)
                       False -> (1,Pos (i-1) 1)

maxDist (l,None) (n,v) = case (eMin>0) of
                               True ->  (n,(Pos eMin (l+eMin)))
                               False -> (n,None)
                              where eMin = truncate $ diff / 2
                                    diff= fromIntegral $ n-l

maxDist (l,(Pos e i)) (n,v) = case (eMin>e) of
                               True ->  (n,(Pos eMin (l+eMin)))
                               False -> (n,(Pos e i))

                              where eMin = truncate $ diff / 2
                                    diff= fromIntegral $ n-l

getPos' n xs  = case (l,p) of
                 (i,None) -> case ((n-i)>0) of
                               True -> n
                               False -> 0
                 (_,(Pos e i)) -> i
                where(l,p) = getPos n xs

manage size 0 _ = return []
manage size nbActs xs = do
                         action <- getNumbers 2
                         let value = action !! 1
                         case (action !! 0) of
                          1 -> do
                                let pos = getPos' size xs
                                liftM (pos:) $  manage size (nbActs-1) $ insert pos xs value

                          2 -> manage size (nbActs-1) $ remove value xs

insert:: Int -> [(Int,Int)] -> Int -> [(Int,Int)]
insert pos xs v = case (pos) of
                  0 -> []
                  otherwise -> ins v pos  xs
                where
                  ins val p ((pp,vv):ys) = case (pp>p) of
                              True -> (p,val):(pp,vv):ys
                              False -> (pp,vv):(ins val p ys)
                  ins val p ([]) = [(p,val)]

remove:: Int -> [(Int,Int)] -> [(Int,Int)]
remove v ((pp,vv):xs) = case (vv==v) of
                          True -> xs
                          False -> (pp,vv):(remove v xs)
remove v [] = []

import System.IO (getChar)
import Control.Monad (liftM)
import Data.IntMap
import Data.Maybe (fromMaybe)
import Prelude hiding(lookup,null)
--import Control.Monad.Trans(lift)
--import Control.Monad.Trans.State

newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }

instance (Monad m) => Functor (StateT s m) where
	fmap f m = StateT $ \s -> do
		(x, s') <- runStateT m s
		return (f x, s')

instance (Monad m) => Monad (StateT s m) where
	return a = StateT $ \s -> return (a, s)
	m >>= k  = StateT $ \s -> do
		(a, s') <- runStateT m s
		runStateT (k a) s'
	fail str = StateT $ \_ -> fail str

evalStateT :: (Monad m) => StateT s m a -> s -> m a
evalStateT m s = do
	(a, _) <- runStateT m s
	return a

execStateT :: (Monad m) => StateT s m a -> s -> m s
execStateT m s = do
	(_, s') <- runStateT m s
	return s'

lift m = StateT $ \s -> do
		a <- m
		return (a, s)

get   = StateT $ \s -> return (s, s)
put s = StateT $ \_ -> return ((), s)

data Intv = Intv {getInf::Int,
                  getSup::Int
                 } deriving Show

data  Env = Env {
                 sizeLot::Int,
                 values::IntMap Int,
                 eIntvs::IntMap (IntMap Intv),
                 bIntvs::IntMap (Int,Intv)
                }  deriving Show

type LotState a = StateT Env IO a

data Pos = Pos Int Int | None deriving Show

data BIntv = BIntv (Int,Intv) | BNotFound

main :: IO ()
main = do
         nbS <- getNumbers 2
         let size = nbS !! 0
         let nbActs = nbS !! 1
         runManage size nbActs -- >>= printRes

printRes (x:xs) = print x >> printRes xs
printRes [] = return ()

getNumber =  do
              s <- getNumber'
              case s of
               [] -> return Nothing
               otherwise -> return $ Just (read $ s :: Int)

getNumber'  = do
                c <- catch getChar  (\err-> return ' ')
                case c of
                  ' ' ->  return ""
                  '\n' ->  return ""
                  otherwise -> do l <- getNumber'
                                  return (c:l)

getNumbers n | (n<=0) = return []
getNumbers n = do
                mbNum <- getNumber
                case mbNum of
                 Nothing -> return []
                 Just num -> (liftM (num:) (getNumbers(n-1)))

ins:: Int -> LotState Int
ins v = do
          pos <- takePos
          insertValue pos v >> return pos

insertValue pos v = do
                      s <- get
                      put $ s {values = insert v pos $ values s}

takeValue v = do
                   s <- get
                   let curValues = values s
                   let pos = curValues ! v
                   --put $ s {values = delete v curValues}
                   return pos

deleteInEIntvs bInf e = do
                      env <- get
                      let curEIntvs = eIntvs env
                      let newBIntvs = delete bInf $ bIntvs env
                      put $ env {eIntvs = alter f e curEIntvs,bIntvs=newBIntvs}
                      --let intvs = curEIntvs ! e
                      --let newIntvs = delete bInf intvs
                      --if (null newIntvs)
                      --  then put $ env {eIntvs = delete e curEIntvs,bIntvs=newBIntvs}
                      --  else put $ env {eIntvs = insert e newIntvs curEIntvs,bIntvs=newBIntvs}
                      where
                        f Nothing =  Nothing
                        f (Just a) = let newIntvs = delete bInf a
                                     in if null newIntvs
                                         then Nothing
                                         else (Just newIntvs)

updateEIntvs m = do
                   s <- get
                   put $ s {eIntvs = m}

insertEIntvs e v = do
                    s <- get
                    let curEIntvs = eIntvs s
                    put $ s {eIntvs = insert e v curEIntvs}

updateBIntvs m = do
                   s <- get
                   put $ s {bIntvs = m}

insertBIntvs bInf v = do
                        s <- get
                        put s {bIntvs = insert bInf v $ bIntvs s}

takePos:: LotState Int
takePos = do
            s <- get
            let curEIntvs = eIntvs s
            let curBIntvs = bIntvs s

            let (e,maxIntvs) = findMax curEIntvs
            let (minBInf,intv) = findMin maxIntvs

            let newBIntvs = delete minBInf curBIntvs
            updateBIntvs newBIntvs
            let sz = sizeLot s
            let newIntvs = delete minBInf maxIntvs
            let newEIntvs = if (null newIntvs)
                               then delete e curEIntvs
                               else insert e newIntvs curEIntvs

            updateEIntvs newEIntvs

            case intv of
             (Intv bInf bSup) | (bInf==bSup) ->  return bInf
             (Intv 1 bSup) | (bSup==sz) -> insertIntv (e-1) (Intv 2 sz) >> return 1  --ok
             (Intv 1 bSup) -> insertIntv (calcEcart 2 bSup) (Intv 2 bSup) >> return 1   --ok
             (Intv bInf bSup) | (bSup==sz) -> insertIntv (calcEcart bInf (sz-1)) (Intv bInf (sz-1)) >> return sz --ok
             (Intv bInf bSup) | e==0 -> insertIntv 0 (Intv bSup bSup) >> return bInf --ok
             (Intv bInf bSup) -> do
                                   let pos = bInf+e
                                   let eFirst = calcEcart bInf (pos-1)
                                   let eSecond = calcEcart (pos+1) bSup
                                   insertIntv eFirst $ Intv bInf (pos-1)
                                   insertIntv eSecond $ Intv (pos+1) bSup
                                   return pos

            where calcEcart bInf bSup = truncate $ (diff bInf bSup) / 2
                  diff bInf bSup = fromIntegral $ bSup-bInf

insertIntv e v = do
                   s <- get
                   let bInf = getInf v
                   let curEIntvs = eIntvs s
                   insertBIntvs bInf (e,v)
                   case (lookup e curEIntvs) of
                     Just intvs -> insertEIntvs e (insert bInf v intvs)
                     Nothing -> insertEIntvs e (singleton bInf v)

insFusion bInf bSup = do
                        env <- get
                        let sz = sizeLot env
                        let  e = case (bInf,bSup) of
                                 (1,b) -> b-1
                                 (a,b) | (b==sz) -> sz-a
                                 (a,b) -> let diff = fromIntegral (b-a)
                                          in truncate $ diff / 2
                        insertIntv e (Intv bInf bSup)

remV v = do
          pos <- takeValue v
          remPos pos

remPos p = do
             env <- get
             let sz = sizeLot env
             let curBIntvs = bIntvs env
             let (mins,_) = split p curBIntvs
             let bInf = if (p==1)
                         then BNotFound
                         else if null mins
                               then BNotFound
                               else let (_,(e,i)) = (findMax mins)
                                    in if ((getSup i)==(p-1))
                                      then  BIntv (e,i)
                                      else BNotFound

             let bSup = if (p==sz)
                   then BNotFound
                   else fromMaybe BNotFound $ do
                            (e,i) <- lookup (p+1) curBIntvs
                            return $ BIntv (e,i)

             case (bInf,bSup) of
                (BIntv (eInf,iInf),BIntv (eSup,iSup)) -> do
                                                           deleteInEIntvs (getInf iInf) eInf
                                                           deleteInEIntvs (getInf iSup) eSup
                                                           insFusion (getInf iInf) (getSup iSup)

                (BIntv (eInf,iInf),_) -> do
                                           deleteInEIntvs (getInf iInf) eInf
                                           insFusion (getInf iInf) p

                (_,BIntv (eSup,iSup)) -> do
                                           deleteInEIntvs (getInf iSup) eSup
                                           insFusion p (getSup iSup)
                otherwise ->  insFusion p p

initEnv n = Env {sizeLot=n,
                 values = empty,
                 bIntvs = singleton 1 ((n-1),(Intv 1 n)),
                 eIntvs = singleton (n-1) (singleton 1 (Intv 1 n))
                }

getState n xs = execStateT (test xs)  (initEnv n)
testState n xs = evalStateT (test xs)  (initEnv n)

test [] = return []
test (action:xs) = do
                     let value = snd action
                     case (fst action ) of
                          1 -> do
                                pos <- ins value
                                liftM (pos:) $  test xs
                          2 -> remV value >> test xs

runManage n nbActs = evalStateT (manage nbActs) (initEnv n)

manage 0 = return ()
manage 100000 = return ()
manage nbActs= do
                  action <- lift $ getNumbers 2
                  let value = action !! 1
                  case (action !! 0) of

                          1 -> do
                                pos <- ins value
                                --liftM (pos:) $  manage (nbActs-1)
                                (lift $ print pos) >> manage (nbActs-1)
                          2 -> remV value >> manage (nbActs-1)


{-# LANGUAGE BangPatterns #-}
import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
--import Data.Array.Unboxed

prefMins :: Ord t => (a -> t) -> [a] -> [t]
prefMins f li = tail $ scanl' min (f $ head li) $ map f li

fib n = go n (0,1)
  where
    go !n (!a, !b) | n==0      = a
                   | otherwise = go (n-1) (b, a+b)

gao (n, k) = go (n, k) (0, 1)
  where
    go (!n, !k) (!t, !i) | i >= n = t
                         | i >= k = t + (div (n-i+k-1) (k))
                         | otherwise = go (n, k) (t+1, i*2)

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n, k] <- getInts 2
    pure $ putInts [gao (n, k)]

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun $ P.words inp
  P.putStr $ toLazyByteString outp

import qualified Control.Monad as CM
import qualified Data.List as DL
import Data.Bits
import System.IO

solve :: IO ()
solve = do
  ~[n,k] <- readv :: IO [Int]
  let lk = lgCeil k
  print $  lk + divCeil (n - shiftL 1 lk) k

lg n = fromIntegral $ finiteBitSize n - countLeadingZeros n - 1
lgCeil n = lg n + if popCount n == 1 then 0 else 1
divCeil n d = q + if r==0 then 0 else 1 where (q,r)=divMod n d

printv :: Show a => [a] -> IO ()
printv xs =  putStrLn $ unwords $ fmap show xs

readv :: Read a => IO [a]
readv = fmap read . words <$> getLine

main :: IO ()
main = do
  ~[n] <- readv
  CM.replicateM_ n solve

import qualified Control.Monad as CM
import qualified Data.List as DL
import Data.Bits
import System.IO

solve :: IO ()
solve = do
  ~[n,k] <- readv :: IO [Int]
  print $  lgCeil k + divCeil (n - 2 ^ lgCeil k) k

lg n = fromIntegral $ finiteBitSize n - countLeadingZeros n - 1
lgCeil n = lg n + if popCount n == 1 then 0 else 1
divCeil n d = q + if r==0 then 0 else 1 where (q,r)=divMod n d

printv :: Show a => [a] -> IO ()
printv xs =  putStrLn $ unwords $ fmap show xs

readv :: Read a => IO [a]
readv = fmap read . words <$> getLine

main :: IO ()
main = do
  ~[n] <- readv
  CM.replicateM_ n solve

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

calc :: Int -> Int -> Int
calc 1 1 = 0
calc n 1 = n-1
calc n k =
  let (ans, cur) = stage1 k 0 1
  in
    if cur < n then ans + ((n - cur + k - 1) `div` k)
    else ans

stage1 :: Int -> Int -> Int -> (Int, Int)
stage1 k it acc | acc >= k = (it, acc)
stage1 k it acc | otherwise =
  stage1 k (it+1) (acc*2)

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let [n,k] = map read $ words line :: [Int]
    --print "abc"
    --print $ stage1 k 0 1
    print $ calc n k

{-# 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 { n :: Integer, k :: Integer }

input :: Scanner TC
input = do
  n <- integer
  k <- integer
  return TC {..}

-- type Output = String

-- output :: Output -> C.ByteString
output = showB

-- solve :: TC -> Output
solve TC {..} = compute 1 (n - 1)
  where
    compute d r
      | r <= 0 = 0
      | d >= k = (r + k - 1) `div` k
      | otherwise = let u = minimum [k, d, r] in 1 + compute (d + u) (r - u)

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

{-# LANGUAGE BangPatterns #-}

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

main :: IO ()
main = do
  [t] <- readInts
  replicateM_ t $ do
    [n, k] <- readIntegers
    print $ solve n k 1

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

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

solve n k a
  | a >= n = 0
  | a >= k = (n - a - 1) `div` k + 1
  | otherwise = 1 + (solve n k $ 2 * a)

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

isqrt :: Int -> Int
isqrt = ceiling . sqrt . fromIntegral

calc :: Int -> Int -> Int
calc 1 1 = 0
calc n 1 = n-1

-- 1. max k <= k : k*(k+1) <= n
calc n k =
  let k2 = ((isqrt (8*n+1)) - 1) `div` 2
      k3 = min k k2
      r = max 0 $ n-((k3*(k3+1)) `div` 2)
      m = r `mod` k
      add = if m > 0 then 1 else 0
  in
    k3 + (r `div` k) + add

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let [n,k] = map read $ words line :: [Int]
    --print "123"
    --print $ ((isqrt (8*2+1)) - 1) `div` 2
    --print $ max 0 $ (n-((2*(2+1)) `div` 2))
    print $ calc n k

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

isqrt :: Int -> Int
isqrt = floor . sqrt . fromIntegral

calc :: Int -> Int -> Int
calc 1 1 = 0
calc n 1 = n-1

-- 1. max k <= k : k*(k+1) <= n
calc n k =
  let k2 = ((isqrt (4*n+1)) - 1) `div` 2
      k3 = min k k2
      r = n-k3
      m = r `mod` k
      add = if m > 0 then 1 else 0
  in
    k3 + (r `div` k) + add

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let [n,k] = map read $ words line :: [Int]
    print $ calc n k