The only difference between this problem and D1 is that you don't have to provide the way to construct the answer in D1, but you have to do it in this problem.There's a table of $$$n \times m$$$ cells ($$$n$$$ rows and $$$m$$$ columns). The value of $$$n \cdot m$$$ is even.A domino is a figure that consists of two cells having a common side. It may be horizontal (one of the cells is to the right of the other) or vertical (one of the cells is above the other).You need to place $$$\frac{nm}{2}$$$ dominoes on the table so that exactly $$$k$$$ of them are horizontal and all the other dominoes are vertical. The dominoes cannot overlap and must fill the whole table.

The first line contains one integer $$$t$$$ ($$$1 \le t \le 10$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case consists of a single line. The line contains three integers $$$n$$$, $$$m$$$, $$$k$$$ ($$$1 \le n,m \le 100$$$, $$$0 \le k \le \frac{nm}{2}$$$, $$$n \cdot m$$$ is even) — the count of rows, columns and horizontal dominoes, respectively.

For each test case:   print "NO" if it's not possible to place the dominoes on the table in the described way;  otherwise, print "YES" on a separate line, then print $$$n$$$ lines so that each of them contains $$$m$$$ lowercase letters of the Latin alphabet — the layout of the dominoes on the table. Each cell of the table must be marked by the letter so that for every two cells having a common side, they are marked by the same letters if and only if they are occupied by the same domino. I.e. both cells of the same domino must be marked with the same letter, but two dominoes that share a side must be marked with different letters. If there are multiple solutions, print any of them.

YES
accx
aegx
bega
bdda
YES
aha
aha
YES
zz
aa
zz
NO
YES
aaza
bbza
NO
YES
bbaabbaabbaabbaay
ddccddccddccddccy
NO

import Control.Monad (replicateM_, guard)
import Data.List (intercalate)

genElems :: Int -> [a] -> [a]
genElems n = take n . concat . repeat

appendColumn :: [a] -> [[a]] -> [[a]]
appendColumn = zipWith (:)

evenMatrix :: (Int, Int, Int) -> [[Char]]
evenMatrix (n, m, k) = go (n, m, k) "xy" where
  go (0, _, _) _ = []
  go (n, m, remHorz)  vertChars = (r1 ++ c1) : (r2 ++ c2) : next where
    numHorz = if remHorz >= m then m else remHorz
    numVert = m - numHorz
    nextVertChars = if vertChars == "xy" then "ij" else "xy"
    r1 = genElems numHorz "aabb"
    r2 = genElems numHorz "ccdd"
    c1 = genElems numVert nextVertChars
    c2 = genElems numVert nextVertChars
    next = go (n - 2, m, remHorz - numHorz) nextVertChars

solve :: (Int, Int, Int) -> Maybe [[Char]]
solve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems m "aabb"]
solve (n, 1, k) = do guard $ k == 0 ; return $ genElems n ["p", "p", "q", "q"]
solve (n, m, k)
  | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)
  | odd m = do
      let x = (n * m) `div` 2 - k - n `div` 2
      guard $ x >= 0 && even x
      let col = genElems n "ppqq" ; mat = evenMatrix (n, m - 1, k)
      return $ appendColumn col mat
  | otherwise = do
      let x = k - m `div` 2
      guard $ x >= 0 && even x
      return $ genElems m "eeff" : evenMatrix (n - 1, m, k - m `div` 2)

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, m, k] <- readInts
    let mat = solve (n, m, k)
    putStrLn $ maybe "NO" (intercalate "\n" . ("YES":)) mat

import Control.Arrow ((>>>))
import Data.Bool (bool)
import Control.Monad (guard)
import Data.List (intercalate)

main :: IO ()
main =
  interact $
    lines
      >>> drop 1
      >>> map (words >>> map read >>> solve >>> maybe "NO" (intercalate "\n" . ("YES":)))
      >>> unlines

type Sol = Maybe [[Char]]

solve :: [Int] -> Sol
solve [0, _, 0] = Just []
solve [0, _, _] = Nothing
solve [n, m, k]
  | n == 2 = do
      guard $ k <= n * m'
      guard $ even k
      let rowH0 = stream k "aabb"
      let rowH1 = stream k "ccdd"
      let rowV = stream (m - k) "pq"
      return [rowH0 ++ rowV, rowH1 ++ rowV]
  | even n = do
      guard $ k <= n * m'
      guard $ even k
      let pick = min k (2 * m')
      top <- conv <$> solve [2, m, pick]
      rest <- solve [n - 2, m, k - pick]
      return $ top ++ rest
  | odd n = do
      guard $ k >= m'
      g <- solve [n - 1, m, k - m']
      let top = stream m "yyzz"
      return $ top : g
  where
    m' = m `div` 2
    stream l = take l . concat . repeat
    conv = if n `mod` 4 == 2 then id else map (map change)
    change 'p' = 'r'
    change 'q' = 's'
    change c = c

import Control.Monad (replicateM_, guard)
import Data.List (intercalate)

genElems :: Int -> [a] -> [a]
genElems n = take n . concat . repeat

appendColumn :: [a] -> [[a]] -> [[a]]
appendColumn = zipWith (:)

evenMatrix :: (Int, Int, Int) -> [[Char]]
evenMatrix (n, m, k) = go (n, m, k) "xy" where
  go (0, _, _) _ = []
  go (n, m, remHorz)  vertChars = (r1 ++ c1) : (r2 ++ c2) : next where
    numHorz = if remHorz >= m then m else remHorz
    numVert = m - numHorz
    nextVertChars = if vertChars == "xy" then "ij" else "xy"
    r1 = genElems numHorz "aabb"
    r2 = genElems numHorz "ccdd"
    c1 = genElems numVert nextVertChars
    c2 = genElems numVert nextVertChars
    next = go (n - 2, m, remHorz - numHorz) nextVertChars

solve :: (Int, Int, Int) -> Maybe [[Char]]
solve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k "aabb"]
solve (n, 1, k) = do guard $ k == 0 ; return $ genElems n ["p", "p", "q", "q"]
solve (n, m, k)
  | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)
  | odd m = do
      let x = (n * m) `div` 2 - k - n `div` 2
      guard $ x >= 0 && even x
      let col = genElems n "ppqq" ; mat = evenMatrix (n, m - 1, k)
      return $ appendColumn col mat
  | otherwise = do
      let x = k - m `div` 2
      guard $ x >= 0 && even x
      return $ genElems m "eeff" : evenMatrix (n - 1, m, k - m `div` 2)

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, m, k] <- readInts
    let mat = solve (n, m, k)
    putStrLn $ maybe "NO" (intercalate "\n" . ("YES":)) mat

import Control.Monad (replicateM_, guard)
import Data.List (intercalate)

genElems :: Int -> [a] -> [a]
genElems n = take n . concat . repeat

appendColumn :: [a] -> [[a]] -> [[a]]
appendColumn = zipWith (:)

evenMatrix :: (Int, Int, Int) -> [[Char]]
evenMatrix (n, m, k) = go (n, m, k) "xy" where
  go (0, _, _) _ = []
  go (n, m, remHorz)  vertChars = (r1 ++ c1) : (r2 ++ c2) : next where
    numHorz = if remHorz >= m then m else remHorz
    numVert = m - numHorz
    nextVertChars = if vertChars == "xy" then "ij" else "xy"
    r1 = genElems numHorz "aabb"
    r2 = genElems numHorz "ccdd"
    c1 = genElems numVert nextVertChars
    c2 = genElems numVert nextVertChars
    next = go (n - 2, m, remHorz - numHorz) nextVertChars

solve :: (Int, Int, Int) -> Maybe [[Char]]
solve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k "aabb"]
solve (n, 1, k) = do guard $ k == 0 ; return $ genElems n ["p", "p", "q", "q"]
solve (n, m, k)
  | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)
  | odd m = do
      guard $ even $ (n * m) `div` 2 - k - n `div` 2
      let col = genElems n "ppqq" ; mat = evenMatrix (n, m - 1, k)
      return $ appendColumn col mat
  | otherwise = do
      guard $ even $ k - m `div` 2
      return $ genElems m "eeff" : evenMatrix (n - 1, m, k - m `div` 2)

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, m, k] <- readInts
    let mat = solve (n, m, k)
    putStrLn $ maybe "NO" (intercalate "\n" . ("YES":)) mat

import Control.Monad (replicateM_, guard)
import Data.List (intercalate)

genElems :: Int -> [a] -> [a]
genElems n = take n . concat . repeat

appendColumn :: [a] -> [[a]] -> [[a]]
appendColumn = zipWith (:)

evenMatrix :: (Int, Int, Int) -> [[Char]]
evenMatrix (n, m, k) = go (n, m, k) "xy" where
  go (0, _, _) _ = []
  go (n, m, remHorz)  vertChars = (r1 ++ c1) : (r2 ++ c2) : next where
    numHorz = if remHorz >= m then m else remHorz
    numVert = m - numHorz
    nextVertChars = if vertChars == "xy" then "ij" else "xy"
    r1 = genElems numHorz "aabb"
    r2 = genElems numHorz "ccdd"
    c1 = genElems numVert nextVertChars
    c2 = genElems numVert nextVertChars
    next = go (n - 2, m, remHorz - numHorz) nextVertChars

solve :: (Int, Int, Int) -> Maybe [[Char]]
solve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k "aabb"]
solve (n, 1, k) = do guard $ k == 0 ; return $ genElems n ["p", "p", "q", "q"]
solve (n, m, k)
  | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)
  | odd m = do
      guard $ even $ (n * m) `div` 2 - k - n `div` 2
      let col = genElems n "ppqq" ; mat = evenMatrix (n, m - 1, k)
      return $ appendColumn col mat
  | otherwise = do
      guard $ even $ k - m `div` 2
      return $ genElems m "eeff" : evenMatrix (n - 1, m, k)

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, m, k] <- readInts
    let mat = solve (n, m, k)
    putStrLn $ maybe "NO" (intercalate "\n" . ("YES":)) mat

import Control.Monad (replicateM_, guard)
import Data.List (intercalate)

genElems :: Int -> [a] -> [a]
genElems n = take n . concat . repeat

appendColumn :: [a] -> [[a]] -> [[a]]
appendColumn = zipWith (:)

evenMatrix :: (Int, Int, Int) -> [[Char]]
evenMatrix (n, m, k) = go (n, m, k) "xy" where
  go (0, _, _) _ = []
  go (n, m, remHorz)  vertChars = (r1 ++ c1) : (r2 ++ c2) : next where
    numHorz = if remHorz >= m then m else remHorz
    numVert = m - numHorz
    nextVertChars = if vertChars == "xy" then "ij" else "xy"
    r1 = genElems numHorz "aabb"
    r2 = genElems numHorz "ccdd"
    c1 = genElems numVert nextVertChars
    c2 = genElems numVert nextVertChars
    next = go (n - 2, m, remHorz - numHorz) nextVertChars

solve :: (Int, Int, Int) -> Maybe [[Char]]
solve (1, m, k) = do guard $ m `div` 2 == k ; return [genElems k "aabb"]
solve (n, 1, k) = do guard $ k == 0 ; return $ genElems n ["p", "q"]
solve (n, m, k)
  | even n && even m = do guard $ even k ; return $ evenMatrix (n, m, k)
  | odd m = do
      guard $ even $ (n * m) `div` 2 - k - n `div` 2
      let col = genElems n "pq" ; mat = evenMatrix (n, m - 1, k)
      return $ appendColumn col mat
  | otherwise = do
      guard $ even $ k - m `div` 2
      return $ genElems m "eeff" : evenMatrix (n - 1, m, k)

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [n, m, k] <- readInts
    let mat = solve (n, m, k)
    putStrLn $ maybe "NO" (intercalate "\n" . ("YES":)) mat

import Control.Arrow ((>>>))
import Data.Bool (bool)
import Control.Monad (guard)

main :: IO ()
main =
  interact $
    lines
      >>> drop 1
      >>> map (words >>> map read >>> solve >>> maybe "NO" (unlines . ("YES":)))
      >>> unlines

type Sol = Maybe [[Char]]

solve :: [Int] -> Sol
solve [0, _, 0] = Just []
solve [0, _, _] = Nothing
solve [n, m, k]
  | n == 2 = do
      guard $ k <= n * m'
      guard $ even k
      let rowH0 = stream k "aabb"
      let rowH1 = stream k "ccdd"
      let rowV = stream (m - k) "pq"
      return [rowH0 ++ rowV, rowH1 ++ rowV]
  | even n = do
      guard $ k <= n * m'
      guard $ even k
      let pick = min k (2 * m')
      top <- conv <$> solve [2, m, pick]
      rest <- solve [n - 2, m, k - pick]
      return $ top ++ rest
  | odd n = do
      guard $ k >= m'
      g <- solve [n - 1, m, k - m']
      let top = stream m "yyzz"
      return $ top : g
  where
    m' = m `div` 2
    stream l = take l . concat . repeat
    conv = if n `mod` 4 == 2 then id else map (map change)
    change 'p' = 'r'
    change 'q' = 's'
    change c = c


Vova again tries to play some computer card game.The rules of deck creation in this game are simple. Vova is given an existing deck of n cards and a magic number k. The order of the cards in the deck is fixed. Each card has a number written on it; number ai is written on the i-th card in the deck.After receiving the deck and the magic number, Vova removes x (possibly x = 0) cards from the top of the deck, y (possibly y = 0) cards from the bottom of the deck, and the rest of the deck is his new deck (Vova has to leave at least one card in the deck after removing cards). So Vova's new deck actually contains cards x + 1, x + 2, ... n - y - 1, n - y from the original deck.Vova's new deck is considered valid iff the product of all numbers written on the cards in his new deck is divisible by k. So Vova received a deck (possibly not a valid one) and a number k, and now he wonders, how many ways are there to choose x and y so the deck he will get after removing x cards from the top and y cards from the bottom is valid?

The first line contains two integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109). The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the numbers written on the cards.

Print the number of ways to choose x and y so the resulting deck is valid.

NoteIn the first example the possible values of x and y are:  x = 0, y = 0;  x = 1, y = 0;  x = 2, y = 0;  x = 0, y = 1.

-- http://codeforces.com/contest/818/submission/28343312

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

getInt = read `fmap` getLine :: IO Int
getInt64s = (map parseInt64 . BS8.words) `fmap` BS.getLine :: IO [Int64]
parseInt64 = fromIntegral . fst . fromJust . BS8.readInteger

main = do
    [n,k] <- getInt64s
    cs <- getInt64s
    let cards = listArray (0,fromIntegral n - 1) cs :: Array Int Int64
    print (solve cards n k)

solve :: Array Int Int64 -> Int64 -> Int64 -> Int64
solve cards n k = f (0,0,-1,0) where
    f :: (Int64, Int64, Int64, Int64) -> Int64
    f (l, r, prev, answer)
        | r >= n = answer
        | curr /= 0 = answer
        | curr2 == 0 = f (l'+1, r'+1, l', answer')
        | otherwise = f (l'+1, r'+1, prev, answer)
        where
            (r', curr) = g (r, 1, [l..n-1])
            (l', curr2) = h (l, 1, [r',r'-1..0])
            answer' = answer + (l' - prev) * (n - r')
    g (r, curr, []) = (r, curr)
    g (r, curr, (i:is))
        | curr' == 0 = (i, curr')
        | otherwise = g (r, curr', is)
        where curr' = (curr * (cards ! (fromIntegral i))) `mod` k
    h (l, curr, []) = (l, curr)
    h (l, curr, (i:is))
        | curr' == 0 = (i, curr')
        | otherwise = h (l, curr', is)
        where curr' = (curr * (cards ! (fromIntegral i))) `mod` k


Polycarp got an array of integers $$$a[1 \dots n]$$$ as a gift. Now he wants to perform a certain number of operations (possibly zero) so that all elements of the array become the same (that is, to become $$$a_1=a_2=\dots=a_n$$$). In one operation, he can take some indices in the array and increase the elements of the array at those indices by $$$1$$$.For example, let $$$a=[4,2,1,6,2]$$$. He can perform the following operation: select indices 1, 2, and 4 and increase elements of the array in those indices by $$$1$$$. As a result, in one operation, he can get a new state of the array $$$a=[5,3,1,7,2]$$$.What is the minimum number of operations it can take so that all elements of the array become equal to each other (that is, to become $$$a_1=a_2=\dots=a_n$$$)?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)  — the number of test cases in the test. The following are descriptions of the input test cases. The first line of the description of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$)  — the array $$$a$$$. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — elements of the array $$$a$$$.

For each test case, print one integer  — the minimum number of operations to make all elements of the array $$$a$$$ equal.

NoteFirst test case:   $$$a=[3,4,2,4,1,2]$$$ take $$$a_3, a_5$$$ and perform an operation plus one on them, as a result we get $$$a=[3,4,3,4,2,2]$$$.  $$$a=[3,4,3,4,2,2]$$$ we take $$$a_1, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,3,4,3,3]$$$.  $$$a=[4,4,3,4,3,3]$$$ we take $$$a_3, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,4,4,4,4]$$$. There are other sequences of $$$3$$$ operations, after the application of which all elements become equal.Second test case:   $$$a=[1000,1002,998]$$$ 2 times we take $$$a_1, a_3$$$ and perform an operation plus one on them, as a result we get $$$a=[1002,1002,1000]$$$.  $$$a=[1002,1002,1000]$$$ also take $$$a_3$$$ 2 times and perform an operation plus one on it, as a result we get $$$a=[1002,1002,1002]$$$. Third test case:   $$$a=[12,11]$$$ take $$$a_2$$$ and perform an operation plus one on it, as a result we get $$$a=[12,12]$$$.

-- https://codeforces.com/contest/1624/problem/A
-- A. Plus One on the Subset
import qualified Data.List as L
import System.IO
import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder.Prim as Prim
import Data.ByteString.Builder

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

handleData1 [] = []
handleData1 intss = do
	let
		ints = head intss
		maxi = L.maximum ints
		mini = L.minimum ints
		in (maxi - mini) : (handleData1 (tail intss))

-- read_intss :: Int -> IO ([[Int]])
read_intss 0 = do return []
read_intss ints_count = do
	int_count_str <- getLine
	ints_str <- getLine
	last_intss <- read_intss (ints_count-1)
	let now_inst =map (\x -> read x :: Int) $ words ints_str
		in return (now_inst : last_intss)

main = do
	hSetBuffering stdout NoBuffering
	data_count_str <- getLine
	intss <- read_intss $ read $ data_count_str
	-- putStrLn $ L.intercalate "\n" $ putInts $ handleData1 intss
	P.putStr $ toLazyByteString $ putInts $ handleData1 intss

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

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

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    a <- getInts n
    pure $ putInts [maximum a - minimum a]

type SP = State [P.ByteString]

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

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

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

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

-- https://codeforces.com/contest/1624/problem/A
-- A. Plus One on the Subset
import qualified Data.List as L

handleData1 [] = []
handleData1 intss = do
	let
		ints = head intss
		maxi = L.maximum ints
		mini = L.minimum ints
		in (show (maxi - mini)) : (handleData1 (tail intss))

-- read_intss :: Int -> IO ([[Int]])
read_intss 0 = do return []
read_intss ints_count = do
	int_count_str <- getLine
	ints_str <- getLine
	last_intss <- read_intss (ints_count-1)
	let now_inst =map (\x -> read x :: Int) $ words ints_str
		in return (now_inst : last_intss)

main = do
	data_count_str <- getLine
	intss <- read_intss $ read $ data_count_str
	putStrLn $ L.intercalate "\n" $ handleData1 intss

import System.IO
import qualified Data.List as L

handleData1 0 = do return ()
handleData1 dataCount = do
	int_count_str <- getLine
	ints_str <- getLine
	let ints = map (\x -> read x :: Int) $ words ints_str
		in print $ (L.maximum ints) - (L.minimum ints)
	handleData1 (dataCount-1)

main = do
	data_count_str <- getLine
	let data_count = read data_count_str
		in handleData1 data_count

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

import Data.Maybe
import Control.Monad

solve = do
  nStr <- B.getLine
  asStr <- B.getLine

  let n = fst $ fromJust $ C.readInt nStr
  let as = map (fst . fromJust . C.readInt) (C.words asStr)

  print (maximum as - minimum as)

main = do
  str <- B.getLine

  let t = fst $ fromJust $ C.readInt str

  replicateM_ t solve

import Control.Monad
import System.IO

solve = do
  n <- readLn :: IO Int
  str <- getLine

  let as = map (read :: String -> Int) (words str)

  print (maximum as - minimum as)

main :: IO()
main = do
  hSetBuffering stdout LineBuffering

  t <- readLn :: IO Int

  replicateM_ t solve

import Control.Monad

solve = do
  n <- readLn :: IO Int
  str <- getLine

  let as = map (read :: String -> Int) (words str)

  print (maximum as - minimum as)

main = do
  t <- readLn :: IO Int

  replicateM_ t solve

import Control.Monad(replicateM)
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Builder.Prim as Prim
import Data.ByteString.Builder
import Control.Monad.Trans.State
import Data.Maybe
import System.IO

solve :: SB Builder
solve = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n]  <- getInts 1
    xs    <- getInts n
    return $ putInts [maximum xs - minimum xs]

-- stdin/out from solution by clyring
type SB = State [B.ByteString]

getNext :: Int -> SB [B.ByteString]
getNext = state . splitAt

parseInt = fst . fromJust . B.readInt

getInts :: Int -> SB [Int]
getInts n = map parseInt <$> getNext n

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

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- B.getContents
  let  out = evalState solve $ B.words inp
  B.putStr $ toLazyByteString out

import Control.Monad(replicateM)
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Builder.Prim as Prim
import Data.ByteString.Builder
import Control.Monad.Trans.State
import Data.Maybe
import System.IO

solve :: SB Builder
solve = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n]  <- getInts 1
    xs    <- getInts n
    return $ putInts [maximum xs - minimum xs]

-- stdin/out from solution by clyring
type SB = State [B.ByteString]

getNext :: Int -> SB [B.ByteString]
getNext = state . splitAt

getInts :: Int -> SB [Int]
getInts n = map parseInt <$> getNext n
  where
    parseInt = fst . fromJust . B.readInt

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

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- B.getContents
  let  out = evalState solve $ B.words inp
  B.putStr $ toLazyByteString out

import Control.Monad(replicateM_)

solve :: [Int] -> Int
solve xs = max - min
  where
    max = maximum xs
    min = minimum xs

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

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    getLine
    xs  <- readInts
    let ans = solve xs
    print ans

-- https://codeforces.com/contest/1624/problem/A
import Control.Monad (replicateM_)

main = getLine >>= flip replicateM_ run . read
run = do
    getLine
    a <- (read <$>) . words <$> getLine
    print $ maximum a - minimum a

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

solve [] = 0
solve lst = maximum lst - minimum lst

rep 0 = return ()
rep x = do
    n <- getLine
    arr <- getLine
    let intList = map (read::String->Int) (words arr)
    print(solve intList)
    rep (x - 1)

main :: IO ()
main = do
    t <- getLine
    rep (read t)

import Control.Monad
import Data.List

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

solve :: Integer -> [Integer] -> Integer
solve _ a = sum $ zipWith subtract a' (tail a')
  where
    a' = sort a

main = readLn >>= sequence_ . flip replicate (getLine >> getLine >>= print . ((-) <$> maximum <*> minimum) . map read . words)

readInt :: IO Int
readInt = readLn

readIntArray :: IO [Int]
readIntArray = (map read . words) <$> getLine

main :: IO ()
main = do
    test <- readInt
    solve test

solve :: Int -> IO ()
solve 0 = pure ()
solve test = do
    n <- readInt
    dt <- readIntArray
    print $ maximum dt - minimum dt
    solve $ test - 1

module Main where

readInt :: IO Int
readInt = readLn

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

solve :: Int -> IO ()
solve 0 = return ()
solve t = do n <- readInt
             ns <- readInts
             let ans = maximum ns - minimum ns in
               print ans
             solve (t - 1)

main :: IO ()
main = do t <- readInt
          solve t

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf i xs = take i xs : chunksOf i (drop i xs)

toArr :: Read a => String -> [a]
toArr = map read . words

type InType  = [Int]
type OutType = Int

solve :: InType -> OutType
solve xs = maximum xs - minimum xs

receive :: [String] -> InType
receive [_, s] = toArr s
receive x = error  "wrong input"

main :: IO ()
main = interact $ unlines . map (show . solve . receive) . chunksOf 2 . tail . lines

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

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

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

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    a <- getInts n
    let
      b = sort a
      z = last b - head b
    pure $ putInts [z]

type SP = State [P.ByteString]

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

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

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

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

import Data.Char
main :: IO()
main = do
    -- print 5
    tStr <- getLine
    -- print $ show tStr
    let t = read tStr :: Int
    solve t

solve :: Int -> IO()
solve 0 = return ()
solve t = do
    nStr <- getLine
    -- print nStr
    let n = read nStr :: Int

    aStr <- getLine
    -- print aStr
    let as = readIntList aStr  :: [Int]

    -- print as

    print (maxVal as - minVal as)
    solve (t-1)

readIntList :: String -> [Int]
readIntList [] = []
readIntList (h : t)
    | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)
    | otherwise = readIntList t

maxVal :: [Int] -> Int
maxVal = foldr max 0

minVal :: [Int] -> Int
minVal = foldr min 1000000000

module Main where

import           Control.Monad (replicateM_)

main = do
  t <- read <$> getLine
  replicateM_ t
    $ do
      n <- getLine
      xs <- map read . words <$> getLine
      print (maximum xs - minimum xs)

-- https://codeforces.com/contest/1624/problem/A
import Control.Monad (replicateM_)
import qualified Data.ByteString.Char8 as B
import Data.Maybe (fromJust)

main = getLine >>= flip replicateM_ run . read
run = do
    getLine
    a <- (fst.fromJust.B.readInt <$>) . B.words <$> B.getLine
    print $ maximum a - minimum a

-- https://codeforces.com/contest/1624/problem/A
import Control.Monad (replicateM_)
import Data.Maybe (fromJust)
import qualified Data.ByteString.Char8 as B

main = getLine >>= flip replicateM_ run . read
run = do
    getLine
    a <- (fst.fromJust.B.readInt <$>) . B.words <$> B.getLine
    print $ maximum a - minimum a


There is a city that can be represented as a square grid with corner points in $$$(0, 0)$$$ and $$$(10^6, 10^6)$$$.The city has $$$n$$$ vertical and $$$m$$$ horizontal streets that goes across the whole city, i. e. the $$$i$$$-th vertical streets goes from $$$(x_i, 0)$$$ to $$$(x_i, 10^6)$$$ and the $$$j$$$-th horizontal street goes from $$$(0, y_j)$$$ to $$$(10^6, y_j)$$$. All streets are bidirectional. Borders of the city are streets as well.There are $$$k$$$ persons staying on the streets: the $$$p$$$-th person at point $$$(x_p, y_p)$$$ (so either $$$x_p$$$ equal to some $$$x_i$$$ or $$$y_p$$$ equal to some $$$y_j$$$, or both).Let's say that a pair of persons form an inconvenient pair if the shortest path from one person to another going only by streets is strictly greater than the Manhattan distance between them.Calculate the number of inconvenient pairs of persons (pairs $$$(x, y)$$$ and $$$(y, x)$$$ are the same pair).Let's recall that Manhattan distance between points $$$(x_1, y_1)$$$ and $$$(x_2, y_2)$$$ is $$$|x_1 - x_2| + |y_1 - y_2|$$$.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first line of each test case contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$2 \le n, m \le 2 \cdot 10^5$$$; $$$2 \le k \le 3 \cdot 10^5$$$) — the number of vertical and horizontal streets and the number of persons. The second line of each test case contains $$$n$$$ integers $$$x_1, x_2, \dots, x_n$$$ ($$$0 = x_1 < x_2 < \dots < x_{n - 1} < x_n = 10^6$$$) — the $$$x$$$-coordinates of vertical streets. The third line contains $$$m$$$ integers $$$y_1, y_2, \dots, y_m$$$ ($$$0 = y_1 < y_2 < \dots < y_{m - 1} < y_m = 10^6$$$) — the $$$y$$$-coordinates of horizontal streets. Next $$$k$$$ lines contains description of people. The $$$p$$$-th line contains two integers $$$x_p$$$ and $$$y_p$$$ ($$$0 \le x_p, y_p \le 10^6$$$; $$$x_p \in \{x_1, \dots, x_n\}$$$ or $$$y_p \in \{y_1, \dots, y_m\}$$$) — the coordinates of the $$$p$$$-th person. All points are distinct. It guaranteed that sum of $$$n$$$ doesn't exceed $$$2 \cdot 10^5$$$, sum of $$$m$$$ doesn't exceed $$$2 \cdot 10^5$$$ and sum of $$$k$$$ doesn't exceed $$$3 \cdot 10^5$$$.

For each test case, print the number of inconvenient pairs.

NoteThe second test case is pictured below:   For example, points $$$3$$$ and $$$4$$$ form an inconvenient pair, since the shortest path between them (shown red and equal to $$$7$$$) is greater than its Manhattan distance (equal to $$$5$$$).Points $$$3$$$ and $$$5$$$ also form an inconvenient pair: the shortest path equal to $$$1000001$$$ (shown green) is greater than the Manhattan distance equal to $$$999999$$$.But points $$$5$$$ and $$$9$$$ don't form an inconvenient pair, since the shortest path (shown purple) is equal to its Manhattan distance.

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE Strict #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Function
import Data.Int
import qualified Data.IntMap as M
import qualified Data.IntSet as S
import Data.List
import Data.Maybe
import Data.Tuple (swap)
import Debug.Trace (trace)

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

type PII = (Int, Int)
type Input = ([Int], [Int], [PII])
type Output = Int64

input :: Scanner Input
input = do
  n <- int
  m <- int
  k <- int
  xs <- n >< int
  ys <- m >< int
  ps <- k >< pair int int
  return (xs, ys, ps)

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

solve :: Input -> Output
solve (S.fromList -> xs, S.fromList -> ys, ps) = compute ps xs ys + compute (map swap ps) ys xs

compute :: [PII] -> S.IntSet -> S.IntSet -> Int64
compute ps xs ys = fst $ foldl update (0, (0, M.empty)) ps'
  where
    ps' = sort $ [(x, -1) | x <- S.elems xs] ++ [(x, y) | (x, y) <- ps, S.notMember x xs]

    update (acc, (prv, m)) (x, -1) = (acc, (0, M.empty))
    update (acc, (prv, m)) (x, y) = (acc + prv - find y m, (prv + 1, incr y m))

    find y = fromMaybe 0 . M.lookup y
    incr y = M.insertWith (+) y 1

fi = fromIntegral

-- debug a = trace (show a) a
-- debugS v a = trace (v ++ " = " ++ show a) a
debug = id
debugS _ = id

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

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

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

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

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

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

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

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

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Function
import Data.Int
import qualified Data.IntMap as M
import qualified Data.IntSet as S
import Data.List
import Data.Maybe
import Data.Tuple (swap)
import Debug.Trace (trace)

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

type PII = (Int, Int)
type Input = ([Int], [Int], [PII])
type Output = Int64

input :: Scanner Input
input = do
  n <- int
  m <- int
  k <- int
  xs <- n >< int
  ys <- m >< int
  ps <- k >< pair int int
  return (xs, ys, ps)

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

solve :: Input -> Output
solve (S.fromList -> xs, S.fromList -> ys, ps) = compute ps xs ys + compute (map swap ps) ys xs

compute :: [PII] -> S.IntSet -> S.IntSet -> Int64
compute ps xs ys = fst $ foldl update (0, (0, M.empty)) ps'
  where
    ps' = sort $ [(x, -1) | x <- S.elems xs] ++ [(x, y) | (x, y) <- ps, S.notMember x xs]

    update (acc, (prv, m)) (x, -1) = (acc, (0, M.empty))
    update (acc, (prv, m)) (x, y) = (acc + prv - find y m, (prv + 1, incr y m))

    find y = fromMaybe 0 . M.lookup y
    incr y = M.insertWith (+) y 1

fi = fromIntegral

-- debug a = trace (show a) a
-- debugS v a = trace (v ++ " = " ++ show a) a
debug = id
debugS _ = id

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

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

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

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

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

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

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

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

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
import Data.Array.Unboxed
import Data.Int
import qualified Data.Map.Strict as M

binSearch :: (Int -> Bool) -> Int -> Int -> Int
binSearch fun = go  where
  go x y = if x == y
    then  x
    else  let  m = x + div (y - x) 2
    in  if  fun m
    then  go x m
    else  go (m+1) y

getIx :: UArray Int Int -> Int -> Int
getIx arr val = let
  (p, q) = bounds arr
  in  binSearch (\i -> arr ! i >= val) p $ q + 1

solve :: UArray Int Int -> UArray Int Int -> [(Int, Int)] -> Int64
solve xs ys ps = let
  (1, n) = bounds xs
  (1, m) = bounds ys
  interest :: [(Bool, Int, Int)]
  interest = do
    (xp, yp) <- ps
    let  [xix, yix] = zipWith getIx [xs, ys] [xp, yp]
    case  (xp == xs ! xix, yp == ys ! yix)  of
      (True, True) -> []
      (False, True) -> [(False, xix, yix)]
      (True, False) -> [(True, xix, yix)]
      _ -> error "invalid input"
  uff :: M.Map (Bool, Int, Int) Int
  uff = M.fromListWith (+) $ zip interest $ repeat 1
  rows :: UArray Int Int
  rows = accumArray (+) 0 (1, n)
    $ [(xix, 1) | (False, xix, _) <- interest]
  cols :: UArray Int Int
  cols = accumArray (+) 0 (1, m)
    $ [(yix, 1) | (True,  _, yix) <- interest]
  w2 x = let
    x64 = fromIntegral x
    in  x64 * (x64 - 1)
  in  (`div` 2) $ foldl' (+) 0 $ map w2 (concatMap elems [rows, cols])
      ++ do
  (_k, ct) <- M.toList uff
  pure $ negate (w2 ct)

mainFun :: SO
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n, m, k] <- getInts 3
    xs <- listArray (1, n) <$> getInts n
    ys <- listArray (1, m) <$> getInts m
    ps <- replicateM k $ do
      ~[xp, yp] <- getInts 2
      pure (xp, yp)
    pure $ putInt64s [solve xs ys ps]

type SP = State [P.ByteString]
type SO = SP Builder

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

getInts :: Int -> SP [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

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

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

import Control.Monad
import Data.Function
import Data.Int
import Data.List
import Data.Maybe
import Data.Tuple
import qualified Data.ByteString.Char8 as C
import qualified Data.IntSet as IS

solve :: IO ()
solve = do
    [n, m, k] <- readInts
    xs <- IS.fromList <$> readInts
    ys <- IS.fromList <$> readInts
    pts <- replicateM k $ (\[x, y] -> (x, y)) <$> readInts
    let ways xs = sum $ zipWith (*) xs $ scanl (+) 0 xs :: Int64
        go xs pts =
            sum $ map (ways . map (fromIntegral . length) . group . sort . map snd) $
            groupBy ((==) `on` fst) $ sort $
            [(l, y) | pt@(x, y) <- pts, let l = fromJust $ IS.lookupLE x xs, l /= x]
    print $ go xs pts + go ys (map swap pts)

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

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


DZY loves chemistry, and he enjoys mixing chemicals.DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.Find the maximum possible danger after pouring all the chemicals one by one in optimal order.

The first line contains two space-separated integers n and m . Each of the next m lines contains two space-separated integers xi and yi (1 ≤ xi < yi ≤ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input. Consider all the chemicals numbered from 1 to n in some order.

Print a single integer — the maximum possible danger.

NoteIn the first sample, there's only one way to pour, and the danger won't increase.In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring).

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.IntSet as IS
import Data.STRef
import GHC.Arr (Array, Ix, range, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

type Vertex = Int
type Edge = (Vertex, Vertex)
type Graph = Array Vertex [Vertex]

mkGraph :: (Int, Int) -> [Edge] -> Graph
mkGraph bnd edges = unsafeAccumArray (flip (:)) [] bnd edges

vertices :: Graph -> [Vertex]
vertices gr = range $ bounds gr

edges :: Graph -> [Edge]
edges gr = [(from, to) | from <- vertices gr, to <- unsafeAt gr from ]

dfsAll :: Graph -> [Vertex] -> [[Vertex]]
dfsAll gr vs = filter (not.null) $ runST $ do
  vis <- newArray (bounds gr) False :: ST s (STUArray s Vertex Bool)
  mapM (dfsM gr vis) vs

dfsM :: Graph -> STUArray s Vertex Bool -> Vertex -> ST s [Vertex]
dfsM gr vis root = do
  let go res (v:vs) = do
        visited <- unsafeRead vis v
        if visited then go res vs
        else do
          unsafeWrite vis v True
          go (v:res) (unsafeAt gr v ++ vs)
      go res [] = return $ reverse res
  go [] [root]

topSort :: Graph -> [Vertex]
topSort gr = runST $ do
  vis   <- newArray (bounds gr) False :: ST s (STUArray s Vertex Bool)
  stack <- newSTRef []                :: ST s (STRef s [Vertex])
  let visit v = do
        visited <- unsafeRead vis v
        unless visited $ do
          unsafeWrite vis v True
          mapM_ visit $ unsafeAt gr v
          modifySTRef stack (v:)
  mapM_ visit $ vertices gr
  readSTRef stack

scc :: Graph -> [[Vertex]]
scc gr = dfsAll gr $ topSort gr

main :: IO ()
main = do
  [n,_] <- map read.words <$> getLine
  edges <- toEdges.map (subtract 1.readInt).B.words <$> B.getContents
  print $ solve n $ mkGraph (0,n-1) edges

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

solve :: Int -> Graph -> Integer
solve 1 _ = 1
solve n gr = (2^) . sum . map (pred.length) $ scc gr

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.IntSet as IS
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

type Vertex = Int
type Edge = (Vertex, Vertex)
type Graph = Array Vertex [Vertex]

mkGraph :: (Int, Int) -> [Edge] -> Graph
mkGraph bnd edges = unsafeAccumArray (flip (:)) [] bnd edges

main :: IO ()
main = do
  [n,m] <- map read.words <$> getLine
  edges <- toEdges.map (subtract 1.readInt).B.words <$> B.getContents
  print $ solve n $ mkGraph (0,n-1) edges

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

solve :: Int -> Graph -> Integer
solve n gr = 2 ^ (maximum (map (dfs gr) [0..n-1]) - 1)

dfs :: Graph -> Vertex -> Int
dfs gr v = go (IS.singleton v) [v]
   where
     go :: IS.IntSet -> [Vertex] -> Int
     go !visited (top:stack) = go (foldl' (flip $ IS.insert) visited nvs) (nvs++stack)
      where
        nvs :: [Vertex]
        nvs = filter (`IS.notMember` visited) $ unsafeAt gr top
     go visited [] = IS.size visited


As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.

The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).

Output on a single line the desired probability with at least 4 digits after the decimal point.

main = do [n, m, k] <- (map read . words) `fmap` getLine
          print $ solve n m k

solve n m k | n+k < m = 0.0
            | k >= m  = 1.0
            | otherwise = 1.0 - product [(m-k+i) / (n+k-i+1) | i <-[0.0..k]]

import Control.Applicative
import Control.Monad
import Data.Ratio
import Text.Printf

main :: IO ()
main = getLine >>= solve

solve :: String -> IO ()
solve = do
  [n, m, k] <- map read . words
  return . printf "%f\n" $ p n m k

p :: Integer -> Integer -> Integer -> Double
p n m k
  | m <= k    = 1
  | n + k < m = 0
  | otherwise = 1 - fromRational (a % b)
 where a = product [m - k .. m]
       b = product [n + 1 .. n + k + 1]

main :: IO()
main = interact work

work :: String -> String
work input = show $ solve n m k
    where [n, m, k] = map (\i -> read i :: Int) . words $ input

solve :: Int -> Int -> Int -> Double
solve n m k = max 0 (1 - product [fromIntegral (m - i) / fromIntegral (n + i + 1) | i <- [0..k]])

main = do
    [n,m,k] <- fmap (map read . words) getLine :: IO [Int]
    print $ 1.0 - if n + k - m < 0 then 1.0 else f m n k where
        f m n k
            | k == 0 = fromIntegral m / fromIntegral (n + 1)
            | otherwise = fromIntegral (m - k) / fromIntegral (n + k + 1) * (f m n $ k - 1)

main = do
    [n,m,k] <- fmap (map read . words) getLine :: IO [Int]
    print $ 1.0 - f m n k where
        f m n 0 = fromIntegral m / fromIntegral (n + 1)
        f m n k = fromIntegral (m - k) / fromIntegral (n + k + 1) * (f m n $ k - 1)

main = do
    [n,m,k] <- fmap (map read . words) getLine :: IO [Int]
    print $ 1.0 - f m n k where
        f m n k
            | n + k - m < 0 = 0
            | k == 0 = fromIntegral m / fromIntegral (n + 1)
            | otherwise = fromIntegral (m - k) / fromIntegral (n + k + 1) * (f m n $ k - 1)


You are given a tree (an undirected connected graph without cycles) and an integer $$$s$$$.Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is $$$s$$$. At the same time, he wants to make the diameter of the tree as small as possible.Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.Find the minimum possible diameter that Vanya can get.

The first line contains two integer numbers $$$n$$$ and $$$s$$$ ($$$2 \leq n \leq 10^5$$$, $$$1 \leq s \leq 10^9$$$) — the number of vertices in the tree and the sum of edge weights. Each of the following $$$n−1$$$ lines contains two space-separated integer numbers $$$a_i$$$ and $$$b_i$$$ ($$$1 \leq a_i, b_i \leq n$$$, $$$a_i \neq b_i$$$) — the indexes of vertices connected by an edge. The edges are undirected. It is guaranteed that the given edges form a tree.

Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to $$$s$$$. Your answer will be considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is considered correct if $$$\frac {|a-b|} {max(1, b)} \leq 10^{-6}$$$.

NoteIn the first example it is necessary to put weights like this:  It is easy to see that the diameter of this tree is $$$2$$$. It can be proved that it is the minimum possible diameter.In the second example it is necessary to put weights like this:

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

data ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil

main :: IO ()
main = do
  [n,s] <- map read . words <$> getLine :: IO [Int]
  vals <- valencies n <$> BSL.getContents
  print $ (fromIntegral (2*s) /)
    (fromIntegral $ length $ filter (==1) $ A.elems $ vals ::Double)

valencies :: Int -> BSL.ByteString -> UArray Int Int
valencies n bstr = runSTUArray $ do
  valencies_ <- A.newArray (1,n) (0::Int)
  forM_ (take (2*n-2) $ unfoldr (BSL.readInt . BSL.dropWhile (<'-')) bstr)
    $ \ v -> A.readArray valencies_ v >>= A.writeArray valencies_ v . (+1)
  return valencies_

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

data ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil

main :: IO ()
main = do
  [n,s] <- map read . words <$> getLine :: IO [Int]
  codd <- preprocess n <$> BSL.getContents
  print $ (fromIntegral (2*s) /) (fromIntegral $ valency1 codd ::Double)
    where
      {-# INLINE processInt #-}
      processInt = \(!i,!bs) -> do
        (!e,!bs1) <- BS.readInt $ BS.dropWhile (< '-') bs
        return $! ((i,e),(i+1,bs1))

{-# INLINE children_ #-}
children_ :: UArray Int Int -> Int -> Int -> [Int]
children_ codd parent this =
  filter (/= parent)
  $ map (codd A.!) [codd A.! (this-1) .. codd A.! this - 1]

valency1 :: UArray Int Int -> Int
valency1 !codd = leaves codd (-1) 1 + if length children <= 1 then 1 else 0
  where
    children = children_ codd (-1) 1

leaves :: UArray Int Int -> Int -> Int -> Int
leaves !codd parent this
  | null children = 1
  | otherwise     = sum $ map (leaves codd this) children
  where
    children = children_ codd parent this

{-# INLINE preprocess #-}
preprocess :: Int -> BSL.ByteString -> UArray Int Int
preprocess n bstr = codd
  where
    {-# INLINE processInt #-}
    processInt = \(!i,!bs) -> do
      (!e,!bs1) <- BSL.readInt $ BSL.dropWhile (< '-') bs
      return $! ((i,e),(i+1,bs1))
    -- domcods :: UArray Int Int
    -- domcods = A.array (0, 2*n - 3) $ unfoldr processInt (0,bstr)
    codd :: UArray Int Int
    codd = runSTUArray $ do
      domcods_ <- A.newArray_ (0,2*n-3) :: ST s (STUArray s Int Int)
      arr <- A.newArray (0,3*n-2) 0
      forM_ (take (2*n-2) $ unfoldr processInt (0,bstr)) $ \ (!i,!e) -> do
        A.writeArray domcods_ i e
      forM_ [0..2*n-3] $ \ !i -> do
        j <- A.readArray domcods_ i
        when (j < n) $ do
          x <- A.readArray arr (j+1)
          A.writeArray arr (j+1) (x+1)
      A.writeArray arr 0 (n+1)
      forM_ [1..n] $ \ !i -> do
        x <- A.readArray arr (i-1)
        y <- A.readArray arr i
        A.writeArray arr i (x+y)
      forM_ [0,2..2*(n-2)] $ \ !i -> do
        dom <- A.readArray domcods_ i
        cod <- A.readArray domcods_ (i+1)
        j_dom <- A.readArray arr dom
        A.writeArray arr dom (j_dom+1)
        A.writeArray arr j_dom cod
        j_cod <- A.readArray arr cod
        A.writeArray arr cod (j_cod+1)
        A.writeArray arr j_cod dom
      return arr


A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

module Main (main)
    where

import Data.List (elemIndices)

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

indices :: [Int] -> (Int, Int, Int)
indices xs = let (a,b) = (minimum xs, maximum xs)
                 n = length xs
              in (n,
                  last $ a `elemIndices` xs,
                  head $ b `elemIndices` xs)

main :: IO ()
main = print . steps . indices . map read . words =<< (getLine >> getLine)
    where steps (n,a,b) = let i = if a < b then -1 else 0
                           in i + n + b - a - 1

import Data.List
import Data.Maybe

-- Snippet: readItems
readItems = do
    line <- getLine
    return $ map read $ words line

main = do
    n <- readLn
    a <- readItems :: IO [Int]
    let diffMin = fromJust $ findIndex (== (minimum a)) (reverse a)
    let diffMax = fromJust $ findIndex (== (maximum a)) a
    let diff = diffMin + diffMax
    putStrLn $ show $ if diff < n then diff else diff - 1

minIndex :: [Int] -> (Int, Int)
minIndex [x] = (0, x)
minIndex (x:l) =
  let (i, y) = minIndex l
  in if x < y then (0, x) else (i+1, y)

maxIndex :: [Int] -> (Int, Int)
maxIndex [x] = (0, x)
maxIndex (x:l) =
  let (i, y) = maxIndex l
  in if x >= y then (0, x) else (i+1, y)

main = do
  getLine
  line <- getLine
  let soldiers = map read $ words line
      min = fst $ minIndex soldiers
      max = fst $ maxIndex soldiers
      len = length soldiers
      secs = max + (len - 1 - min) - if max > min then 1 else 0
  putStrLn $ show secs

import Data.List
import Data.Maybe

main = do
  getLine
  as <- fmap (map read . words) getLine :: IO [Int]
  let
    n = length as
    i = fromJust (elemIndex (maximum as) as)
    j = n-1 - (fromJust $ elemIndex (minimum as) (reverse as))

  print $ if i < j then i + (n-1-j) else i + (n-1-j) - 1

import Data.List
import Data.List.Split

(|>) x f = f x
main = interact solve

solve contents = let
  nums = contents |> lines |> (!! 1) |> words |> map read :: [Int]
  in swaps nums |> show

swaps nums = let
  mx = maximum nums
  (before, after) = span (/= mx) nums
  nums' = (head after):(before ++ tail after)
  mn = minimum nums'
  lastMinIndex = nums' |> findIndices (== mn) |> last
  in length before + length nums - 1 - lastMinIndex

import Data.List

main = interact $ show . solve . input

input :: String -> [Int]
input = (map read) . words

solve (n:xs) = posMax + (n - posMin - 1) - swapMaxMin where
    posMax = minimum (maximum xs `elemIndices` xs)
    posMin = maximum (minimum xs `elemIndices` xs)
    swapMaxMin = if posMin < posMax then 1 else 0

import Control.Applicative
main = do
  n <- readLn
  a <- map read . words <$> getLine
  print $ solve a (0, 0) (101, 0) 0 n

solve [] (_, a) (_, b) _ n = a+n-b-1-(if a > b then 1 else 0)
solve (a:as) (ma, maxp) (mi, minp) p n =
  solve as (if ma < a then (a, p) else (ma, maxp)) (if mi >= a then (a, p) else (mi, minp)) (p+1) n

import Control.Applicative
main = do
  n <- readLn
  a <- map read . words <$> getLine
  print $ solve a (0, 0) (101, 0) 0 n

solve [] (_, a) (_, b) _ n = a + n - b - 1 - if a > b then 1 else 0
solve (a:as) (ma, maxp) (mi, minp) p n =
  solve as (if ma < a then (a, p) else (ma, maxp)) (if mi >= a then (a, p) else (mi, minp)) (p+1) n

getminTail ::[Int] ->Int
getminTail a = fst$last$filter (\x -> snd x == minimum a) (zip [1..(length a)] a)
getmaxHead ::[Int] ->Int
getmaxHead a = fst$head$filter (\x -> snd x == maximum a) (zip [1..(length a)] a)
calc ::Int ->Int -> Int -> Int
calc n mt mh |mt < mh = (n-mt)+(mh-2)
             |otherwise =(n-mt)+(mh-1)
getAns ::[Int] -> Int
getAns a = calc (length a) (getminTail a) (getmaxHead a)
main=interact$show.getAns.(map read).tail.words

import Data.List
import Data.Maybe
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ show.solve . concat.map (map read.words).take 2 . lines
solve :: [Int]->Int
solve (x:xs) = let  minidx = last $ elemIndices  (minimum xs) xs  ; maxidx = fromJust $ elemIndex  (maximum xs) xs in if maxidx<minidx then maxidx +x-minidx-1 else maxidx +x-minidx-2

import List

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

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

firstMaximum :: [Int] -> Int
firstMaximum xs = head (elemIndices (maximum xs) xs)

lastMinimum :: [Int] -> Int
lastMinimum xs = head (elemIndices (minimum xs) (reverse xs))

solve :: Int -> [Int] -> Int
solve n xs
  | (a + b) >= n  =  a + b - 1
  | otherwise     =  a + b
  where
    a = firstMaximum xs
    b = lastMinimum xs

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

import Control.Applicative
import Data.List (elemIndices)

main = do
  n <- read <$> getLine
  xs <- map read . words <$> getLine :: IO [Int]
  let mn = minimum xs
      mx = maximum xs
      mxi = head . elemIndices mx $ xs
      mni = last . elemIndices mn $ xs
  print $ n-1-mni + mxi - if mxi > mni then 1 else 0

rightMostMin nos = snd $ foldl newMin (101, 0) (zip nos [0..])
  where newMin (a, b) (x, y) = if a >= x
                               then (x, y)
                               else (a, b)

leftMostMax nos = snd $ foldr newMax (-1, 0) (zip nos [0..])
  where newMax (x, y) (a, b) = if x >= a
                               then (x, y)
                               else (a, b)

getMinTime :: Int -> [Int] -> Int
getMinTime n nos | minPos > maxPos = (n - 1 - minPos) + maxPos
                 | otherwise = (n - 1 - minPos) + maxPos - 1
                   where minPos = rightMostMin nos
                         maxPos = leftMostMax nos

main = do
  line <- getLine
  let n = read line :: Int
  line <- getLine
  let nos = map (\x -> read x :: Int) (words line)
      ans = getMinTime n nos
  putStrLn $ show ans

import Control.Monad
import Data.Array
import Data.Char
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
-- import qualified Data.Text as T
import qualified Data.ByteString.Char8 as B
getList :: Read a => IO [a]
getList = fmap (map (read . B.unpack) . B.words) B.getLine
getIntList :: IO [Int]
getIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine

solve :: [Int] -> Int
solve a = maxH + (n - 1 - minL) + (if maxH < minL then 0 else -1)
    where n    = length a
          maxi = maximum a
          mini = minimum a
          maxH = head $ elemIndices maxi a
          minL = last $ elemIndices mini a

main :: IO ()
main = do
        _ <- getLine
        a <- getIntList
        print $ solve a

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

process a  = pma  +  pmi  + if pma >=(length a- pmi) then (-1) else 0
    where mi = minimum a
          ma = maximum a
          pmi = fromJust $ elemIndex mi (reverse a)
          pma = fromJust $ elemIndex ma a

main=do
    getLine
    a<-map read <$> words <$> getLine ::IO [Int]
    print $ process a

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

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

parseInput = do
    n <- readInt
    seq <- replicateM n readInt
    return seq
  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

solve seq = ans
  where
    maxv = maximum seq
    minv = minimum seq

    n = length seq

    ans = minimum [ i + (n - 1 - j) - if j < i then 1 else 0
                  | (i, ai) <- zip [0..] seq
                  , (j, aj) <- zip [0..] seq
                  , ai == maxv && aj == minv && i /= j
                  ]

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

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 ((\\), elemIndex)
import Data.Maybe (fromJust)

main :: IO ()
main = getContents >>= print . solve . map read . words . (!!1) . lines

solve :: [Int] -> Int
solve xs = fromJust (elemIndex (maximum xs) xs) + fromJust (elemIndex (minimum xs) xs')
  where xs' = reverse (xs \\ [maximum xs])

import Data.List
main = do
  n <- readLn
  as <- fmap (map read . words) getLine :: IO [Int]
  let i = head (elemIndices (maximum as) as)
      j = last (elemIndices (minimum as) as)
  print $ i + n - j - 1 - if i > j then 1 else 0

import Data.List
solve :: [Int] -> Int
solve xs | ok xs = 0
         | otherwise = solve (step xs) + 1
ok :: [Int] -> Bool
ok xs = head xs == maximum xs && last xs == minimum xs
step :: [Int] -> [Int]
step xs | head xs == maximum xs = exchange2 xs minIndex
        | otherwise = exchange2 xs $ maxIndex-1
    where minIndex = last $ elemIndices (minimum xs) xs
          maxIndex = head $ elemIndices (maximum xs) xs
exchange2 :: [a] -> Int -> [a]
exchange2 (x:y:ys) 0 = y:x:ys
exchange2 (x:xs) l = x : exchange2 xs (l-1)
main = getLine >> fmap (map read . words) getLine >>= print . solve

-- Vicfred
-- https://codeforces.com/problemset/problem/144/A

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

getIntList :: IO [Int]
getIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine

solve :: [Int] -> Int
solve a = maxH + (n - 1 - minL) + (if maxH < minL then 0 else -1)
    where n     = length a
          maxi  = maximum a
          mini  = minimum a
          maxH  = head $ elemIndices maxi a
          minL  = last $ elemIndices mini a

main :: IO ()
main = do
    _ <- getLine
    a <- getIntList
    print $ solve a

import Control.Applicative

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

solve :: Int -> [Int] -> Int
solve n xs
 | l == h    = 0
 | l < h     = (n-l) + (h-1) -1
 | otherwise = (n-l) + (h-1)
   where h = succ $ (n-) $ snd $ maximum $ zip xs [n,(n-1)..1]
         l = succ $ (n-) $ snd $ minimum $ zip xs [n,(n-1)..1]

import Data.Function
import Data.List

moveMax xs = [x] ++ takeWhile (<x) xs ++ (tail.dropWhile (<x)$xs)
	where x = maximum xs

findMax xs = head.findIndices (==x)$xs
	where x = maximum xs

findMin xs = length xs - 1 - (last.findIndices (==x)$xs)
	where x = minimum xs

findAll :: [Int]->Int
findAll xs = findMax xs + findMin (moveMax xs)

result [n,xs] = findAll.map read.words$xs

main=interact$show.result.lines

import Data.List
import Control.Monad

placemax list =
    let
        (list0, list1) = span (> minimum list) (reverse list)

    in length list0

placemin list =
    let
        (list0, list1) = span (< maximum list) list
        list' = head list1 : (list0 ++ tail list1)

    in (length list0, list')

main = do
    n <- liftM read getLine :: IO Int
    list <- liftM (map read . words) getLine :: IO [Int]

    let (ans1, list') = placemin list
        ans2 = placemax list'

    putStrLn $ show $ ans1 + ans2

m=minimum
x=maximum
s(_:h)=q(n+m(l$x h)-x(l$m h)-1)where n=length h;q x|x<n=x|1>0=x-1;l k=[i|i<-[0..n-1],h!!i==k]
main=interact$show.s.map read.words

m=minimum
x=maximum
s(c:h)=q$n+m(l$x h)-x(l$m h)where n=c-1;q x|x>n=x-1|1>0=x;l k=[i|i<-[0..n],h!!i==k]
main=interact$show.s.map read.words

m=minimum
x=maximum
s(n:h)|r<n=r|1>0=r-1 where r=n+m(l$x h)-1-x(l$m h);l k=[i|i<-[0..n-1],h!!i==k]
main=interact$show.s.map read.words

m=minimum
x=maximum
s(n:h)=q$n+m(l$x h)-1-x(l$m h)where q x|x<n=x|1>0=x-1;l k=[i|i<-[0..n-1],h!!i==k]
main=interact$show.s.map read.words

import Control.Applicative
import Data.List

main= do
	n<- read <$> getLine ::IO Int
	x<- map read. words <$> getLine ::IO [Int]
	let x1 = minimum x
	let p1 = last $ elemIndices x1 x
	let x2 = maximum x
	let p2 = head $ elemIndices x2 x
	print $ p2 + n-p1-1 + if (p2>p1) then (-1) else 0

{-
A. Arrival of the General
==========================
time limit per test: 2 seconds
memory limit per test: 256 megabytes
input: standard input
output: standard output

A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.

By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.

For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.

Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

Input
-----
The first input line contains the only integer n (2 ≤ n ≤ 100) which represents the number of soldiers in the line. The second line contains integers a1, a2, ..., an (1 ≤ ai ≤ 100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1, a2, ..., an are not necessarily different.

Output
------
Print the only integer — the minimum number of seconds the colonel will need to form a line-up the general will like.

Sample test(s)
--------------
input
4
33 44 11 22
output
2

input
7
10 10 58 31 63 40 76
output
10

Note
------
In the first sample the colonel will need to swap the first and second soldier and then the third and fourth soldier. That will take 2 seconds. The resulting position of the soldiers is (44, 33, 22, 11).

In the second sample the colonel may swap the soldiers in the following sequence:

(10, 10, 58, 31, 63, 40, 76)
(10, 58, 10, 31, 63, 40, 76)
(10, 58, 10, 31, 63, 76, 40)
(10, 58, 10, 31, 76, 63, 40)
(10, 58, 31, 10, 76, 63, 40)
(10, 58, 31, 76, 10, 63, 40)
(10, 58, 31, 76, 63, 10, 40)
(10, 58, 76, 31, 63, 10, 40)
(10, 76, 58, 31, 63, 10, 40)
(76, 10, 58, 31, 63, 10, 40)
(76, 10, 58, 31, 63, 40, 10)
-}
import Data.List (elemIndices)

swapNumber :: [Int] -> Int
swapNumber xs = (posMax - 1 + lenXS - posMin) + if (posMax > posMin) then -1 else 0
  where
    lenXS  = length xs
    posMax = (head $ elemIndices (maximum xs) xs) + 1 :: Int -- count from 1
    posMin = (last $ elemIndices (minimum xs) xs) + 1 :: Int -- count from 1

reader :: String -> [Int]
reader s = map read $ words ss
  where _:ss:_ = lines s

main = do
  input <- getContents
  let xs = reader input
  print $ swapNumber xs

import Data.List
main = interact $ show . f . map read . words . (!! 1) . lines
         where f :: [Int] -> Int
               f x = length x - 1 - mini + maxi - if maxi > mini then 1 else 0
                 where maxi = head $ elemIndices (maximum x) x
                       mini = last $ elemIndices (minimum x) x

import Data.List
main = getLine >> getLine >>= putStrLn.show.solve.map read.words

solve :: [Int] -> Int
solve soldiers = tallest + shortest - crossed
  where find f set = maybe 0 (+0) $ findIndex (==f set) set
        tallest    = find maximum soldiers
        shortest   = find minimum $ reverse soldiers
        crossed    = if tallest + shortest < length soldiers then 0 else 1

import Data.List (maximumBy, minimumBy)
import Data.Ord (comparing)

maxIndex ::  Ord a => [a] -> Int
maxIndex = fst . maximumBy (comparing snd) . zip [0..]

minIndex :: Ord a => [a] -> Int
minIndex = fst . minimumBy (comparing snd) . zip [0..]

process :: [Int] -> Int
process xs
    | imax + imin > n-1 = imax + imin - 1
    | otherwise = imax + imin
    where
        n = length xs
        xs' = reverse xs
        imax = n-1 - maxIndex xs'
        imin = minIndex xs'

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    xs <- fmap (map readInt.words) getLine
    print $ process xs

import Data.List
import Data.Char

ans xs = if mi>ma then ma+(length xs) -mi-1 else ma+(length xs)-mi-2
    where (mi,ma)=(last $ elemIndices (minimum xs) xs,head $ elemIndices (maximum xs) xs)

main = do
    getLine
    n<-getLine
    let input = map (\x->read x::Int) $ words n
    print $ ans input

import Data.List

main = interact $ show . s . map read . tail . words

s :: [Int] -> Int
s xs = length xs + maxIn xs - minIn xs - if maxIn xs > minIn xs then 2 else 1 where
    maxIn t = head (elemIndices (maximum t) t)
    minIn t = last (elemIndices (minimum t) t)

import Data.List
import Data.Maybe

cost :: [Int] -> Int
cost sq =
    let mx = maximum sq
        mn = minimum sq
        leftTall = fromJust $ elemIndex mx sq
        rightShort = last $ elemIndices mn sq
        len = length sq
        extraDecrement = if (leftTall > rightShort) then 1 else 0
    in leftTall + len - rightShort - 1 - extraDecrement

solve :: String -> String
solve = show . cost . map read . tail. words

main :: IO ()
main = interact $ solve

import Data.List
import Data.Maybe

main = do
  getLine
  as <- fmap (map read . words) getLine :: IO [Int]
  let
    n = length as
    i = fromJust $ elemIndex (maximum as) as
    j = n - (fromJust $ elemIndex (minimum as) (reverse as)) + 1

  print $ if i < j then i + (n-j+1) else i+n-j

import Data.List ((\\), elemIndex)
import Data.Maybe (fromJust)

main :: IO ()
main = getContents >>= print . solve . map read . words . (!!1) . lines

solve :: [Int] -> Int
solve xs = fromJust (elemIndex (maximum xs) xs) + fromJust (elemIndex (minimum xs) xs')
  where xs' = reverse xs \\ [maximum xs]

-- Vicfred
-- https://codeforces.com/problemset/problem/144/A

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

getIntList :: IO [Int]
getIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine

solve :: [Int] -> Int
solve a = maxH + (n-1-minL) + (if maxH < minL then 0 else -1)
    where n     = length a
          maxi  = maximum a
          mini  = minimum a
          maxH  = head $ elemIndices maxi a
          minL  = head $ elemIndices mini a

main :: IO ()
main = do
    getLine
    a <- getIntList
    print $ solve a

import Data.List
main = getLine >> getLine >>= putStrLn.show.solve.map read.words

solve :: [Int] -> Int
solve soldiers = pred $ tallest + shortest
  where find f set = maybe 0 (+0) $ findIndex (==f set) set
        tallest    = find maximum soldiers
        shortest   = find minimum $ reverse soldiers

import Data.List (maximumBy, minimumBy)
import Data.Ord (comparing)

maxIndex ::  Ord a => [a] -> Int
maxIndex = fst . maximumBy (comparing snd) . zip [0..]

minIndex :: Ord a => [a] -> Int
minIndex = fst . minimumBy (comparing snd) . zip [0..]

process :: [Int] -> Int
process xs
    | imax + imin > n-1 = imax + imin - 1
    | otherwise = imax + imin
    where
        n = length xs
        imax = maxIndex xs
        imin = minIndex (reverse xs)

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    xs <- fmap (map readInt.words) getLine
    print $ process xs


There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes.The schedule on Monday is known for each group, i. e. time slots when group will have classes are known.Your task is to determine the minimum number of rooms needed to hold classes for all groups on Monday. Note that one room can hold at most one group class in a single time slot.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of groups.  Each of the following n lines contains a sequence consisting of 7 zeroes and ones — the schedule of classes on Monday for a group. If the symbol in a position equals to 1 then the group has class in the corresponding time slot. In the other case, the group has no class in the corresponding time slot.

Print minimum number of rooms needed to hold all groups classes on Monday.

NoteIn the first example one room is enough. It will be occupied in each of the seven time slot by the first group or by the second group.In the second example three rooms is enough, because in the seventh time slot all three groups have classes.

import Data.List
import Data.Array
import Data.Ord

extract (x:xs)=take (read x::Int) xs
calc x=length (filter (=='1') x)
solve x=maximum $ map calc $ map (\k->(map (\y->y!!k) x)) [0..6]

main=interact$show.solve.extract.lines

{-
	fmap (map (\x->read x::Int).words)  $ getLine
-}

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

main = do
    n <- readLn :: IO Int
    print =<< maximum . foldr (zipWith (+)) (replicate 7 0) <$> replicateM n ( map digitToInt <$> getLine)


You are given a huge decimal number consisting of $$$n$$$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.You are also given two integers $$$0 \le y < x < n$$$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.

The first line of the input contains three integers $$$n, x, y$$$ ($$$0 \le y < x < n \le 2 \cdot 10^5$$$) — the length of the number and the integers $$$x$$$ and $$$y$$$, respectively. The second line of the input contains one decimal number consisting of $$$n$$$ digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1.

Print one integer — the minimum number of operations you should perform to obtain the number having remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.

NoteIn the first example the number will be $$$11010100100$$$ after performing one operation. It has remainder $$$100$$$ modulo $$$100000$$$.In the second example the number will be $$$11010100010$$$ after performing three operations. It has remainder $$$10$$$ modulo $$$100000$$$.

import Data.Char

main = do
    header <- getLine
    l <- getLine
    putStrLn . show $ solve header l

solve :: String -> String -> Int
solve header l_ =
    let [n, x, y] = (map read . words) header in
    let l = (take x . reverse) l_ in
    let f (pos, val) =
            if pos == y then
                (if val == '0' then 1 else 0)
            else
                (if val == '1' then 1 else 0)
    in
    sum $ map f (zip [0..] l)

import Data.List
import qualified Data.ByteString as B

main = do
    zz <- fmap (map read . words) getLine :: IO [Int]
    let n = zz !! 0
    let x = zz !! 1
    let y = zz !! 2
    s <- fmap (map (== '1') . reverse) getLine
    let t = take x s
    let ans = (foldl' (\s x -> if x then s + 1 else s) 0 t) - (if t !! y then 1 else (-1))
    putStrLn $ show ans
    return ()

--prewritten code: https://github.com/antma/algo
{-# LANGUAGE BangPatterns, Safe #-}
{-# 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
import Data.Bits

getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int

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

solve :: [C.ByteString] -> Builder
solve (sn:sx:sy:s:_) = intDec res <> char7 '\n'
  where
    !n = ri sn
    !x = ri sx
    !y = ri sy
    !res = sum $ zipWith xor (replicate y 0 ++ (1 : repeat 0)) $  map (subtract 48 .  ord) $ C.unpack $ C.take x $ C.reverse s

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

module Main where

main :: IO ()
main = do
  params <- (fmap read . words) <$> getLine
  digits <- getLine
  print $ minOps params digits

minOps :: [Int] -> String -> Int
minOps [n, x, y] digits = let
  digits' = drop (n-x) digits
  digits'' = take (x -y -1) digits' ++
    [case digits' !! (x -y-1) of
      '0' -> '1'
      '1' -> '0'] ++ drop  (x-y) digits'
  in
  length $ filter (=='1') digits''


One day Ms Swan bought an orange in a shop. The orange consisted of n·k segments, numbered with integers from 1 to n·k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 ≤ i ≤ k) child wrote the number ai (1 ≤ ai ≤ n·k). All numbers ai accidentally turned out to be different.Now the children wonder, how to divide the orange so as to meet these conditions:  each child gets exactly n orange segments;  the i-th child gets the segment with number ai for sure;  no segment goes to two children simultaneously. Help the children, divide the orange and fulfill the requirements, described above.

The first line contains two integers n, k (1 ≤ n, k ≤ 30). The second line contains k space-separated integers a1, a2, ..., ak (1 ≤ ai ≤ n·k), where ai is the number of the orange segment that the i-th child would like to get. It is guaranteed that all numbers ai are distinct.

Print exactly n·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces. You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.

getList :: Int -> Int -> Int -> Int -> [Int] -> [Int]
getList cur sub n k a
	| cur == n * k		= []
	| mod cur n == 0 	= (a !! (div cur n)) : (getList (cur + 1) sub n k a)
	| contain sub a		= getList cur (sub + 1) n k a
	| otherwise			= sub : (getList (cur + 1) (sub + 1) n k a)

contain :: Int -> [Int] -> Bool
contain _ [] = False
contain c (x:xs) = (x == c) || (contain c xs)

printList :: [Int] -> IO()
printList [] = do
	putStrLn ""
printList (x:xs) = do
	putStr ((show x) ++ " ")
	printList xs

main :: IO()
main = do
	str1 <- getLine
	str2 <- getLine
	let n = read ((words str1) !! 0)
	let k = read ((words str1) !! 1)
	let a = map read (words str2)
	printList (getList 0 1 n k a)

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

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

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

main = do
    (n,k) <- readIntPair
    as <- readInts
    let oranges = [1..n*k] \\ as
    let go [] _ = return ()
        go (a:as) l  = do
            let (l1,l2) = splitAt (n-1) l
            putStrLn $ unwords $ map show $ (a:l1)
            go as l2
    go as oranges

module Main where
import Data.List
import Control.Applicative

main = do
    [n,k] <- map (read :: String -> Int) . words <$> getLine
    ks <- map (read :: String -> Int) . words <$> getLine
    let a = [1..n*k] \\ ks
        m = n-1
        b =  if null a then replicate k [] else unfoldr (\x -> if null x then Nothing else Just (take m x, drop m x)) a
    putStrLn $ concat $ intersperse "\n" $ map (concat . intersperse " " . map show) $ zipWith (:) ks b

import Control.Monad (liftM)
import Data.List ((\\), intercalate)
import Prelude hiding (reads)

reads :: Read a => IO [a]
reads  =  liftM (map read . words) getLine

solve :: Int -> Int -> [Int] -> [[Int]]
solve n k xs  =  solve' xs ([1..n*k] \\ xs)
  where
    solve' [] _  =  []
    solve' (x:xs) ys  =  (x : take (n-1) ys) : solve' xs (drop (n - 1) ys)

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

main :: IO ()
main  =  do
    [n, k]  <-  reads
    xs  <-  reads
    mapM_ prints $ solve n k xs

-- Codeforces 244A

import Data.List

main :: IO ()
main = getContents >>= putStrLn . solve . map read . words

solve :: [Int] -> String
solve (n:k:xs) = intercalate "\n" $ map (intercalate " " . map show . sort) $ transpose $ (xs:) $ map (\i -> take k $ drop ((i-1)*k) other) [1..n-1] where other = filter (`notElem` xs) [1..n*k]

import Control.Applicative
import Data.List

main = do
       [n,k] <- map read.words <$> getLine
       xs <- map read.words <$> getLine
       let rest = [1..n*k]\\xs
           ans = transpose $ xs:slices k rest
       putStr.unlines.map (unwords.map show) $ ans

slices :: Int -> [a] -> [[a]]
slices _ [] = []
slices n xs = let (ys,zs) = splitAt n xs in ys:slices n zs

import Data.List

main = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines
solve [[n, k], xs]  =  solve' xs ([1..n*k] \\ xs)
  where
    solve' [] _  =  []
    solve' (x:xs) ys  =  (x : take (n-1) ys) : solve' xs (drop (n - 1) ys)

module Main where
import Data.List
import Control.Applicative

main = do
    [n,k] <- map (read :: String -> Int) . words <$> getLine
    ks <- map (read :: String -> Int) . words <$> getLine
    let a = [1..n*k] \\ ks
        m = n-1
        b =  unfoldr (\x -> if null x then Nothing else Just (take m x, drop m x)) a
    putStrLn $ concat $ intersperse "\n" $ map (concat . intersperse " " . map show) $ zipWith (:) ks b

import Data.List

main = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines
solve [[n, 1], a] = [[1..n]]
solve [[n, k], a] = zipWith (:) a $ splitEvery (k-1) $ [1..n*k] \\ a
    where
        splitEvery _ [] = []
        splitEvery x ys = take x ys : splitEvery x (drop x ys)

import Data.List

main = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines
solve [[1, k], a] = map (\x -> [x]) a
solve [[n, 1], a] = [[1..n]]
solve [[n, k], a] = zipWith (:) a $ splitEvery (k-1) $ [1..n*k] \\ a
    where
        splitEvery _ [] = []
        splitEvery x ys = take x ys : splitEvery x (drop x ys)