import Control.Exception.Base
import Debug.Trace
import Data.Functor
import Data.List

readInts :: IO [Int]
readInts = map read <$> words <$> getContents
parsePairs :: [Int] -> [(Int, Int)]
parsePairs [] = []
parsePairs (x:y:rs) = (x, y) : parsePairs rs

main = readInts >>= putStrLn . show . solve . parsePairs . tail

solve :: [(Int, Int)] -> Integer
solve rs = let n = toInteger $ length rs in n * (n-1) * (n-2) `div` 6 - countDegen rs

countDegen :: [(Int, Int)] -> Integer
countDegen = f . sort where
    f [] = 0
    f (r:[]) = 0
    f (r:rs) = go r rs + f rs

geoMult :: Num a => (a, a) -> (a, a) -> (a, a) -> a
geoMult (x0, y0) (x1, y1) (x2, y2) = (x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)

go center rs = sum $ map (f . length) $ groupBy (\x y -> cmp center x y == EQ) $ sortBy (cmp center) rs
    where f x = toInteger $ x * (x - 1) `div` 2

cmp center x y
    | r < 0 = LT
    | r > 0 = GT
    | r == 0 = EQ
    where r = geoMult center x y

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

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

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

main = do
  n <- readLn
  ps <- replicateM n $ (\[x, y] -> (x, y)) <$> getInts

  let
    count n = n'*(n'-1)*(n'-2) `div` 6 where n' = fromIntegral n :: Int64
    count2 n = n'*(n'-1) `div` 2 where n' = fromIntegral n :: Int64

    r = count n - (sum $ map f $ init $ tails ps)
      where
        f ((x, y):ps) = sum vs
          where
            vs = map (count2 . length) $ group $ sort $ map norm $ map (\(xx, yy) -> (xx-x, yy-y)) ps
              where
                norm (x, y) = (x' `div` d, y' `div` d)
                  where
                    (x', y') = if x < 0 || x == 0 && y < 0 then (-x, -y) else (x, y)
                    d = gcd x y

  print r

import Control.Exception.Base
import Debug.Trace
import Data.Functor
import Data.List

readInts :: IO [Int]
readInts = map read <$> words <$> getContents
parsePairs :: [Int] -> [(Int, Int)]
parsePairs [] = []
parsePairs (x:y:rs) = (x, y) : parsePairs rs

main = readInts >>= putStrLn . show . solve . parsePairs . tail

solve :: [(Int, Int)] -> Integer
solve rs = let n = toInteger $ length rs in n * (n-1) * (n-2) `div` 6 - countDegen rs

countDegen :: [(Int, Int)] -> Integer
countDegen = f . sort where
    f [] = 0
    f (r:[]) = 0
    f ((x0, y0):rs) = go (map (\(x, y) -> (x-x0, y-y0)) rs) + f rs

simplify (x, y)
    | x == 0 = (0, 1)
    | y == 0 = (1, 0)
    | otherwise = let g = gcd x y in f (div x g) (div y g)
    where f x y = if x > 0 then (x, y) else (-x, -y)

go = sum . map (pairs . length) . group . sort . map simplify
    where pairs x = toInteger $ x * (x - 1) `div` 2

import Data.List (group, sort)
import Control.Applicative ((<$>), liftA)
import Control.Monad (replicateM)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8

parse :: ByteString -> (Int, Int)
parse = (\(Just [a, b]) -> (a, b)). sequence . fmap readInt . B8.words
    where
    readInt :: ByteString -> Maybe Int
    readInt = (liftA fst) . B8.readInt

f :: Int -> Int
f n = n * (n - 1) `div` 2

tria :: Int -> [(Int, Int)] -> Int
tria acc [] = acc
tria acc [(x, y)] = acc
tria acc ((x,y):rest) = tria acc' rest
    where
    n = length rest :: Int
    a = fmap length . group . sort . fmap slope $ rest :: [Int]

    acc' = acc + f n - (sum . fmap f $ a) :: Int

    slope :: (Int, Int) -> (Int, Int)
    slope (u, v)
        | u == x = (0, 1)
        | v == y = (1, 0)
        | otherwise = (dx `div` w', dy `div` w')
        where
        dx = x - u :: Int
        dy = y - v :: Int
        w = gcd dx dy :: Int
        w' = if (dx < 0) == (w < 0) then w else (-w) :: Int

main = read <$> getLine >>= \n ->
    tria 0 . fmap parse <$> replicateM n B.getLine >>= print

import Data.List (group, sort)

data Point = Point Int Int
             deriving (Show, Eq)
type Input = [Point]

parse :: String -> Input
parse = map (parsePoint . map read . words) . lines
        where parsePoint [x, y] = Point x y
              parsePoint _      = undefined

instance Ord Point where
    (Point x y) <= (Point x' y') = x < x' || x == x' && y <= y'

normalize :: Int -> Int -> Point
normalize 0 0 = Point 0 0
normalize x y
    | invalid   = normalize (-x) (-y)
    | otherwise = let g = gcd x y in Point (x `div` g) (y `div` g)
    where invalid = y < 0 || y == 0 && x < 0

pairs :: Int -> Int
pairs n = n * (n - 1) `div` 2

colinears :: [Point] -> Int
colinears = sum . map (pairs . length) . group . sort

solve' :: Point -> [Point] -> Int
solve' (Point x0 y0) ps' = pairs (n - 1) - colinears ps
                           where n  = length ps
                                 ps = map (\(Point x y) -> normalize (x - x0) (y - y0)) ps'

solve :: Input -> Integer
solve ps = sum [fromIntegral (solve' p ps) | p <- ps] `div` 3

main :: IO ()
main = do
       _ <- getLine
       print . solve . parse =<< getContents

import Data.List (group, sort)

data Point = Point Int Int
             deriving (Show, Eq)
type Input = [Point]

parse :: String -> Input
parse = map (parsePoint . map read . words) . lines
        where parsePoint [x, y] = Point x y
              parsePoint _      = undefined

instance Ord Point where
    (Point x y) <= (Point x' y') = x < x' || x == x' && y <= y'

normalize :: Point -> Point
normalize p@(Point 0 0) = p
normalize (Point x y)
    | invalid         = normalize (Point (-x) (-y))
    | otherwise = let g = gcd x y in Point (x `div` g) (y `div` g)
    where invalid = y < 0 || y == 0 && x < 0

solve' :: Point -> [Point] -> Int
solve' (Point x0 y0) ps' = pairs (length ps - 1) - colineras
                           where ps = map f ps'
                                 f (Point x y) = normalize (Point (x - x0) (y - y0))
                                 colineras = sum . map (pairs . length) . group . sort $ ps
                                 pairs n = n * (n - 1) `div` 2

solve :: Input -> Integer
solve ps = sum [fromIntegral (solve' p ps) | p <- ps] `div` 3

main :: IO ()
main = do
       _ <- getLine
       print . solve . parse =<< getContents

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

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

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

main = do
  n <- readLn
  ps <- replicateM n $ (\[x, y] -> (x, y)) <$> getInts

  let
    count n = n'*(n'-1)*(n'-2) `div` 6 where n' = fromIntegral n :: Int64

    r = count n - (sum $ map f $ init $ tails ps)
      where
        f ((x, y):ps) = sum vs
          where
            vs = map (count . (+1) . length) $ group $ sort $ map norm $ map (\(xx, yy) -> (xx-x, yy-y)) ps
              where
                norm (x, y) = (x' `div` d, y' `div` d)
                  where
                    (x', y') = if x < 0 || x == 0 && y < 0 then (-x, -y) else (x, y)
                    d = gcd x y

  print r

import Data.List (group, sort)

data Point = Point Int Int
             deriving (Show, Eq)
type Input = [Point]

parse :: String -> Input
parse = map (parsePoint . map read . words) . lines
        where parsePoint [x, y] = Point x y
              parsePoint _      = undefined

instance Ord Point where
    (Point x y) <= (Point x' y') = x < x' || x == x' && y <= y'

normalize :: Point -> Point
normalize p@(Point 0 0) = p
normalize (Point x y)
    | invalid         = normalize (Point (-x) (-y))
    | otherwise = let g = gcd x y in Point (x `div` g) (y `div` g)
    where invalid = y < 0 || y == 0 && x < 0

solve' :: Point -> [Point] -> Int
solve' (Point x0 y0) ps' = pairs (length ps - 1) - colineras
                           where ps = map f ps'
                                 f (Point x y) = normalize (Point (x - x0) (y - y0))
                                 colineras = sum . map (pairs . length) . group . sort $ ps
                                 pairs n = n * (n - 1) `div` 2

solve :: Input -> Int
solve ps = sum [solve' p ps | p <- ps] `div` 3

main :: IO ()
main = do
       _ <- getLine
       print . solve . parse =<< getContents


import Data.List

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

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

solve' :: [Int] -> [Int] -> [Int] -> Int
solve' [] [] [] = 0
solve' [] curr next = (length curr) - 1 + solve' (reverse next) [] []
solve' (a:ax) [] [] = solve' ax [a] []
solve' (a:ax) (c:cx) next | a == c = solve' ax (c:cx) (a:next)
                          | otherwise = solve' ax (a:c:cx) next

import Data.List

main::IO ()
main = getLine >> do
  us <- fmap (map read. words) getLine :: IO [Int]
  print $ snd $ foldl' go (Nothing, 0::Int) $ sort us where
    go (Nothing , acc) el   = (Just (el, 1::Int, 0::Int), acc)
    go (Just (p, reps, racc), acc) el
      | p == el && racc > 0 = (Just (el, reps + 1, racc - 1), acc + 1)
      | p == el             = (Just (el, reps + 1, racc    ), acc)
      | otherwise           = (Just (el, 1, racc + reps - 1), acc + 1)

module Main where

import Data.Complex
import Data.Char
import Data.List
import Data.Functor
import Control.Monad

type R = Double
type Z = Int
type B = Integer
type Q = Rational
type C = Complex

type A = Char
type S = String

readR = map read <$> words <$> getLine :: IO [R]
readR1 = head <$> readR

readZ = map read <$> words <$> getLine :: IO [Z]
readZ1 = head <$> readZ

readB = map read <$> words <$> getLine :: IO [B]
readB1 = head <$> readB

g :: (Ord a) => [a] -> [[a]]
g [x] = [[x]]
g (x:xs)
    | x < head y = (x : y) : ys
    | otherwise = [x] : zs
    where zs@(y:ys) = g xs

f :: (Ord a) => [[a]] -> [[a]]
f [] = []
f xs = h xs (length xs)
    where
    h (y:ys) n
        | m == n = zs
        | otherwise = h zs m
        where
        zs = f' y ys
        m = length zs
    f' y [] = [y]
    f' y zs'@(z:zs)
        | last y < head z = (y ++ z) : zs
        | otherwise = z : f' y zs

main :: IO ()
main = do
    _ <- readZ1
    xs <- readZ
    print $ sum . map (\x -> length x - 1) . f . g . sort $ xs

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

import           System.IO hiding (char8)
import           Control.Applicative
import           Control.Monad
import           Data.List
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function
import           Data.Array
-- import           Data.Array.ST
-- import           Data.Array.Unsafe
import           Data.Maybe
import           Data.Monoid hiding ((<>))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import           Data.ByteString.Builder
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as IntMap
-- import           Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))
-- import qualified Data.Sequence as S

out = stdout

main = do
  _ <- readInt1 <$> BS.getLine
  ns <- readIntN <$> BS.getLine
  print $ solve ns

solve :: [Int] -> Int
solve = sum . map (pred.length) . transpose . group . sort where

-- makeTable :: -> Table
-- makeTable

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

readInt1 :: BS.ByteString -> Int
readInt1 = fst . fromJust . BS.readInt

readInt2 :: BS.ByteString -> (Int,Int)
readInt2 = toTuple . readIntN

readInt3 :: BS.ByteString -> (Int,Int,Int)
readInt3 = toTriple . readIntN

readIntN :: BS.ByteString -> [Int]
readIntN =  map readInt1 . BS.words

toTuple :: [a] -> (a, a)
toTuple [x, y] = (x, y)

toTriple :: [a] -> (a, a, a)
toTriple [x, y, z] =(x, y, z)

fromTuple :: (a, a) -> [a]
fromTuple (x, y) = [x, y]

fromTriple :: (a, a, a) -> [a]
fromTriple (x, y, z) = [x, y, z]

-- if not applying, use "const"

applyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')
applyTuple f g (x, y) = (f x, g y)

applyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')
applyTriple f g h (x, y, z) = (f x, g y, h z)

-- output functions

data Cell  = ByteStringC BL.ByteString
           | IntC Int
           | Int64C Int64
           deriving( Eq, Ord, Show )

data Row   = ListR [Cell]
           | TupleR (Cell,Cell)
           | TripleR (Cell,Cell,Cell)
           deriving( Eq, Ord, Show )

type Table = [Row]

infixr 4 <>
(<>) :: Monoid m => m -> m -> m
(<>) = mappend

putAns :: Handle -> Table -> IO ()
putAns o = hPutBuilder o . renderTable

renderTable :: Table -> Builder
renderTable rs = mconcat [renderRow r <> char8 '\n' | r <- rs]

renderRow :: Row -> Builder
renderRow (ListR []) = mempty
renderRow (ListR (c:cs)) = renderCell c <> mconcat [ char8 ' ' <> renderCell c' | c' <- cs ]
renderRow (TupleR (x,y)) = renderCell x <> char8 ' ' <> renderCell y
renderRow (TripleR (x,y,z)) = renderCell x <> char8 ' ' <> renderCell y <> char8 ' ' <> renderCell z

renderCell :: Cell -> Builder
renderCell (ByteStringC cs) = lazyByteString cs
renderCell (IntC i) = intDec i
renderCell (Int64C i) = int64Dec i

import Data.List

solve :: [Int] -> Int
solve xs = (length xs) - (maximum $ map length $ group $ sort xs)

main = print . solve . map read . words . head . tail . lines =<< getContents

import Control.Applicative

main = (words <$> getLine) >>= print


{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import Data.Ord
import Data.Int
import Data.Char
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if s then
                aux s
            else
                return id
        else
            liftM ((.) $ showChar x) $ aux False
    in liftM (flip ($) []) $ aux True

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

class IOInteract a where
    convertEither :: String -> Either String a
    toShowS :: a -> String -> String
    toShow :: a -> String
    toShow x = toShowS x []

instance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where
    convertEither = convertEitherp (undefined :: flag)
    toShowS = toShowSp (undefined :: flag)

type family IOType x where
    IOType String = HString
    IOType [x] = HList
    IOType x = HNormal

class IOInteractp flag a where
    convertEitherp :: flag -> String -> Either String a
    toShowSp :: flag -> a -> String -> String

instance (Show a, Read a) => IOInteractp HNormal a where
    convertEitherp _ x = readEither x
    toShowSp _ x = shows x

instance IOInteractp HString String where
    convertEitherp _ x = Right x
    toShowSp _ x = showString x

instance (IOInteract a) => IOInteractp HList [a] where
    convertEitherp _ x = mapM convertEither $ words x
    toShowSp _ [] = id
    toShowSp _ (x : []) = toShowS x
    toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

main :: IO ()
main = do
    o <- runExceptT main_
    case o of
        Right () -> return ()
        Left s -> putStrLn s

main_ :: EIO ()
-- template --
main_ = do
    (n, m) <- liftM2 (,) get get
    a <- replicateM n get
    putln $ f1 a n m

f1 :: [Int64] -> Int -> Int -> Int64
f1 a n m =  if n >= m + 1
            then 0
            else let aa = array (1, length a) (zip [1..length a] a) :: UArray Int Int64 in
                foldl (\s i ->
                    foldl (\s j ->
                        (mod (s * (abs ((aa ! i) - (aa ! j)))) (fromIntegral m))
                    ) s [i+1..length a]
                ) 1 [1..length a]

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

main = do
  (n:m:_) <- map read.words <$> getLine
  as <- map read.words <$> getLine
  if any (> 1) $ map length $ group $ sort $ map (`mod` m) as
    then print 0
    else print $ foldr (\a b -> (a * b) `mod` m) 1 [abs (ai - aj) `mod` m | i <- [0..n - 1], let (pre, (aj:_)) = genericSplitAt i as, ai <- pre]

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

main = do
  (n:m:_) <- map read.words <$> getLine
  as <- map read.words <$> getLine
  if any (> 1) $ map length $ group $ sort $ map (`mod` m) as
    then print 0
    else print $ product [abs (ai - aj) `mod` m | i <- [0..n - 1], let (pre, (aj:_)) = splitAt i as, ai <- pre] `mod` m

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

main = do
  (n:m:_) <- map read.words <$> getLine
  as <- map read.words <$> getLine
  if any (> 1) $ map length $ group $ sort $ map (`mod` m) as
    then print 0
    else print $ product [abs $ ai - aj | i <- [0..n - 1], let (pre, (aj:_)) = splitAt i as, ai <- pre] `mod` m

{-# LANGUAGE TypeFamilies, UndecidableInstances, FlexibleInstances, MultiParamTypeClasses, ScopedTypeVariables #-}
import Data.Ord
import Data.Int
import Data.Char
import Data.Foldable
import Data.List
import Data.Maybe
import Data.Either
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.Trans.Except
import Control.Monad.Trans.Class
import Text.Read (readEither)

getToken :: IO String
getToken =
    let aux s = do
        x <- getChar
        if x == ' ' || x == '\t' || x == '\n' then
            if s then
                aux s
            else
                return id
        else
            liftM ((.) $ showChar x) $ aux False
    in liftM (flip ($) []) $ aux True

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

class IOInteract a where
    convertEither :: String -> Either String a
    toShowS :: a -> String -> String
    toShow :: a -> String
    toShow x = toShowS x []

instance (IOType a ~ flag, IOInteractp flag a) => IOInteract a where
    convertEither = convertEitherp (undefined :: flag)
    toShowS = toShowSp (undefined :: flag)

type family IOType x where
    IOType String = HString
    IOType [x] = HList
    IOType x = HNormal

class IOInteractp flag a where
    convertEitherp :: flag -> String -> Either String a
    toShowSp :: flag -> a -> String -> String

instance (Show a, Read a) => IOInteractp HNormal a where
    convertEitherp _ x = readEither x
    toShowSp _ x = shows x

instance IOInteractp HString String where
    convertEitherp _ x = Right x
    toShowSp _ x = showString x

instance (IOInteract a) => IOInteractp HList [a] where
    convertEitherp _ x = mapM convertEither $ words x
    toShowSp _ [] = id
    toShowSp _ (x : []) = toShowS x
    toShowSp dum (x : xs) = toShowS x . showChar ' ' . toShowSp dum xs

get :: IOInteract a => EIO a
get = ExceptT $ liftM convertEither getToken
put :: IOInteract a => a -> EIO ()
put = lift . putStr . toShow
putln :: IOInteract a => a -> EIO ()
putln = lift . putStrLn . toShow

main :: IO ()
main = do
    o <- runExceptT main_
    case o of
        Right () -> return ()
        Left s -> putStrLn s

main_ :: EIO ()
-- template --
main_ = do
    (n, m) <- liftM2 (,) get get
    a <- replicateM n get
    putln $ f1 a n m

f1 :: [Int64] -> Int -> Int -> Int64
f1 a n m =  if n + 1 >= m
            then 0
            else let aa = array (1, length a) (zip [1..length a] a) :: UArray Int Int64 in
                foldl (\s i ->
                    foldl (\s j ->
                        (mod (s * (abs ((aa ! i) - (aa ! j)))) (fromIntegral m))
                    ) s [i+1..length a]
                ) 1 [1..length a]


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

import qualified Data.ByteString as B (getLine)
import qualified Data.ByteString.Char8 as C (readInt, words)
import qualified Data.Maybe as M (fromJust)
import qualified Data.List as L (sort)
import qualified Data.Sequence as Q ((|>), viewl, viewr, ViewL((:<)), ViewR((:>)), empty, length)

readInt = fst . M.fromJust . C.readInt

run m k s [] ans = ans
run m k s (x:xs) ans = run m k rs xs r where
    ns = niter (s Q.|> x)
    niter ns@(Q.viewl -> l Q.:< ls) | x - l >= m = niter ls | otherwise = ns
    aiter ans (Q.length -> 0) = (ans, Q.empty)
    aiter ans ns@(Q.viewr -> rs Q.:> r) | Q.length ns >= k = aiter (ans + 1) rs | otherwise = (ans, ns)
    (r, rs) = aiter ans ns

main = do
    (map readInt . C.words -> [n, m, k]) <- B.getLine
    (L.sort . map readInt . C.words -> xs) <- B.getLine
    putStrLn $ show $ run m k Q.empty xs 0

module Main where
import qualified Data.ByteString.Char8 as B
import Data.List
import qualified Data.Sequence as S
import Data.Array.Unboxed

main = B.interact exec
exec = B.pack . show . solve . map (maybe undefined fst . B.readInt) . B.words
solve (n:m:k:xs0) = sum $ snd $ mapAccumL (\q ((l, _), (r, o)) -> let q' = (if o then (S.|> r) else id) $ S.dropWhileL (< l) q in if S.length q' >= k then (S.take (k - 1) q', S.length q' - k + 1) else (q', 0)) (S.fromList $ map fst $ filter snd ps) $ zip (tail xs) rs
  where
  xs = assocs (accumArray (flip const) False (0, hi) $ zip xs0 (repeat True) :: UArray Int Bool)
  (ps, rs) = splitAt m xs
  hi = 10^6


import Data.List
import qualified Data.Map as Map
f::Map.Map Int Int->Int->Bool
f ms x=let Just x1=Map.lookup x ms
           Just x2=Map.lookup x1 ms
           Just x3=Map.lookup x2 ms
       in if x==x3 then True else False

main = do
       a<-getLine
       b<-getLine
       let e=read a::Int
           xs=map read (words b)::[Int]
           ms=Map.fromList $ zip [1..e] xs
       putStrLn $ if (any (==True ) ( map (f ms) xs))==True then "YES" else "NO"

import Data.Array (listArray, (!))
process :: [Int] -> Bool
process xs = any (\i -> a!i /= i && a!(a!(a!i)) == i) [1..n]
    where
        n = length xs
        a = listArray (1,n) xs

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    fs <- fmap (map readInt.words) getLine
    if process fs
        then putStrLn "YES"
        else putStrLn "NO"

import Data.Array
main = interact $ solve . map read . words
solve (n:as) | any (\i -> g!(g!(g!i)) == i) (indices g) = "YES" | otherwise = "NO"
  where g = listArray (1,n) as

import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array
import qualified Data.Map as M

check n lk x | n>lk = False
             | n /=t1 && t1 /=t2 && t2 /=t3 && t3==n =True
	     | otherwise = check (n+1) lk x
	where 	t1 = fromJust $ M.lookup n x
		t2= fromJust $ M.lookup t1 x
		t3 = fromJust $ M.lookup t2 x
process k = do
		let x = M.fromList $ zip [1..] k
		let lk = length k
		if check 1 lk x then "Yes" else "No"

main = do
		n<-read <$> getLine ::IO Int
		k<- map read <$> words <$> getLine ::IO [Int]
		putStrLn $ process k


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
    let
      initArr :: UArray Int Bool
      initArr = listArray (1, n) $ replicate n False
      step :: UArray Int Bool -> Int -> UArray Int Bool
      step arr x = if  x > n || (x >= 1 && arr ! x)
        then  step arr (x `div` 2)
        else  arr // [(x, True) | x >= 1]
      ans = and $ elems $ foldl' step initArr a
    pure $ string7 $ if  ans
      then  "YES\n"
      else  "NO\n"

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.ByteString.Char8 (ByteString)
import Data.Maybe (fromJust, listToMaybe)
import Data.Set (Set)
import Control.Monad ( foldM )

import qualified Data.ByteString.Char8 as B
import qualified Data.Set as S

main :: IO()
main = B.interact $ B.unlines . parse . map (fst . fromJust . B.readInt) . tail . B.words

parse :: [Int] -> [ByteString]
parse (n:rest) = solve n (take n rest) : parse (drop n rest)
parse []       = []

solve :: Int -> [Int] -> ByteString
solve n arr = maybe (B.pack "NO") (const $ B.pack "YES") $ foldM exec S.empty arr where
    exec mySet x = (`S.insert` mySet) <$> cook_x where
        cook_x = listToMaybe $ dropWhile bad $ takeWhile (>0) $ iterate (`div` 2) x
        bad y = y > n || S.member y mySet

import Data.ByteString.Char8 (ByteString)
import Data.Maybe (fromJust)
import Data.List (sort)
import Data.Set (Set)

import qualified Data.ByteString.Char8 as B
import qualified Data.Set as S

main :: IO()
main = B.interact $ B.unlines . parse . map (fst . fromJust . B.readInt) . tail . B.words

parse :: [Int] -> [ByteString]
parse (n:rest) = solve n (take n rest) S.empty : parse (drop n rest)
parse []       = []

solve :: Int -> [Int] -> Set Int -> ByteString
solve n (x:xs) mySet = if new_x == 0 then (B.pack "NO") else
    solve n xs (S.insert new_x mySet)
    where
        new_x = judge good_x mySet
        good_x = sitdown x n
solve _ [] _ = B.pack "YES"

sitdown :: Int -> Int -> Int
sitdown x n = if x <= n then x else sitdown (div x 2) n

judge :: Int -> Set Int -> Int
judge x mySet = if S.member x mySet then judge (div x 2) mySet else x

import Data.ByteString.Char8 (ByteString)
import Data.Maybe (fromJust)
import Data.List (sort)
import Data.Set (Set)

import qualified Data.ByteString.Char8 as B
import qualified Data.Set as S

main :: IO()
main = B.interact $ B.unlines . parse . map (fst . fromJust . B.readInt) . tail . B.words

parse :: [Int] -> [ByteString]
parse (n:rest) = solve n (sort . take n $ rest) S.empty : parse (drop n rest)
parse []       = []

solve :: Int -> [Int] -> Set Int -> ByteString
solve n (x:xs) mySet = if new_x == 0 then (B.pack "NO") else
    solve n xs (S.insert new_x mySet)
    where
        new_x = judge good_x mySet
        good_x = sitdown x n
solve _ [] _ = B.pack "YES"

sitdown :: Int -> Int -> Int
sitdown x n = if x <= n then x else sitdown (div x 2) n

judge :: Int -> Set Int -> Int
judge x mySet = if S.member x mySet then judge (div x 2) mySet else x

import Data.Char
import Data.List ((\\))

main :: IO()
main = do
    tStr <- getLine
    let t = read tStr :: Int
    solve t

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

    aStr <- getLine
    let as = readIntList aStr

    let ans = if possible (minimize as) n then "YES" else "NO"

    putStrLn ans
    solve (t-1)

minimize :: [Int] -> [Int]
minimize = map change

change :: Int -> Int
change a
    | a > 50 = change (a `div` 2)
    | otherwise = a

possible :: [Int] -> Int -> Bool
possible [] n = True
possible as n
    | maxi < n = False
    | maxi == n = possible (as \\ [maxi]) (n-1)
    | maxi > n = possible (newEl : (as \\ [maxi])) n
    | otherwise = False
        where
            maxi = foldr max 0 as
            newEl = maxi `div` 2

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

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

solve :: IO ()
solve = do
    ~[n] <- readInts
    as <- readInts
    let go have x = (:have) <$> x' where
            bad y = y > n || y `elem` have
            x' = listToMaybe $ dropWhile bad $ takeWhile (>0) $ iterate (`div` 2) x
    putStrLn $ maybe "NO" (const "YES") $ foldM go [] as

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

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

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

readInt :: IO Int
readInt = readLn

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

main :: IO ()
main = readInt >>= \t -> replicateM_ t test

test :: IO ()
test = do
    n <- readInt
    dt <- (reverse . sort) <$> readIntArray
    putStrLn $ if can dt then "YES" else "NO"

minimize :: Int -> Int -> [Int] -> [Bool] -> Int -> Bool
minimize n pos dt used x
  | pos == n = True
  | x == 0 = False
  | x > n = minimize n pos dt used (div x 2)
  | x <= n && not (used !! x) = minimize n pos dt used (div x 2)
  | otherwise = minimize n nxt dt newUsed (dt !! nxt)
    where
      (left, right) = splitAt x used
      (remove : need) = right
      newUsed = left ++ [False] ++ need
      nxt = pos + 1

can :: [Int] -> Bool
can dt = minimize n 0 dt [True | _ <- [0..n]] (dt !! 0)
  where n = length dt

import Data.Char
import Data.List ((\\))

main :: IO()
main = do
    tStr <- getLine
    let t = read tStr :: Int
    solve t

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

    aStr <- getLine
    let as = readIntList aStr

    let ans = if possible (minimize as) n then "YES" else "NO"

    putStrLn ans
    solve (t-1)

minimize :: [Int] -> [Int]
minimize = map change

change :: Int -> Int
change a
    | a > 50 = change (a `div` 50)
    | otherwise = a

possible :: [Int] -> Int -> Bool
possible [] n = True
possible as n
    | maxi < n = False
    | maxi == n = possible (as \\ [maxi]) (n-1)
    | maxi > n = possible (newEl : (as \\ [maxi])) n
    | otherwise = False
        where
            maxi = foldr max 0 as
            newEl = maxi `div` 2

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


import Control.Monad
import Control.Applicative
import Control.Arrow

import Data.List
import Data.Maybe
import qualified Data.Array as A
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
swap (a,b) = (b,a)

main = do
    n:m:l <- map readInt . B.words <$> B.getContents
    let banned = parse l
    print $ solve n banned

parse l = go l []
    where
    go [] acc = acc
    go (a:b:l) acc = go l ((a,b):acc)

solve :: Int  -> [(Int,Int)]  -> Int
solve n l = sum [ f i | i <- [2..n `div` 2]] +
            if odd n &&
               (validX A.! (div n 2+1) || validY A.! (div n 2+1))
               then 1 else 0
    where
    validX = A.accumArray (\a e -> False) True (1,n) $ l
    validY = A.accumArray (\a e -> False) True (1,n) $ map swap l
    f i = length $ filter id [a A.! j | a <- [validX,validY],
                                        j <- [i,n+1-i]]

import Control.Applicative
import Control.Monad
import Control.Monad.ST
import qualified Data.ByteString.Char8 as B
import Data.Array.Base
import Data.Array.ST (runSTUArray)

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

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

solve :: Int -> [Int] -> Int
solve n xys =  sum $ map f [1..n-2]
   where
     f i | i < n-i-1  = sum [unsafeAt arr j|arr<-[arrX,arrY],j<-[i,n-i-1]]
         | i == n-i-1 = unsafeAt arrX i `max` unsafeAt arrY i
         | otherwise  = 0

     arrX, arrY :: UArray Int Int
     (arrX, arrY) = runST $ do
       arrX <- newArray (0,n-1) 1 :: ST s (STUArray s Int Int)
       arrY <- newArray (0,n-1) 1 :: ST s (STUArray s Int Int)
       let go (x:y:xys) = do
             unsafeWrite arrX x 0
             unsafeWrite arrY y 0
             go xys
           go _ = return ()
       go xys
       (,) <$> unsafeFreeze arrX <*> unsafeFreeze arrY

import Control.Monad
import Control.Applicative
import Control.Arrow

import Data.List
import Data.Maybe
import qualified Data.Array as A
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
swap (a,b) = (b,a)

main = do
    n:m:l <- map readInt . B.words <$> B.getContents
    let banned = parse l
    print $ solve n banned

parse l = go l []
    where
    go [] acc = reverse acc
    go (a:b:l) acc = go l ((a,b):acc)

solve :: Int  -> [(Int,Int)]  -> Int
solve n l = sum [ f i | i <- [2..n `div` 2]] +
            if odd n &&
               (validX A.! (div n 2+1) || validY A.! (div n 2+1))
               then 1 else 0
    where
    validX = A.accumArray (\a e -> False) True (1,n) $ l
    validY = A.accumArray (\a e -> False) True (1,n) $ map swap l
    f i = length $ filter id [a A.! j | a <- [validX,validY],
                                        j <- [i,n+1-i]]

import Control.Monad
import Control.Applicative
import Control.Arrow

import Data.List
import Data.Maybe
import qualified Data.Array.Unboxed as A
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
swap (a,b) = (b,a)

main = do
    n:m:l <- map readInt . B.words <$> B.getContents
    let banned = parse l
    print $ solve n banned

parse l = go l []
    where
    go [] acc = acc
    go (a:b:l) acc = go l ((a,b):acc)

solve :: Int  -> [(Int,Int)]  -> Int
solve n l = sum [ f i | i <- [2..n `div` 2]] +
            if odd n &&
               (validX A.! (div n 2+1) || validY A.! (div n 2+1))
               then 1 else 0
    where
    validX = (A.accumArray (\a e -> False) True (1,n) $ l)::A.UArray Int Bool
    validY = A.accumArray (\a e -> False) True (1,n) $ map swap l
    f i = length $ filter id [a A.! j | a <- [validX,validY],
                                        j <- [i,n+1-i]]

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

toInt s = (read s :: Int)

cToInt ch = (ord ch) - 48

toInt' :: [Char] -> Int
toInt' ys = let toInt'' [] r = r
                toInt'' (x:xs) r = toInt'' xs (r*10 + (cToInt x))
            in toInt'' ys 0

toIntList s = map toInt' $ words s

bannedSet :: [(Int,Int)] -> ((Int,Int) -> Int) -> Set.Set Int
bannedSet bpos sel = Set.fromList $ [ sel p | p <- bpos ]

solve :: Int -> Int -> [(Int,Int)] -> Int
solve n m bpos = let nh = (n+1) `div` 2
                     rbs = bannedSet bpos fst
                     cbs = bannedSet bpos snd
                     goodRows = [ r | r <- [2..(n-1)], Set.notMember r rbs ]
                     goodCols = [ c | c <- [2..(n-1)], Set.notMember c cbs ]

                     groupCount = [ (length $ filter (\x -> (x == g || x == (n-g+1))) goodRows) +
                                    (length $ filter (\x -> (x == g || x == (n-g+1))) goodCols) | g <- [2..nh] ]

                 in if n `mod` 2 == 0
                    then sum groupCount
                    else if last groupCount <= 1
                         then sum groupCount
                         else sum groupCount - 1

main = do fline <- getLine
          let [n,m] = toIntList fline
          bpos <- forM [1..m] (\_ -> do
                       bSt <- getLine
                       let items = words bSt
                           r = items !! 0
                           c = items !! 1
                       return (r,c))
          putStrLn $ show $ solve n m (map (\(rs,cs) -> (toInt' rs, toInt' cs)) bpos)

import Control.Monad
import qualified Data.Set as Set

toInt s = (read s :: Int)
toIntList s = map toInt $ words s

bannedSet :: [(Int,Int)] -> ((Int,Int) -> Int) -> Set.Set Int
bannedSet bpos sel = Set.fromList $ [ sel p | p <- bpos ]

solve :: Int -> Int -> [(Int,Int)] -> Int
solve n m bpos = let rbs = bannedSet bpos fst
                     cbs = bannedSet bpos snd
                     goodRows = Set.fromList [ r | r <- [2..(n-1)], Set.notMember r rbs ]
                     goodCols = [ c | c <- [2..(n-1)], Set.notMember c cbs ]
                     usableCols = Set.fromList [ c | c <- goodCols, ((Set.notMember c rbs) || (Set.notMember (n-c+1) rbs)) ]
                 in (Set.size goodRows) + (length goodCols)

main = do fline <- getLine
          let [n,m] = toIntList fline
          bpos <- forM [1..m] (\_ -> do
                       bSt <- getLine
                       let items = map toInt $ words bSt
                           r = items !! 0
                           c = items !! 1
                       return (r,c))
          putStrLn $ show $ solve n m bpos

import Control.Monad
import qualified Data.Set as Set

toInt s = (read s :: Int)
toIntList s = map toInt $ words s

bannedSet :: [(Int,Int)] -> ((Int,Int) -> Int) -> Set.Set Int
bannedSet bpos sel = Set.fromList $ [ sel p | p <- bpos ]

solve :: Int -> Int -> [(Int,Int)] -> Int
solve n m bpos = let rbs = bannedSet bpos fst
                     cbs = bannedSet bpos snd
                     goodRows = Set.fromList [ r | r <- [2..(n-1)], Set.notMember r rbs ]
                     goodCols = Set.fromList [ c | c <- [2..(n-1)], Set.notMember c cbs ]
                 in Set.size $ Set.union goodRows goodCols

main = do fline <- getLine
          let [n,m] = toIntList fline
          bpos <- forM [1..m] (\_ -> do
                       bSt <- getLine
                       let items = map toInt $ words bSt
                           r = items !! 0
                           c = items !! 1
                       return (r,c))
          putStrLn $ show $ solve n m bpos

import Control.Monad
import qualified Data.Set as Set

toInt s = (read s :: Int)
toIntList s = map toInt $ words s

bannedSet :: [(Int,Int)] -> ((Int,Int) -> Int) -> Set.Set Int
bannedSet bpos sel = Set.fromList $ [ sel p | p <- bpos ]

solve :: Int -> Int -> [(Int,Int)] -> Int
solve n m bpos = let rbs = bannedSet bpos fst
                     cbs = bannedSet bpos snd
                     goodRows = Set.fromList [ r | r <- [2..(n-1)], Set.notMember r rbs ]
                     goodCols = [ c | c <- [2..(n-1)], Set.notMember c cbs ]
                     usableCols = Set.fromList [ c | c <- goodCols, ((Set.notMember c rbs) || (Set.notMember (n-c+1) rbs)) ]
                 in Set.size $ Set.union goodRows usableCols

main = do fline <- getLine
          let [n,m] = toIntList fline
          bpos <- forM [1..m] (\_ -> do
                       bSt <- getLine
                       let items = map toInt $ words bSt
                           r = items !! 0
                           c = items !! 1
                       return (r,c))
          putStrLn $ show $ solve n m bpos

import Control.Monad
import qualified Data.Set as Set

toInt s = (read s :: Int)
toIntList s = map toInt $ words s

bannedSet :: [(Int,Int)] -> ((Int,Int) -> Int) -> Set.Set Int
bannedSet bpos sel = Set.fromList $ [ sel p | p <- bpos ]

solve :: Int -> Int -> [(Int,Int)] -> Int
solve n m bpos = let nh = (n+1) `div` 2
                     rbs = bannedSet bpos fst
                     cbs = bannedSet bpos snd
                     goodRows = [ r | r <- [2..(n-1)], Set.notMember r rbs ]
                     goodCols = [ c | c <- [2..(n-1)], Set.notMember c cbs ]

                     groupCount = [ (length $ filter (\x -> (x == g || x == (n-g+1))) goodRows) +
                                    (length $ filter (\x -> (x == g || x == (n-g+1))) goodCols) | g <- [2..nh] ]

                     fgroupCount = map (\x -> if x > 3 then 3 else x) groupCount

                 in if n `mod` 2 == 0
                    then sum fgroupCount
                    else if last fgroupCount <= 1
                         then sum fgroupCount
                         else sum fgroupCount - 1

main = do fline <- getLine
          let [n,m] = toIntList fline
          bpos <- forM [1..m] (\_ -> do
                       bSt <- getLine
                       let items = map toInt $ words bSt
                           r = items !! 0
                           c = items !! 1
                       return (r,c))
          putStrLn $ show $ solve n m bpos


import Control.Monad
import Data.Array
import Data.Int
import qualified Data.ByteString.Char8 as C

m :: Int64
m = 998244353

newtype MInt = MInt {toInt64 :: Int64}

instance Num MInt where
    MInt a + MInt b = MInt $ if c >= m then c - m else c where c = a + b
    MInt a - MInt b = MInt $ if c < 0 then c + m else c where c = a - b
    MInt a * MInt b = MInt $ a * b `mod` m
    abs             = id
    signum (MInt a) = MInt $ signum a
    fromInteger i   = MInt $ fromInteger i `mod` m

data Portal = Portal {px :: Int, py :: Int, ps :: Int}

solve :: IO ()
solve = do
    n <- readInt
    p <- listArray (1, n) <$> replicateM n ((\[x, y, s] -> Portal x y s) <$> readInts)
    let dp = fArray (1, n) f where
            f :: Int -> MInt
            f i = fromIntegral (x - y) + dpsum!(i - 1) - dpsum!(j - 1) where
                Portal x y s = p!i
                j = binSearchA ((> y) . px) p
        dpsum = fArray (0, n) f where
            f 0 = 0
            f i = dpsum!(i - 1) + dp!i
    print $ toInt64 $ 1 + fromIntegral (px $ p!n) + sum (map (dp!) $ filter ((==1) . ps . (p!)) [1..n])

fArray :: (Ix i) => (i, i) -> (i -> a) -> Array i a
fArray b f = array b [(i, f i) | i <- range b]

binSearchA :: (a -> Bool) -> Array Int a -> Int
binSearchA f a = go (f . (a!)) l (h + 1) where
    (l, h) = bounds a
    go f l h
        | l >= h    = l
        | f m       = go f l m
        | otherwise = go f (m + 1) h
        where m = (l + h) `div` 2

parseInt = f . C.readInt where f (Just (i, _)) = i
readInt = parseInt <$> C.getLine
readInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = solve

import Control.Monad
import Data.Array
import Data.Int
import qualified Data.ByteString.Char8 as C

m :: Int64
m = 998244353

data Portal = Portal {px :: Int, py :: Int, ps :: Int}

solve :: IO ()
solve = do
    n <- readInt
    p <- listArray (1, n) <$> replicateM n ((\[x, y, s] -> Portal x y s) <$> readInts)
    let dp = fArray (1, n) f where
            f i = (fromIntegral (x - y) + dpsum!(i - 1) - dpsum!(j - 1)) `mod` m where
                Portal x y s = p!i
                j = binSearchA ((> y) . px) p
        dpsum = fArray (0, n) f where
            f 0 = 0
            f i = (dpsum!(i - 1) + dp!i) `mod` m
    print $ (1 + fromIntegral (px $ p!n) + sum (map (dp!) $ filter ((==1) . ps . (p!)) [1..n])) `mod` m

fArray :: (Ix i) => (i, i) -> (i -> a) -> Array i a
fArray b f = array b [(i, f i) | i <- range b]

binSearchA :: (a -> Bool) -> Array Int a -> Int
binSearchA f a = go (f . (a!)) l (h + 1) where
    (l, h) = bounds a
    go f l h
        | l >= h    = l
        | f m       = go f l m
        | otherwise = go f (m + 1) h
        where m = (l + h) `div` 2

parseInt = f . C.readInt where f (Just (i, _)) = i
readInt = parseInt <$> C.getLine
readInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = solve


import Control.Monad (forM)
import qualified Data.Map as M

solve t = do
  s <- getLine
  let m = M.fromListWith (+) [(c, 1) | c <- s]
      ans = foldl (\x i -> x ++ replicate (snd i) (fst i)) "" (M.toList m)
  putStrLn ans

main = do
tlen <- readLn :: IO Int
forM [0..(tlen - 1)] (\t -> do solve t)

import Data.List
main=interact$unlines.map sort.tail.lines

module Main where

import Control.Monad
import Data.List (sort)

main = do
    t <- fmap read getLine
    forM_ [1..t] $ \_ -> do
        str <- getLine
        putStrLn $ sort str


import Control.Monad
import Data.List

stripIndex lst = map (\(a,b) -> b) lst

strToInt :: String -> Int
strToInt [] = 0
strToInt lst = read lst

calc :: String -> Int
calc s =
  let (left', right') = partition (\(i,a) -> odd i) $ zip [1..] s
      left = stripIndex left'
      right = stripIndex right'
      a = strToInt left
      b = strToInt right
  in
    (a+1)*(b+1)-2

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    --let (left', right') = partition (\(i,a) -> odd i) $ zip [1..] line
    --print line
    --print left'
    --print right'
    putStrLn $ show $ calc line

{-# LANGUAGE LambdaCase #-}

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.Char
import Data.Function
import Data.Int
import Data.List
import Data.Maybe

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

-- type Input = ()
-- type Output = ()

-- input :: Scanner Input
input = str

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

-- solve :: Input -> Output
solve = subtract 2 . fst . fst . foldl compute init . map digitToInt . reverse
  where
    init = ((1, 0), (0, 0))
    withC d = 9 - d
    withoutC d = d + 1
    compute ((at00, at01), (at10, at11)) d =
      ( ( {- dp[0, 0] = -} at00 * withoutC d + at10 * withoutC (d - 1),
          {- dp[0, 1] = -} at00 * withC d + at10 * withC (d - 1)
        ),
        ( {- dp[1, 0] = -} at01 * withoutC d + at11 * withoutC (d - 1),
          {- dp[1, 1] = -} at01 * withC d + at11 * withC (d - 1)
        )
      )

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

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

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

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

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

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

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

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

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

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

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

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

(><) = times

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

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

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

import Control.Arrow ((>>>))

main :: IO ()
main = interact $ lines >>> tail >>> map (solve >>> show) >>> unlines

solve :: String -> Int
solve ns = compute odd ns * compute even ns - 2
  where
    compute p = (1 +) . read . ('0' :) . map snd . filter (p . fst) . zip [1 ..]


{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE CPP #-}

import Control.Applicative
import Control.Monad
import Data.Array
import Data.Char
import Data.Function
import Data.Maybe
import Data.Monoid
import Data.Semigroup

import qualified Data.ByteString.Lazy.Char8 as BS

#if __GLASGOW_HASKELL__ >= 713
import Control.Monad.Trans.State
import Control.Monad.Trans.Reader
import Data.Functor.Identity
#endif

-- {{{ Functors

#if __GLASGOW_HASKELL__ < 713
newtype Identity a = Identity {runIdentity :: a}

instance Functor Identity where
  fmap f (Identity x) = Identity $ f x
#endif

-- }}}

-- {{{ Monads

#if __GLASGOW_HASKELL__ < 713
newtype Reader a b = Reader {runReader :: a -> b}
newtype State s a = State {runState :: s -> (a, s)}

instance Functor (Reader a) where
  fmap f =  Reader . (f . ). runReader
  {-# INLINE fmap #-}

instance Applicative (Reader a) where
  pure = Reader . const
  {-# INLINE pure #-}
  a <*> b = Reader f'
    where
      f1 = runReader a
      f2 = runReader b
      f' = \p -> (f1 p) (f2 p)
  {-# INLINE (<*>) #-}

instance Monad (Reader a) where
  r1 >>= r2 = Reader $ \a -> runReader (r2 $ runReader r1 a) a
  {-# INLINE (>>=) #-}
  return = pure

ask :: Reader a a
ask = Reader id
{-# INLINE ask #-}
local :: (a -> a) -> Reader a b -> Reader a b
local f r = let f' = (runReader r) . f in Reader f'
{-# INLINE local #-}

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

instance Applicative (State s) where
  pure = State . (,)
  {-# INLINE pure #-}
  s1 <*> s2 = State $ \s ->
    let (f, s') = runState s1 s
        (a, s'') = runState s2 s'
    in (f a, s'')

instance Monad (State s) where
  s1 >>= ms2 = State $ \s ->
    let (a, s') = runState s1 s
    in runState (ms2 a) s'
  return = pure

put :: s -> State s ()
put = State . const . ((,) ())
{-# INLINE put #-}
get :: State s s
get = State $ \s -> (s, s)
{-# INLINE get #-}
execState :: State s a -> s -> s
execState st s0 = snd $ runState st s0
#endif

-- }}}

-- {{{ Lens

type CylLens a s b t = forall f. Functor f => (a -> f s) -> b -> f t
type CylLens' a b = CylLens a a b b
lens :: (b -> a) -> (b -> s -> t) -> CylLens a s b t
lens r w g b = w b <$> g (r b)
{-# INLINE lens #-}
iso :: (a -> b) -> (b -> a) -> CylLens' a b
iso f f' = let f'' _ a = f a in lens f' f''
{-# INLINE iso #-}
lensGet :: CylLens a s b t -> b -> a
lensGet lens = getConst . lens Const
{-# INLINE lensGet #-}
lensSet :: CylLens a s b t -> b -> s -> t
lensSet lens b s = runIdentity $ lens (Identity . const s) b
{-# INLINE lensSet #-}

#if __GLASGOW_HASKELL__ < 713
infix 1 &
#endif

infix 8 ^.
infix 4 .=, %=
infixr 4 .~, %~

#if __GLASGOW_HASKELL__ < 713
(&) :: a -> (a -> b) -> b
a & f = f a
{-# INLINE (&) #-}
#endif

(^.) :: b -> CylLens a s b t -> a
b ^. lens = lensGet lens b
{-# INLINE (^.) #-}
(%~) :: CylLens a s b t -> (a -> s) -> (b -> t)
(lens %~ f) b = lensSet lens b (f $ lensGet lens b)
{-# INLINE (%~) #-}
(.~) :: CylLens a s b t -> s -> (b -> t)
(lens .~ v) b = lensSet lens b v
{-# INLINE (.~) #-}
(.=) :: CylLens a a' s s -> a' -> State s ()
lens .= v = do {s <- get; put $ s & lens .~ v}
{-# INLINE (.=) #-}
(%=) :: CylLens a a' s s -> (a -> a') -> State s ()
lens %= f = do {s <- get; put $ s & lens %~ f}
{-# INLINE (%=) #-}
view :: CylLens a a' s s' -> Reader s a
view l = ask >>= return . (^. l)
use :: CylLens a a' s s' -> State s a
use l = get >>= return . (^. l)

-- }}}

-- {{{ Handy IO

type StringReader a = State BS.ByteString a

readFrom :: BS.ByteString -> StringReader a -> a
readFrom s = fst . flip runState s

isLineBreak :: Char -> Bool
isLineBreak c = c == '\n' || c == '\r'

stripLineBreak :: StringReader ()
stripLineBreak = do
  modify $ BS.dropWhile isLineBreak

getLine :: StringReader BS.ByteString
getLine = do
  s <- get
  let (l, s') = BS.span (not . isLineBreak) s
  put s'
  stripLineBreak
  return l

restLines :: StringReader [BS.ByteString]
restLines = do
  s <- get
  put BS.empty
  return $ BS.lines s

getInt :: Num a => StringReader a
getInt = do
  s <- get
  let l' = BS.dropWhile isSpace s
      (d, ll') = BS.span isDigit l'
  put ll'
  return $ case BS.readInt d of
    Just (i, _) -> fromIntegral i
    Nothing -> error $ "Not an integer: " ++ show d

-- }}}

solve :: Int -> [(Int, Int)] -> [Int]
solve n xs = map (fromMaybe 0) $ rot 0 Nothing (zip zs ys)  []
  where
    d s t
      | t >= s = t - s
      | otherwise = n - s + t
    xs' = map (\(a, b) -> (a - 1, Just (Sum n, Min $ d (a - 1) (b - 1)))) xs
    ysR = accumArray (<>) Nothing (0, n - 1) xs'
    ys = map (fmap (\(Sum k, Min dt) -> k + dt - n)) $ elems ysR
    zs = scanr1 (<>) $ map (\(y, i) -> (Max . (+i)) <$> y) $ zip ys [0..]

    mInt :: CylLens' Int (Max Int)
    mInt = iso Max getMax

    rot :: Int -> Maybe (Max Int) -> [(Maybe (Max Int), Maybe Int)] -> [Maybe Int] -> [Maybe Int]
    rot _ _ [] acc = reverse acc
    rot offset prevMax ((maxX, x):t) acc =
      rot (offset + 1)
          (((& (mInt %~ (subtract 1))) <$> prevMax) <> ((Max . (+(n - 1))) <$> x))
          t
          ((getMax <$> prevMax <> ((& mInt %~ (subtract offset)) <$> maxX)):acc)

main :: IO ()
main = do
  contents <- BS.getContents
  let (n, xs) = readFrom contents $ do
        _n <- getInt
        _m <- getInt
        _xs <- replicateM _m $ (,) <$> getInt <*> getInt
        return (_n, _xs)
      ans = solve n xs
  putStrLn $ unwords $ map show ans
  return ()

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

module Main where

--import Debug.Trace

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

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

---- Answer Code Section ----

dist nNode src dst = if src < dst then dst - src else dst + (nNode - src)

shortestTimeNode :: Int -> Int -> Int -> [Int] -> Int
shortestTimeNode _     _        _    []      = 0
shortestTimeNode nNode initNode node candies = beforeLast + shortestLast where
    nLoop = if initNode == node then length candies - 2 else length candies - 1
    beforeLast = nNode * nLoop + dist nNode initNode node
    shortestLast = minimum $ map (dist nNode node) candies

shortestTimeNodes nNode filteredCandies initNode =
    maximum $ map (uncurry $ shortestTimeNode nNode initNode) filteredCandies

process :: [[Int]] -> [Int]
process nodeCandies = map (shortestTimeNodes n filteredCandies) [0..(n-1)] where
    n = length nodeCandies
    maxCandy = maximum (map length nodeCandies)
    filteredCandies = filter (\(i, nc) -> length nc >= maxCandy - 1) (zip [0..] nodeCandies)

main = do
    n:m:[] <- getInts
    nodeCandyArray <- newArray (1, n) [] :: IO (IA.IOArray Int [Int])
    replicateM_ m (writeCandy nodeCandyArray)
    nodeCandies <- getElems nodeCandyArray :: IO [[Int]]
    putStrLn $ showCandies $ process nodeCandies

writeCandy candies = do
    node:candy:[] <- getInts
    candyList <- readArray candies node
    writeArray candies node ((candy-1) : candyList)

showCandies = unwords . map show

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

module Main where

--import Debug.Trace

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

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

---- Answer Code Section ----

dist nNode src dst = if src < dst then dst - src else dst + (nNode - src)

shortestTimeNode :: Int -> Int -> Int -> (Int, Int) -> Int
shortestTimeNode nNode initNode node (nLoop, lastTime) = if lastTime == 0 then 0 else beforeLast + lastTime where
    nLoop' = if initNode == node then nLoop - 1 else nLoop
    beforeLast = nNode * (nLoop'- 1) + dist nNode initNode node

shortestTimeNodes nNode filteredCandiesInfo initNode =
    maximum $ map (uncurry $ shortestTimeNode nNode initNode) filteredCandiesInfo

process :: [[Int]] -> [Int]
process nodeCandies = map (shortestTimeNodes n filteredCandiesInfo) [0..(n-1)] where
    n = length nodeCandies
    maxCandy = maximum (map length nodeCandies)
    filteredCandies = filter (\(i, nc) -> length nc >= max 1 (maxCandy - 1)) (zip [0..] nodeCandies)
    filteredCandiesInfo = map (\(i, nc) -> (i, (length nc, minimum $ map (dist n i) nc))) filteredCandies

main = do
    n:m:[] <- getInts
    nodeCandyArray <- newArray (1, n) [] :: IO (IA.IOArray Int [Int])
    replicateM_ m (writeCandy nodeCandyArray)
    nodeCandies <- getElems nodeCandyArray :: IO [[Int]]
    putStrLn $ showCandies $ process nodeCandies

writeCandy candies = do
    node:candy:[] <- getInts
    candyList <- readArray candies node
    writeArray candies node ((candy-1) : candyList)

showCandies = unwords . map show

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

module Main where

--import Debug.Trace

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

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

---- Answer Code Section ----

dist nNode src dst = if src < dst then dst - src else dst + (nNode - src)

shortestTimeNode :: Int -> Int -> Int -> [Int] -> Int
shortestTimeNode _     _        _    []      = 0
shortestTimeNode nNode initNode node candies = beforeLast + shortestLast where
    nLoop = if initNode == node then length candies - 2 else length candies - 1
    beforeLast = nNode * nLoop + dist nNode initNode node
    shortestLast = minimum $ map (dist nNode node) candies

shortestTimeNodes nNode filteredCandies initNode =
    maximum $ map (uncurry $ shortestTimeNode nNode initNode) filteredCandies

process :: [[Int]] -> [Int]
process nodeCandies = map (shortestTimeNodes n filteredCandies) [0..(n-1)] where
    n = length nodeCandies
    maxCandy = maximum (map length nodeCandies)
    filteredCandies = filter (\(i, nc) -> length nc == maxCandy) (zip [0..] nodeCandies)

main = do
    n:m:[] <- getInts
    nodeCandyArray <- newArray (1, n) [] :: IO (IA.IOArray Int [Int])
    replicateM_ m (writeCandy nodeCandyArray)
    nodeCandies <- getElems nodeCandyArray :: IO [[Int]]
    putStrLn $ showCandies $ process nodeCandies

writeCandy candies = do
    node:candy:[] <- getInts
    candyList <- readArray candies node
    writeArray candies node ((candy-1) : candyList)

showCandies = unwords . map show

import Control.Monad
import Control.Monad.Trans.State
import Data.Array
import Data.Char

import qualified Data.ByteString.Lazy.Char8 as BS

-- {{{ Handy IO

type StringReader a = State BS.ByteString a

readFrom :: BS.ByteString -> StringReader a -> a
readFrom s = fst . flip runState s

isLineBreak :: Char -> Bool
isLineBreak c = c == '\n' || c == '\r'

stripLineBreak :: StringReader ()
stripLineBreak = do
  modify $ BS.dropWhile isLineBreak

getLine :: StringReader BS.ByteString
getLine = do
  s <- get
  let (l, s') = BS.span (not . isLineBreak) s
  put s'
  stripLineBreak
  return l

restLines :: StringReader [BS.ByteString]
restLines = do
  s <- get
  put BS.empty
  return $ BS.lines s

getInt :: Num a => StringReader a
getInt = do
  s <- get
  let l' = BS.dropWhile isSpace s
      (d, ll') = BS.span isDigit l'
  put ll'
  return $ case BS.readInt d of
    Just (i, _) -> fromIntegral i
    Nothing -> error $ "Not an integer: " ++ show d

-- }}}

solve :: Int -> [(Int, Int)] -> [Int]
solve n xs = rot 0 0 (zip zs ys)  []
  where
    d s t
      | t >= s = t - s
      | otherwise = n - s + t
    xs' = map (\(a, b) -> (a - 1, d (a - 1) (b - 1))) xs
    ysR = accumArray (\(b, l) dt -> (b + n, min l dt)) (0, n) (0, n - 1) xs'
    ys = map ((subtract n) . uncurry (+)) $ elems ysR
    zs = scanr1 max $ map (uncurry (+)) $ zip ys [0..]

    rot :: Int -> Int -> [(Int, Int)] -> [Int] -> [Int]
    rot _ _ [] acc = reverse acc
    rot offset prevMax ((maxX, x):t) acc =
      rot (offset + 1) (max (prevMax - 1) (x + n - 1)) t (max prevMax (maxX - offset):acc)

main :: IO ()
main = do
  contents <- BS.getContents
  let (n, xs) = readFrom contents $ do
        _n <- getInt
        _m <- getInt
        _xs <- replicateM _m $ (,) <$> getInt <*> getInt
        return (_n, _xs)
      ans = solve n xs
  putStrLn $ unwords $ map show ans
  return ()


main = interact $ solve . map read . words

solve :: (Integral a, Show a) => [a] -> String
solve [n, k] | n * (n - 1) > 2 * k = unlines $ map (("4 " ++) . show) [1 .. n]
             | otherwise           = "no solution"

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}
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.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 = B.readInt >>> fmap fst >>> fromMaybe 0
readInts = map readInt . 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)
itof :: Int -> Double
itof = fromIntegral

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

main = do
    [n,k] <- readLns
    if k >= n * (n - 1) `div` 2 then
        putStrLn "no solution"
    else
        forM_ [0..n-1] $ \i-> printf "0 %d\n" (i :: Int)

import Data.List
import Control.Monad

main = do [n, k] <- fmap (map read . words) getLine
          if n * (n - 1) <= 2 * k then
            putStrLn "no solution"
            else
            mapM_ (\x -> putStrLn ("0 " ++ show x)) [1..n]

main=interact$f.map read.words
f :: [Integer] -> String
f[n,k]
  | k >= sum[n-i|i<-[1..n]] = "no solution"
  | otherwise = unlines.map(("0 "++).show)$take (fromIntegral n) [0..]

main = do
  [n, k] <- (map read . words) `fmap` getLine
  if k >= n*(n-1) `div` 2
  then
    putStrLn "no solution"
  else
    putStr $ unlines $ map (\i -> "0 " ++ (show i)) $ take n $ [0..]

main = do
  [n, k] <- (map read . words) `fmap` getLine
  if k > n*(n-1) `div` 2
  then
    putStrLn "no solution"
  else
    putStr $ unlines $ map (\i -> "0 " ++ (show i)) $ take n $ [0..]

main=interact$f.map read.words
f :: [Integer] -> String
f[n,k]
  | k >= n*(n+1)`div`2-1 = "no solution"
  | otherwise = unlines.map(("0 "++).show)$take (fromIntegral n) [10^9,(10^9)-1..]


import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)
import Data.Maybe (catMaybes)
import Data.Fixed (Pico)

data Point = Point Pico Pico
data Vector = Vector Pico Pico

vect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)
Vector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1
Vector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2
Point x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)

eps = 1e-7

main = do
	[n, m] <- map read . words <$> getLine
	ps <- map ((\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine
	ls <- map ((\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine

	let
		solve (lp, lq) =
				(dist lp lq) * (sum $ map (\((z1, z2), _) -> z2 - z1) $ filter (\(_, c) -> c /= 0) $ zip (zip zs (tail zs ++ zs)) cs')
			where
				lv = vect lp lq
				(zs, cs) = unzip $ sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps
				cs' = scanl1 (+) cs

				intersect p q
					| s1 == s2 = Nothing
					| otherwise = Just (z, c)
					where
						sgn m = if m <= - eps then -1 else if m >= eps then 1 else 0
						s1 = sgn $ lv `cross` (vect lp p)
						s2 = sgn $ lv `cross` (vect lp q)

						z = ((vect lp p) `cross` pq) / (lv `cross` pq)
							where
								pq = vect p q

						c = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)

	putStr $ unlines $ map (show . solve) ls

import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)
import Data.Maybe (catMaybes)
import Data.Fixed (Pico)

data Point = Point Pico Pico
data Vector = Vector Pico Pico

vect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)
Vector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1
Vector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2

-- TODO how Pico to Double ?
Point x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)

eps = 1e-7

main = do
	[n, m] <- map read . words <$> getLine
	ps <- map ((\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine
	ls <- map ((\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine

	let
		solve (lp, lq) =
				(dist lp lq) * (sum $ map fst $ filter ((/= 0) . snd) $ zip ds cs')
			where
				(zs, cs) = unzip $ sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps
				ds = zipWith (flip (-)) zs (tail zs ++ zs)
				cs' = scanl1 (+) cs

				intersect p q
					| s1 == s2 = Nothing
					| otherwise = Just (z, c)
					where
						lv = vect lp lq
						sgn m = if m <= - eps then -1 else if m >= eps then 1 else 0
						s1 = sgn $ lv `cross` (vect lp p)
						s2 = sgn $ lv `cross` (vect lp q)

						z = ((vect lp p) `cross` pq) / (lv `cross` pq)
							where
								pq = vect p q

						c = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)

	putStr $ unlines $ map (show . solve) ls

import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)
import Data.Maybe (catMaybes)
import Data.Fixed (Pico)

data Point = Point Pico Pico deriving (Show)
data Vector = Vector Pico Pico

vect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)
Vector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1
Vector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2
Point x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)

eps = 1e-7

main = do
	[n, m] <- map read . words <$> getLine
	ps <- map ((\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine
	ls <- map ((\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine

	let
		solve (lp, lq) =
				((dist lp lq) *) $ sum $ map (\(z1, z2, _) -> z2 - z1) $ filter (\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'
			where
				lv = vect lp lq
				(zs, cs) = unzip $ sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps
				cs' = scanl1 (+) cs

				intersect p q
					| s1 == s2 = Nothing
					| otherwise = Just (z, c)
					where
						sgn m = if m <= - eps then -1 else if m >= eps then 1 else 0
						s1 = sgn $ lv `cross` (vect lp p)
						s2 = sgn $ lv `cross` (vect lp q)

						z = ((vect lp p) `cross` pq) / (lv `cross` pq)
							where
								pq = vect p q

						c = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)

	putStr $ unlines $ map (show . solve) ls

import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)
import Data.Maybe (catMaybes)
import Data.Fixed (Pico)

data Point = Point Pico Pico deriving (Show)
data Vector = Vector Pico Pico

vect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)
Vector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1
Vector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2
Point x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)

eps = 1e-7

main = do
	[n, m] <- map read . words <$> getLine
	ps <- map ((\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine
	ls <- map ((\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine

	let
		solve (lp, lq) =
				((dist lp lq) *) $ sum $ map (\(z1, z2, _) -> z2 - z1) $ filter (\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'
			where
				lv = vect lp lq
				is = sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps
				(zs, cs) = unzip is
				cs' :: [Int]
				cs' = scanl1 (+) cs

				intersect p q
					| s1 == s2 = Nothing
					| otherwise = Just (z, c)
					where
						sgn m = if m <= - eps then -1 else if m >= eps then 1 else 0
						s1 = sgn $ lv `cross` (vect lp p)
						s2 = sgn $ lv `cross` (vect lp q)

						z = ((vect lp p) `cross` pq) / (lv `cross` pq)
							where
								pq = vect p q

						c = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)

	putStr $ unlines $ map (show . solve) ls

import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)
import Data.Maybe (catMaybes)
import Data.Fixed (Pico)

data Point = Point Pico Pico
data Vector = Vector Pico Pico

vect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)
Vector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1
Vector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2
Point x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)

eps = 1e-7

main = do
	[n, m] <- map read . words <$> getLine
	ps <- map ((\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine
	ls <- map ((\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine

	let
		solve (lp, lq) =
				(dist lp lq) * (sum $ map fst $ filter (\(_, c) -> c /= 0) $ zip (zipWith (flip (-)) zs (tail zs ++ zs)) cs')
			where
				lv = vect lp lq
				(zs, cs) = unzip $ sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps
				cs' = scanl1 (+) cs

				intersect p q
					| s1 == s2 = Nothing
					| otherwise = Just (z, c)
					where
						sgn m = if m <= - eps then -1 else if m >= eps then 1 else 0
						s1 = sgn $ lv `cross` (vect lp p)
						s2 = sgn $ lv `cross` (vect lp q)

						z = ((vect lp p) `cross` pq) / (lv `cross` pq)
							where
								pq = vect p q

						c = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)

	putStr $ unlines $ map (show . solve) ls

import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)
import Data.Maybe (catMaybes)
import Data.Fixed (Pico)

data Point = Point Pico Pico
data Vector = Vector Pico Pico

vect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)
Vector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1
Vector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2
Point x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)

eps = 1e-7

main = do
	[n, m] <- map read . words <$> getLine
	ps <- map ((\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine
	ls <- map ((\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine

	let
		solve (lp, lq) =
				((dist lp lq) *) $ sum $ map (\(z1, z2, _) -> z2 - z1) $ filter (\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'
			where
				lv = vect lp lq
				(zs, cs) = unzip $ sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps
				cs' = scanl1 (+) cs

				intersect p q
					| s1 == s2 = Nothing
					| otherwise = Just (z, c)
					where
						sgn m = if m <= - eps then -1 else if m >= eps then 1 else 0
						s1 = sgn $ lv `cross` (vect lp p)
						s2 = sgn $ lv `cross` (vect lp q)

						z = ((vect lp p) `cross` pq) / (lv `cross` pq)
							where
								pq = vect p q

						c = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)

	putStr $ unlines $ map (show . solve) ls

{-# OPTIONS_GHC -O2 #-}
import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)
import Data.Maybe (catMaybes)
import Data.Fixed (Pico)
-- import Debug.Trace (trace)

data Point = Point Pico Pico deriving (Show)
data Vector = Vector Pico Pico

vect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)
Vector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1
Vector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2
Point x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)

eps = 1e-6

main = do
	[n, m] <- map read . words <$> getLine
	ps <- map ((\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine
	ls <- map ((\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine

	let
		solve (lp, lq) = -- trace (show is) $
				((dist lp lq) *) $ sum $ map (\(z1, z2, _) -> z2 - z1) $ filter (\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'
			where
				lv = vect lp lq
				is = sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps
				(zs, cs) = unzip is
				cs' :: [Int]
				cs' = scanl1 (+) cs

				intersect p q
					| s1 == s2 = Nothing
					| otherwise = Just (z, c)
					where
						sgn m = if m <= - eps then -1 else if m >= eps then 1 else 0
						s1 = sgn $ lv `cross` (vect lp p)
						s2 = sgn $ lv `cross` (vect lp q)

						z = ((vect lp p) `cross` pq) / (lv `cross` pq)
							where
								pq = vect p q

						c = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)

	putStr $ unlines $ map (show . solve) ls

import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)
import Data.Maybe (catMaybes)
-- import Debug.Trace (trace)

data Point = Point Double Double deriving (Show)
data Vector = Vector Double Double

vect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)
Vector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1
Vector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2

eps = 1e-9

main = do
	[n, m] <- map read . words <$> getLine
	ps <- map ((\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine
	ls <- map ((\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine

	let
		solve (lp, lq) = -- trace (show is) $
				((sqrt (lv `dot` lv)) *) $ sum $ map (\(z1, z2, _) -> z2 - z1) $ filter (\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'
			where
				lv = vect lp lq
				is = sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps
				(zs, cs) = unzip is
				cs' :: [Int]
				cs' = scanl1 (+) cs

				intersect p q
					| s1 == s2 = Nothing
					| otherwise = Just (z, c)
					where
						sgn m = if m <= - eps then -1 else if m >= eps then 1 else 0
						s1 = sgn $ lv `cross` (vect lp p)
						s2 = sgn $ lv `cross` (vect lp q)

						z = ((vect lp p) `cross` pq) / (lv `cross` pq)
							where
								pq = vect p q

						c = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)

	putStr $ unlines $ map (show . solve) ls

{-# OPTIONS_GHC -O2 #-}
import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)
import Data.Maybe (catMaybes)
-- import Debug.Trace (trace)

data Point = Point Double Double deriving (Show)
data Vector = Vector Double Double

vect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)
Vector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1
Vector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2
Point x1 y1 `dist` Point x2 y2 = sqrt $ (x2-x1)^2 + (y2-y1)^2

eps = 1e-3

main = do
	[n, m] <- map read . words <$> getLine
	ps <- map ((\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine
	ls <- map ((\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine

	let
		solve (lp, lq) = -- trace (show is) $
				((dist lp lq) *) $ sum $ map (\(z1, z2, _) -> z2 - z1) $ filter (\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'
			where
				lv = vect lp lq
				is = sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps
				(zs, cs) = unzip is
				cs' :: [Int]
				cs' = scanl1 (+) cs

				intersect p q
					| s1 == s2 = Nothing
					| otherwise = Just (z, c)
					where
						sgn m = if m <= - eps then -1 else if m >= eps then 1 else 0
						s1 = sgn $ lv `cross` (vect lp p)
						s2 = sgn $ lv `cross` (vect lp q)

						z = ((vect lp p) `cross` pq) / (lv `cross` pq)
							where
								pq = vect p q

						c = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)

	putStr $ unlines $ map (show . solve) ls

{-# OPTIONS_GHC -O2 #-}
import Control.Applicative ((<$>))
import Control.Monad (replicateM)
import Data.List (sort)
import Data.Maybe (catMaybes)
import Data.Fixed (Pico)
-- import Debug.Trace (trace)

data Point = Point Pico Pico deriving (Show)
data Vector = Vector Pico Pico

vect (Point x1 y1) (Point x2 y2) = Vector (x2-x1) (y2-y1)
Vector x1 y1 `cross` Vector x2 y2 = x1*y2 - x2*y1
Vector x1 y1 `dot` Vector x2 y2 = x1*x2 + y1*y2
Point x1 y1 `dist` Point x2 y2 = realToFrac $ sqrt $ (read $ show $ (x2-x1)^2 + (y2-y1)^2 :: Double)

eps = 1e-3

main = do
	[n, m] <- map read . words <$> getLine
	ps <- map ((\[x, y] -> Point x y) . map read . words) <$> replicateM n getLine
	ls <- map ((\[x1, y1, x2, y2] -> (Point x1 y1, Point x2 y2)) . map read . words) <$> replicateM m getLine

	let
		solve (lp, lq) = -- trace (show is) $
				((dist lp lq) *) $ sum $ map (\(z1, z2, _) -> z2 - z1) $ filter (\(_, _, c) -> c /= 0) $ zip3 zs (tail zs ++ zs) cs'
			where
				lv = vect lp lq
				is = sort $ catMaybes $ zipWith intersect ps $ tail ps ++ ps
				(zs, cs) = unzip is
				cs' :: [Int]
				cs' = scanl1 (+) cs

				intersect p q
					| s1 == s2 = Nothing
					| otherwise = Just (z, c)
					where
						sgn m = if m <= - eps then -1 else if m >= eps then 1 else 0
						s1 = sgn $ lv `cross` (vect lp p)
						s2 = sgn $ lv `cross` (vect lp q)

						z = ((vect lp p) `cross` pq) / (lv `cross` pq)
							where
								pq = vect p q

						c = (if s1 > s2 then 1 else -1) * (if s1 /= 0 && s2 /= 0 then 2 else 1)

	putStr $ unlines $ map (show . solve) ls


{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))
import safe Data.List (group, sort)

main :: IO ()
main =
  interact $
    lines >>> map (words >>> map read) >>> solve >>> show >>> (++ "\n")

solve :: [[Integer]] -> Integer
solve [[n, k], a]
  | maximum (map snd groups) >= k = 0
  | otherwise = minimum $ map (get k) [lt, rt, comb]
  where
    groups = getGroups a
    lt = compute groups
    rt = reverse . compute . reverse $ groups
    comb = zip (repeat n) $ zipWith (+) (map snd lt) (map snd rt)

type PII = (Integer, Integer)

-- merge :: [PII] -> [PII] -> [PII]
-- merge = zipWith cadd
--   where
--     cadd (l, c) (l', c') = (l + l', c + c')

getGroups :: [Integer] -> [PII]
getGroups =
  map (\u -> (head u, fromIntegral $ length u))
    . group
    . sort

inf :: Integer
inf = 10 ^ 18

get :: Integer -> [(Integer, Integer)] -> Integer
get k =
  foldl min inf
    . map ((+ k) . uncurry (flip (-)))
    . filter ((>= k) . fst)

--         [(value,   length)]  -> [(length,  cost)]
compute :: [(Integer, Integer)] -> [(Integer, Integer)]
compute [] = []
compute [(_, l)] = [(l, 0)]
compute (x : x' : xs) = (len, cost) : res
  where
    res = compute (x' : xs)
    len = snd x + fst (head res)
    cost = snd (head res) + fst (head res) * abs (fst x - fst x')

import Control.Arrow
import Data.List

main = interact $
  lines >>> map (words >>> map read) >>> solve >>> show >>> (++"\n")

solve :: [[Integer]] -> Integer
solve [[n,k], a]
  | foldl1 max (map snd groups) >= k = 0
  | otherwise = foldl1 min $ map (get k) [lt, rt, comb]
  where
    groups = getgroups a
    lt = compute groups
    rt = reverse $ compute $ reverse groups
    comb = map(\(_, c) -> (n, c)) $ merge lt rt

merge a b = map (\((l, c), (l', c')) -> (l + l', c + c'))
             $ zip a b

getgroups a = map (\u -> (head u, fromIntegral $ length u))
               $ group $ sort a

inf = 1000000000000000000 :: Integer
get k xs = foldl min inf
            $ map (\(l, c) -> c - l + k)
              $ filter (\(l, _) -> l >= k) xs

--         [(value,   length)]  -> [(length,  cost)]
compute :: [(Integer, Integer)] -> [(Integer, Integer)]
compute [] = []
compute [(v, l)] = [(l, 0)]
compute (a:b:rest) = (len, cost) : res
  where
    res = compute (b:rest)
    len = snd a + fst (head res)
    cost = snd (head res) + (fst (head res)) * abs (fst a - fst b)


import Control.Applicative ((<$>))
import Data.ByteString.Char8 (getLine, words, readInt)
import Data.Maybe (fromJust)
import Data.List (sort)
import Data.Tuple (swap)
import Prelude hiding (words, getLine)

readInt' = fst . fromJust .readInt

main = do
	_ <- getLine
	as <- map readInt' . words <$> getLine
	bs <- map readInt' . words <$> getLine

	let
		as' = sort as
		bs' = sort $ zip bs [1..]

		solve n _ [] = []
		solve n [] (b:bs) = (n, snd b) : (solve n [] bs)
		solve n (a:as) (b:bs)
			| a > fst b = (n, snd b) : (solve n (a:as) bs)
			| otherwise = solve (n + 1) as (b:bs)

		zs = solve 0 as' bs'
		rs = map snd . sort $ map swap zs

	putStrLn . unwords $ map show rs

-- B. Queries about less or equal elements

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

compute :: [Int] -> [Int] -> [Int]
compute a b = map snd . sort $ zip (map snd bs) (compute' (sort a) (map fst bs) 0)
    where bs = sort $ zip b [0::Int ..]
          compute' :: [Int] -> [Int] -> Int -> [Int]
          compute' _ [] _ = []
          compute' [] b' x = map (const x) b'
          compute' a'@(ah:at) b'@(bh:bt) x
              | ah <= bh  = compute' at b' (x + 1)
              | otherwise = x : compute' a' bt x

main :: IO()
main =
    do  _ <- C.getLine
        a <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine
        b <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine
        putStrLn . unwords . map show $ compute a b

import Control.Applicative
import Control.Arrow
import Data.Function
import Data.List
import Data.Maybe
import qualified Data.ByteString.Char8 as BS

main = do
	(n : _ : input) <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getContents
	let (as, bs) = (first sort) . (second $ (sort . (flip zip) [0 ..])) $ splitAt n input
	putStrLn $ concatMap (($ " ") . (shows . fst)) $ sortBy (compare `on` snd) $ scanl1 (\(acc, _) (v, i) -> (acc + v, i)) $ f as bs

f _ [] 				= []
f [] bs				= map (first $ const 0) bs
f as ((b, i) : bs)	= let (smaller, larger) = span (<= b) as in (length smaller, i) : f larger bs

import Data.List as L
import qualified Data.Set as Set
import Data.ByteString.Char8 as LC

maxval = 2000000001

readInt :: String -> Int
readInt = read

solve :: Set.Set (Int, Int) -> [Int] -> [Int]
solve aset [] = []
solve aset (x:xs) = ans:(solve aset xs)
  where Just (_, ans) = Set.lookupLT (x, maxval) aset

convert :: [Int] -> [Int]
convert nums =
  let n = nums !! 0
      (alist, blist) = L.splitAt n (L.drop 2 nums)
  in  solve (Set.fromList $ L.zip ((-maxval):(L.sort alist)) [0..]) blist

readIntBs :: LC.ByteString -> Int
readIntBs bs = case LC.readInt bs of
                 Just (x, _) -> x
                 Nothing -> error "may Paul Hudak have mercy on my soul"

main = do
  input <- LC.getContents
  Prelude.putStrLn $ L.intercalate " " . L.map show . convert . (L.map readIntBs) . LC.words $ input

{-# LANGUAGE OverloadedStrings #-}
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Char (digitToInt)
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import Data.List (sort, scanl1, group)
import Data.Maybe (fromMaybe)
import Data.Functor ((<$>))

parseInt :: ByteString -> Int
parseInt s
  | BS.head s == '-' = negate (go 0 (BS.tail s))
  | otherwise = go 0 s
  where
    go i s
      | BS.null s = i
      | otherwise = go (i*10 + digitToInt (BS.head s)) (BS.tail s)

main :: IO ()
main = do
  l0 <- BS.getLine
  let [a, b] = map parseInt . BS.words $ l0
  l1 <- BS.getLine
  let as = group . sort . map parseInt . BS.words $ l1
  let lst = zip (map head as) (scanl1 (+) (map length as))
  let tree = IM.fromAscList lst
  l2 <- BS.getLine
  let bs = map parseInt . BS.words $ l2
  let answers = map (\b -> fromMaybe 0 (snd <$> IM.lookupLE b tree)) bs
  BS.putStrLn (BS.unwords (map (BS.pack . show) answers))


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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

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

import Prelude
import Control.Monad
import Data.List
import Data.Tuple

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

    (putStr . unlines . map solve) tcs

readTC = do
    n <- readLn
    replicateM n getLine

solve = show . maximum . map solvePMs . transpose . map toPlusMinus . toCharCounts

toCharCounts ws = transpose . map (charFreqs ws) $ ['a'..'e']
charFreqs ws c = map (charFreq c) ws
charFreq c = length . filter (==c)

toPlusMinus cnts = (map.g.sum) cnts cnts
  where
    g len cnt = (cnt, len - cnt)     -- (this char, other chars of the word)

solvePMs = length . takeWhile (>0) . scanl1 (+) . map (uncurry (-)) . sortOn (uncurry (-) . swap)

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

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

import Prelude
import Control.Monad
import Data.List
import Data.Tuple

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

    (putStr . unlines . map solve) tcs

readTC = do
    n <- readLn
    replicateM n getLine

solve = show . maximum . map solvePMs . transpose . map toPlusMinus . toCharCounts

toCharCounts ws = transpose . map (charFreqs ws) $ ['a'..'e']
charFreqs ws c = map (charFreq c) ws
charFreq c = length . filter (==c)

toPlusMinus cnts = map (g.sum $ cnts) cnts
  where
    g len cnt = (cnt, len - cnt)     -- (this char, other chars of the word)

solvePMs = length . takeWhile (>0) . scanl1 (+) . map (uncurry (-)) . sortOn (uncurry (-) . swap)

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

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

import Prelude
import Control.Monad
import Data.List
import Data.Tuple

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

    (putStr . unlines . map solve) tcs

readTC = do
    n <- readLn
    replicateM n getLine

solve = show . maximum . map solvePMs . transpose . map toPlusMinus . toCharCounts

toCharCounts :: [String] -> [[Int]]
toCharCounts ws = transpose . map (charFreqs ws) $ ['a'..'e']

charFreqs :: [String] -> Char -> [Int]
charFreqs ws c = map (charFreq c) ws

charFreq :: Char -> String -> Int
charFreq c = length . filter (==c)

toPlusMinus :: [Int] -> [(Int,Int)]
toPlusMinus cnts = map (g.sum $ cnts) cnts
  where
    g len cnt = (cnt, len - cnt)     -- (this char, other chars of the word)

solvePMs = length . takeWhile (>0) . scanl1 (+) . map (uncurry (-)) . sortOn (uncurry (-) . swap)

import Control.Monad (replicateM_, replicateM)
import Data.List (transpose, sortBy)
import Data.Map ((!), (!?))
import qualified Data.Map as M

type CharMap = M.Map Char Int

scoreWord :: String -> CharMap
scoreWord s = M.map score finalCnt where
  ins k = M.insertWith (+) k 1
  cnt = foldr ins M.empty s
  l = M.foldr (+) 0 cnt
  score x = x - (l - x)
  insMissing k = M.insertWith (\_ x -> x) k 0
  finalCnt = foldr insMissing cnt ['a'..'e']

interestingWords :: [String] -> Int
interestingWords words = maximum $ map findMax scoreByChar where
  scoreMaps = map scoreWord words
  scoreMatrix = map (map snd . M.toList) scoreMaps
  sortDesc = sortBy (flip compare)
  scoreByChar = map sortDesc $ transpose scoreMatrix
  findMax = length . takeWhile (>0) . scanl1 (+)

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    n <- readLn
    words <- replicateM n getLine
    print $ interestingWords words

import Control.Monad
import Data.IntMap (IntMap)
import qualified Data.IntMap as M
import Data.List
import Data.Maybe
import Data.Ord

numToInt :: Char -> Int
numToInt 'a' = 0
numToInt 'b' = 1
numToInt 'c' = 2
numToInt 'd' = 3
numToInt 'e' = 4
numToInt _ = undefined

-- | Take a sequence of elements and convert into frequency mapping
collect :: [Int] -> IntMap Int
collect = foldl ins_ $ M.fromList [(i, 0) | i <- [0 .. 4]]
  where
    ins_ m n = M.alter (Just . maybe 1 (+ 1)) n m

solution' :: Int -> [IntMap Int] -> Int
solution' l words = length correctWords
  where
    diff m = 2 * (m M.! l) - sum (M.elems m)
    sortedWords = sortOn (Down . diff) words
    aggWords = scanl1 (M.unionWith (+)) sortedWords
    correctWords = takeWhile ((> 0) . diff) aggWords

prepareWords :: [String] -> [IntMap Int]
prepareWords words = do
  word <- words
  let wordNum = numToInt <$> word
  return $ collect wordNum

solution :: [String] -> Int
solution words = maximum $ (`solution'` prepareWords words) <$> [0 .. 4]

main :: IO ()
main = do
  n <- read <$> getLine
  forM_ [1 .. n] $ \_ -> do
    n' <- read <$> getLine
    words <- traverse (const getLine) [1 .. n']
    print $ solution words

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE Strict #-}

import Control.Applicative (liftA2)
import Control.Monad (replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.List (sort, sortBy)
import Data.Maybe (fromJust)

main :: IO ()
main = C.interact $ runScanner (C.unlines <$> numberOf (C.pack <$> testCase))

testCase :: Scanner String
testCase = show . solve <$> numberOf str

solve :: [String] -> Int
solve ws = maximum . map compute $ ['a' .. 'e']
  where
    compute :: Char -> Int
    compute c =
      length
        . takeWhile (> 0)
        . scanl1 (+)
        . reverse
        . sort
        $ map cost ws
      where
        cost w = 2 * count c w - length w

-------------------------- Template ------------------------------------------
count :: Eq a => a -> [a] -> Int
count x = length . filter (== x)

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

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

integer :: Scanner Integer
integer = read . C.unpack <$> bstr

double :: Scanner Double
double = read . C.unpack <$> bstr

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 (,)

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P

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

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

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

maxlen xs ch = res
  where a = map (\word -> (length $ filter (==ch) word, length word)) xs
        b = sortBy (\x1 x2 -> let diff (q,w) = w - 2*q in compare (diff x1) (diff x2)) a
        (res, _, _) = foldl (\(taken, good, bad) (q,w) -> let (g,b) = (good+q, bad+w-q) in
                                                    (if g > b then (taken+1, g, b) else (taken, good, bad))) (0, 0, 0) b

solve :: IO ()
solve = do
  n <- readLn :: IO Int
  a <- readrows n
  let sol = maximum $ map (maxlen a) ['a'..'e'] in
    print sol

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

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

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

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

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

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -Weverything                     #-}

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

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

import Prelude
import Control.Monad

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

    (putStr . unlines . map solve) tcs

readTC = do
    n <- readLn
    replicateM n getLine

solve = const "123"