import Data.List

solve :: Int -> [Int] -> Int
solve m xs = sum $ map count $ group $ sort xs
  where
    count ys@(y:_) = if y > m then length ys else length ys - 1

(-->) = flip fmap

main = do
  m <- getLine --> read
  xs <- getLine --> words --> map read
  print $ solve m xs

import Data.List

answer1 :: String -> Int
answer1 str = sum.map f $ group str
  where
    f = \x -> if length x `mod` 5 == 0 then length x `div` 5 else length x `div` 5 + 1

answer2 :: Int -> [Int] -> Int
answer2 n xs = sum.map f.group.sort $ xs
  where
    f v = if n < head v
                then length v
                else length v -1

main = do n <- getLine
          print.answer2 (read n).map read.words =<< getLine

import Data.List

solve (n:xs) = n - (length $ group $ sort $ filter (<=n) xs)

main = interact $ show.solve.map read.words

import Data.Array

solve n xs = length $ filter (==0) finalTable
  where finalTable = elems $ foldr updateTable initialTable xs
        initialTable = array (1, n) [(i, 0) | i <- [1..n]]
        updateTable x table = table // if x <= n then
                                         [(x, (table ! x) + 1)]
                                       else
                                         []

main = do n <- fmap read getLine
          xs <- fmap (map read.words) getLine
          putStrLn $ show $ solve n xs

import List
main = interact $ show.s.sort.map read.tail.words
s xs = let n = length xs in n - (length $ group $ filter (<=n) xs)

import Control.Monad
import qualified Data.IntSet as S
main = do
  n <- readLn
  print . (n -) . S.size . S.fromList . filter (<= n) . map read . words =<< getLine

import Data.List

main :: IO ()
main = do n <- getLine
          xs <- getLine
          print $ check (read n) $ map read $ words xs

check :: Int -> [Int] -> Int
check n xs = sum [f x | x <- group $ sort xs]
    where f x = length x - (if (head x) > n then 0 else 1)

import Data.List

main :: IO()
main = do
	getLine
	x <- getLine
	putStr $ show $ getAnswer $ map (\x -> read x :: Integer) (words x)

getAnswer xs = length $ (sort xs) `minus` [1..fromIntegral $ length xs]

minus :: (Ord a) => [a] -> [a] -> [a]
minus = minusBy compare

-- |  'minusBy' is the non-overloaded version of 'minus'
minusBy :: (a -> a -> Ordering) -> [a] -> [a] -> [a]
minusBy cmp = loop
  where
     loop [] _ys = []
     loop xs [] = xs
     loop (x:xs) (y:ys)
       = case cmp x y of
          LT -> x : loop xs (y:ys)
          EQ ->     loop xs ys
          GT ->     loop (x:xs) ys

main :: IO ()
main = do n <- getLine
          xs <- getLine
          print $ solve n xs

read' :: String -> Int
read' = read

solve ::  String -> String -> Int
solve n' xs' = length $ filter id $ map (flip notElem xs) [1..n]
   where n = read' n'
         xs = map read' $ words xs'

import Data.List
import Data.Array

main = do
   n <- fmap read getLine :: IO Int
   a <- fmap (map read . words) getLine :: IO [Int]
   print . length . filter id . elems $ accumArray (&&) True (1, n) [(i, False) | i <- a, i >= 1 && i <= n]

-- vim: set expandtab:

{-# LANGUAGE BangPatterns, ViewPatterns, PatternGuards, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
import qualified Data.IntSet as Set

main :: IO ()
main = do
  n   <- readLn
  xs  <- map read . words <$> getLine
  let ys = takeWhile (<= n) $ Set.toList $ Set.fromList xs
  print $ n - length ys

f s x | null s = x | head s `elem` x = f (tail s) x | otherwise = f (tail s) (head s :x)
fu s n = n - length (f s [])
solve s = [x | x<-tail s, x `elem` [1..head s]]
check s | null $ solve s  = head s | otherwise = fu (solve s) (head s)
main = interact $ show . check . map read .words

import Control.Monad
solve :: Int -> [Int] -> Int
solve 0 _ = 0
solve n xs
    | n `elem` xs = solve (n-1) xs
    | otherwise = 1 + (solve (n-1) xs)
main = do
  n <- readLn
  getLine >>=
       (\str -> putStrLn $
                (show . solve n . map read. words) str)

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

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

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

main = do
  n <- readLn
  xs <- getInts

  print $ sum $ map (\(i, x) -> if elem i [1..n] then max (x-1) 0 else x) $ assocs $ (accumArray (+) 0 (1, 5000) $ zip xs $ repeat (1 :: Int) :: UArray Int Int)

import List
main = interact $ show. gao. map read. words
gao (n:xs) = n - (length. takeWhile (<=n). map head.group.sort $ xs)

-- rearranges
import Array

readL [] a akk = (read $ reverse a :: Int) : akk
readL (' ':xs) a akk = readL xs [] ((read $ reverse a :: Int) : akk)
readL (x:xs) a akk = readL xs (x:a) akk

solve [] a = a
solve (x:xs) a | (inRange (bounds a) x) = solve xs (a//[(x,0)])
               | otherwise = solve xs a

main = do
			qty <- readLn :: IO Int
			slist <- getLine
			print $ foldr (+) 0 (elems (solve (readL slist [] []) (array (1,qty) [(i,1) | i <- [1..qty]])))

module Main
    where

import IO

get_num :: Char -> Int

get_num c = case c of
    '0' -> 0
    '1' -> 1
    '2' -> 2
    '3' -> 3
    '4' -> 4
    '5' -> 5
    '6' -> 6
    '7' -> 7
    '8' -> 8
    '9' -> 9

strtoInt' :: Int -> String -> [Int]

strtoInt' tmp [] = [tmp]
strtoInt' tmp (s1:ss) =
    if (s1 == ' ')
        then tmp:(strtoInt' 0 ss)
        else strtoInt' (tmp * 10 + (get_num s1)) ss

strtoInt = strtoInt' 0

sort :: [Int] -> [Int]

sort [] = []
sort (x:xs) = (sort [k | k <- xs, k < x]) ++ [x] ++ (sort [k | k <- xs, k >= x])

count :: [Int] -> Int

count (x1:x2:xs) =
    if x1 /= x2
        then 1 + count (x2:xs)
        else count (x2:xs)
count list = length list

badnum :: [Int] -> Int
badnum list = len - count (filter (\x -> x <= len) list)
    where len = length list

res_function :: String -> String

res_function = show . badnum . sort . strtoInt

main = do
    hSetBuffering stdin LineBuffering
    tmp <- getLine
    tmp2 <- getLine
    putStrLn  (res_function tmp2)

import Data.List

solve :: [Int] -> Int
solve (n:xs) = n - (length (takeWhile (<= n) values))
    where
        values = map head.group.sort $ xs

main = interact $ show.solve.map read.words

import List
getAns a = (length a) - (length (intersect [1..(length a)] a))
main=interact$show.getAns.map read.tail.words

import List

readWords :: IO [String]
readWords = getLine >>= return . words

reads :: Read a => IO [a]
reads = readWords >>= return . (map read)

solve :: Int -> [Int] -> Int
solve n xs = n - length (nub (filter (<=n) xs))

main :: IO ()
main = do
    n <- readLn
    xs <- Main.reads
    print (solve n xs)

module Main where
import Data.List
main :: IO ()
main = do
    n <- readLn
    l <- getLine
    let ns = nub (map read $ words l :: [Integer])
        outside = fromInteger $ sum [1 | x <- ns, x > n]
    print (fromInteger n - length ns + fromInteger outside)

module Main where
import Data.List
main :: IO ()
main = do
    _ <- getLine
    l <- getLine
    let ns = sort $ (map read $ words l :: [Integer])
        folddat (changes, curr) x =
            if curr == x
                then (changes + 1, x)
                else (changes, x)
        (ans,_) = foldl folddat (0, head ns) (tail ns)
    print ans

module Main where
import Data.List
main :: IO ()
main = do
    n <- readLn
    l <- getLine
    let ns = nub (map read $ words l :: [Integer])
    print (n - length ns)

module Main where
import Data.List
main :: IO ()
main = do
    _ <- getLine
    l <- getLine
    let ns = sort $ (map read $ words l :: [Integer])
        folddat (changes, curr) x =
            if curr == x
                then (changes + 1, x)
                else (changes + x - curr - 1, x)
        (ans,_) = foldl folddat (0, head ns) (tail ns)
    print ans

import Data.List

answer1 :: String -> Int
answer1 str = sum.map f $ group str
  where
    f = \x -> if length x `mod` 5 == 0 then length x `div` 5 else length x `div` 5 + 1

answer2 :: Int -> [Int] -> Int
answer2 n xs = sum.map f.zip [1..n].sort $ xs
  where
    f (i,v) = if i==v then 0 else 1

main = do n <- getLine
          print.answer2 (read n).map read.words =<< getLine

import Data.List

answer1 :: String -> Int
answer1 str = sum.map f $ group str
  where
    f = \x -> if length x `mod` 5 == 0 then length x `div` 5 else length x `div` 5 + 1

answer2 :: String -> Int
answer2 str = f.foldl max 1.map length.group.sort.words $ str
  where
    f 1 = 0
    f n = n-1

main = getLine >> getLine >>= print.answer2

import Data.List

solve (n:xs) = n - (length $ group $ sort xs)

main = interact $ show.solve.map read.words

import List
main = interact $ show.length.filter id.(zipWith (/=) [1..]).sort.map read.tail.words

import Control.Monad
import qualified Data.IntSet as S
main = print =<< liftM2 (-) readLn (liftM (S.size . S.fromList . map read . words) getLine)

import Data.List

main :: IO()
main = do
	getLine
	x <- getLine
	putStr $ show $ getAnswer $ map (\x -> read x :: Integer) (words x)

getAnswer xs = length xs - length (nub xs)

import Data.List(sort)

main :: IO ()
main = do n <- getLine
          xs <- getLine
          print $ solve n xs

read' :: String -> Int
read' = read

solve ::  String -> String -> Int
solve n' xs' = length $ filter id $ zipWith (/=) (sort xs) [1..n]
   where n = read' n'
         xs = map read' $ words xs'

import Data.List

main :: IO ()
main = do n <- getLine
          xs <- getLine
          print $ check $ map read $ words xs

check :: [Int] -> Int
check xs = sum [length x - 1 | x <- group $ sort xs]

import Data.List
import Data.Array

main = do
   n <- fmap read getLine :: IO Int
   a <- fmap (map read . words) getLine :: IO [Int]
   print . length . filter id . elems $ accumArray (||) False (1, n) [(i, True) | i <- a]

-- vim: set expandtab:

import Data.List
import Data.Array

main = do
   n <- fmap read getLine :: IO Int
   a <- fmap (map read . words) getLine :: IO [Int]
   print . length . filter id . elems $ accumArray (&&) True (1, n) [(i, False) | i <- a, i <- [1..n]]

-- vim: set expandtab:

import Data.List

main = do
   n <- fmap read getLine :: IO Int
   a <- fmap (map read . words) getLine :: IO [Int]
   print . sum $ zipWith (\x y -> abs $ x - y) (sort a) [1..n]

-- vim: set expandtab:

import Data.List

main = do
   n <- fmap read getLine :: IO Int
   a <- fmap (map read . words) getLine :: IO [Int]
   print . length . filter id $ zipWith (/=) (sort a) [1..n]

-- vim: set expandtab:

f s x | null s = x | head s `elem` x = f (tail s) x | otherwise = f (tail s) (head s :x)
fu s = head s  - length (f s [])
solve s = [x | x<-tail s, x `elem` [1..head s]]
check s | null $ solve s  = head s | otherwise = fu s
main = interact $ show . check . map read .words

import List
main = interact $ show. gao. words
gao (n:xs) = (read n) - (length. group. sort $ xs)

module Main
    where

import IO

get_num :: Char -> Int

get_num c = case c of
    '0' -> 0
    '1' -> 1
    '2' -> 2
    '3' -> 3
    '4' -> 4
    '5' -> 5
    '6' -> 6
    '7' -> 7
    '8' -> 8
    '9' -> 9

strtoInt' :: Int -> String -> [Int]

strtoInt' tmp [] = [tmp]
strtoInt' tmp (s1:ss) =
    if (s1 == ' ')
        then tmp:(strtoInt' 0 ss)
        else strtoInt' (tmp * 10 + (get_num s1)) ss

strtoInt = strtoInt' 0

sort :: [Int] -> [Int]

sort [] = []
sort (x:xs) = [k | k <- xs, k < x] ++ [x] ++ [k | k <- xs, k >= x]

badnum :: [Int] -> Int

badnum (x1:x2:xs) =
    if x1 == x2
        then 1 + badnum (x2:xs)
        else badnum (x2:xs)
badnum _ = 0

res_function :: String -> String

res_function = show . badnum . sort . strtoInt

main = do
    hSetBuffering stdin LineBuffering
    tmp <- getLine
    tmp2 <- getLine
    putStrLn  (res_function tmp2)

import Data.List

solve :: [Int] -> Int
solve (n:xs) = n - (length (takeWhile (<= n) values))
    where values = head $ group $ sort $ xs

main = interact $ show.solve.map read.words


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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

main = do
	n <- readInt
	as <- readInts
	let
		positions = map snd $ sort $ zip as [ 0 .. ]
	print $ solve ( 0, 0 ) positions

solve a b = solve' 0 a b

solve' res _ [] = res
solve' res ( x, y ) ( a : b : rest ) =　res `seq` solve' ( res + min d1 d2 ) ( a, b ) rest
	where
		d1 = abs ( a - x ) + abs ( b - y )
		d2 = abs ( b - x ) + abs ( a - y )

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

main = do
	n <- readInt
	as <- readInts
	let
		positions = map snd $ sort $ zip as [ 0 .. ]
	print $ solve ( 0, 0 ) positions

solve a b = solve' 0 a b

solve' res _ [] = res
solve' res ( x, y ) ( a : b : rest ) = solve' ( res + min d1 d2 ) ( a, b ) rest
	where
		d1 = abs ( a - x ) + abs ( b - y )
		d2 = abs ( b - x ) + abs ( a - y )

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

main = do
	n <- readInt
	as <- readInts
	let
		positions = map snd $ sort $ zip as [ 0 .. ]
	print $ solve ( 0, 0 ) positions

solve _ [] = 0
solve ( x, y ) ( a : b : rest ) = min d1 d2 + solve ( a, b ) rest
	where
		d1 = abs ( a - x ) + abs ( b - y )
		d2 = abs ( b - x ) + abs ( a - y )

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

main = do
	n <- readInt
	as <- readInts
	let
		positions = map snd $ sort $ zip as [ 0 .. ]
	print $ solve ( 0, 0 ) positions

solve a b = solve' 0 a b

solve' !res _ [] = res
solve' !res ( x, y ) ( a : b : rest ) = res `seq` solve' ( res + min d1 d2 ) ( a, b ) rest
	where
		d1 = abs ( a - x ) + abs ( b - y )
		d2 = abs ( b - x ) + abs ( a - y )

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

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

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

import qualified Data.ByteString.Char8 as B

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

-- import Debug.Trace
import Text.Printf

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

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

main = do
	n <- readInt
	as <- readInts
	let
		positions = map snd $ sort $ zip as [ 0 .. ]
	print $ solve ( 0, 0 ) positions

solve a b = solve' 0 a b

solve' !res _ [] = res
solve' !res !( x, y ) ( a : b : rest ) = solve' ( res + min d1 d2 ) ( a, b ) rest
	where
		d1 = abs ( a - x ) + abs ( b - y )
		d2 = abs ( b - x ) + abs ( a - y )

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

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA

import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

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

---- Answer Code Section ----

process :: Int -> Map Int [Int] -> Integer
process n tiers = l where
    (_, l) = foldl walk ((1, 1), 0 :: Integer) [1..n]
    dist a b = abs (a - b)
    walk ((p1, p2), l) n = ret where
        [d1, d2] = tiers Map.! n
        case1 = dist p1 d1 + dist p2 d2
        case2 = dist p1 d2 + dist p2 d1
        ret = if case1 < case2 then ((d1, d2), l + toInteger case1) else ((d2, d1), l + toInteger case2)

main = do
    n <- getInt
    tiers <- makeMap n <$> getInts :: IO (Map Int [Int])
    print $ process n tiers

makeMap n (tiers ::[Int]) = foldl (\m (i, tier) -> Map.update (Just . (:) i) tier m) initMap (zip [1..] tiers) where
    initMap = Map.fromList $ zip [1..n] (repeat [])

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

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA

import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

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

---- Answer Code Section ----

process :: Int -> Map Int [Int] -> Int
process n tiers = l1 + l2 where
    (tiers', _, l1) = foldl firstWalk (tiers , 1, 0) [1..n]
    (_     , _, l2) = foldl secondWalk (tiers', 1, 0) [1..n]
    dist a b = abs (a - b)
    firstWalk (m :: Map Int [Int], p, l) n = (m', p', l') where
        [d1, d2] = m Map.! n
        (dest, rest) = if dist p d1 < dist p d2 then (d1, d2) else (d2, d1)
        m' = Map.update (const $ Just [rest]) n m
        p' = dest
        l' = l + dist p p'
    secondWalk (m, p, l) n = (m, p', l') where
        [d] = m Map.! n
        p' = d
        l' = l + dist p p'

main = do
    n <- getInt
    tiers <- makeMap n <$> getInts :: IO (Map Int [Int])
    print $ process n tiers

makeMap n (tiers ::[Int]) = foldl (\m (i, tier) -> Map.update (Just . (:) i) tier m) initMap (zip [1..] tiers) where
    initMap = Map.fromList $ zip [1..n] (repeat [])

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

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA

import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

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

---- Answer Code Section ----

process :: Int -> Map Int [Int] -> Int
process n tiers = l where
    (_, l) = foldl walk ((1, 1), 0) [1..n]
    dist a b = abs (a - b)
    walk ((p1, p2), l) n = ret where
        [d1, d2] = tiers Map.! n
        case1 = dist p1 d1 + dist p2 d2
        case2 = dist p1 d2 + dist p2 d1
        ret = if case1 < case2 then ((d1, d2), l + case1) else ((d2, d1), l + case2)

main = do
    n <- getInt
    tiers <- makeMap n <$> getInts :: IO (Map Int [Int])
    print $ process n tiers

makeMap n (tiers ::[Int]) = foldl (\m (i, tier) -> Map.update (Just . (:) i) tier m) initMap (zip [1..] tiers) where
    initMap = Map.fromList $ zip [1..n] (repeat [])


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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  diff -sdu -- <(cat -- input.txt | ./a.out) output.txt  &&  cat -- *.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

import Prelude
import Control.Monad
import Data.List
import Data.Array

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

    (putStr . unlines . map (concat . map ((++" ").show) . solve)) tcs

readTC = do
    [n,m] <- map read . words <$> getLine    :: IO [Int]
    return (n,m)

solve (n,m) | (n < m)   = solve (m,n)
            | otherwise = sort fld
  where
    (offV, offV_e) = centerProps n
    (offH, offH_e) = centerProps m

    maxDistFromCenter = (offV_e - 1) + (offH_e - 1)

    fld = bfs maxDistFromCenter (n,m) (offV, offH) (offV_e, offH_e)

centerProps :: Int -> (Int, Int)
centerProps n = (i, i+w)
                -- offsets of the center (start, past the end)
  where
    i = (n-w) `div` 2

    w = case (n`mod`2) of 0 -> 2
                          1 -> 1
                          _ -> error "bad parity"

bfs x (n, m) (r_b, c_b) (r_e, c_e) = elems arr
  where
    arr = array ((0,0), (n-1,m-1))
                [((r,c), f (r,c)) | r <- [0..n-1],
                                    c <- [0..m-1]]

    f (r,c) | (r_b <= r && r < r_e &&
               c_b <= c && c < c_e)    = x
            | otherwise                = 1 + (arr ! iprev (r,c))

    iprev (r,c) | (r' /= r)  = (r', c )
                | (c' /= c)  = (r , c')
                | otherwise  = error "no prev cell"
      where
        r' = iprev1D (r_b,r_e) r
        c' = iprev1D (c_b,c_e) c

iprev1D (b,e) n | (n <  b)   = n+1
                | (n >= e)   = n-1
                | otherwise  = n

import Control.Monad
import Data.List

test :: IO ()
test = do
  [n, m] <- (<$>) read . words <$> getLine
  let a = (enumFromTo <*> (+ (m - 1))) <$> [0 .. n - 1]
  let grid = foldl1 (zipWith (zipWith max)) [a, reverse a, reverse <$> a, reverse $ reverse <$> a]
  let values = sort $ concat grid
  putStrLn $ unwords $ show <$> values

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

{-

1 2 3
2 3 4
3 4 5
4 5 6

4 5 6
3 4 5
2 3 4
1 2 3

3 2 1
4 3 2
5 4 3
6 5 4

6 5 4
5 4 3
4 3 2
3 2 1

6 5 6
5 4 5
5 4 5
6 5 6

-}

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

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n, m] <- getInts 2
    pure $ putInts $ sort [ (max i (n-1-i)) + (max j (m-1-j)) | i <- [0..n-1], j <- [0..m-1]]

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

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  diff -sdu -- <(cat -- input.txt | ./a.out) output.txt  &&  cat -- *.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

import Prelude
import Control.Monad
import Data.List

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

          (putStr . unlines . map (concat . map ((++" ").show) . solve)) tcs

readTC = do [n,m] <- map read . words <$> getLine    :: IO [Int]
            return (n,m)

solve (n,m) = sort [md n r + md m c | r <- [1..n],
                                      c <- [1..m]]
md n r = max (r-1) (n-r)

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

-- (ghc -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  diff -sdu -- <(cat -- input.txt | ./a.out) output.txt  &&  cat -- *.hs | xclip -selection clipboard  &&  echo COPIED  ||  echo ERROR)

import Prelude
import Control.Monad
import Data.List
import Data.Array

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

    (putStr . unlines . map (concat . map ((++" ").show) . solve)) tcs

readTC = do
    [n,m] <- map read . words <$> getLine    :: IO [Int]
    return (n,m)

solve (n,m) | (n < m)   = solve (m,n)
            | otherwise = sort fld
  where
    (offV, _lenV, offV_e) = centerProps n
    (offH, _lenH, offH_e) = centerProps m

    maxDistFromCenter = (offV_e - 1) + (offH_e - 1)

    fld = bfs maxDistFromCenter (n,m) (offV, offH) (offV_e, offH_e)

centerProps :: Int -> (Int, Int, Int)
centerProps n = (i, w, i+w)
                -- offset and length of the center,
                -- also offset past the center
  where
    i = (n-w) `div` 2

    w = case (n`mod`2) of 0 -> 2
                          1 -> 1
                          _ -> error "bad parity"

bfs x (n, m) (r_b, c_b) (r_e, c_e) = elems arr
  where
    arr = array ((0,0), (n-1,m-1))
                [((r,c), f (r,c)) | r <- [0..n-1],
                                    c <- [0..m-1]]

    f (r,c) | (r_b <= r && r < r_e &&
               c_b <= c && c < c_e)    = x
            | otherwise                = 1 + (arr ! iprev (r,c))

    iprev (r,c) | (r' /= r)  = (r', c )
                | (c' /= c)  = (r , c')
                | otherwise  = error "no prev cell"
      where
        r' = iprev1D (r_b,r_e) r
        c' = iprev1D (c_b,c_e) c

iprev1D (b,e) n | (n <  b)   = n+1
                | (n >= e)   = n-1
                | otherwise  = n


import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Control.Monad
import Control.Monad.ST.Safe
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  getLine >>= \ns -> C.getLine >>= \bs -> let [f1,f2] = map read $ words ns in (mapM_ print).(solve f1 bs) =<< (forM [1..f2] $ \ i ->C.getLine>>= \js -> let [a,b] = C.words js in return $ (fst $ fromJust $ C.readInt a,C.head b) )
solve n xs1 xs2 = map (snd) $ tail $ scanl f (ms,s) xs2
  where
  ms=Map.fromList $ [(0,'a')] ++ (zip [1..] $ C.unpack xs1) ++ [(n+1,'a')]
  s=sum $ map (\a -> C.length a -1 ) $ C.groupBy (\a b -> a==b && a=='.') xs1
  f (b1,b2) (a1,a2) | (a2=='.' && b1 Map.! a1=='.') || (a2/='.' && b1 Map.! a1/='.')  = (Map.insert a1 a2 b1, b2)
                    | a2=='.' && b1 Map.! (a1-1)=='.' &&  b1 Map.! (a1+1)=='.'        = (Map.insert a1 a2 b1, b2+2)
                    | a2/='.' && b1 Map.! (a1-1)=='.' &&  b1 Map.! (a1+1)=='.'        = (Map.insert a1 a2 b1, b2-2)
                    | a2=='.' && (b1 Map.! (a1-1)=='.' ||  b1 Map.! (a1+1)=='.')      = (Map.insert a1 a2 b1, b2+1)
                    | a2/='.' && (b1 Map.! (a1-1)=='.' ||  b1 Map.! (a1+1)=='.')      = (Map.insert a1 a2 b1, b2-1)
                    | otherwise  = (Map.insert a1 a2 b1, b2)

{-# LANGUAGE BangPatterns, RecordWildCards #-}

import Control.Monad
import Data.Bits
import Data.Maybe
import qualified Data.ByteString.Char8 as B

data Tree =
    Leaf !Char |
    Node {
        left    :: !Tree,
        right   :: !Tree,
        _size   :: !Int,
        _prefix :: !Int,
        _suffix :: !Int,
        _count  :: !Int
    }

size (Leaf _)    = 1
size (Node {..}) = _size

prefix (Leaf '.')  = 1
prefix (Leaf _)    = 0
prefix (Node {..}) = _prefix

suffix (Leaf '.')  = 1
suffix (Leaf _)    = 0
suffix (Node {..}) = _suffix

count (Leaf _)    = 0
count (Node {..}) = _count

dotsOnly (Leaf '.')  = True
dotsOnly (Leaf _)    = False
dotsOnly (Node {..}) = _prefix == _size

make left right = Node left right newSize newPrefix newSuffix newCount
    where
    newSize   = size left + size right
    newPrefix = prefix left + if dotsOnly left then prefix right else 0
    newSuffix = suffix right + if dotsOnly right then suffix left else 0
    newCount  = count left + count right + joint
    joint     = if suffix left > 0 && prefix right > 0 then 1 else 0

construct s
    | B.length s == 1 = Leaf $ B.head s
    | otherwise =
        let (left, right) = B.splitAt (B.length s `unsafeShiftR` 1) s
        in make (construct left) (construct right)

update c = update'
    where
    update' (Leaf _) !_ = Leaf c
    update' (Node {..}) !i
        | i < size left = make (update' left i) right
        | otherwise     = make left (update' right (i - size left))

run 0 !_ = return ()

run q !tree = do
    (i, tl) <- liftM (fromJust . B.readInt) B.getLine
    let next = update (tl `B.index` 1) tree (i - 1)
    putStrLn $ show $ count next
    run (q - 1) next

main = do
    m <- liftM (fst . fromJust . B.readInt . head . tail . B.split ' ') B.getLine
    B.getLine >>= run m . construct

{-# LANGUAGE OverloadedStrings #-}
import Data.Maybe (fromJust)
import Control.Applicative ((<$>))
import Control.Monad (replicateM, forM)
import Control.Arrow (second)
import Data.List (group)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

import Data.Array.Unboxed (UArray, listArray)
import Control.Monad.ST.Strict (ST, runST)
import Data.Array.ST (STUArray,readArray, writeArray, thaw)
import Data.STRef (newSTRef, readSTRef, writeSTRef)

update :: Int -> Bool -> (Bool, Bool, Bool) -> Int
update val t (x, y, z)
    | t == y    = val
    | t         = val + inc
    | otherwise = val - inc
    where inc = (if x then 1 else 0) + if z then 1 else 0

solve :: Int -> UArray Int Bool -> [(Int, Bool)] -> [Int]
solve val' arr' query = runST $ do
    arr <- thaw arr' :: ST s (STUArray s Int Bool)
    val <- newSTRef val'

    forM query $ \(i, t) -> do
        x <- readArray arr $ pred i
        y <- readArray arr i
        z <- readArray arr $ succ i
        cur <- readSTRef val

        writeSTRef val $ update cur t (x, y, z)
        writeArray arr i t
        readSTRef val

wrap :: Int -> ByteString -> [ByteString] -> [Int]
wrap n line query = solve val arr mut
    where
    mut = second pred . fromJust . C.readInt <$> query
        where pred = (== " .") . C.take 2

    arr = listArray (0, n + 1) run
    run = False: C.foldr (\i acc -> (i == '.'):acc) [False] line
    val = sum . map (pred . length) . filter head . group $ run

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = do
    [n, m] <- parse <$> B.getLine
    line   <- C.take n <$> B.getLine
    query  <- replicateM m B.getLine
    mapM_ print $ wrap n line query

{-# LANGUAGE OverloadedStrings #-}
import Data.Maybe (fromJust)
import Control.Applicative ((<$>))
import Control.Monad (replicateM, forM)
import Control.Arrow (second)
import Data.List (group)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

import Data.Array.Unboxed (UArray, listArray)
import Control.Monad.ST.Strict (ST, runST)
import Data.Array.ST (STUArray,readArray, writeArray, thaw)

count :: Bool -> [Bool] -> Int
count t xs = if t then inc else -inc
    where inc = length $ filter id xs

solve :: Int -> UArray Int Bool -> [(Int, Bool)] -> [Int]
solve val inp query = tail . scanl (+) val $ runST $ do
    arr <- thaw inp :: ST s (STUArray s Int Bool)

    forM query $ \(i, t) -> do
        xi <- readArray arr i
        if xi == t
        then return 0
        else do
            a <- readArray arr $ pred i
            b <- readArray arr $ succ i
            writeArray arr i t
            return $ count t [a, b]

wrap :: Int -> ByteString -> [ByteString] -> [Int]
wrap n line query = solve val arr mut
    where
    mut = second pred . fromJust . C.readInt <$> query
        where pred = (== " .") . C.take 2

    arr = listArray (0, n + 1) run
    run = False: C.foldr (\i acc -> (i == '.'):acc) [False] line
    val = sum . map (pred . length) . filter head . group $ run

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = do
    [n, m] <- parse <$> B.getLine
    line   <- C.take n <$> B.getLine
    query  <- replicateM m B.getLine
    mapM_ print $ wrap n line query

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Control.Monad
import Control.Monad.ST.Safe
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  getLine >>= \ns -> C.getLine >>= \bs -> let [f1,f2] = map read $ words ns in (mapM_ print).(solve f1 bs) =<< (forM [1..f2] $ \ i ->C.getLine>>= \js -> let [a,b] = C.words js in return $ (fst $ fromJust $ C.readInt a,C.head b) )
solve n xs1 xs2 = map (snd) $ tail $ scanl f (ms,s) xs2
  where
  ms=Map.fromList $ [(0,'a')] ++ (zip [1..] $ C.unpack xs1) ++ [(n+1,'a')]
  s=sum $ map (\a -> C.length a -1 ) $ C.groupBy (\a b -> a==b && a=='.') xs1
  f (b1,b2) (a1,a2) | a2=='.' && b1 Map.! (a1-1)=='.' &&  b1 Map.! (a1+1)=='.'     = (Map.insert a1 a2 b1, b2+2)
                    | a2/='.' && b1 Map.! (a1-1)=='.' &&  b1 Map.! (a1+1)=='.'     = (Map.insert a1 a2 b1, b2-2)
                    | a2=='.' && (b1 Map.! (a1-1)=='.' ||  b1 Map.! (a1+1)=='.')   = (Map.insert a1 a2 b1, b2+1)
                    | a2/='.' && (b1 Map.! (a1-1)=='.' ||  b1 Map.! (a1+1)=='.')   = (Map.insert a1 a2 b1, b2-1)
                    | otherwise                                                    = (Map.insert a1 a2 b1, b2)

{-# LANGUAGE OverloadedStrings #-}
import Data.Maybe (fromJust)
import Control.Applicative ((<$>))
import Control.Monad (replicateM, forM)
import Control.Arrow (second)
import Data.List (group)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

import Data.Array.Unboxed (UArray, listArray)
import Control.Monad.ST.Strict (ST, runST)
import Data.Array.ST (STUArray,readArray, writeArray, thaw)
import Data.STRef (newSTRef, readSTRef, writeSTRef)

update :: Int -> Bool -> (Bool, Bool, Bool) -> Int
update val t (x, y, z)
    | t == y    = val
    | t         = val + inc
    | otherwise = val - inc
    where inc = (if x then 1 else 0) + if z then 1 else 0

solve :: Int -> UArray Int Bool -> [(Int, Bool)] -> [Int]
solve val' arr' query = runST $ do
    arr <- thaw arr' :: ST s (STUArray s Int Bool)
    val <- newSTRef val'

    forM query $ \(i, t) -> do
        x <- readArray arr $ pred i
        y <- readArray arr i
        z <- readArray arr $ succ i
        cur <- readSTRef val

        writeSTRef val $ update cur t (x, y, z)
        writeArray arr i t
        readSTRef val

wrap :: Int -> ByteString -> [ByteString] -> [Int]
wrap n line query = solve val arr mut
    where
    mut = second (== " .") . fromJust . C.readInt <$> query
    arr = listArray (0, n + 1) run
    run = False: C.foldr (\i acc -> (i == '.'):acc) [False] line
    val = sum . map (pred . length) . filter head . group $ run

parse :: ByteString -> [Int]
parse line = fst . fromJust . C.readInt <$> C.words line

main = do
    [n, m] <- parse <$> B.getLine
    line   <- B.getLine
    query  <- replicateM m B.getLine
    mapM_ print $ wrap n line query


solve :: [Int] -> [String]
solve [x, y, a, b] =
  let variants = [[i, j] | i <- [a .. x], j <- [b .. y], i > j]
  in (show $ length variants):(map (unwords . map show) variants)

main = interact $ unlines . solve . map read . words

main = do
	x <- getLine
	putStrLn $ show $ length $ res x
	putStrLn $ unlines $ map (\(a,b) -> unwords [show a, show b]) $ res x
	where
		res = f . map (\a -> read a::Int) . words

f :: [Int] -> [(Int, Int)]
f [a,b,c,d] = [(x,y) | x <- [c..a], y<-[d..b], x>y]

import Control.Monad (liftM)

solve :: [Int] -> [(Int, Int)]
solve [x, y, a, b]  =  [(i, j) | i <- [a .. x], j <- [b .. y], i > j]

prints :: (Show a, Show b) => [(a, b)] -> IO ()
prints xs  =  print (length xs) >> mapM_ prints' xs
  where
    prints' (a, b)  =  putStrLn $ show a ++ " " ++ show b

main :: IO ()
main  =  liftM (map read . words) getLine >>= prints . solve

import Data.List

main = do
    [x,y,a,b] <- fmap (map read . words) getLine
    let pairs = solve [x,y,a,b]
    print $ length pairs
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) pairs

solve :: [Integer] -> [(Integer,Integer)]
solve [x,y,a,b] = sort [(f,g) | f <- [a..x], g <- [b..y], f > g]

main = do
  [x,y,a,b] <- fmap (map read.words) getLine
  let ans = [unwords$map show[sv,sp]|sv<-[a..x],sp<-[b..y],sv>sp+0]
  print $ length ans
  putStrLn $ unlines ans

main = interact $ unlines . map (unwords . map show) . solve . map read . words
solve [x, y, a, b] = [length out] : out
  where out = [[c, d] | c <- [a..x], d <- [b..y], c > d]

import Data.List
main = solve.map read.words =<< getLine
solve :: [Int] -> IO ()
solve [x,y,a,b] = do
    let s = sln a b x y
    print $ length s
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) s
sln a b x y = concatMap f [a..x]
    where f n = [(n,d) | d <- takeWhile (\x' -> x' <= y) [b..], d < n]

main = do
  [x, y, a, b] <- fmap (map read . words) getLine
  let z = [[i, j] | i <- [a .. x], j <- [b .. y], i > j] :: [[Int]]
  print $ length $ z
  putStr $ unlines $ map (unwords . map show) z

main = interact $ unlines . map (unwords . map show) . solve . map read . words

solve [x, y, a, b] = [length outcomes] : outcomes
  where
  outcomes = [[c, d] | c <- [a..x], d <- [b..y], c > d]

import Data.List
main = solve.map read.words =<< getLine
solve [x,y,a,b] = do
    let s = sln a b x y
    print $ length s
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) s
sln a b x y = concatMap f [(min (b+1) a) .. x]
    where f n = [(n,d) | d <- takeWhile (\x' -> x' <= y) [b..], d < n]

import Data.List
main = solve.map read.words =<< getLine
solve [x,y,a,b] = do
    let s = sln a b x y
    print $ length s
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) s
sln a b x y = concatMap f [(min (b+1) a) .. x]
    where f n = [(n,d) | d <- takeWhile (\x' -> x' <= y && x' < n) [b..], d < n]

import Data.List
main = solve.map read.words =<< getLine
solve [x,y,a,b] = do
    let s = sln a b x y
    print $ length s
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) s
sln a b x y = concatMap f [(min (b+1) a) .. x]
    where f n = [(n,d) | d <- takeWhile (\x' -> x' <= y && x' < n+1) [b..], d < n]

import Data.List
main = solve.map read.words =<< getLine
solve [x,y,a,b] = do
    let s = sln a b x y
    print $ length s
    mapM_ (\(x,y) -> putStrLn $ show x ++ " " ++ show y) s
sln a b x y = concatMap f [(min (b+1) a) .. x]
    where f n = [(n,d) | d <- takeWhile (\x' -> x' <= y && x' < n-1) [b..], d < n]

import Control.Monad (liftM)

solve :: [Int] -> [(Int, Int)]
solve [x, y, a, b]  =  [(i, j) | i <- [a .. x], j <- [b .. y], i > j]

prints :: (Show a, Show b) => [(a, b)] -> IO ()
prints xs  =  mapM_ prints' xs
  where
    prints' (a, b)  =  putStrLn $ show a ++ " " ++ show b

main :: IO ()
main  =  liftM (map read . words) getLine >>= prints . solve


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

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

main :: IO ()
main = do
  _ <- C.getLine
  (as : ass) <- replicateM 4 (fmap (zip [1..]) getInts)
  let
    cmp (_, c1) (_, c2) = compare c1 c2
    trans pres edges nexts (j, cost) =
      case filter (\(i, _) -> S.notMember (i, j) edges) pres of
        ((_, c) : _) -> (j, c + cost) : nexts
        _ -> nexts
    acc pres ys = do
      [m] <- getInts
      edges <- S.fromList <$> replicateM m (getInts >>= \[i, j] -> return (i, j))
      return $ sortBy cmp $ foldl' (trans pres edges) [] ys
  results <- foldM acc (sortBy cmp as) ass
  putStrLn $ if null results then "-1" else show $ snd $ head results

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

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

import Data.Array.Unboxed
import qualified Data.IntMap.Strict as Map

type SIO = StateT P.ByteString IO

sentinel :: Int
sentinel = 5 * 10 ^ (8 :: Int)

step :: UArray Int Int -> [(Int, Int)] -> UArray Int Int -> UArray Int Int
step prevCosts excls currCosts = let
  initMap = Map.fromListWith (+) $ zip (sentinel : elems prevCosts) (repeat 1)
  updateFun 1 = Nothing
  updateFun v = Just (v - 1)
  remove = flip $ Map.update updateFun
  exclusionResults :: Array Int (Map.IntMap Int)
  exclusionResults = accumArray remove initMap (bounds currCosts)
    $ [(yi, prevCosts ! xi) | (xi, yi) <- excls]
  in  array (bounds currCosts) $ do
  (i, v) <- assocs currCosts
  let  nv = v + fst (Map.findMin $ exclusionResults ! i)
  pure (i, min sentinel nv)

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  ns <- readInts
  [a, b, c, d] <- forM ns $ \ni -> listArray (1, ni) <$> readInts
  [excl1, excl2, excl3] <- replicateM 3 $ do
    [mi] <- readInts
    replicateM mi $ do
      [xi, yi] <- readInts
      pure (xi, yi)
  let
    s2 = step a excl1 b
    s3 = step s2 excl2 c
    s4 = step s3 excl3 d
    ans = case  foldl' min sentinel $ elems s4  of
      v | v == sentinel -> 0-1
        | otherwise -> v
  putInts [ans]

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

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

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

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

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Array
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable
import System.IO

------

type Hopper r = State [r]

type HopperT r = StateT [r]

runHopper :: Hopper r a -> [r] -> (a, [r])
runHopper = runState

evalHopper :: Hopper r a -> [r] -> a
evalHopper = evalState

runHopperT :: HopperT r m a -> [r] -> m (a, [r])
runHopperT = runStateT

evalHopperT :: Monad m => HopperT r m a -> [r] -> m a
evalHopperT = evalStateT

type MonadHopper r m = MonadState [r] m

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

popJust :: MonadHopper r m => m r
popJust = fromJust <$> pop

------

popInt :: MonadHopper B.ByteString m => m Int
popInt = fst . fromJust . B.readInt <$> popJust

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

popInteger :: MonadHopper B.ByteString m => m Integer
popInteger = fst . fromJust . B.readInteger <$> popJust

popIntegers :: MonadHopper B.ByteString m => m [Integer]
popIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust

------

dropCR :: B.ByteString -> B.ByteString
dropCR s | not (B.null s) && B.last s == '\r' = B.init s
         | otherwise = s

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

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

------

run :: Hopper B.ByteString B.ByteString
run = do
  ~[n1, n2, n3, n4] <- popInts
  a <- popInts
  b <- popInts
  c <- popInts
  d <- popInts
  ab <- popPairs n1
  bc <- popPairs n2
  cd <- popPairs n3
  return $ bshow (solve n1 n2 n3 n4 a b c d ab bc cd) <> "\n"

  where
    popPairs n = do
      m <- popInt
      buildPairs n <$> replicateM m ((\ ~[x, y] -> (x - 1, y - 1)) <$> popInts)

    buildPairs n ps = IntSet.fromList <$> accumArray (flip (:)) [] (0, n - 1) ps

inf = (maxBound :: Int)

third (_, _, x) = x

solve :: Int -> Int -> Int -> Int -> [Int] -> [Int] -> [Int] -> [Int] ->
         Array Int IntSet -> Array Int IntSet -> Array Int IntSet -> Int
solve n1 n2 n3 n4 a b c d ab bc cd =
  case sortOn snd $ id' of
    [] -> -1
    ((_, v):_) -> v

  where
    ia :: [(Int, Int)]
    ia = sortOn snd $ zip [0..] a

    ib :: [(Int, Int)]
    ib = makeI ia n2 b ab

    ic :: [(Int, Int)]
    ic = makeI ib n3 c bc

    id' :: [(Int, Int)]
    id' = makeI ic n4 d cd

    makeI :: [(Int, Int)] -> Int -> [Int] -> Array Int IntSet -> [(Int, Int)]
    makeI is jn jv bans =
      sortOn snd $
      map (\(i, x, y) -> (i, x + y)) $
      filter ((/= inf) . third) $
      zip3 [0..] jv $
      make bans is [0 .. jn - 1]

    make :: Array Int IntSet -> [(Int, Int)] -> [Int] -> [Int]
    make bans is js = map snd $ sort $ makeV [] bans is js

    makeV :: [(Int, Int)] -> Array Int IntSet -> [(Int, Int)] -> [Int] ->
             [(Int, Int)]
    makeV acc _ [] js = (zip js $ repeat inf) ++ acc
    makeV acc _ _ [] = acc
    makeV acc bans ((i, x) : is) js = makeV' acc bans i x is js []

    makeV' :: [(Int, Int)] -> Array Int IntSet -> Int -> Int -> [(Int, Int)] ->
              [Int] -> [Int] -> [(Int, Int)]
    makeV' acc bans i x is [] js' = makeV acc bans is js'
    makeV' acc bans i x is (j : js) js'
      | IntSet.member j (bans ! i) = makeV' acc bans i x is js (j : js')
      | otherwise = makeV' ((j, x) : acc) bans i x is js js'


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

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Monoid
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.Base
import Data.Function(on)
import Data.Tuple(swap)
import qualified Data.Map as M
import qualified Data.IntMap as IM
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

solve :: Int -> [Int] -> IM.IntMap Int
solve 0 _ = IM.empty
solve 1 (p:_) = IM.singleton p (p+1)
solve n ps = merge (solve n1 ps) (solve n2 (drop n1 ps)) where
    n1 = div n 2
    n2 = n - n1

merge :: IM.IntMap Int -> IM.IntMap Int -> IM.IntMap Int
merge l1 l2 = uncurry IM.union $ go ((,) l2 (IM.empty)) l1 where
    go = IM.foldlWithKey' $ \(!m,!acc) a b ->
        case IM.lookup b m of
            Just c  -> (,) (IM.delete b m) (IM.insert a c acc)
            Nothing -> (,) m (IM.insert a b acc)

main :: IO ()
main = do
    n <- readLn
    ps <- readInts
    let l = solve n ps
    let d = IM.foldlWithKey' (\acc a b -> max acc (b - a)) 0 l
    print $ n - d

-- IO
readInt :: B.ByteString -> Int
readInt = fromJust . fmap fst . B.readInt
readInts :: IO [Int]
readInts = map readInt . B.words <$> B.getLine
readIntPair :: IO (Int,Int)
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readAllInts :: IO [[Int]]
readAllInts = map (map readInt . B.words) . B.lines <$> B.getContents
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine

-- Utilities
l2p :: [a] -> (a,a)
l2p (a:b:_) = (a,b)
l2p _ = error "l2p: the input list is too short"
p2l :: (a,a) -> [a]
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
inf :: Int
inf = maxBound `div` 2

-- Monad
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i0 judge incr step = sub i0 where
    sub i | judge i = step i >> sub (incr i)
          | otherwise = return ()
rep_ :: Monad m => Int -> (Int -> m ()) -> m ()
rep_ n = stepM_ 0 (<n) (+1)
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
memoize :: (Monad m) => (k -> m (Maybe v)) -> (k -> v -> m ()) -> k -> m v -> m v
memoize getter setter key action = do
    mv <- getter key
    case mv of
        Just v -> return v
        Nothing -> action >>= thru (setter key)

-- Array
newUArray :: (MArray (STUArray s) e (ST s),Ix i) =>
             (i,i) -> e -> ST s (STUArray s i e)
newUArray = newArray
newBArray :: (Ix i) => (i,i) -> e -> ST s (STArray s i e)
newBArray = newArray
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
fromEdges :: Ix i => (i,i) -> [(i,e)] -> Array i [e]
fromEdges = accumArray (flip (:)) []

import Data.List.Split (splitOn)
import Data.List

longestsubsequence :: [(Int, Int)] -> (Int, Int) -> Int -> Int -> Int

longestsubsequence [] prev count maxi   = maxi
longestsubsequence (x:xs) prev count maxi
    | snd prev < snd x                  = longestsubsequence xs x (count+1) thus
    | snd prev > snd x && count > maxi  = longestsubsequence xs x 1 count
    | otherwise                         = longestsubsequence xs x 1 maxi
        where thus = if (count+1) > maxi then count+1 else maxi
main = do
    asd <- getLine
    dsa <- getLine
    let amount = read asd :: Int
    let sequence = [read x :: Int | x <- splitOn " " dsa]
    let sortedlist = sort (zip sequence [0..])
    putStrLn (show (amount - longestsubsequence (tail sortedlist) (head sortedlist) 1 1))

{-
Codeforces Round #335

Problem 606 C. Sorting Railway

@author yamaton
@date 2015-12-11
-}

import Control.Applicative
import Control.Monad
-- import Text.Printf (printf)
import qualified Data.List as L
-- import qualified Data.Map.Strict as M
-- import qualified Data.Set as S
-- import qualified Data.Foldable as F
-- import qualified Data.Traversable as T

-- Longest contiguous increasing sequence length
lcis :: Ord a => [a] -> Int
lcis []     = 0
lcis (x:xs) = helper 1 1 x xs
  where
    helper :: Ord a => Int -> Int -> a -> [a] -> Int
    helper best _    _ []    = best
    helper best curr p (q:qs)
      | p <= q    = helper (max best curr_p1) curr_p1 q qs
      | otherwise = helper best               1       q qs
      where curr_p1 = curr + 1

invPerm :: [Int] -> [Int]
invPerm xs = map snd . L.sort $ zip xs [1..]

solve :: [Int] -> Int -> Int
solve xs n = n - lcis (invPerm xs)

main :: IO ()
main = do
    n <- readLn :: IO Int
    xs <- (map read . words) <$> getLine :: IO [Int]
    let result = solve xs n
    print result

    -- IO.hPutStrLn IO.stderr $ printf "xs = %s" (show xs)
    -- IO.hPutStrLn IO.stderr $ printf "result = %d" result

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

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

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

groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy' _   []                        = []
groupBy' _   [x]                       = [[x]]
groupBy' cmp (x:xs@(x':_)) | cmp x x'  = (x:y):ys
                           | otherwise = [x]:r
                           where r@(y:ys) = groupBy' cmp xs

main = do
  n <- readLn
  xs <- getInts :: IO [Int]

  print $ minimum $ map (\x -> n-x) $ map length $ groupBy' (<=) $ elems $ array (1, n) $ zip xs [1..]

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

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Monoid
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.Base
import Data.Function(on)
import Data.Tuple(swap)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

solve :: [Int] -> [(Int,Int)]
solve [] = []
solve [p] = [(p,p+1)]
solve ps = merge (solve ps1) (solve ps2) where
    n = length ps
    (ps1,ps2) = splitAt (div n 2) ps

merge :: [(Int,Int)] -> [(Int,Int)] -> [(Int,Int)]
merge l1 l2 = go (M.fromList l2) l1 where
    go m [] = M.toList m
    go m ((a,b):l) =
        case M.lookup b m of
            Just c -> (a,c) : go (M.delete b m) l
            Nothing -> (a,b) : go m l

main :: IO ()
main = do
    n <- readLn
    ps <- readInts
    let l = solve ps
    print $ n - maximum [ b - a | (a,b) <- l ]

-- IO
readInt :: B.ByteString -> Int
readInt = fromJust . fmap fst . B.readInt
readInts :: IO [Int]
readInts = map readInt . B.words <$> B.getLine
readIntPair :: IO (Int,Int)
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readAllInts :: IO [[Int]]
readAllInts = map (map readInt . B.words) . B.lines <$> B.getContents
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine

-- Utilities
l2p :: [a] -> (a,a)
l2p (a:b:_) = (a,b)
l2p _ = error "l2p: the input list is too short"
p2l :: (a,a) -> [a]
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
inf :: Int
inf = maxBound `div` 2

-- Monad
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i0 judge incr step = sub i0 where
    sub i | judge i = step i >> sub (incr i)
          | otherwise = return ()
rep_ :: Monad m => Int -> (Int -> m ()) -> m ()
rep_ n = stepM_ 0 (<n) (+1)
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
memoize :: (Monad m) => (k -> m (Maybe v)) -> (k -> v -> m ()) -> k -> m v -> m v
memoize getter setter key action = do
    mv <- getter key
    case mv of
        Just v -> return v
        Nothing -> action >>= thru (setter key)

-- Array
newUArray :: (MArray (STUArray s) e (ST s),Ix i) =>
             (i,i) -> e -> ST s (STUArray s i e)
newUArray = newArray
newBArray :: (Ix i) => (i,i) -> e -> ST s (STArray s i e)
newBArray = newArray
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
fromEdges :: Ix i => (i,i) -> [(i,e)] -> Array i [e]
fromEdges = accumArray (flip (:)) []

import Data.List.Split (splitOn)
import Data.List

longestsubsequence :: [(Int, Int)] -> (Int, Int) -> Int -> Int -> Int

longestsubsequence [] prev count maxi   = maxi
longestsubsequence (x:xs) prev count maxi
    | snd prev < snd x                  = longestsubsequence xs x (count+1) maxi
    | snd prev > snd x && count > maxi  = longestsubsequence xs x 1 count
    | otherwise                         = longestsubsequence xs x 1 maxi

main = do
    asd <- getLine
    dsa <- getLine
    let amount = read asd :: Int
    let sequence = [read x :: Int | x <- splitOn " " dsa]
    let sortedlist = sort (zip sequence [0..])
    putStrLn (show (amount - longestsubsequence (tail sortedlist) (head sortedlist) 1 1))

import Data.List.Split (splitOn)
import Data.List

longestsubsequence :: [(Int, Int)] -> (Int, Int) -> Int -> Int -> Int

longestsubsequence [] prev count maxi   = maxi
longestsubsequence (x:xs) prev count maxi
    | snd prev < snd x                  = longestsubsequence xs x (count+1) maxi
    | snd prev > snd x && count > maxi  = longestsubsequence xs x 1 count
    | otherwise                         = longestsubsequence xs x 1 maxi

main = do
    asd <- getLine
    dsa <- getLine
    let amount = read asd :: Int
    let sequence = [read x :: Int | x <- splitOn " " dsa]
    let sortedlist = sort (zip sequence [0..])
    putStrLn (show (amount - longestsubsequence (tail sortedlist) (head sortedlist) 1 0))

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

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

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

groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy' _   []                        = []
groupBy' _   [x]                       = [[x]]
groupBy' cmp (x:xs@(x':_)) | cmp x x'  = (x:y):ys
                           | otherwise = [x]:r
                           where r@(y:ys) = groupBy' cmp xs

main = do
  n <- readLn
  xs <- getInts :: IO [Int]

  print $ minimum $ map (\x -> n-x) $ map length $ groupBy (<=) $ elems $ array (1, n) $ zip xs [1..]


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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

-- (ghc -Werror -Wno-error=unsafe -O1 -no-keep-o-files -no-keep-hi-files -rtsopts -o a.out *.hs  &&  set -o pipefail  &&  cat -- input.txt | ./a.out > tmp.txt  &&  diff -sdu -- output.txt tmp.txt  &&  cat -- tmp.txt)

import Prelude
import Control.Monad

main :: IO ()
main = do
    t <- readLn
    tcs <- replicateM t readLn :: IO [Integer]

    (putStr . unlines . map (showP . solve)) tcs

solve k | (b     <= k && k <= b+i-1  ) = (k-b+1, i        )
        | (b+i-1 <  k && k <  b+2*i-1) = (i,     b+2*i-1-k)
        | otherwise                    = error "bad b calculation?"
  where
    i = (floor.sqrt) (fromIntegral (k-1) :: Double) + 1
    b = (i-1)*(i-1) + 1

showP (a,b) = show a ++ " " ++ show b

import Control.Monad

getCellPosByIndex :: Integer -> (Integer, Integer)
getCellPosByIndex cell_index = (x, y)
    where
    wave_index = floorSqrt cell_index
    local_index = cell_index - wave_index ^ 2
    x = min wave_index (2 * wave_index - local_index)
    y = min wave_index local_index

floorSqrt :: Integer -> Integer
floorSqrt x = binarySearch 0 x
    where
    binarySearch l r
        | l == r = mid
        | mid ^ 2 <= x = binarySearch mid r
        | otherwise    = binarySearch l (mid-1)
        where mid = (l + r + 1) `div` 2

process_test :: String -> String
process_test input = output
    where
    k = read input
    (x, y) = getCellPosByIndex (k - 1)
    output = show (y+1) ++ " " ++ show (x+1)

main :: IO()
main = do
    tests_n <- read <$> getLine
    tests_inputs <- replicateM tests_n getLine
    let outputs = map process_test tests_inputs
    mapM_ putStrLn outputs

import Control.Monad

getCellPosByIndex :: Integer -> (Integer, Integer)
getCellPosByIndex cell_index = (x, y)
    where
        wave_index = floorSqrt cell_index
        local_index = cell_index - wave_index ^ 2
        x = min wave_index (2 * wave_index - local_index)
        y = min wave_index local_index

floorSqrt :: Integer -> Integer
floorSqrt x = binary_search 0 x
    where binary_search l r
              | l == r = mid
              | mid ^ 2 <= x = binary_search mid r
              | otherwise    = binary_search l (mid-1)
              where mid = (l + r + 1) `div` 2

process_test :: String -> String
process_test input = output
    where
        k = read input
        (x, y) = getCellPosByIndex (k - 1)
        output = show (y+1) ++ " " ++ show (x+1)

main :: IO()
main = do
    tests_n <- read <$> getLine
    tests_inputs <- replicateM tests_n getLine
    let outputs = map process_test tests_inputs
    mapM_ putStrLn outputs

import Control.Monad

getCellPosByIndex :: Integer -> (Integer, Integer)
getCellPosByIndex cell_index = (x, y)
    where i_wave = floorSqrt cell_index
          local_index = cell_index - i_wave ^ 2
          x = min (2*i_wave - local_index) i_wave
          y = min local_index i_wave

floorSqrt :: Integer -> Integer
floorSqrt i = fromIntegral $ length $ takeWhile (<= i) positive_squares
    where positive_squares = map (^2) [1..]

process_test :: String -> String
process_test input = output
    where k = read input
          (x, y) = getCellPosByIndex (k - 1)
          output = show (y+1) ++ " " ++ show (x+1)

main :: IO()
main = do
    tests_n <- read <$> getLine
    tests_inputs <- replicateM tests_n getLine
    let outputs = map process_test tests_inputs
    mapM_ putStrLn outputs

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

a002522_list = scanl (+) 1 [1, 3..] :: [Int64]

calc :: Int64 -> [Int64]
calc 1 = [1,1]
calc 2 = [1,2]
calc x =
  let first = dropWhile (\(i,an) -> an <= x) $ zip [1..] a002522_list
      ((m,an1):_) = first
      n = m-1
      an = (n-1)*(n-1)+1
  in
    if (x-an) <= ((an1-an) `div` 2) then
      [x-an+1, n]
    else
      [n, an1-x]

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let k = read line :: Int64
    putStrLn $ unwords $ map show $ calc k

position :: Int -> (Int, Int)
position n = let
  p | steps == 0 = (sqrtN, 1)
    | steps <= (sqrtN + 1) = (steps, sqrtN + 1)
    | otherwise = (sqrtN + 1, sqrtN * 2 + 2 - steps)
  in p
  where
    sqrtN = (floor . sqrt . fromIntegral) n
    steps = n - sqrtN ^ 2

loop :: Int -> IO()
loop 0 = return ()
loop n = do
    nth <- readLn :: IO Int
    let (r, c) = position nth
    putStrLn $ concat [show r, " ", show c]
    loop $ n - 1

main :: IO()
main = do
    input <- getLine
    let n = read input :: Int
    loop n

import Data.Function ((&))

main = do
    t <- read <$> getLine :: IO Int
    mapM_ main' [1..t]

main':: Int -> IO ()
main' _ = do
    k <- read <$> getLine :: IO Int
    solve k & show' & putStrLn

show' :: (Int, Int) -> String
show' (a, b) = show a ++ " " ++ show b

solve :: Int -> (Int, Int)
solve k
    | row == 0      = (l, 1)
    | row <= l + 1  = (row, l + 1)
    | otherwise     = (l + 1, col)
    where
        l = k & fromIntegral & sqrt & floor :: Int
        row = k - l * l
        col = (l + 1) * (l + 1) - k + 1

module Main where

import           Control.Monad (replicateM_)

main = do
  t <- read <$> getLine
  replicateM_ t
    $ do
      getLine
        >>= (\(x, y) -> putStrLn (show x ++ " " ++ show y)) . solve . read

solve :: Int -> (Int, Int)
solve k = (ij - max (diag - k) 0, ij - max (k - diag) 0)
  where
    ij = contSq k

    diag = ij ^ 2 - ij + 1

contSq :: Int -> Int
contSq x = until ((x <=) . (^ 2)) (+ 1) 1
{-
>>>contSq 100000000
10000

>>>solve 100000000
(10000,1)

(2,4)
-}

import Control.Monad
readInts = fmap (map read.words) getLine :: IO [Int]

printResult = do
    k <- readLn :: IO Integer
    let n =  ceiling $ sqrt $ fromInteger k
        a = n*n - k
        r = if a <= n - 1 then n else  n - (a - (n-1))
        c = if a <= n - 1 then a + 1 else n
    putStrLn . unwords . map show $ [r,c]

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

import Control.Monad

getCellPosByIndex :: Integer -> (Integer, Integer)
getCellPosByIndex cell_index = (x, y)
    where
        wave_index = floorSqrt cell_index
        local_index = cell_index - wave_index ^ 2
        x = min wave_index (2 * wave_index - local_index)
        y = min wave_index local_index

floorSqrt :: Integer -> Integer
floorSqrt x = binarySearch 0 x
    where
        binarySearch l r
            | l == r = mid
            | mid ^ 2 <= x = binarySearch mid r
            | otherwise    = binarySearch l (mid-1)
            where mid = (l + r + 1) `div` 2

processTest :: String -> String
processTest input = output
    where
        k = read input
        (x, y) = getCellPosByIndex (k - 1)
        output = show (y+1) ++ " " ++ show (x+1)

main :: IO()
main = do
    tests_n <- read <$> getLine
    tests_inputs <- replicateM tests_n getLine
    let outputs = map processTest tests_inputs
    mapM_ putStrLn outputs