import Control.Monad (liftM)
import List (sort)

{-
import HUnit

test  =  run $ TestList "Tests"
  [
    Test "Test #01" $ assertEq 1 $ solve 1 [],
    Test "Test #02" $ assertEq 0 $ solve 1 [1,2],
    Test "Test #03" $ assertEq 0 $ solve 1 [2,1],
    Test "Test #04" $ assertEq 0 $ solve 2 [1,2,3],
    Test "Test #05" $ assertEq 0 $ solve 1 [1],
    Test "Test #06" $ assertEq 1 $ solve 2 [1,2],
    Test "Test #07" $ assertEq 3 $ solve 3 [2,1],
    Test "Test #08" $ assertEq 2 $ solve 1 [4,2,3,1],
    Test "Test #09" $ assertEq 1 $ solve 3 [1,2,4,5],
    Test "Test #10" $ assertEq 3 $ solve 4 [1,2,3,5],
    Test "Test #11" $ assertEq 0 $ solve 2 [1,2,2,2,4],
    Test "Test #12" $ assertEq 2 $ solve 1 [1,1,2,3,4,5],
    Test "Test #13" $ assertEq 1 $ solve 10 [10,20,30],
    Test "Test #14" $ assertEq 4 $ solve 4 [1,2,3]
  ]
-}

solve :: Int -> [Int] -> Int
solve x xs  =  solve' n (find (1,0) (sort xs)) - n
  where
    n  =  length xs
    find (l,r) []  =  (l, r)
    find (l,r) (y:ys)
      | y <  x  =  find (l+1,r+1) ys
      | y == x  =  find (l, r+1) ys
      | otherwise  =  (l, r)
    solve' n (l,r)
      | n' >= l && n' <= r  =  n
      | otherwise  =  solve' (n+1) (l, r+1)
      where
        n'  =  div (n + 1) 2

main :: IO ()
main  =  do
    [_, x]  <-  liftM (map read . words) getLine
    xs  <-  liftM (map read . words) getLine
    print $ solve x xs

-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-- File Name : 0001A.hs
-- Creation Date : 17-10-2012
-- Last Modified : Sun 21 Oct 2012 04:43:42 PM EEST
-- Created By : Greg Liras <gregliras@gmail.com>
--_._._._._._._._._._._._._._._._._._._._._.

--{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.List (sort)
import Data.List (insert)
import Data.List (elemIndex)
import Data.List (elemIndices)

median ls = head $ drop ((((length ls) + 1) `div` 2) - 1) ls

countDist x med sls len =
    if x == med
        then 0
        else if x < med
                then
                    medind - (head $ reverse $ elemIndices x sls)
                else
                    res - medind
                    where
                        medind  = (len + 1) `div` 2  - 1 -- index
                        res     =
                            let ans = elemIndex x sls
                            in case ans of
                                    Just(y) -> y
                                    Nothing -> 0

calc x sls len = calcAdditions x (median sls) (countDist x (median sls) sls len) len
    where
        calcAdditions x med dist len=
            if x == med
                then 0
                else if len `mod` 2 == 0
                        then if x < med
                            then 2 * dist
                            else 2 * dist - 1
                    else if x < med
                            then 2 * dist - 1
                            else 2 * dist

main :: IO ()
main =
    do
        all <- BS.getContents
        let Just (n, r1)    = readInteger all
        let Just (x, r2)    = readInteger r1
        let (ls, _)         = readMany readInteger r2
        let sls = sort ls
        if x `elem` sls
            then
                print $ calc x sls (fromIntegral n)
            else
                print $ 1 + (calc x (insert x sls) ((fromIntegral n) + 1))
    where
        readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
            Just (x, r) ->  let
                                (xs, t) = readMany readf r
                            in
                                (x : xs, t)
            Nothing     ->  ([], s)

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Debug.Trace

countLess :: Integral a => [a] -> a -> a -> a -> (a,a)
countLess [] median count plithos = (count, plithos)
countLess (x:xs) median count plithos
	| x<median = countLess xs median (count+1) plithos
	| x==median = countLess xs median count (plithos+1)
	| otherwise = countLess xs median count plithos

calcMinNum length countLess 0
	| (countLess+1 == medPos) = 1
	| (countLess+1 > medPos) = 2*(countLess+1) - (length + 1)
	| (countLess+1 < medPos) = (length+1) + 1 - 2*(countLess+1)
	where medPos = (length + 2) `div` 2
calcMinNum length countLess plithos
	| (countLess+1 <= medPos) && (countLess + plithos >= medPos) = 0
	| (countLess+1 > medPos) = 2*(countLess+1) - 1 - length
	| (countLess + plithos < medPos) = length - 2*(countLess + plithos)
	where medPos = (length + 1) `div` 2

solve length median x =
	let
		(countLessRes, plithos) = countLess x median 0 0
	in
		calcMinNum length countLessRes plithos

main =
  do all <- BS.getContents
     let Just (length, r1) = readInteger all
     let Just (median, r2) = readInteger r1
     let  (x, _)  = readMany readInteger r2
     --print (length)
     --print (median)
     --print (x)
     print (solve length median x)
    -- print ((count_less x median 0 0) == length `div` 2)
  where readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
          Just (x, r) -> let (xs, t) = readMany readf r
                         in  (x : xs, t)
          Nothing     -> ([], s)

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

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

parseInput = do
    n <- readInt
    x <- readInt
    a <- replicateM n readInt
    return (x, a)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

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

median s = sort s !! ((length s - 1) `div` 2)

inf = 10^5

solve (x, a)
    | m == x    = 0
    | otherwise = solve (x, x : a) + 1
  where
    m = median a

-- {{{ A minimal State Monad
class (Monad m) => MonadState s m | m -> s where
	get :: m s
	put :: s -> m ()

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

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

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

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

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

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

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

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

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

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

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

state = State
-- }}}

import Data.List

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

solve :: [Int] -> Int
solve (_:x:ys)
  | notElem x ls = if l < g then g-l else l-g+1
  | l < g        = g-l
  | otherwise    = max 0 (l-lx-g-lx+1)
   where (ls,gs) = partition (<=x) ys
         [l,g] = map length [ls,gs]
         lx = length.filter(x==)$ls

s[[_,m],xs]= c where
  l = length$ filter(<m+0) xs
  g = length$ filter(>m) xs
  e = length xs - l - g
  c = max 0 $ max (g-l-e) (l-g-e+1)
main=interact$show.s.map(map read.words).lines

{-# OPTIONS_GHC -O2 -optc-O2 #-}

-- solution for: http://codeforces.com/problemset/problem/166/c

solve :: Int ->  [Int] -> (Int, Int, Int) -> Int
solve x [] (l,e,g) = (final (l,e,g))
solve x (a:aa) (l,e,g) =
	if (a == x)
		then solve x aa (l,e+1,g)
		else if (a < x)
			then solve x aa (l+1,e,g)
			else solve x aa (l,e,g+1)

final :: (Int, Int, Int) -> Int
final (l,e,g) =
	if (l == g)
	then if (e > 0)
		then 0
		else 1
	else finall (l,e,g)

finall :: (Int, Int, Int) -> Int
finall (l,0,g) = 1 + finall (l,1,g)
finall (l,e,g) =
	if (l < g)
	then if (l + e >= g)
		then 0
		else (g - l - e)
	else if (l < e + g)
		then 0
		else (l - g - e + 1)

main =
  do m <- getLine
     let [n,x] = map read (words m)
     str <- getLine
     let a  = map read (words str)
     print (solve x a (0,0,0))

-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-- File Name : 0001A.hs
-- Creation Date : 17-10-2012
-- Last Modified : Sun 21 Oct 2012 05:20:15 PM EEST
-- Created By : Greg Liras <gregliras@gmail.com>
--_._._._._._._._._._._._._._._._._._._._._.

{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.List (sort)
import Data.List (insert)
import Data.List (elemIndex)
import Data.List (elemIndices)

median ls = head $ drop el ls
  where el = ((length ls) + 1) `div` 2 - 1

countDist x med sls len =
  if x == med
    then 0
    else if x < med
        then medind - (head $ reverse $ elemIndices x sls)
        else res - medind
          where
            medind    = (len + 1) `div` 2 - 1 -- index
            Just(res)   = elemIndex x sls

calc x sls len = calcAdditions x medianS sls len
  where
    medianS           = median sls
    calcAdditions x med sls len =
      if x == med
        then 0
        else if len `mod` 2 == 0
            then if x < med
              then 2 * dist
              else 2 * dist - 1
          else if x < med
              then 2 * dist - 1
              else 2 * dist
        where
          dist = countDist x med sls len

main :: IO ()
main =
  do
    all <- BS.getContents
    let Just (n, r1)  = readInteger all
    let Just (x, r2)  = readInteger r1
    let (ls, _)     = readMany readInteger r2
    let sls = sort ls
    if x `elem` sls
      then
        print $ calc x sls (fromIntegral n)
      else
        print $ 1 + (calc x (insert x sls) ((fromIntegral n) + 1))
  where
    readInt s = BSC.readInt (BSC.dropWhile isSpace s)
    readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
    readMany readf s = case readf s of
      Just (x, r) ->  let
                (xs, t) = readMany readf r
              in
                (x : xs, t)
      Nothing   ->  ([], s)

{-# OPTIONS_GHC -O3 -fno-spec-constr-count #-}
{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.ByteString.Char8 as B
import qualified Data.Char as C

atoi :: B.ByteString -> Int
atoi = B.foldl' (\a c -> a*10 + C.ord c - C.ord '0') 0

solve :: Int -> [Int] -> Int
solve x xs
    | xs !! m == x = 0
    | otherwise = 1 + (solve x $ insert x xs)
  where m = (length xs - 1) `div` 2

main = do
    [n, x] <- map atoi . B.words <$> B.getLine
    xs <- sort . map atoi . B.words <$> B.getLine
    putStrLn . show $ solve x xs

module Main where

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

import Data.Time.Calendar

main = interact (show . solve . map (map read . words) . lines)

solve :: [[Int]] -> Int
solve ([_, x] : arr : _) = addition + max 0 (e - b - nx) + max 0 (b + 1 - nx - e) where
    b = length start
    e = length rest
    nx = length xs

    (xs,  rest) = break (/= x) arr'
    (start, arr') = break (== x) sortedArray

    sortedArray = sort correctArray

    (addition, correctArray) = if x `elem` arr then (0, arr) else (1, x : arr)

-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-- File Name : 0001A.hs
-- Creation Date : 17-10-2012
-- Last Modified : Sun 21 Oct 2012 01:09:15 PM EEST
-- Created By : Greg Liras <gregliras@gmail.com>
--_._._._._._._._._._._._._._._._._._._._._.

--{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.List (sort)
import Data.List (insert)
import Data.List (elemIndex)
import Data.List (elemIndices)

median ls = head $ drop ((length ls) `div` 2) ls

-- calcAdditions :: Int->Int->Int
calcAdditions x med dist len=
    if len `mod` 2 == 0
        then
            if x < med
                then
                    2 * dist
                else
                    2 * dist - 1
        else
            if x < med
                then
                    2 * dist - 1
                else
                    2 * dist

countDist x med sls len =
    if x == med
        then
            0
        else
            if x < med
                then
                    medind - (head $ reverse $ elemIndices x sls)
                else
                    res - medind
                    where
                        medind  = (len + 1) `div` 2  - 1 -- index
                        res     =
                            let
                                ans = elemIndex x sls
                            in
                                case ans of
                                    Just(y) -> y
                                    Nothing -> 0

calc x sls len = calcAdditions x (median sls) (countDist x (median sls) sls len) len

main :: IO ()
main =
    do
        all <- BS.getContents
        let Just (n, r1)    = readInteger all
        let Just (x, r2)    = readInteger r1
        let (ls, _)         = readMany readInteger r2
        let sls = sort ls
        if x `elem` sls
            then
                print $ calc x sls (fromIntegral n)
            else
                print $ 1 + (calc x (insert x sls) ((fromIntegral n) + 1))

    where
        readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
            Just (x, r) ->  let
                                (xs, t) = readMany readf r
                            in
                                (x : xs, t)
            Nothing     ->  ([], s)

-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-- File Name : 0001A.hs
-- Creation Date : 17-10-2012
-- Last Modified : Sun 21 Oct 2012 04:32:20 PM EEST
-- Created By : Greg Liras <gregliras@gmail.com>
--_._._._._._._._._._._._._._._._._._._._._.

--{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.List (sort)
import Data.List (insert)
import Data.List (elemIndex)
import Data.List (elemIndices)

median ls = head $ drop ((((length ls) + 1) `div` 2) - 1) ls

countDist x med sls len =
    if x == med
        then 0
        else if x < med
                then
                    medind - (head $ reverse $ elemIndices x sls)
                else
                    res - medind
                    where
                        medind  = (len + 1) `div` 2  - 1 -- index
                        res     =
                            let ans = elemIndex x sls
                            in case ans of
                                    Just(y) -> y
                                    Nothing -> 0

calc x sls len = calcAdditions x (median sls) (countDist x (median sls) sls len) len
    where
        calcAdditions x med dist len=
            if len `mod` 2 == 0
                then if x < med
                        then 2 * dist
                        else 2 * dist - 1
                else if x < med
                        then 2 * dist - 1
                        else 2 * dist

main :: IO ()
main =
    do
        all <- BS.getContents
        let Just (n, r1)    = readInteger all
        let Just (x, r2)    = readInteger r1
        let (ls, _)         = readMany readInteger r2
        let sls = sort ls
        if x `elem` sls
            then
                print $ calc x sls (fromIntegral n)
            else
                print $ 1 + (calc x (insert x sls) ((fromIntegral n) + 1))
    where
        readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
            Just (x, r) ->  let
                                (xs, t) = readMany readf r
                            in
                                (x : xs, t)
            Nothing     ->  ([], s)

-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-- File Name : 0001A.hs
-- Creation Date : 17-10-2012
-- Last Modified : Sun 21 Oct 2012 04:36:40 PM EEST
-- Created By : Greg Liras <gregliras@gmail.com>
--_._._._._._._._._._._._._._._._._._._._._.

--{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.List (sort)
import Data.List (insert)
import Data.List (elemIndex)
import Data.List (elemIndices)

median ls = head $ drop ((((length ls) + 1) `div` 2) - 1) ls

countDist x med sls len =
    if x == med
        then 0
        else if x < med
                then
                    medind - (head $ reverse $ elemIndices x sls)
                else
                    res - medind
                    where
                        medind  = (len + 1) `div` 2  - 1 -- index
                        res     =
                            let ans = elemIndex x sls
                            in case ans of
                                    Just(y) -> y
                                    Nothing -> 0

calc x sls len = calcAdditions x (median sls) (countDist x (median sls) sls len) len
    where
        calcAdditions x med dist len=
            if len `mod` 2 == 0
                then if x < med
                        then 2 * dist
                        else 2 * dist - 1
                else if x < med
                        then 2 * dist - 1
                        else 2 * dist

main :: IO ()
main =
    do
        all <- BS.getContents
        let Just (n, r1)    = readInteger all
        let Just (x, r2)    = readInteger r1
        let (ls, _)         = readMany readInteger r2
        let sls = sort ls
        if x `elem` sls
            then
                print $ calc x sls (fromIntegral n)
            else
                print $ 1 + (calc x (insert x sls) ((fromIntegral n) + 1))
    where
        readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
            Just (x, r) ->  let
                                (xs, t) = readMany readf r
                            in
                                (x : xs, t)
            Nothing     ->  ([], s)

-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-- File Name : 0001A.hs
-- Creation Date : 17-10-2012
-- Last Modified : Sat 20 Oct 2012 07:44:58 PM EEST
-- Created By : Greg Liras <gregliras@gmail.com>
--_._._._._._._._._._._._._._._._._._._._._.

{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.List (sort)
import Data.List (insert)
import Data.List (findIndex)
import Data.List (findIndices)

median ls = head $ drop ((length ls) `div` 2) $ ls

calcAdditions :: Int->Int->Int
calcAdditions dist len =
    if len `mod` 2 == 0
        then
            (2 * dist)
        else
            2*dist

countDist x med sls =
    if x == med
        then
            0
        else
            if x < med
                then
                    ((length sls) `div` 2) - (head $ reverse $ findIndices (==x) sls)
                else
                    res - (length sls) `div` 2
                    where
                        res =
                            let
                                ans = findIndex (==x) sls
                            in
                                case ans of
                                    Just(x) -> x
                                    Nothing -> 0

main :: IO ()
main =
    do
        all <- BS.getContents
        let Just (n, r1)    = readInteger all
        let Just (x, r2)    = readInteger r1
        let (ls, _)         = readMany readInteger r2
        let sls = sort ls
        if x `elem` sls
            then
                print $ calcAdditions (countDist x (median sls) sls) (length sls)
            else
                print $ 1 + (calcAdditions (countDist x (median (insert x sls)) (insert x sls)) (length sls))

    where
        readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
            Just (x, r) ->  let
                                (xs, t) = readMany readf r
                            in
                                (x : xs, t)
            Nothing     ->  ([], s)

-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-- File Name : 0001A.hs
-- Creation Date : 17-10-2012
-- Last Modified : Sat 20 Oct 2012 07:46:55 PM EEST
-- Created By : Greg Liras <gregliras@gmail.com>
--_._._._._._._._._._._._._._._._._._._._._.

{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.List (sort)
import Data.List (insert)
import Data.List (findIndex)
import Data.List (findIndices)

median ls = head $ drop ((length ls) `div` 2) $ ls

calcAdditions :: Int->Int->Int
calcAdditions dist len =
    if len `mod` 2 == 0
        then
            (2 * dist) - 1
        else
            2*dist

countDist x med sls =
    if x == med
        then
            0
        else
            if x < med
                then
                    ((length sls) `div` 2) - (head $ reverse $ findIndices (==x) sls)
                else
                    res - (length sls) `div` 2
                    where
                        res =
                            let
                                ans = findIndex (==x) sls
                            in
                                case ans of
                                    Just(x) -> x
                                    Nothing -> 0

main :: IO ()
main =
    do
        all <- BS.getContents
        let Just (n, r1)    = readInteger all
        let Just (x, r2)    = readInteger r1
        let (ls, _)         = readMany readInteger r2
        let sls = sort ls
        if x `elem` sls
            then
                print $ calcAdditions (countDist x (median sls) sls) (length sls)
            else
                print $ 1 + (calcAdditions (countDist x (median (insert x sls)) (insert x sls)) (length (insert x sls)))

    where
        readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
            Just (x, r) ->  let
                                (xs, t) = readMany readf r
                            in
                                (x : xs, t)
            Nothing     ->  ([], s)

-- -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-- File Name : 0001A.hs
-- Creation Date : 17-10-2012
-- Last Modified : Sat 20 Oct 2012 07:43:34 PM EEST
-- Created By : Greg Liras <gregliras@gmail.com>
--_._._._._._._._._._._._._._._._._._._._._.

{-# OPTIONS_GHC -O2 -optc-O2 #-}

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.List (sort)
import Data.List (insert)
import Data.List (findIndex)
import Data.List (findIndices)

median ls = head $ drop ((length ls) `div` 2) $ ls

calcAdditions :: Int->Int->Int
calcAdditions dist len =
    if len `mod` 2 == 0
        then
            (2 * dist) - 1
        else
            2*dist

countDist x med sls =
    if x == med
        then
            0
        else
            if x < med
                then
                    ((length sls) `div` 2) - (head $ reverse $ findIndices (==x) sls)
                else
                    res - (length sls) `div` 2
                    where
                        res =
                            let
                                ans = findIndex (==x) sls
                            in
                                case ans of
                                    Just(x) -> x
                                    Nothing -> 0

main :: IO ()
main =
    do
        all <- BS.getContents
        let Just (n, r1)    = readInteger all
        let Just (x, r2)    = readInteger r1
        let (ls, _)         = readMany readInteger r2
        let sls = sort ls
        if x `elem` sls
            then
                print $ calcAdditions (countDist x (median sls) sls) (length sls)
            else
                print $ 1 + (calcAdditions (countDist x (median (insert x sls)) (insert x sls)) (length sls))

    where
        readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
            Just (x, r) ->  let
                                (xs, t) = readMany readf r
                            in
                                (x : xs, t)
            Nothing     ->  ([], s)

import Data.Char (isSpace)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Debug.Trace

countLess :: Integral a => [a] -> a -> a -> a -> (a,a)
countLess [] median count plithos = (count, plithos)
countLess (x:xs) median count plithos
	| x<median = countLess xs median (count+1) plithos
	| x==median = countLess xs median count (plithos+1)
	| otherwise = countLess xs median count plithos

calcMinNum length countLess 0
	| (countLess+1 == medPos) = 1
	| (countLess+1 > medPos) = 2*(countLess+1) - (length + 1)
	| (countLess+1 < medPos) = (length+1) + 1 - 2*(countLess+1)
	where medPos = (length + 2) `div` 2
calcMinNum length countLess plithos
	| (countLess+1 <= medPos) && (countLess + plithos >= medPos) = 0
	| (countLess+1 > medPos) = 2*(countLess+1) - 1 - length
	| (countLess + plithos < medPos) = length - 2*(countLess + plithos)
	where medPos = (length + 1) `div` 2

solve length median x =
	let
		(countLessRes, plithos) = countLess x median 0 0
	in
		calcMinNum length countLessRes plithos

main =
  do all <- BS.getContents
     let Just (length, r1) = readInteger all
     let Just (median, r2) = readInteger r1
     let  (x, _)  = readMany readInteger r2
     print (length)
     print (median)
     print (x)
     print (solve length median x)
    -- print ((count_less x median 0 0) == length `div` 2)
  where readInt s = BSC.readInt (BSC.dropWhile isSpace s)
        readInteger s = BSC.readInteger (BSC.dropWhile isSpace s)
        readMany readf s = case readf s of
          Just (x, r) -> let (xs, t) = readMany readf r
                         in  (x : xs, t)
          Nothing     -> ([], s)

import Data.List

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

solve :: [Int] -> Int
solve (n:x:ys) = case map succ.elemIndices x $ ys' of
                   []  -> (\l->2*l-n+1).length.takeWhile (<x) $ ys'
                   (z:zs) | m`elem`(z:zs) -> 0
                          | m < z         -> z - m
                          | otherwise     -> m - last (z:zs)
   where m = (n+1)`div`2
         ys' = sort ys

import Data.List

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

solve :: [Int] -> Int
solve (_:x:ys)
  | notElem x ls = succ.abs $ (l-g)
  | l < g        = g-l
  | l > g + 1    = l-1-g
  | otherwise    = 0
   where (ls,gs) = partition (<=x) ys
         [l,g] = map length [ls,gs]

import Data.List

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

solve :: [Int] -> Int
solve (_:x:ys)
  | notElem x ls = succ.abs $ (l-g)
  | l < g        = g-l
  | otherwise    = max 0 (l-lx-g-lx+1)
   where (ls,gs) = partition (<=x) ys
         [l,g] = map length [ls,gs]
         lx = length.filter(x==)$ls

import Data.List

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

solve :: [Int] -> Int
solve (_:x:ys)
  | notElem x ls = succ.abs $ (l-g)
  | l < g        = g-l
  | otherwise    = max 0 (l-g-lx)
   where (ls,gs) = partition (<=x) ys
         [l,g] = map length [ls,gs]
         lx = length.filter(x==)$ls

import Data.List

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

solve :: [Int] -> Int
solve (_:x:ys)
  | notElem x ls = if l <= g then g-l else l-g+1
  | l < g        = g-l
  | otherwise    = max 0 (l-lx-g-lx+1)
   where (ls,gs) = partition (<=x) ys
         [l,g] = map length [ls,gs]
         lx = length.filter(x==)$ls

import Data.List

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

solve :: [Int] -> Int
solve (n:x:ys) = case map succ.elemIndices x $ ys' of
                   []  -> (\l->abs(2*l-n)+1).length.takeWhile (<x) $ ys'
                   (z:zs) | m`elem`(z:zs) -> 0
                          | m < z         -> z - m
                          | otherwise     -> m - last (z:zs)
   where m = (n+1)`div`2
         ys' = sort ys

solve :: Int ->  [Int] -> (Int, Int, Int) -> Int
solve x [] (l,e,g) = (final (l,e,g))
solve x (a:aa) (l,e,g) =
    if (a == x)
        then solve x aa (l,e+1,g)
        else if (a < x)
            then solve x aa (l+1,e,g)
            else solve x aa (l,e,g+1)

final :: (Int, Int, Int) -> Int
final (l,e,g) = if (l == g) then 0 else finall (l,e,g)

finall :: (Int, Int, Int) -> Int
finall (l,0,g) = 1 + finall (l,1,g)
finall (l,e,g) =
    if (l < g)
    then if (l + e >= g)
        then 0
        else (g - l - e)
    else if (l < e + g)
        then 0
        else (l - g - e + 1)

main =
  do m <- getLine
     let [n,x] = map read (words m)
     str <- getLine
     let a  = map read (words str)
     print (solve x a (0,0,0))


import Control.Monad (liftM, replicateM)
import Data.Array (Array, (!), array, bounds)
import Data.Char (ord)
import Data.List (intercalate)

solve :: Int -> [(Int, Int)] -> [(Int, Int)]
solve n as  =  [(a, i) | i <- [1..n], i /= a]
  where
    a  =  head $ filter (not . elem') [1..n]
    elem' x  =  elem x (map fst as) || elem x (map snd as)

main :: IO ()
main  =  do
    [n, m]  <-  reads
    as  <-  replicateM m readPair
    print (n-1)
    mapM_ printPair $ solve n as
  where

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

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

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

    printPair :: Show a => (a, a) -> IO ()
    printPair (a, b)  =  prints [a,b]

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Ord
import qualified Data.IntSet as IS

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

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

main :: IO ()
main = do
  [n,m] <- map read.words <$> getLine
  edges <- map readInt.B.words <$> B.getContents
  let res = solve n edges
  print $ length res
  putStr.unlines.map(unwords.map show) $ res

solve :: Int -> [Int] -> [[Int]]
solve 1 _ = []
solve n [] = map (:[n]) [1..n-1]
solve n edges = go (IS.fromList [1..n]) edges
   where
     v = f [1..] . map head.group$ sort edges
     iset = IS.fromList [1..n]
     go !rest (from:to:es) = filter (not.null) $ filter(const$IS.member from rest)[v,from]:filter(const$IS.member to rest)[v,to]:go rest' es
      where
        rest' = IS.delete to.IS.delete from $ IS.delete v rest
     go rest _ = map (:[v]) $ IS.toList rest

f (i:is) (v:vs)
  | i==v = f is vs
  | otherwise = i
f (i:is) [] = i

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Ord
import qualified Data.IntSet as IS

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

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

main :: IO ()
main = do
  [n,m] <- map read.words <$> getLine
  edges <- map readInt.B.words <$> B.getContents
  let res = solve n edges
  print $ length res
  putStr.unlines.map(unwords.map show) $ res

solve :: Int -> [Int] -> [[Int]]
solve 1 _ = []
solve n [] = map (:[n]) [1..n-1]
solve n edges = go (IS.fromList [1..n]) edges
   where
     v = f [1..] $ sort edges
     iset = IS.fromList [1..n]
     go !rest (from:to:es) = [v,from]:[v,to]:go rest' es
      where
        rest' = IS.delete to.IS.delete from $ IS.delete v rest
     go rest _ = map (:[v]) $ IS.toList rest

f (i:is) (v:vs)
  | i==v = f is vs
  | otherwise = i
f (i:is) [] = i


import Control.Monad

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

routine :: IO ()
routine = do
  n <- readLn
  putStrLn $ solve n

solve :: Int -> String
solve n
  |n `mod` 4 ==0 = "YES\n"++ (unwords.map show) l
  |otherwise = "NO"
  where
    l = [2,4..n] ++ [1,3..(n-3)] ++ [(n*3 `div` 2)-1]

import Control.Monad

main = readLn >>= flip replicateM_ test

test = do
    n <- readLn :: IO Integer
    if odd (n `div` 2)
        then putStrLn "NO"
        else do
            putStrLn "YES"
            let as = (2 *) <$> [1 .. n `div` 4]
                a = 100000000
            putStrLn . unwords . map show $ ((a +) <$> as) ++ ((a -) <$> as) ++ ((a + 1 +) <$> as) ++ ((a - 1 -) <$> as)

interleave :: String -> [String] -> [String]
interleave _ []       = []
interleave c (x : xs) = x : c : (interleave c xs)

generateSecond :: [Int] -> Int -> [Int]
generateSecond []       _    = []
generateSecond (x : xs) sign = (x + sign * 1) : (generateSecond xs (-sign))

solveFor :: Int -> String
solveFor n
  | n `div` 2 `mod` 2 == 1
  = "NO"
  | otherwise
  = "YES\n" ++ concat (interleave " " (map show firstHalf)) ++ concat
    (interleave " " (map show $ generateSecond firstHalf 1))
  where firstHalf = map fst $ zip (iterate (10 +) 2) [1 .. (n `div` 2)]

solveCase :: IO ()
solveCase = do
  nLine <- getLine
  let n   = read nLine :: Int
  let res = solveFor n
  putStrLn res

main :: IO ()
main = do
  tline <- getLine
  let ts = read tline :: Int
  sequence_ [ solveCase | _ <- [1 .. ts] ]

import Data.List

evens :: Int -> [Int]
evens n = [s + 2, s + 4]
  where s = 6 * n

odds :: Int -> [Int]
odds n = [s + 1, s + 5]
  where s = 6 * n

makeList :: Int -> [Int]
makeList n = evenList ++ oddList
  where evenList = concat $ map evens [1..e]
        oddList = concat $ map odds [1..e]
        e = div n 4

stringify :: [Int] -> String
stringify x = unwords $ map show x

test :: String -> String
test s
  | rem n 4 /= 0 = "NO"
  | otherwise = "YES\n" ++ (stringify $ makeList n)
  where n = read s :: Int

main = do
  getLine
  interact $ unlines . map test . lines

import Control.Monad (replicateM_)

main :: IO ()
main = readLn >>= flip replicateM_ solveIO

solveIO :: IO ()
solveIO = readLn >>= putStrLn . decorate . f where
    decorate Nothing = "NO"
    decorate (Just xs) = "YES\n" ++ (unwords . map show) xs

f :: Int -> Maybe [Int]
f n = if n `mod` 4 /= 0 then Nothing else Just $
    let k = n `div` 2
        p1 = take k [2,4..]
        p2 = take (k-1) [1,3..]
    in p1 ++ p2 ++[sum p1 - sum p2]

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

process a | mod a 4>0 = putStrLn "NO"
	  | otherwise = do
				putStrLn "YES"
				let x= take (div a 2) [2,4..]
				let sx = sum x
				putStr $ intercalate " " $map show  x
				putStr " "
				let lx = length x
				let y =take ((div a 2)- 1) [1,3..]
				let sy =sum y
				putStr $ intercalate " " $ map show y
				putStrLn $ " "++ show (sx-sy)
main = do
		n<-   getLine
		a<- map read <$> lines  <$> getContents::IO [Int]
		mapM_ process a

process :: Int -> [Int]
process n
    | n `mod` 4 /= 0 = []
    | otherwise = take n2 [2,4..] ++ take (n2-1) [1,3..] ++ [n+n2-1]
    where n2 = n `div` 2

readInt :: String -> Int
readInt = read

run :: Int -> IO ()
run 0 = return ()
run t = do
    n <- fmap readInt getLine
    let as = process n
    if null as
        then putStrLn "NO"
        else do
            putStrLn "YES"
            putStrLn . unwords . map show $ as
    run (t-1)

main :: IO ()
main = do
    t <- fmap readInt getLine
    run t

import Data.List as L

solve :: Integer -> Maybe [Integer]
solve n
  | odd mid = Nothing
  | otherwise = Just (evens ++ someOdds ++ m)
  where mid = div n 2
        evens = (L.take (fromIntegral mid) [i | i <- [2..], even i])
        someOdds = (L.take (fromIntegral $ mid-2) [i | i <- [1..], odd i])
        sumEvens = L.sum evens
        sumOdds = L.sum someOdds
        m = magic (sumEvens - sumOdds) (if L.null someOdds then (-1) else (L.last someOdds))

magic :: Integer -> Integer -> [Integer]
magic n l = head [[a, b] | a <- [(l+2),(l+3)..n],
                           b <- [n, (n-1)..(l+2)],
                           odd a,
                           odd b,
                           a+b == n]

parse :: String -> String
parse input = case solve n of
                Just a -> "YES\n" ++ (L.intercalate " " $ map show a)
                Nothing -> "NO"
  where n = read input :: Integer

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

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

process a | mod a 2>0 = putStrLn "NO"
	  | otherwise = do
				putStrLn "YES"
				let x= take a [2,4..]
				let sx = sum x
				putStr $ intercalate " " $map show  x
				putStr " "
				let lx = length x
				let y =take (a- 1) [1,3..]
				let sy =sum y
				putStr $ intercalate " " $ map show y
				putStrLn $ " "++ show (sx-sy)
main = do
		n<-   getLine
		a<- map read <$> lines  <$> getContents::IO [Int]
		mapM_ process a

import Control.Monad

main = readLn >>= flip replicateM_ test

test = do
    n <- readLn :: IO Integer
    if odd (n `div` 2)
        then putStrLn "NO"
        else do
            putStrLn "YES"
            let as = (2 *) <$> [1 .. n `div` 4]
                a = 100000000
            putStrLn . unwords . map show $ ((a +) <$> as) ++ ((a -) <$> as) ++ ((a + 1 +) <$> as) ++ ((a - 1 +) <$> as)

interleave :: String -> [String] -> [String]
interleave _ []       = []
interleave c (x : xs) = x : c : (interleave c xs)

generateSecond :: [Int] -> Int -> [Int]
generateSecond []       _    = []
generateSecond (x : xs) sign = (x + sign * 1) : (generateSecond xs (-sign))

solveFor :: Int -> String
solveFor n
  | n `div` 2 `mod` 2 == 1
  = "NO"
  | otherwise
  = "YES\n" ++ concat (interleave " " (map show firstHalf)) ++ concat
    (interleave " " (map show $ generateSecond firstHalf 1))
  where firstHalf = map fst $ zip (iterate (10 +) 2) [1 .. n]

solveCase :: IO ()
solveCase = do
  nLine <- getLine
  let n   = read nLine :: Int
  let res = solveFor n
  putStrLn res

main :: IO ()
main = do
  tline <- getLine
  let ts = read tline :: Int
  sequence_ [ solveCase | _ <- [1 .. ts] ]

import Data.List

quad :: Int -> [Int]
quad n = [s + 2, s + 4, s + 1, s + 5]
  where s = 6 * n

makeList :: Int -> [Int]
makeList n = foldl1 (++) (map quad [1..(div n 4)])

stringify :: [Int] -> String
stringify x = unwords $ map show x

test :: String -> String
test s
  | rem n 4 /= 0 = "NO"
  | otherwise = "YES\n" ++ (stringify $ makeList n)
  where n = read s :: Int

main = do
  getLine
  interact $ unlines . map test . lines

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

process a | mod a 4>0 = putStrLn "NO"
	  | otherwise = do
				putStrLn "YES"
				let x= take a [2,4..]
				let sx = sum x
				putStr $ intercalate " " $map show  x
				putStr " "
				let lx = length x
				let y =take (a- 1) [1,3..]
				let sy =sum y
				putStr $ intercalate " " $ map show y
				putStrLn $ " "++ show (sx-sy)
main = do
		n<-   getLine
		a<- map read <$> lines  <$> getContents::IO [Int]
		mapM_ process a


{-# LANGUAGE TupleSections #-}

-- For Input
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
--import qualified Data.ByteString.Lex.Double as BSD
import Data.Char (isSpace)
import Data.IORef
import Text.Printf

--import Test.QuickCheck
--import Test.QuickCheck.Property
--import Data.List.Ordered (isSorted)

-- Data Structure Imports
import Data.Maybe
import Data.List
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

-- These should be imported by default... :)
import Control.Monad
import Control.Applicative
import Control.Arrow

import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed
import Data.Array.IO

import Debug.Trace

--------------------------------------------------------------------------------
------------------------------- SOLUTION ---------------------------------------
--------------------------------------------------------------------------------

primesUpTo :: Int -> Set Int
primesUpTo n = Set.fromList [p | (p, True) <- assocs $ sieve n]

sieve :: Int -> UArray Int Bool
sieve n = runSTUArray $ do
    sieve <- newArray (2, n) True
    forM_ [2..n] $ \p -> do
        isPrime <- readArray sieve p
        when isPrime $ do
            forM_ [p*2, p*3 .. n] $ \k -> do
                writeArray sieve k False
    return sieve

lim :: Int
lim = 100000

primes :: Set Int
primes = primesUpTo lim

isPrime :: Int -> Bool
isPrime n = Set.member n primes

goldbach :: Int -> (Int, Int)
goldbach n =
  head $ concatMap (\x -> if Set.member (n-x) primes then [(x,n-x)] else [])
       $ Set.toList primes

--goldbachs :: UArray Int (Int,Int)
--goldbachs = listArray (4,lim) $ map goldbach [4..lim]

operations :: Int -> Int -> [(Int,Int)]
operations i j
    | diff == 0 = []
    | diff <= 2 = [(i,j)]
    | diff + 1 <= 9 = doGoldbach diff
    | even diff = doGoldbach diff
    | otherwise = (j-1,j):operations i (j-1)
    where diff = j - i
          doGoldbach n =
              let (x,y) = goldbach (n+2)
              in [(i+x-1,j), (i, i+x-1)]
                         -- i+x-1-i+1=x
                         -- x+y-1-x+1=y
opsCorrect :: Int -> Int -> Bool
opsCorrect i j
    | i < 0 || j < 0 = opsCorrect (abs i) (abs j)
    | i > j = opsCorrect j i
    | otherwise =
                   let ops = operations i j
                       walk [] = True
                       walk ((x,y):t) =
                           isPrime (y-x+1) && walk t
                   in walk ops

walkOps :: IOUArray Int Int -> [(Int,Int)] -> Set (Int,Int) ->
           IO (Set (Int,Int))
walkOps a [] heap = return heap
walkOps a ((i,j):t) heap = do
--  elems <- getElems a
--  putStrLn $ show ("Calling walkOps with", elems, i, j, heap, t)
  vi <- readArray a i
  vj <- readArray a j
  writeArray a i vj
  writeArray a j vi
  let heap' = Set.delete (vi,i) . Set.delete (vj,j)
              . Set.insert (vj,i) . Set.insert (vi,j) $ heap
--  putStrLn $ show ("New heap will be", heap')
  heap' `seq` walkOps a t heap'

printOps :: [(Int,Int)] -> IO ()
printOps ops = forM_ ops $ \(i,j) -> putStrLn $ show i ++ " " ++ show j

solve :: IOUArray Int Int -> Set (Int,Int) -> Int -> Int -> IO [(Int,Int)]
solve a heap i k | i > k = return []
                 | otherwise = do
--  elems <- getElems a
--  putStrLn $ show ("Calling solve with", elems, i, heap)
  let (mv,mi) = Set.findMin heap
      ops     = operations i mi
  heap' <- walkOps a ops heap
  let heap'' = Set.delete (i,mv) heap'
  fmap (ops++) $ solve a heap'' (i+1) k

main :: IO ()
main = do
  all   <- BS.getContents
  input <- newIORef all
  let parse = next input
  k <- parse int
  a <- parse $ intMany k
  a' <- newListArray (1,k) a :: IO (IOUArray Int Int)
  let heap = Set.fromList $ zipWith (,) a [1..k]
  ops <- solve a' heap 1 k
  putStrLn $ show $ length ops
  printOps ops
--  elems <- getElems a'
--  putStrLn $ show elems

{-
main :: IO ()
main = quickCheck $ forAllShrink (fmap abs arbitrary) shrink $ \n ->
         forAll (permute [1..n]) $ \a ->
             prop a

permute :: [Int] -> Gen [Int]
permute [] = return []
permute l  = elements l >>= (\x -> fmap (x:) (permute $ delete x l))

prop :: [Int] -> Property
prop a = morallyDubiousIOProperty $ do
  let k = length a
  a' <- newListArray (1,k) a :: IO (IOUArray Int Int)
  let heap = Set.fromList $ zipWith (,) a [1..k]
  ops <- solve a' heap 1 k
  elems <- getElems a'
  return $ isSorted elems
-}
--------------------------------------------------------------------------------
-------------------------- IO Function Helpers ---------------------------------
--------------------------------------------------------------------------------

type Parser a = BSC.ByteString -> (a, BSC.ByteString)

int :: Parser Int
int = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt

int2 :: Parser (Int, Int)
int2 = uncurry (first . (,)) . second int . int

int3 :: Parser (Int, Int, Int)
int3 = uncurry (first . (uncurry (,,))) . second int . int2

--double :: Parser Double
--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble

char :: Parser Char
char = BSC.head &&& BSC.tail

letter :: Parser Char
letter = second (BSC.dropWhile isSpace) . char

string :: Parser String
string = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)

readMany :: Parser a -> Int -> Parser [a]
readMany f n bs = first reverse $
                  foldr (\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]

intMany :: Int -> Parser [Int]
intMany = readMany int

next :: IORef BSC.ByteString -> Parser a -> IO a
next input parse = do
  bs <- readIORef input
  let (x, bs') = parse bs
  writeIORef input bs'
  return x

{- CODE JAM input

  cases <- parse int
  forM_ [1..cases] $ \caseNum -> do
         -- Read Data
         -- let solution =
         -- solution <-
         printf "Case #%d: %d\n" caseNum solution
-}

{-# LANGUAGE BangPatterns #-}

import Text.Printf

import Data.Array.IO
import qualified Data.Array.MArray as M
import qualified Data.Array.IArray as I
import Data.Array.Unboxed
import Control.Monad
import Data.Int

import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Data.Char

readInt :: IO Int
readInt = do line <- BS.getLine
             let Just (n,_) = BS.readInt line
             return n

parseInts :: Int -> ByteString -> [Int]
parseInts k bs | k <= 0 = []
parseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of
                   Nothing -> []
                   Just (n,bs') -> n : parseInts (k-1) bs'

isqrt :: Integral a => a -> Int
isqrt n = floor $ sqrt ((fromIntegral n) :: Double)

sieve arr = do
  (_,hi) <- getBounds arr
  let maxi = isqrt hi
  forM_ [2..maxi] $ \i -> do
    v <- readArray arr i
    if v == 0
      then let v = i*i in forM_ [v,v+i..hi] $ \j -> writeArray arr j (fromIntegral i)
      else return ()

genPrimes :: Integral a => Int -> IO [a]
genPrimes n = do
  parr' <- newArray (2,n) 0 :: IO (IOUArray Int Int)
  sieve parr'
  parr <- M.freeze parr' :: IO (UArray Int Int)
  let primes = map (fromIntegral.fst) $ filter (\(i,v) -> v == 0) $ I.assocs parr
  return primes

ind :: Integral a => a -> a -> (Int,a)
ind p n = go 0 n
  where go !k m = case m `divMod` p of
                    (q,0)     -> go (k+1) q
                    otherwise -> (k,m)

factor :: Integral a => [a] -> a -> [(a,Int)]
factor [] n
  | n == 1 = []
  | otherwise = [(n,1)]  -- assume n is prime
factor (p:ps) n = case ind p n of
                    (0,_) -> factor ps n
                    (k,m) -> (p,k) : factor ps m

prod :: Integral a => [(a,Int)] -> a
prod = product . map (\(p,k) -> p^k)

solve :: UArray Int Int -> Int -> [Int] -> IO (Int,[(Int,Int)])
solve largestP n ns = do
  nums <- newArray (1,n) 0 :: IO (IOUArray Int Int)
  inv  <- newArray (1,n) 0 :: IO (IOUArray Int Int)
  swapi <- newArray (0,5*n) 0 :: IO (IOUArray Int Int)
  swapj <- newArray (0,5*n) 0 :: IO (IOUArray Int Int)
  forM_ (zip [1..] ns) $ \(i,a) -> do writeArray nums i a; writeArray inv a i
  let loop s i =   -- nums[j] = i
        do j <- readArray inv i
           let d = j - i + 1
           if d < 2
             then return s
             else do let p = largestP ! d
                     -- swap nums[j-p+1] and nums[j]
                     writeArray swapi s (j-p+1)
                     writeArray swapj s j
                     a <- readArray nums (j-p+1)
                     let b = i
                     writeArray nums (j-p+1) b
                     writeArray nums j       a
                     -- before: nums[j-p+1] = a  --> inv[a] = j-p+1
                     --         nums[j]     = b  --> inv[b] = j
                     -- swap inv[a] and inv[b]
                     writeArray inv  b       (j-p+1)
                     writeArray inv  a       j
                     loop (s+1) i
  s <- foldM loop 0 [1..n]
  swapi' <- M.freeze swapi :: IO (UArray Int Int)
  swapj' <- M.freeze swapj :: IO (UArray Int Int)
  let swaps = [ (swapi' ! k, swapj' ! k) | k <- [0..s-1] ]
  return $ (s, swaps)

check :: UArray Int Int -> Int -> [Int] -> IO Bool
check largestP n ns = do
  (s,swaps) <- solve largestP n ns
  arr <- newArray (1,n) 0 :: IO (IOUArray Int Int)
  forM_ (zip [1..] ns) $ \(i,a) -> do writeArray arr i a
  -- execute the swaps
  forM_ swaps $ \(i,j) -> do
    a <- readArray arr i
    b <- readArray arr j
    writeArray arr i b
    writeArray arr j a
  -- make sure arr[i] == i
  arr' <- M.freeze arr :: IO (UArray Int Int)
  let ok1 = all (\i -> arr' ! i == i) [1..n]
  if not ok1
    then do putStrLn "not sorted: "
            forM_ [1..n] $ \i -> putStr $ " " ++ show (arr' ! i)
    else return ()
  let ok2 = s <= 5*n
  if not ok2
    then putStrLn $ "too many swaps: " ++ show s
    else return ()
  return $ ok1 && ok2

makeLargestP :: Int -> IO (UArray Int Int)
makeLargestP n = do
  primes' <- newArray (2,n) 0 :: IO (IOUArray Int Int)
  sieve primes'
  primes <- M.freeze primes' :: IO (UArray Int Int)
  largestP' <- newArray (0,n) 0 :: IO (IOUArray Int Int)
  let go p i = do let p' = if primes ! i == 0 then i else p
                  writeArray largestP' i p'
                  return p'
  foldM_ go 2 [2..n]
  M.freeze largestP' :: IO (UArray Int Int)

mainCheck = do
  n <- fmap read getLine
  largestP <- makeLargestP n
  ns <- fmap (parseInts n) BS.getLine
  check largestP n ns

mainSolve = do
  n <- fmap read getLine
  largestP <- makeLargestP n
  ns <- fmap (parseInts n) BS.getLine
  (s,swaps) <- solve largestP n ns
  print s
  forM_ swaps $ \(i,j) -> do
    putStrLn $ (show i) ++ " " ++ (show j)
  return ()

main = mainSolve

{-# LANGUAGE TupleSections #-}

-- For Input
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
--import qualified Data.ByteString.Lex.Double as BSD
import Data.Char (isSpace)
import Data.IORef
import Text.Printf

-- Data Structure Imports
import Data.Maybe
import Data.List
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

-- These should be imported by default... :)
import Control.Monad
import Control.Applicative
import Control.Arrow

import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed
import Data.Array.IO

import Debug.Trace

--------------------------------------------------------------------------------
------------------------------- SOLUTION ---------------------------------------
--------------------------------------------------------------------------------

primesUpTo :: Int -> Set Int
primesUpTo n = Set.fromList [p | (p, True) <- assocs $ sieve n]

sieve :: Int -> UArray Int Bool
sieve n = runSTUArray $ do
    sieve <- newArray (2, n) True
    forM_ [2..n] $ \p -> do
        isPrime <- readArray sieve p
        when isPrime $ do
            forM_ [p*2, p*3 .. n] $ \k -> do
                writeArray sieve k False
    return sieve

lim :: Int
lim = 100000

primes :: Set Int
primes = primesUpTo lim

isPrime :: Int -> Bool
isPrime n = Set.member n primes

goldbach :: Int -> (Int, Int)
goldbach n = head $ concatMap (\x -> if Set.member (n-x) primes then [(x,n-x)]
                                     else [])
             $ Set.toList primes

--goldbachs :: UArray Int (Int,Int)
--goldbachs = listArray (4,lim) $ map goldbach [4..lim]

operations :: Int -> Int -> [(Int,Int)]
operations i j
    | j == i = []
    | j == i + 1 = [(i,j)]
    | j == i + 2 = [(i,j)]
    | otherwise  =
        let (x,y) = goldbach (j - i + 1) in
        [(i+x-1,j), (i, i+x-1)]

walkOps :: IOUArray Int Int -> [(Int,Int)] -> Set (Int,Int) ->
           IO (Set (Int,Int))
walkOps a [] heap = return heap
walkOps a ((i,j):t) heap = do
  vi <- readArray a i
  vj <- readArray a j
  writeArray a i vj
  writeArray a j vi
  return $ Set.delete (i,vi) $ Set.delete (j,vj)
         $ Set.insert (i,vj) $ Set.insert (j,vi) $ heap

printOps :: [(Int,Int)] -> IO ()
printOps ops = forM_ ops $ \(i,j) -> putStrLn $ show i ++ " " ++ show j

solve :: IOUArray Int Int -> Set (Int,Int) -> Int -> Int -> IO [(Int,Int)]
solve a heap i k | i > k = return []
                 | otherwise = do
  let (mv,mi) = Set.findMin heap
      ops     = operations i mi
  heap' <- walkOps a ops heap
  let heap'' = Set.delete (i,mv) heap'
  fmap (ops++) $ solve a heap'' (i+1) k

main :: IO ()
main = do
  all   <- BS.getContents
  input <- newIORef all
  let parse = next input
  k <- parse int
  a <- parse $ intMany k
  a' <- newListArray (1,k) a :: IO (IOUArray Int Int)
  let heap = Set.fromList $ zipWith (,) a [1..k]
  ops <- solve a' heap 1 k
  putStrLn $ show $ length ops
  printOps ops

--------------------------------------------------------------------------------
-------------------------- IO Function Helpers ---------------------------------
--------------------------------------------------------------------------------

type Parser a = BSC.ByteString -> (a, BSC.ByteString)

int :: Parser Int
int = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt

int2 :: Parser (Int, Int)
int2 = uncurry (first . (,)) . second int . int

int3 :: Parser (Int, Int, Int)
int3 = uncurry (first . (uncurry (,,))) . second int . int2

--double :: Parser Double
--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble

char :: Parser Char
char = BSC.head &&& BSC.tail

letter :: Parser Char
letter = second (BSC.dropWhile isSpace) . char

string :: Parser String
string = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)

readMany :: Parser a -> Int -> Parser [a]
readMany f n bs = first reverse $
                  foldr (\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]

intMany :: Int -> Parser [Int]
intMany = readMany int

next :: IORef BSC.ByteString -> Parser a -> IO a
next input parse = do
  bs <- readIORef input
  let (x, bs') = parse bs
  writeIORef input bs'
  return x

{- CODE JAM input

  cases <- parse int
  forM_ [1..cases] $ \caseNum -> do
         -- Read Data
         -- let solution =
         -- solution <-
         printf "Case #%d: %d\n" caseNum solution
-}

{-# LANGUAGE TupleSections #-}

-- For Input
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
--import qualified Data.ByteString.Lex.Double as BSD
import Data.Char (isSpace)
import Data.IORef
import Text.Printf

--import Test.QuickCheck
--import Test.QuickCheck.Property
--import Data.List.Ordered (isSorted)

-- Data Structure Imports
import Data.Maybe
import Data.List
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

-- These should be imported by default... :)
import Control.Monad
import Control.Applicative
import Control.Arrow

import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed
import Data.Array.IO

import Debug.Trace

--------------------------------------------------------------------------------
------------------------------- SOLUTION ---------------------------------------
--------------------------------------------------------------------------------

primesUpTo :: Int -> Set Int
primesUpTo n = Set.fromList [p | (p, True) <- assocs $ sieve n]

sieve :: Int -> UArray Int Bool
sieve n = runSTUArray $ do
    sieve <- newArray (2, n) True
    forM_ [2..n] $ \p -> do
        isPrime <- readArray sieve p
        when isPrime $ do
            forM_ [p*2, p*3 .. n] $ \k -> do
                writeArray sieve k False
    return sieve

lim :: Int
lim = 100000

primes :: Set Int
primes = primesUpTo lim

isPrime :: Int -> Bool
isPrime n = Set.member n primes

goldbach :: Int -> (Int, Int)
goldbach n =
  head $ concatMap (\x -> if Set.member (n-x) primes then [(x,n-x)] else [])
       $ Set.toList primes

--goldbachs :: UArray Int (Int,Int)
--goldbachs = listArray (4,lim) $ map goldbach [4..lim]

operations :: Int -> Int -> [(Int,Int)]
operations i j
    | diff == 0 = []
    | diff <= 2 = [(i,j)]
    | diff + 1 <= 9 = doGoldbach (diff + 1)
    | even (diff + 1) = doGoldbach (diff + 1)
    | otherwise = (j-3,j):operations i (j-3)
    where diff = j - i
          doGoldbach n = let (x,y) = goldbach n
                         in [(i+x-1,j), (i, i+x-1)]

walkOps :: IOUArray Int Int -> [(Int,Int)] -> Set (Int,Int) ->
           IO (Set (Int,Int))
walkOps a [] heap = return heap
walkOps a ((i,j):t) heap = do
--  elems <- getElems a
--  putStrLn $ show ("Calling walkOps with", elems, i, j, heap, t)
  vi <- readArray a i
  vj <- readArray a j
  writeArray a i vj
  writeArray a j vi
  let heap' = Set.delete (vi,i) . Set.delete (vj,j)
              . Set.insert (vj,i) . Set.insert (vi,j) $ heap
--  putStrLn $ show ("New heap will be", heap')
  heap' `seq` walkOps a t heap'

printOps :: [(Int,Int)] -> IO ()
printOps ops = forM_ ops $ \(i,j) -> putStrLn $ show i ++ " " ++ show j

solve :: IOUArray Int Int -> Set (Int,Int) -> Int -> Int -> IO [(Int,Int)]
solve a heap i k | i > k = return []
                 | otherwise = do
--  elems <- getElems a
--  putStrLn $ show ("Calling solve with", elems, i, heap)
  let (mv,mi) = Set.findMin heap
      ops     = operations i mi
  heap' <- walkOps a ops heap
  let heap'' = Set.delete (i,mv) heap'
  fmap (ops++) $ solve a heap'' (i+1) k

main :: IO ()
main = do
  all   <- BS.getContents
  input <- newIORef all
  let parse = next input
  k <- parse int
  a <- parse $ intMany k
  a' <- newListArray (1,k) a :: IO (IOUArray Int Int)
  let heap = Set.fromList $ zipWith (,) a [1..k]
  ops <- solve a' heap 1 k
  putStrLn $ show $ length ops
  printOps ops
--  elems <- getElems a'
--  putStrLn $ show elems
{-
permute :: [Int] -> Gen [Int]
permute [] = return []
permute l  = elements l >>= (\x -> fmap (x:) (permute $ delete x l))

prop :: [Int] -> Property
prop a = morallyDubiousIOProperty $ do
  let k = length a
  a' <- newListArray (1,k) a :: IO (IOUArray Int Int)
  let heap = Set.fromList $ zipWith (,) a [1..k]
  ops <- solve a' heap 1 k
  elems <- getElems a'
  return $ isSorted elems
-}
--------------------------------------------------------------------------------
-------------------------- IO Function Helpers ---------------------------------
--------------------------------------------------------------------------------

type Parser a = BSC.ByteString -> (a, BSC.ByteString)

int :: Parser Int
int = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt

int2 :: Parser (Int, Int)
int2 = uncurry (first . (,)) . second int . int

int3 :: Parser (Int, Int, Int)
int3 = uncurry (first . (uncurry (,,))) . second int . int2

--double :: Parser Double
--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble

char :: Parser Char
char = BSC.head &&& BSC.tail

letter :: Parser Char
letter = second (BSC.dropWhile isSpace) . char

string :: Parser String
string = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)

readMany :: Parser a -> Int -> Parser [a]
readMany f n bs = first reverse $
                  foldr (\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]

intMany :: Int -> Parser [Int]
intMany = readMany int

next :: IORef BSC.ByteString -> Parser a -> IO a
next input parse = do
  bs <- readIORef input
  let (x, bs') = parse bs
  writeIORef input bs'
  return x

{- CODE JAM input

  cases <- parse int
  forM_ [1..cases] $ \caseNum -> do
         -- Read Data
         -- let solution =
         -- solution <-
         printf "Case #%d: %d\n" caseNum solution
-}

{-# LANGUAGE TupleSections #-}

-- For Input
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
--import qualified Data.ByteString.Lex.Double as BSD
import Data.Char (isSpace)
import Data.IORef
import Text.Printf

-- Data Structure Imports
import Data.Maybe
import Data.List
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

-- These should be imported by default... :)
import Control.Monad
import Control.Applicative
import Control.Arrow

import Control.Monad.ST
import Data.Array.ST
import Data.Array.Unboxed
import Data.Array.IO

import Debug.Trace

--------------------------------------------------------------------------------
------------------------------- SOLUTION ---------------------------------------
--------------------------------------------------------------------------------

primesUpTo :: Int -> Set Int
primesUpTo n = Set.fromList [p | (p, True) <- assocs $ sieve n]

sieve :: Int -> UArray Int Bool
sieve n = runSTUArray $ do
    sieve <- newArray (2, n) True
    forM_ [2..n] $ \p -> do
        isPrime <- readArray sieve p
        when isPrime $ do
            forM_ [p*2, p*3 .. n] $ \k -> do
                writeArray sieve k False
    return sieve

lim :: Int
lim = 100000

primes :: Set Int
primes = primesUpTo lim

isPrime :: Int -> Bool
isPrime n = Set.member n primes

goldbach :: Int -> (Int, Int)
goldbach n = head $ concatMap (\x -> if Set.member (n-x) primes then [(x,n-x)]
                                     else [])
             $ Set.toList primes

--goldbachs :: UArray Int (Int,Int)
--goldbachs = listArray (4,lim) $ map goldbach [4..lim]

operations :: Int -> Int -> [(Int,Int)]
operations i j
    | j == i = []
    | j == i + 1 = [(i,j)]
    | j == i + 2 = [(i,j)]
    | otherwise  =
        let (x,y) = goldbach (j - i + 1) in
        [(i+x-1,j), (i, i+x-1)]

walkOps :: IOUArray Int Int -> [(Int,Int)] -> Set (Int,Int) ->
           IO (Set (Int,Int))
walkOps a [] heap = return heap
walkOps a ((i,j):t) heap = do
--  elems <- getElems a
--  putStrLn $ show ("Calling walkOps with", elems, i, j, heap, t)
  vi <- readArray a i
  vj <- readArray a j
  writeArray a i vj
  writeArray a j vi
  let heap' = Set.delete (vi,i) . Set.delete (vj,j)
              . Set.insert (vj,i) . Set.insert (vi,j) $ heap
--  putStrLn $ show ("New heap will be", heap')
  heap' `seq` walkOps a t heap'

printOps :: [(Int,Int)] -> IO ()
printOps ops = forM_ ops $ \(i,j) -> putStrLn $ show i ++ " " ++ show j

solve :: IOUArray Int Int -> Set (Int,Int) -> Int -> Int -> IO [(Int,Int)]
solve a heap i k | i > k = return []
                 | otherwise = do
--  elems <- getElems a
--  putStrLn $ show ("Calling solve with", elems, i, heap)
  let (mv,mi) = Set.findMin heap
      ops     = operations i mi
  heap' <- walkOps a ops heap
  let heap'' = Set.delete (i,mv) heap'
  fmap (ops++) $ solve a heap'' (i+1) k

main :: IO ()
main = do
  all   <- BS.getContents
  input <- newIORef all
  let parse = next input
  k <- parse int
  a <- parse $ intMany k
  a' <- newListArray (1,k) a :: IO (IOUArray Int Int)
  let heap = Set.fromList $ zipWith (,) a [1..k]
  ops <- solve a' heap 1 k
  putStrLn $ show $ length ops
  printOps ops
--  elems <- getElems a'
--  putStrLn $ show elems

--------------------------------------------------------------------------------
-------------------------- IO Function Helpers ---------------------------------
--------------------------------------------------------------------------------

type Parser a = BSC.ByteString -> (a, BSC.ByteString)

int :: Parser Int
int = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt

int2 :: Parser (Int, Int)
int2 = uncurry (first . (,)) . second int . int

int3 :: Parser (Int, Int, Int)
int3 = uncurry (first . (uncurry (,,))) . second int . int2

--double :: Parser Double
--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble

char :: Parser Char
char = BSC.head &&& BSC.tail

letter :: Parser Char
letter = second (BSC.dropWhile isSpace) . char

string :: Parser String
string = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)

readMany :: Parser a -> Int -> Parser [a]
readMany f n bs = first reverse $
                  foldr (\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]

intMany :: Int -> Parser [Int]
intMany = readMany int

next :: IORef BSC.ByteString -> Parser a -> IO a
next input parse = do
  bs <- readIORef input
  let (x, bs') = parse bs
  writeIORef input bs'
  return x

{- CODE JAM input

  cases <- parse int
  forM_ [1..cases] $ \caseNum -> do
         -- Read Data
         -- let solution =
         -- solution <-
         printf "Case #%d: %d\n" caseNum solution
-}


import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromMaybe)

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

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

solve :: [Int] -> Int
solve xs
  | tot `mod` n /= 0 = -1
  | otherwise = length $ filter (> tot `div` n) xs
  where
    n = length xs
    tot = sum xs

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

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

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

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

    (putStr . unlines . map solve) tcs

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

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

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

solve nums | (m /= 0) = "-1" | otherwise = show $ length . filter (>avg) $ nums
  where
    s = sum nums
    len = length nums
    m = s `mod` len
    avg = s `div` len

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

printResult = do
    n <- readLn :: IO Int
    a <- readInts
    let s = sum a
        r = if mod s n > 0 then -1 else length $ filter (> div s n) a
    print r

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

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

solve :: [Int] -> Int
solve arr = if r > 0 then -1 else length $ filter ffn arr
  where s = sum arr
        avg = div s $ length arr
        r = rem s $ length arr
        ffn x = x > avg

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

import qualified Data.Set as Set
import Data.List
import Control.Monad

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

printS = do
    n<-readLn::IO Int
    a<-readInts
    let s = sum a
    if (mod s n /= 0) then putStrLn"-1"
    else do
        let b = div s n
        print $ sum[1|x<-a,x>b]

main = do
    t<-readLn
    replicateM_ t printS

{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Control.Monad

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

solve :: Int -> [Int] -> Int
solve n xs
  | dividesFairly = length $ filter (> average) xs
  | otherwise = -1
 where
  total = sum xs
  dividesFairly = total `mod` n == 0
  average = total `div` n

--1538/problem/B. Friends and Candies

toInt :: String -> Int
toInt x = read x ::Int

getInts = do
    x <- getLine
    let y = (map$toInt)$words x
    return y

distribute_co::[Int]->Int->Int
distribute_co (hd:lst) ave
    |lst==[] =
        if hd>ave then 1 else 0
    |hd>ave =
        1+distribute_co lst ave
    |otherwise =
        distribute_co lst ave
distribute::Int->[Int]->Int
distribute n lst
    |mod (sum lst) n/=0 =
        -1
    |otherwise = do
        let ave=div (sum lst) (length lst)
        distribute_co lst ave

loop i f
    |i==1 = do
        n' <- getLine
        let n = toInt n'
        lst <- getInts

        print$f n lst

    |otherwise = do
        n' <- getLine
        let n = toInt n'
        lst <- getInts

        print$f n lst

        loop (i-1) f

main = do
    t' <- getLine
    let t = toInt t'

    loop t distribute

makeInteger :: [String] -> [Int]
makeInteger = map read

main :: IO()
main = do
    line <- getLine
    let t = (read line::Int)
    solve_multitest t

solve_multitest :: Int -> IO()
solve_multitest 0 = return ()
solve_multitest t = do
    solve_test
    solve_multitest (t - 1)

solve_test :: IO()
solve_test = do
    line <- getLine
    let n = (read line::Int)
    line <- getLine
    let inparr = words line
    let arr = makeInteger inparr
    let s = sum arr
    if (rem s n) /= 0 then
        putStrLn "-1"
    else
        putStrLn (show (count_larger_than_k arr (quot s n)))

count_larger_than_k :: [Int] -> Int -> Int
count_larger_than_k [] k = 0
count_larger_than_k a k = do
    if head a > k then
        1 + count_larger_than_k (tail a) k
    else
        count_larger_than_k (tail a) k

--prewritten code: https://github.com/antma/algo
{-# LANGUAGE BangPatterns #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

test' :: [Int] -> Int
test' a
  | v /= 0 = -1
  | otherwise = length $ filter (> u) a
  where
    n = length a
    !s = sum a
    (!u, !v) = divMod s n

nl = char7 '\n'

test :: Builder -> Int -> [Int] -> Builder
test buf 0 _ = buf
test buf nt (n:a) = test (buf <> intDec (test' b) <> nl) (pred nt) c
  where
    (b, c) = splitAt n a

solve :: [Int] -> Builder
solve (nt:xs) = test mempty nt xs

main :: IO ()
main = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents

import Control.Arrow ((>>>))

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

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

solve :: [Int] -> Int
solve xs
  | r == 0 = length $ filter (> q) xs
  | otherwise = -1
  where
    (q, r) = divMod (sum xs) (length xs)

module Main where
import Data.Functor ((<&>))
import Control.Monad (forM, replicateM, replicateM_)
import Data.Foldable (traverse_)
import GHC.Float.RealFracMethods (ceilingDoubleInt, floorDoubleInt)
import Data.List (group)
import Data.Ratio ((%))
import Prelude hiding (floor)
import Control.Monad (forM_)

readInts :: IO [Int]
readInts = getLine <&> words <&> fmap read

readString :: IO String
readString = getLine

toDoubles :: (Functor f, Integral a) => f a -> f Double
toDoubles xs = (\x -> fromIntegral x :: Double) <$> xs

toDouble :: (Integral a) => a -> Double
toDouble = fromIntegral

ceil :: Double -> Int
ceil = ceilingDoubleInt

floor :: Double -> Int
floor = floorDoubleInt

main :: IO ()
main = do
  t:_ <- readInts
  replicateM_ t $ do
    n:_ <- readInts
    as <- readInts
    let
      s = sum as
      p = s `div` n
      ans
          | p * n == s = length . filter (> p) $ as
          | otherwise = -1
    print ans


import qualified Data.ByteString.Char8 as B

main :: IO ()
main = print . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents

solve :: [Int] -> Int
solve (_ : as) = f 0 0 as
  where
  f s _ [] = s
  f s b (a : as)
    | b < a = f (s + a - b) a (a : as)
    | otherwise = f (s + 1 - r) (b + 1) (replicate q (a + 1) ++ ys)
    where
    (xs, ys) = break (> a) (a : as)
    (q, r) = length xs `quotRem` 2

import Data.Map as M hiding (map)
import qualified Data.ByteString.Char8 as B

main :: IO ()
main = print . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents

solve :: [Int] -> Int
solve (_ : as) = f 0 0 $ fromListWith (+) [(a, 1) | a <- as]
  where
  f s b as
    | M.null as = s
    | b < a = f (s + a - b) a as
    | otherwise = f (s + 1 - r) (b + 1) (if q > 0 then M.insertWith (+) (a + 1) q as' else as')
    where
    ((a, p), as') = M.deleteFindMin as
    (q, r) = p `quotRem` 2

import Data.List
import qualified Data.ByteString.Char8 as B

main :: IO ()
main = print . solve . map (maybe 0 fst . B.readInt) . B.words =<< B.getContents

solve :: [Int] -> Int
solve (_ : as) = f 0 0 $ map (\x -> (head x, length x)) $ group as
  where
  f s _ [] = s
  f s b ((a, p) : as)
    | b < a = f (s + a - b) a ((a, p) : as)
    | not (null as) && (c == a + 1) = f (s + 1 - r) (b + 1) ([(a + 1, x + q) | x + q > 0] ++ tail as)
    | otherwise = f (s + 1 - r) (b + 1) ([(a + 1, q) | q > 0] ++ as)
    where
    (q, r) = p `quotRem` 2
    (c, x) = head as

import Data.Map as M hiding (map)
import qualified Data.ByteString.Char8 as B

main :: IO ()
main = print . solve . map read . words =<< getContents

solve :: [Int] -> Int
solve (_ : as) = f 0 0 $ fromListWith (+) [(a, 1) | a <- as]
  where
  f s b as
    | M.null as = s
    | b < a = f (s + a - b) a as
    | otherwise = f (s + 1 - r) (b + 1) (if q > 0 then M.insertWith (+) (a + 1) q as' else as')
    where
    ((a, p), as') = M.deleteFindMin as
    (q, r) = p `quotRem` 2

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, TupleSections #-}

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

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

main :: IO ()
main = do
  _ <- getLine
  xs <- map readInt.B.words <$> B.getLine
  print $ solve xs

solve :: [Int] -> Int
solve xs = go 0 0 $ go0 $ foldr insert Empty xs
   where
     go !res !x (y:ys)
       | x==y = go res (x+1) ys
       | otherwise = go (res+y-x) (y+1) ys
     go !res _ _ = res
     go0 Empty = []
     go0 (Fork x []) = [x]
     go0 heap
       | x == minElem heap' = go0 $ insert (x+1) $ deleteMin heap'
       | otherwise =  x : go0 heap'
      where
        (x, heap') = deleteFindMin heap

data Heap a = Empty | Fork a [Heap a]

isEmpty :: Ord a => Heap a -> Bool
isEmpty Empty = True
isEmpty _ = False

insert :: Ord a => a -> Heap a -> Heap a
insert x h = merge (Fork x []) h

minElem :: Heap a -> a
minElem (Fork x _) = x

deleteMin :: Ord a => Heap a -> Heap a
deleteMin (Fork _ hs) = mergePairs hs

deleteFindMin :: Ord a => Heap a -> (a, Heap a)
deleteFindMin (Fork x hs) = (x, mergePairs hs)

merge :: Ord a => Heap a -> Heap a -> Heap a
merge Empty hy = hy
merge hx Empty = hx
merge hx@(Fork x _) hy@(Fork y _)
  | x <= y    = join hx hy
  | otherwise = join hy hx
 where
   join (Fork x hs) h = Fork x (h:hs)

mergePairs :: Ord a => [Heap a] -> Heap a
mergePairs []       = Empty
mergePairs [x]      = x
mergePairs (x:y:hs) = merge (merge x y) (mergePairs hs)

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, TupleSections #-}

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

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

main :: IO ()
main = do
  _ <- getLine
  xs <- map readInt.B.words <$> B.getLine
  print $ solve xs

solve :: [Int] -> Int
solve xs = go 0 0 $ until isOK step $ step xs
   where
     step = mergeAll.map calc.group
     go !res !x (y:ys)
       | x==y = go res (x+1) ys
       | otherwise = go (res+y-x) (y+1) ys
     go !res _ _ = res
     isOK (x:y:xs)
       | x<y = isOK (y:xs)
       | otherwise = False
     isOK _ = True

calc :: [Int] -> [Int]
calc [] = []
calc xs@(x:_) = go x $ length xs
   where
     go !x !l
       | l <= 1 = take l [x]
       | otherwise = let (q,r) = quotRem l 2
                     in if r==0
                           then go (x+1) q
                           else x : go (x+1) q

mergeAll :: [[Int]] -> [Int]
mergeAll [x] = x
mergeAll xs = mergeAll $ mergePairs xs

mergePairs :: [[Int]] -> [[Int]]
mergePairs (x:y:xs) = merge x y : mergePairs xs
mergePairs xs = xs

merge :: [Int] -> [Int] -> [Int]
merge (x:xs) (y:ys)
  | x <= y = x : merge xs (y:ys)
  | otherwise = y : merge (x:xs) ys
merge xs ys = xs ++ ys

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, TupleSections #-}

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

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

main :: IO ()
main = do
  _ <- getLine
  xs <- map readInt.B.words <$> B.getLine
  print $ solve xs

solve :: [Int] -> Int
solve xs = go 0 0 $ go0 $ foldr insert Empty xs
   where
     go !res !x (y:ys)
       | x==y = go res (x+1) ys
       | otherwise = go (res+y-x) (y+1) ys
     go !res _ _ = res
     go0 Empty = []
     go0 (Fork x []) = [x]
     go0 heap
       | x == minElem heap' = go0 $ deleteMin heap'
       | otherwise =  x : go0 heap'
      where
        (x, heap') = deleteFindMin heap

data Heap a = Empty | Fork a [Heap a]

isEmpty :: Ord a => Heap a -> Bool
isEmpty Empty = True
isEmpty _ = False

insert :: Ord a => a -> Heap a -> Heap a
insert x h = merge (Fork x []) h

minElem :: Heap a -> a
minElem (Fork x _) = x

deleteMin :: Ord a => Heap a -> Heap a
deleteMin (Fork _ hs) = mergePairs hs

deleteFindMin :: Ord a => Heap a -> (a, Heap a)
deleteFindMin (Fork x hs) = (x, mergePairs hs)

merge :: Ord a => Heap a -> Heap a -> Heap a
merge Empty hy = hy
merge hx Empty = hx
merge hx@(Fork x _) hy@(Fork y _)
  | x <= y    = join hx hy
  | otherwise = join hy hx
 where
   join (Fork x hs) h = Fork x (h:hs)

mergePairs :: Ord a => [Heap a] -> Heap a
mergePairs []       = Empty
mergePairs [x]      = x
mergePairs (x:y:hs) = merge (merge x y) (mergePairs hs)

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, TupleSections #-}

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

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

main :: IO ()
main = do
  _ <- getLine
  xs <- map readInt.B.words <$> B.getLine
  print $ solve xs

solve :: [Int] -> Int
solve xs = go 0 0 $ go0 $ step xs
   where
     step = mergeAll.map calc.group
     go0 xs
       | isOK xs = xs
       | otherwise = step xs
     go !res !x (y:ys)
       | x==y = go res (x+1) ys
       | otherwise = go (res+y-x) (y+1) ys
     go !res _ _ = res
     isOK (x:y:xs)
       | x<y = isOK (y:xs)
       | otherwise = False
     isOK _ = True

calc :: [Int] -> [Int]
calc [] = []
calc xs@(x:_) = go x $ length xs
   where
     go !x !l
       | l <= 1 = take l [x]
       | otherwise = let (q,r) = quotRem l 2
                     in if r==0
                           then go (x+1) q
                           else x : go (x+1) q

mergeAll :: [[Int]] -> [Int]
mergeAll [x] = x
mergeAll xs = mergeAll $ mergePairs xs

mergePairs :: [[Int]] -> [[Int]]
mergePairs (x:y:xs) = merge x y : mergePairs xs
mergePairs xs = xs

merge :: [Int] -> [Int] -> [Int]
merge (x:xs) (y:ys)
  | x <= y = x : merge xs (y:ys)
  | otherwise = y : merge (x:xs) ys
merge xs ys = xs ++ ys


{-# LANGUAGE TupleSections #-}
import qualified Data.ByteString.Char8 as B
import qualified Data.IntMap as M
import Data.Maybe

main = do
  input <- fmap B.lines B.getContents
  let [n,k] = map readI $ B.words $ input!!0
  let ps = map readI $ B.words $ input!!1
  putStrLn $ unwords $ map show $  solve k ps

readI :: B.ByteString -> Int
readI s = case B.readInt s of Just (n,_) -> n

solve :: Int -> [Int] -> [Int]
solve k as =
  mapMaybe (`M.lookup`assigns) as
  where
    assigns :: M.IntMap Int
    assigns = foldl f M.empty as

    f :: M.IntMap Int -> Int -> M.IntMap Int
    f m x =
      let lx = max 0 (x-k+1) in
      case (M.member x m, mapMaybe (\i-> fmap (i,) (M.lookup i m)) [x-1,x-2..lx]) of
        (True , _)           -> m
        (False, ((si,sx):_))
          | x < sx+k         -> foldr (`M.insert`sx) m [si+1..x]
          | otherwise        -> foldr (`M.insert`(si+1)) m [si+1..x]
        (False, [])          -> foldr (`M.insert`lx) m [lx..x]

import Data.List
import Data.Maybe
import qualified Data.Map as Map

main = do
    [n, k] <- fmap parseInput $ getLine
    ps <- fmap parseInput $ getLine
    putStrLn $ unwords $ map show $ solve n k ps

parseInput = map readInt . words
    where readInt x = (read x) :: Int

solve n k ps = solve' ps $ Map.empty
    where
        solve' [] _ = []
        solve' (p:ps) mapping
            | isJust stored = (fromJust stored):(solve' ps mapping)
            | otherwise = p':(solve' ps mapping')
            where
                stored = Map.lookup p mapping
                left_lookup = Map.filterWithKey (\x _ -> x `elem` [p-k+1..p]) mapping
                (lx, ly) = Map.findMax left_lookup
                (left_bound, merge_bound)
                    | Map.size left_lookup == 0 = (max (p-k+1) 0, -100000000)
                    | otherwise = (lx + 1, ly)

                p' = if (p - merge_bound) < k
                    then merge_bound
                    else left_bound

                mapping' = foldl' insert' mapping [left_bound..p]
                insert' m x = Map.insert x p' m

import qualified Data.ByteString.Char8 as B
import qualified Data.IntMap as M
import Data.Maybe

main = do
  input <- fmap B.lines B.getContents
  let [n,k] = map readI $ B.words $ input!!0
  let ps = map readI $ B.words $ input!!1
  putStrLn $ unwords $ map show $  solve k ps

readI :: B.ByteString -> Int
readI s = case B.readInt s of Just (n,_) -> n

solve :: Int -> [Int] -> [Int]
solve k as =
  mapMaybe (`M.lookup`assigns) as
  where
    assigns :: M.IntMap Int
    assigns = foldl f M.empty as

    f :: M.IntMap Int -> Int -> M.IntMap Int
    f m x =
      case (M.member x m, filter (`M.notMember`m) [max 0 (x-k+1)..x]) of
        (True , _)     -> m
        (False, (s:_)) -> foldr (`M.insert`s) m [s..s+k-1]

import qualified Data.ByteString.Char8 as B
import Data.List

main = do
  input <- fmap B.lines B.getContents
  let [n,k] = map readI $ B.words $ input!!0
  let ps = map readI $ B.words $ input!!1
  putStrLn $ unwords $ solve k ps

readI :: B.ByteString -> Int
readI s = case B.readInt s of Just (n,_) -> n

solve :: Int -> [Int] -> [String]
solve k as =
  sort $ map (show.f) as
  where
    f x = let (q,r) = x`divMod`k in q*k


main = getContents >>= putStr . unlines . map (solve . words) . tail . lines
    where solve (x:_) = x ++ (' ' : (show $ 2 * (read x)))

solve (l, r) = (l, 2 * l)

readInt :: String -> Int
readInt = read

readPair :: [String] -> (Int, Int)
readPair [x, y] = (readInt x, readInt y)

main = do
    contents <- getContents
    let _:xs = lines contents
    let ans = map (solve . readPair . words) xs
    mapM_ (\(x, y) -> (putStrLn ((show x) ++ " " ++ (show y)))) ans

module Main where
import Control.Monad

main = do
    ts <- (readLn :: IO Int) >>= \x -> replicateM x $ map (read :: String -> Integer) . words <$> getLine
    mapM_ (\[a,b] -> putStrLn $ show a ++ " " ++ show (a*2) ) ts

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

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

main :: IO ()
main = do
  n <- read <$> getLine
  replicateM_ n $ do
    [l,r] <- map read . words <$> getLine :: IO [Int]
    putStrLn $ shows l $ ' ' : show (2*l)

import Control.Monad
main = do
  t <- readLn
  replicateM_ t $ do
    [l,r] <- map read . words <$> getLine
    putStrLn $ show l ++ " " ++ show (2*l)

main = getContents >>= putStrLn . unlines . solve . map read . tail . words

solve [] = []
solve (l:_:ls) = ((show l) ++ " " ++ (show (2 * l))) : solve ls

ipt :: Int -> IO ()
ipt t
 | t == 0 = return ()
 | otherwise = do
  z <- getLine
  let x = words z
  putStrLn (show (read (x !! 0) :: Integer) ++ " " ++ show ((read (x !! 0) :: Integer) * 2))
  ipt (t - 1)

main = do
 x <- getLine
 ipt (read x :: Int)

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

process = do
		[a,b]<-map read <$> words <$> getLine :: IO [Int]
		putStrLn $ intercalate " " $ map show $ head [[x,y]|x<-[a..b],y<-[x+x..b], mod y x ==0]
main = do
		n<- read <$> getLine:: IO Int
		replicateM_ n process

process :: Int -> Int -> (Int, Int)
process l r = (l, 2*l)

readInt :: String -> Int
readInt = read

showPair :: (Int, Int) -> String
showPair (x,y) = show x ++ " " ++ show y

main :: IO ()
main = do
    t <- fmap readInt getLine
    ts <- fmap (map (map readInt.words).lines) getContents
    mapM_ (putStrLn.showPair) $ map (\[l,r] -> process l r) ts

ipt :: Int -> IO ()
ipt t
 | t == 0 = return ()
 | otherwise = do
  z <- getLine
  let x = words z
  print (show (read (x !! 0) :: Integer) ++ " " ++ show ((read (x !! 0) :: Integer) * 2))
  ipt (t - 1)

main = do
 x <- getLine
 ipt (read x :: Int)

ipt :: Int -> IO ()
ipt t
 | t == 0 = print ""
 | otherwise = do
  z <- getLine
  let x = words z
  print (show (read (x !! 0) :: Integer) ++ " " ++ show ((read (x !! 0) :: Integer) * 2))
  ipt (t - 1)

main = do
 x <- getLine
 ipt (read x :: Int)


import Control.Applicative
import Control.Monad

main :: IO ()
main = do
  [n, k] <- map read . words <$> getLine
  if n < k * 2 + 1
    then print (-1)
    else do
    print (n*k)
    forM_ [0..n-1] $ \i -> do
      forM_ [1..k] $ \j -> do
        putStrLn $ unwords $ map show [i+1, (i+j)`mod`n+1]

  return ()

import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Array

readInt :: IO Integer
readInt = read <$> getLine
readIntList :: IO [Integer]
readIntList = fmap read . words <$> getLine
readIntArray :: Integer -> IO (Array Integer Integer)
readIntArray n = listArray (0, n-1) <$> readIntList
readSortedIntArray :: Integer -> IO (Array Integer Integer)
readSortedIntArray n = listArray (0, n-1) . sort <$> readIntList

main :: IO ()
main = do
  [n, k] <- readIntList
  if 2 * k <= n-1
    then do
      putStrLn $ show $ n*k
      forM [1..n] $ \i ->
        forM [1..k] $ \j ->
          putStrLn $ show i ++ " " ++ show ((i + j - 1) `mod` n + 1)
      return ()
    else putStrLn $ show (-1)

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad
import Control.Monad.ST

import Data.Bits
import Data.Char
import Data.Either
import Data.Function
import Data.IORef
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
-- }}}
-- silly utilities {{{
(#) = flip ($)
infixl 0 #

glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)

(!>) :: Seq a -> Int -> a
(!>) = Seq.index
-- }}}
-- input and output {{{
inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

main :: IO ()
main = do
	[n, k] <- inputInts
	if (2*k > n-1) then print (-1) else do
		print $ n*k
		printMatrix [[(i+1),((i+j+1)`rem`n + 1)] | i <- [0..n-1], j <- [0..k-1]]

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad
import Control.Monad.ST

import Data.Bits
import Data.Char
import Data.Either
import Data.Function
import Data.IORef
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
-- }}}
-- silly utilities {{{
(#) = flip ($)
infixl 0 #

glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)

(!>) :: Seq a -> Int -> a
(!>) = Seq.index
-- }}}
-- input and output {{{
inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]
-- }}}

main :: IO ()
main = do
	[n, k] <- inputInts
	if (2*k > n-1) then print (-1) else do
		print $ n*k
		sequence_ [printf "%d %d\n" (i+1) ((i+j+1)`rem`n + 1) | i <- [0..n-1], j <- [0..k-1]]

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad
import Control.Monad.ST

import Data.Bits
import Data.Char
import Data.Either
import Data.Function
import Data.IORef
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
-- }}}
-- silly utilities {{{
(#) = flip ($)
infixl 0 #

glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)

(!>) :: Seq a -> Int -> a
(!>) = Seq.index
-- }}}
-- input and output {{{
inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn . unwords $ map show xs
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr . unlines $ map (unwords . map show) xs
-- }}}

main :: IO ()
main = do
	[n, k] <- inputInts
	if (2*k > n-1) then print (-1) else do
		print $ n*k
		printMatrix [[(i+1),((i+j+1)`rem`n + 1)] | i <- [0..n-1], j <- [0..k-1]]

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad
import Control.Monad.ST

import Data.Bits
import Data.Char
import Data.Either
import Data.Function
import Data.IORef
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
-- }}}
-- silly utilities {{{
(#) = flip ($)
infixl 0 #

glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)

(!>) :: Seq a -> Int -> a
(!>) = Seq.index
-- }}}
-- input and output {{{
inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = mapM_ (putStrLn . showMany) xs
-- }}}

main :: IO ()
main = do
	[n, k] <- inputInts
	if (2*k > n-1) then print (-1) else do
		print $ n*k
		printMatrix [[(i+1),((i+j+1)`rem`n + 1)] | i <- [0..n-1], j <- [0..k-1]]

import Control.Applicative
import Control.Monad

main :: IO ()
main = do
  [n, k] <- map read . words <$> getLine
  if n <= k
    then print (-1)
    else do
    print (n*k)
    forM_ [0..n-1] $ \i -> do
      forM_ [1..k] $ \j -> do
        putStrLn $ unwords $ map show [i+1, (i+j)`mod`n+1]

  return ()

import Control.Applicative
import Control.Monad

main :: IO ()
main = do
  [n, k] <- map read . words <$> getLine
  if n == 1
    then print (-1)
    else do
    print (n*k)
    forM_ [0..n-1] $ \i -> do
      forM_ [1..k] $ \j -> do
        putStrLn $ unwords $ map show [i+1, (i+1)`mod`n+1]

  return ()

import Control.Applicative
import Control.Monad

main :: IO ()
main = do
  [n, k] <- map read . words <$> getLine
  if n == 1
    then print (-1)
    else do
    print (n*k)
    forM_ [0..n-1] $ \i -> do
      forM_ [1..k] $ \j -> do
        putStrLn $ unwords $ map show [i+1, (i+j)`mod`n+1]

  return ()