Alice and Bob are playing a game on an array $$$a$$$ of $$$n$$$ positive integers. Alice and Bob make alternating moves with Alice going first.In his/her turn, the player makes the following move: If $$$a_1 = 0$$$, the player loses the game, otherwise: Player chooses some $$$i$$$ with $$$2\le i \le n$$$. Then player decreases the value of $$$a_1$$$ by $$$1$$$ and swaps $$$a_1$$$ with $$$a_i$$$. Determine the winner of the game if both players play optimally.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ $$$(1 \leq t \leq 2 \cdot 10^4)$$$  — the number of test cases. The description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$  — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2 \ldots a_n$$$ $$$(1 \leq a_i \leq 10^9)$$$  — the elements of the array $$$a$$$. It is guaranteed that sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, if Alice will win the game, output "Alice". Otherwise, output "Bob". You can output each letter in any case. For example, "alIcE", "Alice", "alice" will all be considered identical.

NoteIn the first testcase, in her turn, Alice can only choose $$$i = 2$$$, making the array equal $$$[1, 0]$$$. Then Bob, in his turn, will also choose $$$i = 2$$$ and make the array equal $$$[0, 0]$$$. As $$$a_1 = 0$$$, Alice loses.In the second testcase, once again, players can only choose $$$i = 2$$$. Then the array will change as follows: $$$[2, 1] \to [1, 1] \to [1, 0] \to [0, 0]$$$, and Bob loses.In the third testcase, we can show that Alice has a winning strategy.

{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import Data.Bool
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Function
import Data.Int
import Data.List
import Data.Maybe
import Debug.Trace

----- <Solution> --------------------------------------------------------------
data TC = TC { as :: [Int] }

type Output = Bool

input :: Scanner TC
input = do
  as <- numberOf int
  return TC {..}

solve :: TC -> Output
solve TC {..} = head as > minimum as

output :: Int -> Output -> C.ByteString
output ix = bool "Bob" "Alice" >>> C.pack

----- </Solution> -------------------------------------------------------------

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map solve >>> zip [1..] >>> map (uncurry output) >>> C.unlines

----- Template ----------------------------------------------------------------

-- Debug
debug :: Show a => a -> a

#ifdef ONLINE_JUDGE
debug = id
#else
debug a = trace (show a) a
#endif

-- helpers
(>$>) = flip ($)

infixl 0 >$>

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

-- pragmas.hs {{{
-- vim: foldmethod=marker
{-# LANGUAGE AllowAmbiguousTypes        #-}
{-# LANGUAGE BinaryLiterals             #-}
{-# LANGUAGE ConstraintKinds            #-}
{-# LANGUAGE DataKinds                  #-}
{-# LANGUAGE DeriveFoldable             #-}
{-# LANGUAGE DeriveFunctor              #-}
{-# LANGUAGE DeriveGeneric              #-}
{-# LANGUAGE DeriveTraversable          #-}
{-# LANGUAGE FlexibleContexts           #-}
{-# LANGUAGE FlexibleInstances          #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase                 #-}
{-# LANGUAGE MagicHash                  #-}
{-# LANGUAGE MultiParamTypeClasses      #-}
{-# LANGUAGE MultiWayIf                 #-}
{-# LANGUAGE RankNTypes                 #-}
{-# LANGUAGE RecordWildCards            #-}
{-# LANGUAGE ScopedTypeVariables        #-}
{-# LANGUAGE StandaloneDeriving         #-}
{-# LANGUAGE TupleSections              #-}
{-# LANGUAGE TypeApplications           #-}
{-# LANGUAGE TypeFamilies               #-}
{-# LANGUAGE TypeInType                 #-}
{-# LANGUAGE TypeOperators              #-}
{-# LANGUAGE UnboxedTuples              #-}
{-# LANGUAGE UndecidableInstances       #-}
-- pragmas.hs }}}
module Main where

import           Control.Monad         (replicateM_)
import           Data.Array            (Array, (!))
import           Data.Bool             (bool)
import qualified Data.ByteString.Char8 as C
import           Data.Ix               (Ix)
import           Data.List             (unfoldr)

data Player = Alice | Bob deriving Show

solve :: [Int] -> Player
solve xs = bool Bob Alice (head xs /= minimum xs)

docase :: IO ()
docase = do
  _ <- getInt
  xs <- getInts
  print $ solve xs

main :: IO ()
main = getInt >>= flip replicateM_ docase

readInt :: C.ByteString -> Int
readInt s = let Just (i,_) = C.readInt s in i :: Int

readInt2 :: C.ByteString -> (Int, Int)
readInt2 u = (a, b)
  where
  Just (a,v) = C.readInt u
  Just (b,_) = C.readInt (C.tail v)

readInts :: C.ByteString -> [Int]
readInts = unfoldr go where
    go s = do
        (n,s1) <- C.readInt s
        let s2 = C.dropWhile (==' ') s1
        pure (n,s2)

getInt :: IO Int
getInt  = readInt <$> C.getLine

getInt2 :: IO (Int, Int)
getInt2 = readInt2 <$> C.getLine

getInts :: IO [Int]
getInts = readInts <$> C.getLine


Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the same straight line, due to the reason that there is the only one straight street in Vičkopolis.Let's denote the coordinate system on this street. Besides let's number all the hacked computers with integers from 1 to n. So the i-th hacked computer is located at the point xi. Moreover the coordinates of all computers are distinct. Leha is determined to have a little rest after a hard week. Therefore he is going to invite his friend Noora to a restaurant. However the girl agrees to go on a date with the only one condition: Leha have to solve a simple task.Leha should calculate a sum of F(a) for all a, where a is a non-empty subset of the set, that consists of all hacked computers. Formally, let's denote A the set of all integers from 1 to n. Noora asks the hacker to find value of the expression . Here F(a) is calculated as the maximum among the distances between all pairs of computers from the set a. Formally, . Since the required sum can be quite large Noora asks to find it modulo 109 + 7.Though, Leha is too tired. Consequently he is not able to solve this task. Help the hacker to attend a date.

The first line contains one integer n (1 ≤ n ≤ 3·105) denoting the number of hacked computers. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) denoting the coordinates of hacked computers. It is guaranteed that all xi are distinct.

Print a single integer — the required sum modulo 109 + 7.

NoteThere are three non-empty subsets in the first sample test:,  and . The first and the second subset increase the sum by 0 and the third subset increases the sum by 7 - 4 = 3. In total the answer is 0 + 0 + 3 = 3.There are seven non-empty subsets in the second sample test. Among them only the following subsets increase the answer: , , , . In total the sum is (4 - 3) + (4 - 1) + (3 - 1) + (4 - 1) = 9.

module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Data.Int
import Data.Array.Unboxed

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

pairs [] = []
pairs (x:xs) = [(x, x') | x' <- xs] ++ pairs xs

chiến :: Int -> [Int64] -> Int64
chiến n = foldl' (\s (i, x) -> s +% (x *% (twoPows!i) - x *% (twoPows!(n - i - 1)))) 0 . zip [0..] . sort
  where
    m = 1000000007
    twoPows = listArray (0, n) $ iterate (*% 2) 1 :: UArray Int Int64
    a +% b = (a + b) `mod` m
    a *% b = (a * b) `mod` m

main = do
  n <- readInt <$> B.getLine
  xs <- map fromIntegral . readInts <$> B.getLine
  print $ chiến n xs

{-
x1 <= x2 <= ... <= xn
12
13
14
23
24
34
123 -> 13
124 -> 14
134 -> 14
234 -> 24
1234 -> 14

14 -> 3 -> 4
13 -> 2 -> 2
12 -> 1 -> 1
24 ->

xi * (2^i) - xi * 2^(n-i-1)
-}

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

getAllPows :: Int64 -> Int64 -> Int64 -> Int64 -> [Int64]
getAllPows a n p cur
    | p == n = [cur]
    | otherwise = cur : (getAllPows a n (p + 1) (2 `multMod` cur))

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

sub :: Int64 -> Int64 -> Int64
sub a b = (a + modPr - b) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve x p n ps pl = ((x `multMod` (ps `sub` 1)) + modPr - (x `multMod` (pl `sub` 1))) `mod` modPr
    -- | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    -- | otherwise = 123

solve' :: [Int64] -> Int64 -> Int64 -> [Int64] -> [Int64] -> Int64
solve' [] _ _ _ _ = 0
solve' (x:xs) p n (ps:pss) (pl:pls) =  ((solve' xs (p + 1) n pss pls) + (solve x p n ps pl)) `mod` modPr

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

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    -- xs <- sort . map (read :: String -> Int64) . words <$> getLine
    xs <- sort <$> getInt64s
    let ps = getAllPows 2 (n - 1) 0 1
    -- putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]
    putStrLn . show $ solve' xs 0 n ps $ reverse ps

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

getAllPows :: Int64 -> Int64 -> Int64 -> Int64 -> [Int64]
getAllPows a n p cur
    | p == n = [cur - 1]
    | otherwise = (cur `sub` 1) : (getAllPows a n (p + 1) (2 `multMod` cur))

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

sub :: Int64 -> Int64 -> Int64
sub a b = (a + modPr - b) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve x p n ps pl = ((x `multMod` ps) + modPr - (x `multMod` pl)) `mod` modPr

solve' :: [Int64] -> Int64 -> Int64 -> [Int64] -> [Int64] -> Int64
solve' [] _ _ _ _ = 0
solve' (x:xs) p n (ps:pss) (pl:pls) =  ((solve' xs (p + 1) n pss pls) + (solve x p n ps pl)) `mod` modPr

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

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    xs <- sort <$> getInt64s
    let ps = getAllPows 2 (n - 1) 0 1
    putStrLn . show $ solve' xs 0 n ps $ reverse ps

{-# LANGUAGE BangPatterns #-}

import Data.Maybe
import Data.Int
import Data.Bool
import Data.List
import Control.Monad

modulant :: Int64
modulant = 1000000007

twos :: [Int64]
twos = work 1
    where
        work c = c : work (let x = 2*c in if x > modulant then x - modulant else x)

-- >>> all (>= 0) $ take 100000 ((* 1000000007) <$> twos)
-- True
--
main :: IO ()
main = do
    getLine
    sorted <- liftM (\l -> (sort :: [Int64] -> [Int64]) $ read <$> (words l)) getLine
    let a = foldl' (\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> zip twos sorted
        b = foldl' (\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> (zip twos $ reverse sorted)
    print $ (a - b) `mod` modulant

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve x p n ps pl = ((x `multMod` (ps - 1)) + modPr - (x `multMod` (pl - 1))) `mod` modPr
    -- | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    -- | otherwise = 123

solve' :: [Int64] -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve' [] _ _ _ _ = 0
solve' (x : xs) p n ps pl =  ((solve' xs (p + 1) n (ps `multMod` 2) (pl `div` 2)) + (solve x p n ps pl)) `mod` modPr

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

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    -- xs <- sort . map (read :: String -> Int64) . words <$> getLine
    xs <- sort <$> getInt64s
    let ps = 1
        pl = powMod 2 $ n - 1
    -- putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]
    putStrLn . show $ solve' xs 0 n ps pl

import Data.List
import Control.Applicative

modPr = 1000000009 :: Integer

powMod :: Integer -> Integer -> Integer
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

powMod' :: Integer -> Integer -> Integer
powMod' a b = (powMod a b) - 1

solve :: Integer -> Integer -> Integer -> Integer
solve x 0 n = (- (x * (powMod' 2 $ n - 1)))
solve x p n
    | p == (n - 1) = (x * (powMod' 2 $ n - 1))
    | otherwise = (- (x * (powMod' 2 $ p))) + (x * (powMod' 2 $ n - p - 1))

main :: IO ()
main = do
    n <- (read :: String -> Integer) <$> getLine
    xs <- sort . map (read :: String -> Integer) . words <$> getLine
    -- putStrLn . show $ zip xs [0..(n - 1)]
    putStrLn . show $ foldl' (\ acc (x, p) -> acc + (solve x p n)) 0 $ zip xs [0..(n - 1)]

import Data.List
import Control.Applicative

modPr = 1000000009 :: Integer

powMod :: Integer -> Integer -> Integer
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

powMod' :: Integer -> Integer
powMod' x = (powMod 2 x) - 1

multMod :: Integer -> Integer -> Integer
multMod a b = (a * b) `mod` modPr

solve :: Integer -> Integer -> Integer -> Integer
solve x 0 n = (modPr - (x `multMod` (powMod' $ n - 1))) `mod` modPr
solve x p n
    | p == (n - 1) = (x `multMod` (powMod' $ n - 1))
    | otherwise =  ((x `multMod` (powMod' $ n - p - 1)) + modPr - (x `multMod` (powMod' p))) `mod` modPr

main :: IO ()
main = do
    n <- (read :: String -> Integer) <$> getLine
    xs <- sort . map (read :: String -> Integer) . words <$> getLine
    -- putStrLn . show $ zip xs [0..(n - 1)]
    putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]

import Data.List
import Control.Applicative

modPr = 1000000009 :: Integer

powMod :: Integer -> Integer -> Integer
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Integer -> Integer -> Integer
multMod a b = (a * b) `mod` modPr

powMod' :: Integer -> Integer
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

solve :: Integer -> Integer -> Integer -> Integer
solve x p n = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr

{-
solve :: Integer -> Integer -> Integer -> Integer
solve x p n
    | p == 0 = (modPr - (x `multMod` (powMod' $ n - 1))) `mod` modPr
    | p == (n - 1) = (x `multMod` (powMod' $ n - 1)) `mod` modPr
    | otherwise = ((x `multMod` (powMod' $ n - p - 1)) + modPr - (x `multMod` (powMod' p))) `mod` modPr
    where multMod a b = (a * b) `mod` modPr
          powMod' x = (powMod 2 x) - 1
-}

main :: IO ()
main = do
    n <- (read :: String -> Integer) <$> getLine
    xs <- sort . map (read :: String -> Integer) . words <$> getLine
    -- putStrLn . show $ zip xs [0..(n - 1)]
    putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64
solve x p n
    | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    | otherwise = 123

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

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    -- xs <- sort . map (read :: String -> Int64) . words <$> getLine
    xs <- sort <$> getInt64s
    putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64
solve x p n
    | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    | otherwise = 123

solve' :: [Int64] -> Int64 -> Int64 -> Int64
solve' [] _ _ = 0
solve' (x : xs) p n =  ((solve' xs (p + 1) n) + (solve x p n)) `mod` modPr

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

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    -- xs <- sort . map (read :: String -> Int64) . words <$> getLine
    xs <- sort <$> getInt64s
    -- putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]
    putStrLn . show $ solve' xs 0 n

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

sub :: Int64 -> Int64 -> Int64
sub a b = (a + modPr - b) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve x p n ps pl = ((x `multMod` (ps `sub` 1)) + modPr - (x `multMod` (pl `sub` 1))) `mod` modPr
    -- | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    -- | otherwise = 123

solve' :: [Int64] -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve' [] _ _ _ _ = 0
solve' (x : xs) p n ps pl =  ((solve' xs (p + 1) n (ps `multMod` 2) (pl `div` 2)) + (solve x p n ps pl)) `mod` modPr

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

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    -- xs <- sort . map (read :: String -> Int64) . words <$> getLine
    xs <- sort <$> getInt64s
    let ps = 1
        pl = powMod 2 $ n - 1
    -- putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]
    putStrLn . show $ solve' xs 0 n ps pl

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

getAllPows :: Int64 -> Int64 -> Int64 -> Int64 -> [Int64]
getAllPows a n p cur
    | p == n = [cur]
    | otherwise = (cur `sub` 1) : (getAllPows a n (p + 1) (2 `multMod` cur))

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

sub :: Int64 -> Int64 -> Int64
sub a b = (a + modPr - b) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve x p n ps pl = ((x `multMod` ps) + modPr - (x `multMod` pl)) `mod` modPr

solve' :: [Int64] -> Int64 -> Int64 -> [Int64] -> [Int64] -> Int64
solve' [] _ _ _ _ = 0
solve' (x:xs) p n (ps:pss) (pl:pls) =  ((solve' xs (p + 1) n pss pls) + (solve x p n ps pl)) `mod` modPr

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

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    xs <- sort <$> getInt64s
    let ps = getAllPows 2 (n - 1) 0 1
    putStrLn . show $ solve' xs 0 n ps $ reverse ps

import Data.List
import Control.Applicative

modPr = 1000000009 :: Integer

powMod :: Integer -> Integer -> Integer
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Integer -> Integer -> Integer
multMod a b = (a * b) `mod` modPr

powMod' :: Integer -> Integer
powMod' x = (powMod 2 x) - 1

solve :: Integer -> Integer -> Integer -> Integer
solve x p n = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr

{-
solve :: Integer -> Integer -> Integer -> Integer
solve x p n
    | p == 0 = (modPr - (x `multMod` (powMod' $ n - 1))) `mod` modPr
    | p == (n - 1) = (x `multMod` (powMod' $ n - 1)) `mod` modPr
    | otherwise = ((x `multMod` (powMod' $ n - p - 1)) + modPr - (x `multMod` (powMod' p))) `mod` modPr
    where multMod a b = (a * b) `mod` modPr
          powMod' x = (powMod 2 x) - 1
-}

main :: IO ()
main = do
    n <- (read :: String -> Integer) <$> getLine
    xs <- sort . map (read :: String -> Integer) . words <$> getLine
    -- putStrLn . show $ zip xs [0..(n - 1)]
    putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]

import Data.List
import Control.Applicative
import Data.Int
import Data.Maybe (fromJust)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

modPr = 1000000007 :: Int64

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod a b
    | b `mod` 2 == 0 = p
    | otherwise = (p * a) `mod` modPr
    where h = powMod a (b `div` 2)
          p = (h * h) `mod` modPr

multMod :: Int64 -> Int64 -> Int64
multMod a b = (a * b) `mod` modPr

powMod' :: Int64 -> Int64
powMod' x = ((powMod 2 x) + modPr - 1) `mod` modPr

solve :: Int64 -> Int64 -> Int64 -> Int64
solve x p n
    | n < 100000 = ((x `multMod` (powMod' p)) + modPr - (x `multMod` (powMod' $ n - p - 1))) `mod` modPr
    | otherwise = 123

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

main :: IO ()
main = do
    n <- (read :: String -> Int64) <$> getLine
    xs <- sort . map (read :: String -> Int64) . words <$> getLine
    -- xs <- sort <$> getInt64s
    putStrLn . show $ foldl' (\ acc (x, p) -> (acc + (solve x p n)) `mod` modPr) 0 $ zip xs [0..(n - 1)]

{-# LANGUAGE BangPatterns #-}

import Data.Maybe
import Data.Int
import Data.Bool
import Data.List
import Control.Monad

modulant :: Int64
modulant = 1000000007

twos :: [Int64]
twos = work 1
    where
        work c = c : work (let x = 2*c in if x > modulant then x - modulant else x)

main :: IO ()
main = do
    getLine
    sorted <- liftM (\l -> (sort :: [Int64] -> [Int64]) $ read <$> (words l)) getLine
    let a = foldl' (\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> zip twos sorted
        b = foldl' (\acc s -> (acc + s) `mod` modulant) 0 $ (uncurry (*)) <$> (zip twos $ reverse sorted)
    print $ a - b

import Data.Maybe
import Data.Int
import Data.Bool
import Data.List
import Control.Monad

calc :: [Int64] -> Int64
calc = work 0 1
    where
        work acc _ [] = acc
        work acc cnt (x:xs) = work ((acc + x * cnt) `mod` 1000000007) (let c = 2 * cnt in if c > 1000000007 then c - 1000000007 else c) xs

main :: IO ()
main = do
    getLine
    sorted <- liftM (\l -> sort $ read <$> (words l)) getLine
    let a = calc sorted
        b = calc . reverse $ sorted
    print $ a - b

{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Data.Int
import Data.Bits

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

pairs [] = []
pairs (x:xs) = [(x, x') | x' <- xs] ++ pairs xs

chiến :: [Int64] -> Int64
chiến = foldl' (+%) 0 . map (\((i, x), (i', x')) -> (1 `shiftL`  (i' - i - 1)) *% (x' - x)) . pairs . zip [1..] . sort
  where
    m = 1000000007
    a +% b = (a + b) `mod` m
    a *% b = (a * b) `mod` m

main = do
  B.getLine
  xs <- map fromIntegral . readInts <$> B.getLine
  print $ chiến xs

{-
x1 <= x2 <= ... <= xn
12
13
14
23
24
34
123 -> 13
124 -> 14
134 -> 14
234 -> 24
1234 -> 14

14 -> 3 -> 4
13 -> 2 -> 2
12 -> 1 -> 1
24 ->

xi * (2^i) - xi * 2^(n-i-1)
-}

module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

pairs [] = []
pairs (x:xs) = [(x, x') | x' <- xs] ++ pairs xs

chiến n = foldl' (+%) 0 . map (\((i, x), (i', x')) -> (i' - i) *% (x' - x)) . pairs . zip [1..] . sort
  where
    m = 1000000007
    a +% b = (a + b) `mod` m
    a *% b = f a b 0
      where
        f x y acc
          | y == 1 = acc +% x
          | r == 0 = f x2 q acc
          | otherwise = f x2 q (acc +% x)
          where
            (q, r) = y `quotRem` 2
            x2 = x +% x

main = chiến <$> (readInt <$> B.getLine) <*> (readInts <$> B.getLine) >>= print

{-
x1 <= x2 <= ... <= xn
x2-x1: 1
x3-x1: 2
x4-x1: 3
-}


The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each city won the candidate who got the highest number of votes in this city, and if several candidates got the maximum number of votes, then the winner is the one with a smaller index.At the second stage of elections the winner is determined by the same principle over the cities: the winner of the elections is the candidate who won in the maximum number of cities, and among those who got the maximum number of cities the winner is the one with a smaller index.Determine who will win the elections.

The first line of the input contains two integers n, m (1 ≤ n, m ≤ 100) — the number of candidates and of cities, respectively. Each of the next m lines contains n non-negative integers, the j-th number in the i-th line aij (1 ≤ j ≤ n, 1 ≤ i ≤ m, 0 ≤ aij ≤ 109) denotes the number of votes for candidate j in city i. It is guaranteed that the total number of people in all the cities does not exceed 109.

Print a single number — the index of the candidate who won the elections. The candidates are indexed starting from one.

NoteNote to the first sample test. At the first stage city 1 chosen candidate 3, city 2 chosen candidate 2, city 3 chosen candidate 2. The winner is candidate 2, he gained 2 votes.Note to the second sample test. At the first stage in city 1 candidates 1 and 2 got the same maximum number of votes, but candidate 1 has a smaller index, so the city chose candidate 1. City 2 chosen candidate 3. City 3 chosen candidate 1, due to the fact that everyone has the same number of votes, and 1 has the smallest index. City 4 chosen the candidate 3. On the second stage the same number of cities chose candidates 1 and 3. The winner is candidate 1, the one with the smaller index.

import Data.List

main =  do
  s <- getLine
  let
    n:m:[] = words s
  s <- sequence (replicate (read m :: Int) getLine)
  let
    d = map words s
    dd = map (\xs -> map (\x -> read x :: Int) xs) d
    cities = sort $ map cityWin dd
    grouped = map (\xs -> (head xs, length xs) ) (group cities)
    r = foldl (\(bc, bcnt) (city, cnt) -> if cnt > bcnt then (city, cnt) else (bc, bcnt)) (head grouped) grouped

  print (fst r)

cityWin::[Int]->Int
cityWin xs = snd $ foldl (\(bx, bp) (x,p) -> if x > bx then (x,p) else (bx, bp)) (head xs, 1)  $ zip xs [1..]

import Data.List as L
import Control.Applicative
import Data.Ord (comparing)

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

maxVote xs = fst $ head $ filter (\x-> snd x == m) (zip [1..] xs)
  where m = maximum xs

maxCity xs = fst $ head $ groupCount xs

groupCount x = zip (map head groupedOnes) (map length groupedOnes)
  where groupedOnes = groupDes x

groupDes x = L.reverse . L.sortBy (comparing length) . L.group . L.reverse . L.sort $ x

main = do
  votes <- map (map toInt . words) . tail . lines <$> getContents
  let ans = maxCity $ map maxVote votes
  print ans

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

rInt = map (\x -> read x::Int) . words

main :: IO()
main = do
    [n,m] <- fmap rInt getLine
    arr <- forM [1..m] $ \i ->do
        l <- fmap rInt getLine
        return l
    let a = elems $ solve (map rSolve arr)
    let (_, ans) = foldl' (\(a,b) (b1,b2)->if b1>a then (b1,b2) else (a,b)) (0,1) $ zip a [1..]
    print ans

rSolve :: [Int] -> Int
rSolve l = v
 where (_,v) = foldl' f (-1,0) $ zip l [1..]
       f (a,b) (c,d) = if c>a then (c,d) else (a,b)

solve :: [Int] -> UArray Int Int
solve l = runSTUArray $ do
    a <- newArray (1,100) 0
    forM_ l $ \i -> do
        x <- readArray a i
        writeArray a i (x+1)
    return a

import Data.Function
import Data.List

main = do
  getLine
  a <- fmap (map (map read . words) . lines) getContents :: IO [[Int]]

  print $ - (head $ maximumBy (compare `on` (\x -> (length x, x))) $ group $  sort $ map (\a -> snd $ maximum $ zipWith (\a b -> (a, -b)) a [1..]) a)

import Control.Applicative
import Control.Arrow
import Control.Monad
import Data.List

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

main = do
    [n, m] <- readInts
    cities <- map (`zip` map negate [1..]) <$> replicateM m readInts
    print . negate . snd . maximum . map (length &&& head) . group . sort . map (snd . maximum) $ cities

import Data.Array
answer::Int -> [[Int]] -> Int
answer m a = elec m (city a)
elec::Int -> [Int] -> Int
elec m a = getMaxIndex (elems (accumArray (+) 0 (1,m) (zip a (repeat 1))))
city::[[Int]] ->[Int]
city a = map getMaxIndex a
getMaxIndex::[Int] -> Int
getMaxIndex a = getMaxIndex0 (-1) 1 0 a
getMaxIndex0::Int -> Int -> Int -> [Int] ->Int
getMaxIndex0 n m r [] = r
getMaxIndex0 n m r a | n >= h = getMaxIndex0 n (m+1) r (tail a)
                     | otherwise = getMaxIndex0 h (m+1) m (tail a)
                          where h = head a
--main = print $ answer 3 [[1,2,3],[2,3,1],[1,2,1]]
-- main = print $ answer 3 [[10,10,3],
--                          [5,1,6],
--                          [2,2,2],
--                          [1,5,7]]
readInput::Int -> IO [[Int]]
readInput 0 = return []
readInput n = do
               w <- getLine
               let a = [read n::Int|n <- (words w)]
               next <- readInput (n-1)
               return ([a] ++ next)
main = do
        w <- getLine
        let ww = words w
        let m = read (ww !! 0)::Int
        let n = read (ww !! 1)::Int
        a <- readInput n
        print $ answer m a

import Data.List
import Data.Tree
import Data.Int
import Data.Word
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint

readsolveprint::IO()
readsolveprint = getLine >>= \ns -> let [_,n]  = (map (read).words) ns in (solve =<< forM [1..n] ( \i -> map (read).words <$>getLine))
solve::[[Word64]]->IO()
solve xs = print $ f $ map (\a-> (length a, head a)) $ group $ sort  $ map (\as-> f as) $ map (\as-> zipWith (\a b -> (b,a)) [1..] as) xs
  where
  f ds = (snd . head .sortBy (\ (a1,a2) (b1,b2) -> a2 `compare` b2). head . groupBy (\ (a1,a2) (b1,b2) -> a1 == b1) . sortBy (\ (a1,a2) (b1,b2) -> b1 `compare` a1)) ds

-- Codeforces 570A

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

main :: IO ()
main = do
    [n, m] <- fmap (map read . words) getLine :: IO [Int]
    replicateM m getLine >>= print . solve . map (map read . words)

solve :: [[Int]] -> Int
solve = snd . head . sortBy (\x y -> if (fst x) == (fst y) then compare (snd x) (snd y) else compare (fst y) (fst x)) . map (\x -> (length x, head x)) . group . sort . map (\x -> (+ 1) $ fromJust $ elemIndex (maximum x) x)

import Control.Applicative
import Control.Monad
import Data.Array
-----

--be carefull with the type inference

-----

---------
-- get space separated something

getListSp :: Read a => IO [a]
getListSp = (map read . words) <$> getLine

---------

---------
-- output [a] in space separated form

putListSp :: Show a => [a]  -> IO()
putListSp ls = putStrLn $ show $ unwords $ map show ls

---------

--------
-- read an integer N, get N lines, make a list consist of them

getListLn :: Read a => IO [a]
getListLn = do n <- readLn
               s <- replicateM n getLine
	       return (map read s)
--------

main = do [n, m] <- getListSp
          votes <- replicateM m getListSp
	  print $ solve votes

solve :: [[Int]] -> Int
solve = maxInd . cntList . (map maxInd)

maxInd :: [Int] -> Int
maxInd xs = rval $ head $ filter ((== maxVal) . lval) $ zip xs [1..]
             where maxVal = foldl1 max xs
	           lval (x, y) = x
		   rval (x, y) = y

cntList :: [Int] -> [Int]
cntList xs = elems $ accumArray (+) 0 (1, maxVal) (zip xs (repeat 1))
              where maxVal = foldl1 max xs

import Control.Applicative
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.Array

process x =   fromJust $ findIndex (==m) x
  where m = maximum x

process1 n x  = process $ elems xx
  where xx = accumArray (+) 0 (0,n-1) $ zip x (repeat 1)

main::IO ()
main=do
   [n,m]<- map read <$> words <$> getLine ::IO [Int]
   x<-(+1) <$> process1 n <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int
   print x

import Control.Arrow ((&&&))
import Data.List (elemIndex, group, sort)
import Data.Maybe (fromJust)

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

solve :: [[Int]] -> Int
solve = succ . negate . snd . maximum . map (length &&& negate . head) . group . sort . map maximumIndex

maximumIndex :: Ord a => [a] -> Int
maximumIndex xs = fromJust $ elemIndex (maximum xs) xs

import Data.Function
import Data.List
import Data.Monoid
import Control.Arrow
import Control.Monad
readInts = fmap (map read . words) getLine
winner = fst . maximumBy ((compare `on` snd) `mappend` (flip compare `on` fst))
main = do
  [n,m] <- readInts
  cs <- replicateM m (fmap (zip [1..]) readInts)
  let ws = map winner cs
  print $ winner $ map (head &&& length) $ group $ sort ws

import Data.List
import Data.Maybe
import Data.Function

winner :: [Int] -> Int
winner xs = (+1) . fromJust . elemIndex m $ xs
    where m = maximum xs

solve :: [[Int]] -> Int
solve = head . maximumBy (compare `on` length) . group . reverse . sort . map winner

main = do
    [n,m] <- getList
    xs <- mapM (\_ -> getList) [1..m]
    print $ solve xs

getList :: (Read a) => IO [a]
getList = fmap (map read . words) getLine

import System.IO
import qualified Data.List as L

read_ints :: String -> [Int]
read_ints x = map read (words x) :: [Int]

best :: [[Int]] -> Int
best x = fst $ foldl (\(ans,co) gr -> if length gr > co then (head gr,length gr) else (ans,co) ) (0,0) x

compute :: [Int] -> Int
compute x = best ( L.group $ L.sort x )

solve :: [Int] -> Int
solve x = fst $ foldl (\(ans,co) (x,y) -> if x > co then (y,x) else (ans,co) ) (0,negate 1) ( zip x [1..] )

main = do
	ln <- getLine
	let [n,m] = read_ints ln
	ln <- getContents
	let mat = map read_ints (lines ln)

	let winers = foldl (\ans ln -> solve ln : ans ) [] mat
	-- print winers
	let ans = compute winers
	putStr $ show ans

import Data.Ord (comparing)
import Data.List (maximumBy)
import Data.Monoid
import qualified Data.Map as M

main = interact solve >> putChar '\n'

solve :: String -> String
solve rawInput = winner
    where input = (map . map) read $ map words $ lines rawInput :: [[Int]]
          inData = tail input
          indexed = map (zip [1..]) inData
          winners = map fst $ map (maximumBy $ compareOrder) indexed
          occurList = toOccurList winners
          winner = show $ fst $ maximumBy compareOrder occurList

compareOrder = mappend (comparing snd) (flip $ comparing fst)

toOccurList :: [Int] -> [(Int, Int)]
toOccurList = M.toList . foldr (\x map -> M.insertWith (+) x 1 map) M.empty

import Control.Applicative
import Data.List

mymax s =  snd $ head $ filter (\z-> fst z ==m) $ zip s [1..]
	where m = maximum s

main=do
	[n,m]<-map read.words <$> getLine:: IO [Int]
	s<- map (map read). map words . lines <$> getContents ::IO [[Int]]
	let s1 = group $ sort $ map (mymax) s
	let s2 = maximum (map length s1)
	print $ minimum $ map head $ filter (\z-> length z ==s2) s1

import Data.List

count xs = [(head x, length x) | x <- group(sort xs)]

winner:: [(Int,Int)] -> (Int,Int)
winner [x] = x
winner (x:xs)
    | snd x > snd maxVote = x
    | snd x == snd maxVote && fst x < fst maxVote = x
    | otherwise = maxVote
    where maxVote = winner xs

stage1::[[Int]] -> [Int]
stage1 [] = []
stage1 (v:vs) = fst(winner(zip [1..length v] v)) : stage1 vs

replicateM n x = sequence (replicate n x)

readLine = do
    line <- getLine
    return [read n :: Int| n <- words line]

main = do
    numberStr <- getLine
    let [_,m] = [read n::Int | n <- words numberStr]
    votes <- replicateM m readLine
    print (fst(winner(count(stage1(votes)))))

import Control.Arrow ((&&&))
import Data.List (group, sort)

type Input = [[Int]]

parse :: String -> Input
parse = map parseLine . tail . lines
        where parseLine = map read . words

select :: [(Int, Int)] -> Int
select = negate . snd . maximum

solve :: Input -> Int
solve = stage2 . stage1
        where stage1 = map (select. flip zip [-1, -2..]) :: [[Int]] -> [Int]
              stage2 = select . map (length &&& negate . head) . group . sort

main :: IO ()
main = print . solve . parse =<< getContents

import Data.List

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

sol (n:_:xs) = snd . minimum . map (\x -> (- length x, head x)) . group . sort . map det $ spl (map negate xs)
    where det ls = snd . minimum $ zip ls [1..]
          spl [] = []
          spl l = take n l : spl (drop n l)

import Data.List
import Control.Monad

main :: IO ()
main = do
        _:m:_ <- getList
        votes <- getLists m
        print $ solve votes

getLists :: (Read a) => Int -> IO [[a]]
getLists nRows = replicateM nRows getList

getList :: (Read a) => IO [a]
getList = fmap (fmap read . words) getLine

solve :: [[Int]] -> Int
solve = mostCommon . map cityWinner

cityWinner :: [Int] -> Int
cityWinner  = negate . snd . maximum . (`zip` [-1,-2..])

mostCommon :: [Int] -> Int
mostCommon = negate . snd . maximum . fmap (\xs -> (length xs, - head xs)) . group . sort

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

rInt = map (\x -> read x::Int) . words

main :: IO()
main = do
    [n,m] <- fmap rInt getLine
    arr <- forM [1..m] $ \i ->do
        l <- fmap rInt getLine
        return l
    let a = elems $ solve (map rSolve arr)
    print a
    let (_, ans) = foldl' (\(a,b) (b1,b2)->if b1>a then (b1,b2) else (a,b)) (0,1) $ zip a [1..]
    print ans

rSolve :: [Int] -> Int
rSolve l = v
 where (_,v) = foldl' f (0,0) $ zip l [1..]
       f (a,b) (c,d) = if c>a then (c,d) else (a,b)

solve :: [Int] -> UArray Int Int
solve l = runSTUArray $ do
    a <- newArray (1,100) 0
    forM_ l $ \i -> do
        x <- readArray a i
        writeArray a i (x+1)
    return a

import Data.List
import Data.Tree
import Data.Int
import Data.Word
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = getLine >>= \ns -> let [_,n]  = (map (read).words) ns in (solve =<< forM [1..n] ( \i -> map (read).words <$>getLine))
solve::[[Word64]]->IO()
solve xs = print $ f $ map (\a-> (length a, head a)) $ group $ map (\as-> f as) $ map (\as-> zipWith (\a b -> (b,a)) [1..] as) xs
  where
  f ds = (snd . head .sortBy (\ (a1,a2) (b1,b2) -> a2 `compare` b2). head . groupBy (\ (a1,a2) (b1,b2) -> a1 == b1) . sortBy (\ (a1,a2) (b1,b2) -> b1 `compare` a1)) ds

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = C.getLine >>= \ns -> let [_,n]  = (map (fst.fromJust.C.readInteger).C.words) ns in (solve =<< forM [1..n] ( \i -> map (fst.fromJust.C.readInteger).C.words <$>C.getLine))
solve xs = print $ snd $ head $ head $ groupBy (\ (a1,a2) (b1,b2) -> a1 == b1) $ sortBy (\ (a1,a2) (b1,b2) -> b1 `compare` a1) $ map (\a-> (length a, head a)) $ group $ map (\as-> snd $ head $  head $ groupBy (\ (a1,a2) (b1,b2) -> a1 == b1) $ sortBy (\ (a1,a2) (b1,b2) -> b1 `compare` a1) as) $ map (\as-> zipWith (\a b -> (b,a)) [1..] as) xs

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = C.getLine >>= \ns -> let [_,n]  = (map (fst.fromJust.C.readInteger).C.words) ns in (solve =<< forM [1..n] ( \i -> map (fst.fromJust.C.readInteger).C.words <$>C.getLine))
solve xs = print $ f $ map (\a-> (length a, head a)) $ group $ map (\as-> f as) $ map (\as-> zipWith (\a b -> (b,a)) [1..] as) xs
  where
  f ds = (snd . head .sortBy (\ (a1,a2) (b1,b2) -> a2 `compare` b2). head . groupBy (\ (a1,a2) (b1,b2) -> a1 == b1) . sortBy (\ (a1,a2) (b1,b2) -> b1 `compare` a1)) ds

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Bits
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = C.getLine >>= \ns -> let [_,n]  = (map (fst.fromJust.C.readInteger).C.words) ns in (solve =<< forM [1..n] ( \i -> map (fst.fromJust.C.readInteger).C.words <$>C.getLine))
solve xs = print $ fst $ maximumBy (\(a,b) (a1,b1) -> (b `compare` b1) `compare` (a `compare` a1))$ map (\a->(head a, length a)) $ groupBy (==) $ sortBy (\ a b ->b `compare` a ) $ map (\hs -> last $ maximumBy (\(a:b:c:[]) (a1:b1:c1:[]) -> (a `compare` a1) `compare` (c `compare` c1)) hs) $ zipWith (\as bs-> zipWith (\a b -> b:as:a:[]) [1..] bs) [1..]  xs

import Control.Applicative
import Control.Monad
import Data.Array
-----

--be carefull with the type inference

-----

---------
-- get space separated something

getListSp :: Read a => IO [a]
getListSp = (map read . words) <$> getLine

---------

---------
-- output [a] in space separated form

putListSp :: Show a => [a]  -> IO()
putListSp ls = putStrLn $ show $ unwords $ map show ls

---------

--------
-- read an integer N, get N lines, make a list consist of them

getListLn :: Read a => IO [a]
getListLn = do n <- readLn
               s <- replicateM n getLine
	       return (map read s)
--------

main = do [n, m] <- getListSp
          votes <- replicateM m getListSp
	  print $ solve votes

solve :: [[Int]] -> Int
solve = maxInd . cntList . (map maxInd)

maxInd :: [Int] -> Int
maxInd xs = lval $ head $ filter ((== maxVal) . lval) $ zip xs [1..]
             where maxVal = foldl1 max xs
	           lval (x, y) = x

cntList :: [Int] -> [Int]
cntList xs = elems $ accumArray (+) 0 (1, maxVal) (zip (repeat 1) xs)
              where maxVal = foldl1 max xs

import Control.Applicative
import Control.Monad
import Data.Array
-----

--be carefull with the type inference

-----

---------
-- get space separated something

getListSp :: Read a => IO [a]
getListSp = (map read . words) <$> getLine

---------

---------
-- output [a] in space separated form

putListSp :: Show a => [a]  -> IO()
putListSp ls = putStrLn $ show $ unwords $ map show ls

---------

--------
-- read an integer N, get N lines, make a list consist of them

getListLn :: Read a => IO [a]
getListLn = do n <- readLn
               s <- replicateM n getLine
	       return (map read s)
--------

main = do [n, m] <- getListSp
          votes <- replicateM m getListSp
	  print $ solve votes

solve :: [[Int]] -> Int
solve = maxInd . cntList . (map maxInd)

maxInd :: [Int] -> Int
maxInd xs = lval $ head $ filter ((== maxVal) . lval) $ zip xs [1..]
             where maxVal = foldl1 max xs
	           lval (x, y) = x

cntList :: [Int] -> [Int]
cntList xs = elems $ accumArray (+) 0 (1, maxVal) (zip xs (repeat 1))
              where maxVal = foldl1 max xs

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

process x = (+1) $ fromJust $ findIndex (==m) x
  where m = maximum x

main::IO ()
main=do
   getLine
   x<-(+1) <$> process <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int
   print x

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

process x =   fromJust $ findIndex (==m) x
  where m = maximum x

main::IO ()
main=do
   getLine
   x<-(+1) <$> process <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int
   print x

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

process x = (+1) $ fromJust $ findIndex (==m) x
  where m = maximum x

main::IO ()
main=do
   getLine
   x<-process <$> map process <$> map (map (fromIntegral.fst.fromJust.C.readInteger))<$> map C.words <$> C.lines <$> C.getContents ::IO Int
   print x

import System.IO
import qualified Data.List as L

read_ints :: String -> [Int]
read_ints x = map read (words x) :: [Int]

best :: [[Int]] -> Int
best x = fst $ foldl (\(ans,co) gr -> if length gr > co then (head gr,length gr) else (ans,co) ) (0,0) x

compute :: [Int] -> Int
compute x = best ( L.group $ L.sort x )

solve :: [Int] -> Int
solve x = fst $ foldl (\(ans,co) (x,y) -> if x > co then (y,x) else (ans,co) ) (0,0) ( zip x [1..] )

main = do
	ln <- getLine
	let [n,m] = read_ints ln
	ln <- getContents
	let mat = map read_ints (lines ln)

	let winers = foldl (\ans ln -> solve ln : ans ) [] mat
	-- print winers
	let ans = max (compute winers) 1
	putStr $ show ans

import System.IO
import qualified Data.List as L

read_ints :: String -> [Int]
read_ints x = map read (words x) :: [Int]

best :: [[Int]] -> Int
best x = fst $ foldl (\(ans,co) gr -> if length gr > co then (head gr,length gr) else (ans,co) ) (0,0) x

compute :: [Int] -> Int
compute x = best ( L.group $ L.sort x )

solve :: [Int] -> Int
solve x = fst $ foldl (\(ans,co) (x,y) -> if x > co then (y,x) else (ans,co) ) (0,0) ( zip x [1..] )

main = do
	ln <- getLine
	let [n,m] = read_ints ln
	ln <- getContents
	let mat = map read_ints (lines ln)

	let winers = foldl (\ans ln -> solve ln : ans ) [] mat
	-- print winers
	let ans = compute winers
	putStr $ show ans

import Data.List

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

sol (n:m:xs) = snd . minimum . map (\x -> (- length x, head x)) . group . map det $ spl (map negate xs)
    where det ls = snd . minimum $ zip ls [1..]
          spl [] = []
          spl l = take n l : spl (drop n l)


When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds and user-inattention related issues, it is prohibited to register a login if it is similar with an already existing login. More precisely, two logins s and t are considered similar if we can transform s to t via a sequence of operations of the following types:   transform lowercase letters to uppercase and vice versa;  change letter «O» (uppercase latin letter) to digit «0» and vice versa;  change digit «1» (one) to any letter among «l» (lowercase latin «L»), «I» (uppercase latin «i») and vice versa, or change one of these letters to other. For example, logins «Codeforces» and «codef0rces» as well as «OO0OOO00O0OOO0O00OOO0OO_lol» and «OO0OOO0O00OOO0O00OO0OOO_1oI» are considered similar whereas «Codeforces» and «Code_forces» are not.You're given a list of existing logins with no two similar amonst and a newly created user login. Check whether this new login is similar with any of the existing ones.

The first line contains a non-empty string s consisting of lower and uppercase latin letters, digits and underline symbols («_») with length not exceeding 50  — the login itself. The second line contains a single integer n (1 ≤ n ≤ 1 000) — the number of existing logins. The next n lines describe the existing logins, following the same constraints as the user login (refer to the first line of the input). It's guaranteed that no two existing logins are similar.

Print «Yes» (without quotes), if user can register via this login, i.e. none of the existing logins is similar with it. Otherwise print «No» (without quotes).

NoteIn the second sample case the user wants to create a login consisting of three zeros. It's impossible due to collision with the third among the existing.In the third sample case the new login is similar with the second one.

import Data.Char
import Control.Monad

similar :: String -> String -> Bool
similar s1 s2
    | length s1 /= length s2 = False
    | otherwise = similarInner s1 s2

similarInner :: String -> String -> Bool
similarInner s1 s2 = all id $ zipWith similarChar s1 s2

similarChar :: Char -> Char -> Bool
similarChar c1 c2
    | c1 == c2 = True
    | otherwise = any id $ map (($c1) . ($c2)) [similarCase, similarO, similar1]

similarCase :: Char -> Char -> Bool
similarCase c1 c2 = isLower c1 /= isLower c2 && toLower c1 == toLower c2

similarO :: Char -> Char -> Bool
similarO 'O' '0' = True
similarO '0' 'O' = True
similarO 'o' '0' = True
similarO '0' 'o' = True
similarO _   _   = False

similar1 :: Char -> Char -> Bool
similar1 c1 c2 = c1 /= c2 && c1 `elem` ls && c2 `elem` ls
    where ls = "1lLiI"

main = do
    login <- getLine
    n <- readLn
    res <- liftM (any $ similar login) $ replicateM n getLine
    putStrLn $ case res of
                   True -> "No"
                   False -> "Yes"

{-# LANGUAGE ScopedTypeVariables #-}

module Main where

import           Control.Applicative
import           Control.Monad.Cont
import           Data.Char

chZero :: Char -> Char
chZero '0' = 'O'
chZero a   = a

chI :: Char -> Char
chI '1' = 'l'
chI 'I' = 'l'
chI 'i' = 'l'
chI a   = a

minimize :: String -> String
minimize = map (toLower . chI . chZero)

main :: IO ()
main = do
  login <- minimize <$> getLine
  n :: Int <- read <$> getLine
  flip runContT putStrLn $ callCC $ \notOk -> do
    forM_ [1..n] $ \_ -> do
      l2 <- minimize <$> liftIO getLine
      if l2 == login then notOk "No" else return ()
    return "Yes"

import Data.List
import Data.Char

main :: IO ()
main = do
  s <- getLine
  ns <- getLine
  let n = read ns :: Integer
  strings <- mapM (\_ -> getLine) [1..n]
  let solution = solveProblem s strings
  putStrLn solution

solveProblem :: String -> [String] -> String
solveProblem    s         strings   = let s' = fmap (repl . toLower) s
                                          strings' = fmap (fmap (repl . toLower)) strings
                                      in case (length (nub (s':strings')) == length (s':strings')) of
                                           True -> "Yes"
                                           False -> "No"

repl :: Char -> Char
repl 'o' = '0'
repl '1' = 'i'
repl 'l' = 'i'
repl c = c

{-# LANGUAGE ScopedTypeVariables #-}

module Main where

import           Control.Applicative
import           Control.Monad.Cont
import           Data.Char

chZero :: Char -> Char
chZero '0' = 'O'
chZero a   = a

chI :: Char -> Char
chI '1' = 'l'
chI 'I' = 'l'
chI 'i' = 'l'
chI a   = a

minimize :: String -> String
minimize = map (toLower . chI . chZero)

main :: IO ()
main = do
  login <- minimize <$> getLine
  print login
  n :: Int <- read <$> getLine
  flip runContT putStrLn $ callCC $ \notOk -> do
    forM_ [1..n] $ \_ -> do
      l2 <- minimize <$> liftIO getLine
      liftIO $ print login
      if l2 == login then notOk "No" else return ()
    return "Yes"

import Data.List
import Data.Char

main :: IO ()
main = do
  s <- getLine
  ns <- getLine
  let n = read ns :: Integer
  strings <- mapM (\_ -> getLine) [1..n]
  let solution = solveProblem s strings
  putStrLn (show solution)

solveProblem :: String -> [String] -> String
solveProblem    s         strings   = let s' = fmap (repl . toLower) s
                                          strings' = fmap (fmap (repl . toLower)) strings
                                      in case (length (nub (s':strings')) == length (s':strings')) of
                                           True -> "YES"
                                           False -> "NO"

repl :: Char -> Char
repl 'o' = '0'
repl '1' = 'i'
repl 'l' = 'i'
repl c = c


You are given a string $$$s$$$ consisting of exactly $$$n$$$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2').Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'.It is guaranteed that the answer exists.

The first line of the input contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$, $$$n$$$ is divisible by $$$3$$$) — the number of characters in $$$s$$$. The second line contains the string $$$s$$$ consisting of exactly $$$n$$$ characters '0', '1' and '2'.

Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. Because $$$n$$$ is divisible by $$$3$$$ it is obvious that the answer exists. And it is obvious that there is only one possible answer.

-- Codeforces Round #531 (D), Contest 1102, Problem set ?.

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

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

main :: IO ()
main = do
  n <- read <$> getLine :: IO Int
  input <- A.newArray_ (0,n-1) :: IO (IOUArray Int Int)
  acc_ <- A.newArray (0,2) 0 :: IO (IOUArray Int Int)
  forM_ [0..n-1] $ \i -> do
    k_ <- getChar
    let k = fromEnum k_ - fromEnum '0'
    A.writeArray input i k
    A.readArray acc_ k >>= A.writeArray acc_ k . (+1)
  acc <- A.assocs <$> (A.freeze acc_ :: IO (UArray Int Int))
  let ndiv3 = n `div` 3
      diff = (\(i,acc) -> (i,acc-ndiv3)) <$> acc
      decLs = filter ((> 0) . snd) $ diff
      incLs = filter ((< 0) . snd) $ diff
      jobs = buildJobs decLs incLs
      buildJobs ((i,l):xs) ((j,r):ys)
        | l+r > 0 = (i,j,-r) : buildJobs ((i,l+r):xs) ys
        | l+r < 0 = (i,j,l)  : buildJobs xs ((j,l+r):ys)
        | l+r == 0 = (i,j,l) : buildJobs xs ys
      buildJobs [] [] = []
      buildJobs _  _  = error "buildJobs"
      (leftJobs,rightJobs) = partition (\(i,j,_) -> i > j) jobs
  forM_ leftJobs $ \(from,to,moved) -> do
    cnt <- newIORef moved
    forM_ [0..n-1] $ \j -> do
      c <- readIORef cnt
      this <- A.readArray input j
      when (c > 0 && this == from) $ do
        A.writeArray input j to
        writeIORef cnt (c-1)
  forM_ (reverse rightJobs) $ \(from,to,moved) -> do
    cnt <- newIORef moved
    forM_ [n-1,n-2..0] $ \j -> do
      c <- readIORef cnt
      this <- A.readArray input j
      when (c > 0 && this == from) $ do
        A.writeArray input j to
        writeIORef cnt (c-1)
  forM_ [0..n-1] $ \j -> do
    this <- A.readArray input j
    putChar $ toEnum $ this + fromEnum '0'
  putStrLn ""


At the store, the salespeople want to make all prices round. In this problem, a number that is a power of $$$10$$$ is called a round number. For example, the numbers $$$10^0 = 1$$$, $$$10^1 = 10$$$, $$$10^2 = 100$$$ are round numbers, but $$$20$$$, $$$110$$$ and $$$256$$$ are not round numbers. So, if an item is worth $$$m$$$ bourles (the value of the item is not greater than $$$10^9$$$), the sellers want to change its value to the nearest round number that is not greater than $$$m$$$. They ask you: by how many bourles should you decrease the value of the item to make it worth exactly $$$10^k$$$ bourles, where the value of $$$k$$$ — is the maximum possible ($$$k$$$ — any non-negative integer).For example, let the item have a value of $$$178$$$-bourles. Then the new price of the item will be $$$100$$$, and the answer will be $$$178-100=78$$$.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases . Each test case is a string containing a single integer $$$m$$$ ($$$1 \le m \le 10^9$$$) — the price of the item.

For each test case, output on a separate line a single integer $$$d$$$ ($$$0 \le d < m$$$) such that if you reduce the cost of the item by $$$d$$$ bourles, the cost of the item will be the maximal possible round number. More formally: $$$m - d = 10^k$$$, where $$$k$$$ — the maximum possible non-negative integer.

{-# LANGUAGE TypeApplications #-}

import Control.Monad
import Control.Monad.ST
import GHC.Arr

wrap f = getLine >>= putStrLn . f

nums = (10 ^) <$> [0 .. 9]

main = do
  n <- readLn
  forM_ [1 .. n] $
    const $ do
      n <- readLn
      print $ last $ takeWhile (>= 0) $ (n -) <$> nums

arrayshit =
  runST $ do
    a <- newSTArray (0, 10) 0
    writeSTArray a 4 5
    readSTArray a 4
-- >>> 1 + 2

{-# LANGUAGE TypeApplications #-}

import Control.Monad

wrap f = getLine >>= putStrLn . f

nums = (10 ^) <$> [0 .. 9]

main = do
  n <- readLn
  forM_ [1 .. n] $
    const $ do
      n <- readLn
      print $ last $ takeWhile (>= 0) $ (n -) <$> nums
-- >>> 1 + 2

import Control.Monad

wrap f = getLine >>= putStrLn . f
nums = (10^) <$> [0..9]
main = do
  n <- readLn
  forM_ [1..n] $ const $ do
    n <- readLn
    print $ last $ takeWhile (>=0) $ (n-) <$> nums

module Main where

import Control.Monad

solve :: Integer -> Integer
solve m = m - (head . filter ((> m) . (* 10)) $ iterate (* 10) 1)

main = do
  t <- read <$> getLine
  replicateM_ t $
    getLine >>= print . solve . read

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

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

import           Prelude               hiding (getLine)
import           Control.Arrow
import           Control.Monad
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.List

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [m] <- ri
        return m
    mapM_ (putStrLn.show.solve) tcs

solve m = m - roundNum m

roundNum = read . ('1':) . map (const '0') . tail . show :: Int -> Int

import Data.Char (ord, chr)

shrink :: String -> String
shrink [] = "0"
shrink (x: xs) = if x == '0'
  then shrink xs
  else (x: xs)

for :: Int -> IO ()
for 0 = pure ()
for i = do
  a <- getLine
  let c = head a
  if c /= '1'
    then putStrLn ((chr (ord c - 1)): tail a)
    else putStrLn $ shrink $ tail a
  for $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  for n

module Main where

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

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep = id

parse = read

format = show

solve :: Int -> Int
solve x = x - (head $ filter (<= x) [10^i | i <- [9,8..0]])

--
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- {-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}

import Control.Arrow ((>>>))
import Control.Monad (
    MonadPlus (mplus),
    foldM_,
    forM_,
    guard,
    join,
    replicateM,
    replicateM_,
 )
import qualified Control.Monad as M
import qualified Control.Monad.ST.Strict as ST
import qualified Control.Monad.State.Strict as S
import qualified Control.Monad.Trans.Class as T

import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.IO.Safe as IOA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import Data.Bits
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Int

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Bifunctor (bimap)
import Data.Maybe (fromJust, fromMaybe, isJust)
import qualified Data.Maybe as MB

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List   as L
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Ix as Ix
import qualified Data.Ratio as R

import Control.Monad.Cont (MonadIO (liftIO))
import Data.IORef (modifyIORef, newIORef, readIORef)
import GHC.IO.Handle (hDuplicateTo)
import System.IO (
    IOMode (ReadMode, WriteMode),
    openFile,
    stdin,
    stdout,
    hFlush
 )
import System.Posix.Internals (puts)
import Text.Printf (printf)
import qualified Data.Array.IO.Safe as UOA

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace
--
-- tracing t x = trace (t ++ " = " ++ show x) x
-- debugging x t = tracing t x

-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "YES"
                else "NO"
    printf "%s\n" result

{- END OF GENERAL -}

solve :: Int -> Int
solve m = m - last roundPrices
    where
        roundPrices = L.takeWhile (<= m) $ iterate (* 10) 1

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        m <- B8.getLine <&> readIntB8
        let answer = solve m
        printf "%d\n" answer

module Main where

import Control.Monad

solve :: Integer -> Integer
solve m = m - 10 ^ floor (logBase 10 $ fromInteger m)

main = do
  t <- read <$> getLine
  replicateM_ t $
    getLine >>= print . solve . read

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

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

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

import           Prelude               hiding (getLine)
import           Control.Arrow
import           Control.Monad
import qualified Data.ByteString.Char8 as B
import           Data.Char
import           Data.List

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [m] <- ri
        return m
    mapM_ (putStrLn.show.solve) tcs

solve = read . ('1':) . map (const '0') . tail . show :: Int -> Int

import Data.Char (ord, chr)

for :: Int -> IO ()
for 0 = pure ()
for i = do
  a <- getLine
  let c = head a
  if c /= '1'
    then putStrLn ((chr (ord c - 1)): tail a)
    else if a == "1"
      then print 0
      else putStrLn $ tail a
  for $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  for n


One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.

The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.

Output one integer — the number of different variants of group composition.

combi :: Integral a => a -> a -> a
combi n m = (product [n, n - 1 .. n - m + 1]) `div` (product [1 .. m])

main :: IO ()
main = do
    n <- readLn
    print $ (combi n 5) + (combi n 6) + (combi n 7)

main = getLine >>= print . solve . read

solve :: Integer -> Integer
solve n = (cnk n 7) + (cnk n 6) + (cnk n 5)

fact n = product [1..n]

cnk n k | k > n = 0
        | otherwise = product [n,n-1..(n - k + 1)] `div` fact k

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

import qualified Data.ByteString.Char8 as C

main :: IO ()
main = do
    a <- (toInteger.fst.fromJust.C.readInt) <$> C.getLine
    let b = a * (a-1) `div` 2 * (a-2) `div` 3 * (a-3) `div`4 *(a-4)`div`5 *(a-5)`div`6*(a-6)`div`7
    let c = a * (a-1) `div` 2 * (a-2) `div` 3 * (a-3) `div`4 *(a-4)`div`5 *(a-5)`div`6
    let d = a * (a-1) `div` 2 * (a-2) `div` 3 * (a-3) `div`4 *(a-4)`div`5
    print $ b+c+d

fact = (m !!) where m =  scanl (*) 1 [1..]
comb n k = fact n  `div` fact k `div` fact (n - k)
solution k = comb k 7 + comb k 6 + comb k 5
main = getLine >>= print . solution. read

import Control.Monad
main = do
    a <- liftM read getLine
    putStrLn $ show $ (sum $ map (a `choose`) [5..7])
choose n k = (product [(n-k+1)..n]) `div` (product [1..k])

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

comb::Integer->[Integer]->[[Integer]]
comb n []  |n<5 = [[]]
	   | otherwise = []
comb n (s:ss) |n>=s =  [s: y| y<-(comb (n-s) (s:ss))]  ++ (comb n ss)
	      |otherwise = comb n ss

cou n p []=p
cou n p (s:ss) = cou (n-s) (p*(c n s)) ss

main= do
	n<- read  <$>getLine::IO Integer
	print $   sum $   map (c n) [7,6,5]

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

main= do
	n<- read  <$>getLine::IO Integer
	print $   sum $   map (c n) [7,6,5]

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

solve :: Integer -> Integer
solve n = binom n 7 + binom n 6 + binom n 5
    where binom n k = (product [n - k + 1 .. n]) `div` (product [1..k])

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

comb::Integer->[Integer]->[[Integer]]
comb n [] |n>5 = []
	  | otherwise = [[]]

comb n (s:ss) |n>=s =  [s: y| y<-(comb (n-s) (s:ss))]  ++ (comb n ss)
	      |otherwise = comb n ss

cou n p []=p
cou n p (s:ss) = cou (n-s) (p*(c n s)) ss

main= do
	n<- read  <$>getLine::IO Integer
	let s = init $  comb n [7,6,5]
	let t =   sum $  map (cou  n 1) s
	print t

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

comb::Integer->[Integer]->[[Integer]]
comb n []  |n<5 = [[]]
	   | otherwise = []
comb n (s:ss) |n>=s =  [s: y| y<-(comb (n-s) (s:ss))]  ++ (comb n ss)
	      |otherwise = comb n ss

cou n p []=p
cou n p (s:ss) = cou (n-s) (p*(c n s)) ss

main= do
	n<- read  <$>getLine::IO Integer
	print $   sum $  map (cou  n 1) $ comb n [7,6,5]

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

comb::Integer->[Integer]->[[Integer]]
comb n [] |n>=5 = []
	  | otherwise = [[]]

comb n (s:ss) |n>=s =  [s: y| y<-(comb (n-s) (s:ss))]  ++ (comb n ss)
	      |otherwise = comb n ss

cou n p []=p
cou n p (s:ss) = cou (n-s) (p*(c n s)) ss

main= do
	n<- read  <$>getLine::IO Integer
	let s = init $  comb n [7,6,5]
	let t =   map (cou  n 1) s
	print t

import Control.Applicative
import Data.Array

fac = listArray (0,777)  (1:( [product [1..i]| i<-[1..777]]))

c n r = div (fac!n) ((fac!(n-r))*(fac!r))

comb::Integer->[Integer]->[[Integer]]
comb n [] = [[]]
comb n (s:ss) |n>=s =  [s: y| y<-(comb (n-s) (s:ss))]  ++ (comb n ss)
	      |otherwise = comb n ss

cou n p []=p
cou n p (s:ss) = cou (n-s) (p*(c n s)) ss

main= do
	n<- read  <$>getLine::IO Integer
	let s = init $  comb n [7,6,5]
	let t =sum $  map (cou  n 1) s
	print t


Valera has 2·n cubes, each cube contains an integer from 10 to 99. He arbitrarily chooses n cubes and puts them in the first heap. The remaining cubes form the second heap. Valera decided to play with cubes. During the game he takes a cube from the first heap and writes down the number it has. Then he takes a cube from the second heap and write out its two digits near two digits he had written (to the right of them). In the end he obtained a single fourdigit integer — the first two digits of it is written on the cube from the first heap, and the second two digits of it is written on the second cube from the second heap.Valera knows arithmetic very well. So, he can easily count the number of distinct fourdigit numbers he can get in the game. The other question is: how to split cubes into two heaps so that this number (the number of distinct fourdigit integers Valera can get) will be as large as possible?

The first line contains integer n (1 ≤ n ≤ 100). The second line contains 2·n space-separated integers ai (10 ≤ ai ≤ 99), denoting the numbers on the cubes.

In the first line print a single number — the maximum possible number of distinct four-digit numbers Valera can obtain. In the second line print 2·n numbers bi (1 ≤ bi ≤ 2). The numbers mean: the i-th cube belongs to the bi-th heap in your division. If there are multiple optimal ways to split the cubes into the heaps, print any of them.

NoteIn the first test case Valera can put the first cube in the first heap, and second cube — in second heap. In this case he obtain number 1099. If he put the second cube in the first heap, and the first cube in the second heap, then he can obtain number 9910. In both cases the maximum number of distinct integers is equal to one.In the second test case Valera can obtain numbers 1313, 1345, 2413, 2445. Note, that if he put the first and the third cubes in the first heap, he can obtain only two numbers 1324 and 1345.

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

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
readsInt = map readInt . B.words <$> B.getLine
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = map read . words <$> getLine

cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
eqLen a b = length a == length b
eqFst a b = fst a == fst b

swap (a,b) = (b,a)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

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

main = do
    n <- readLn :: IO Int
    l <- readsLine :: IO [Int]
    let uniqueSize = S.size . S.fromList
    let l' = reverse $ sortBy cmpLen $ groupBy eqFst $ sort $ zip l [1..]
    let (l1,l2) = splitTwo l'
    let a = uniqueSize $ map fst l1
    let b = uniqueSize $ map fst l2
    let ans = sort $ map (\(_,i) -> (i,1)) l1 ++ map (\(_,i) -> (i,2)) l2
    print (a*b)
    putStrLn $ unwords $ map (show.snd) ans

splitTwo :: [[(Int,Int)]] -> ([(Int,Int)],[(Int,Int)])
splitTwo l = unzip $ go1 l []
    where
    go1 [] !acc = go2 acc
    go1 ((x1:x2:xs):xss) !acc =
        (x1,x2):go1 xss (xs++acc)
    go1 xss !acc = go2 (concat xss++acc)
    go2 (x1:x2:xs) = (x1,x2):go2 xs
    go2 [] = []

import Control.Monad (liftM)
import Data.Char (ord)
import Data.List (intercalate, delete, group, nub, sort, sortBy)

solve :: [Int] -> (Int, [Int])
solve as  =  (ans, numGs as g1 g2)
  where
    gs  =  sortBy compareByLength $ group $ sort as
    compareByLength a b  =  compare (length a) (length b)
    merge (x:y:xs)  =  (x, y) : merge xs
    merge _  =  []
    g1  =  map fst $ merge $ concat gs
    g2  =  map snd $ merge $ concat gs
    ans  =  (length (nub g1)) * (length (nub g2))
    numGs [] _ _  =  []
    numGs (x:xs) g1 g2
        | elem x g1  =  1 : numGs xs (delete x g1) g2
        | otherwise  =  2 : numGs xs g1 (delete x g2)

main :: IO ()
main  =  do
    getLine
    as  <-  reads
    print $ fst $ solve as
    prints $ snd $ solve as

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

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

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

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
readsInt = map readInt . B.words <$> B.getLine
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = 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)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

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

split2 l = go l
    where
    go (x:y:xs) = (x,y):go xs
    go _ = []

main = do
    n <- readLn :: IO Int
    l <- readsLine :: IO [Int]
    let l' = sort $ zip l [1..]
    let (l1,l2) = unzip $ split2 l'
    let uniqueSize = S.size . S.fromList
    let a = uniqueSize $ map fst l1
    let b = uniqueSize $ map fst l2
    let ans = sort $ map (\(_,i) -> (i,1)) l1 ++ map (\(_,i) -> (i,2)) l2
    print (a*b)
    putStrLn $ unwords $ map (show.snd) ans


Stanley defines the beauty of an array $$$a$$$ of length $$$n$$$, which contains non-negative integers, as follows: $$$$$$\sum\limits_{i = 1}^{n} \left \lfloor \frac{a_{i}}{k} \right \rfloor,$$$$$$ which means that we divide each element by $$$k$$$, round it down, and sum up the resulting values.Stanley told Sam the integer $$$k$$$ and asked him to find an array $$$a$$$ of $$$n$$$ non-negative integers, such that the beauty is equal to $$$b$$$ and the sum of elements is equal to $$$s$$$. Help Sam — find any of the arrays satisfying the conditions above.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first line of each test case contains integers $$$n$$$, $$$k$$$, $$$b$$$, $$$s$$$ ($$$1 \leq n \leq 10^{5}$$$, $$$1 \leq k \leq 10^{9}$$$, $$$0 \leq b \leq 10^{9}$$$, $$$0 \leq s \leq 10^{18}$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print $$$-1$$$ if such array $$$a$$$ does not exist. Otherwise print $$$n$$$ non-negative integers $$$a_1, a_2, \ldots, a_n$$$ ($$$0 \leq a_{i} \leq 10^{18}$$$) — the answer.

NoteIn the first, the second, the fifth and the sixth test cases of the example it is possible to show that such array does not exist.In the third testcase of the example $$$a = [0, 0, 19]$$$. The sum of elements in it is equal to 19, the beauty of it is equal to $$$\left ( \left \lfloor \frac{0}{6} \right \rfloor + \left \lfloor \frac{0}{6} \right \rfloor + \left \lfloor \frac{19}{6} \right \rfloor \right ) = (0 + 0 + 3) = 3$$$.In the fourth testcase of the example $$$a = [0, 3, 3, 3, 29]$$$. The sum of elements in it is equal to $$$38$$$, the beauty of it is equal to $$$(0 + 0 + 0 + 0 + 7) = 7$$$.

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

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        ri
    mapM_ (putStrLn.showAnswer.solve) tcs

showAnswer = maybe "-1" (unwords . map show)

nsReplParam n s = ((  p, e+1),
                   (n-p, e  ))  where  e = s `div` n
                                       p = s - e*n

applyRepl ((p1,e1), (p2,e2)) = replicate p1 e1 ++ replicate p2 e2
maxElem   ((p1,e1), (p2,e2)) = maximum $ applyRepl ((to01 p1, e1),
                                                    (to01 p2, e2))

to01 0 = 0
to01 _ = 1

solve [n,k,b,s] = ans
  where
    bs = (k*) <$> beauties

    beautiesP = nsReplParam n b
    extrasP   = nsReplParam n extrasSum

    beauties = applyRepl beautiesP
    extras   = applyRepl extrasP

    extrasSum = s - b*k

    isGoodExtras = (maxElem extrasP < k)

    ans | (extrasSum < 0)     = Nothing
        | (not isGoodExtras)  = Nothing
        | otherwise           = Just $ zipWith (+) bs extras
solve _         = error "Four nums expected."


Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.Vasya needs to collect all these items, however he won't do it by himself. He uses his brand new robot. The robot has two different arms — the left one and the right one. The robot can consecutively perform the following actions:   Take the leftmost item with the left hand and spend wi · l energy units (wi is a weight of the leftmost item, l is some parameter). If the previous action was the same (left-hand), then the robot spends extra Ql energy units;  Take the rightmost item with the right hand and spend wj · r energy units (wj is a weight of the rightmost item, r is some parameter). If the previous action was the same (right-hand), then the robot spends extra Qr energy units; Naturally, Vasya wants to program the robot in a way that the robot spends as little energy as possible. He asked you to solve this problem. Your task is to find the minimum number of energy units robot spends to collect all items.

The first line contains five integers n, l, r, Ql, Qr (1 ≤ n ≤ 105; 1 ≤ l, r ≤ 100; 1 ≤ Ql, Qr ≤ 104). The second line contains n integers w1, w2, ..., wn (1 ≤ wi ≤ 100).

In the single line print a single number — the answer to the problem.

NoteConsider the first sample. As l = r, we can take an item in turns: first from the left side, then from the right one and last item from the left. In total the robot spends 4·42 + 4·99 + 4·3 = 576 energy units.The second sample. The optimal solution is to take one item from the right, then one item from the left and two items from the right. In total the robot spends (2·4) + (7·1) + (2·3) + (2·2 + 9) = 34 energy units.

{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE MultiWayIf #-}

import Data.List
import Control.Monad

costs l r ql qr ws =
  let total = sum ws
      n = length ws
      lsums = scanl (+) 0 ws
      cost nlefts lsum = lsum*l + (total-lsum)*r + qcost
        where nrights = n-nlefts
              qcost = if | nlefts > nrights -> ql*(nlefts-nrights-1)
                         | nrights > nlefts -> qr*(nrights-nlefts-1)
                         | otherwise        -> 0
  in [ cost k lsum | (k,lsum) <- zip [0..] lsums ]

main = do
  (n:l:r:ql:qr:_) <- fmap (map read . words) getLine
  ws <- fmap (map read . words) getLine              :: IO [Int]
  let answer = minimum $ costs l r ql qr ws
  print answer

{-# LANGUAGE MultiWayIf #-}

import Control.Monad
import Data.Array.IO
import Data.Array
import qualified Data.Array.MArray as M

data Hand = EitherHand | LeftHand | RightHand
  deriving (Show,Eq)

step warr n ql qr l r prev k =
  let best i = let (pr,rh) = prev ! i
                   (pl,lh) = prev ! (i+1)
                   rcost = (warr!(i+k))*r + (if (rh == RightHand) then qr else 0) + pr
                   lcost = (warr!i)*l     + (if (lh == LeftHand) then ql else 0)  + pl
               in if | rcost == lcost -> (rcost,EitherHand)
                     | rcost < lcost  -> (rcost,RightHand)
                     | otherwise      -> (lcost,LeftHand)
  in listArray (1,n-k) [ best i | i <- [1..n-k] ]

step0 n = listArray (1,n) (replicate n (0,EitherHand)) :: Array Int (Int,Hand)

main = do
  (n:l:r:ql:qr:_) <- fmap (map read . words) getLine :: IO [Int]
  ws <- fmap (map read . words) getLine :: IO [Int]
  let warr = listArray (1,n) ws
      -- answer = foldl (\prev k -> step' warr n ql qr l r prev k) step0 [1..n-1]
      s0 = step0 (n+1)
  answer <-
    foldM (\prev k -> do
      let next = step warr n ql qr l r prev k
      -- putStrLn $ "k = " ++ show k ++ ": " ++ show next
      return next) s0 [0..n-1]
  let (total,_) = answer ! 1
  print total


Recently, the Fair Nut has written $$$k$$$ strings of length $$$n$$$, consisting of letters "a" and "b". He calculated $$$c$$$ — the number of strings that are prefixes of at least one of the written strings. Every string was counted only one time.Then, he lost his sheet with strings. He remembers that all written strings were lexicographically not smaller than string $$$s$$$ and not bigger than string $$$t$$$. He is interested: what is the maximum value of $$$c$$$ that he could get.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds: $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$; in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \leq n \leq 5 \cdot 10^5$$$, $$$1 \leq k \leq 10^9$$$). The second line contains a string $$$s$$$ ($$$|s| = n$$$) — the string consisting of letters "a" and "b. The third line contains a string $$$t$$$ ($$$|t| = n$$$) — the string consisting of letters "a" and "b. It is guaranteed that string $$$s$$$ is lexicographically not bigger than $$$t$$$.

Print one number — maximal value of $$$c$$$.

NoteIn the first example, Nut could write strings "aa", "ab", "ba", "bb". These $$$4$$$ strings are prefixes of at least one of the written strings, as well as "a" and "b". Totally, $$$6$$$ strings.In the second example, Nut could write strings "aba", "baa", "bba".In the third example, there are only two different strings that Nut could write. If both of them are written, $$$c=8$$$.

solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer
solve' k [] [] d = 0
solve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'
    where d' = next k d (sc, tc)

solve k s t = solve' k s t 1

next' d ('a', 'a') = 2 * d - 1
next' d ('a', 'b') = 2 * d
next' d ('b', 'a') = 2 * d - 2
next' d ('b', 'b') = 2 * d - 1

next k d pair = if d <= k then next' d pair else d

--solve2 k s t = sum (

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer
solve' k [] [] d = 0
solve' k (sc:s) (tc:t) d
    | d' <= k = min k d' + solve' k s t d'
    | otherwise = k * fromIntegral(length s + 1)
        where d' = case (sc, tc) of
                    ('a', 'a') -> 2*d - 1
                    ('a', 'b') -> 2*d
                    ('b', 'a') -> 2*d - 2
                    ('b', 'b') -> 2*d - 1

solve k s t = solve' k s t 1

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

next' d ('a', 'a') = 2 * d - 1
next' d ('a', 'b') = 2 * d
next' d ('b', 'a') = 2 * d - 2
next' d ('b', 'b') = 2 * d - 1

next k d pair = if d <= k then next' d pair else d

solve :: Integer -> [Char] -> [Char] -> Integer
solve k s t = sum $ map (min k) $ tail $ scanl (next k) 1 (zip s t)

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer
solve' k [] [] d = 0
solve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'
    where d' = if d <= k then next d (sc, tc) else d

solve k s t = solve' k s t 1

next d ('a', 'a') = 2 * d - 1
next d ('a', 'b') = 2 * d
next d ('b', 'a') = 2 * d - 2
next d ('b', 'b') = 2 * d - 1

--solve2 k s t = sum (

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

solve' :: Integer -> [Char] -> [Char] -> Integer -> Integer
solve' k [] [] d = 0
solve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'
    where d' = min d'' k
          d'' = case (sc, tc) of
            ('a', 'a') -> 2*d - 1
            ('a', 'b') -> 2*d
            ('b', 'a') -> 2*d - 2
            ('b', 'b') -> 2*d - 1

solve k s t = solve' k s t 1

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

appendBit num 0 = 2 * num
appendBit num 1 = 2 * num + 1

-- treat 'a' as 0 bit, 'b' as 1 bit
charToBit 'a' = 0
charToBit 'b' = 1

-- After some point the difference will always be bigger than k
optimizedAppendChars k a b sc tc
    | (b - a >= 4 * k) = (a, b)
    | otherwise = (appendBit a (charToBit sc), appendBit b (charToBit tc))

-- Don't care about overflows because difference will persist through them
solve' :: Int-> [Char] -> [Char] -> Int-> Int-> Int
solve' k [] [] a b = 0
solve' k (sc:s) (tc:t) a b = min k (b' - a' + 1) + solve' k s t a' b'
    where (a', b') = optimizedAppendChars k a b sc tc

solve k s t = solve' k s t 0 0

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)

solve' :: Int-> [Char] -> [Char] -> Int-> Int
solve' k [] [] d = 0
solve' k (sc:s) (tc:t) d = min k d' + solve' k s t d'
    where d' = if d <= k then next d (sc, tc) else d

solve k s t = solve' k s t 1

next d ('a', 'a') = 2 * d - 1
next d ('a', 'b') = 2 * d
next d ('b', 'a') = 2 * d - 2
next d ('b', 'b') = 2 * d - 1

--solve2 k s t = sum (

main :: IO ()
main = do
    [_, k] <- fmap (map read.words) getLine
    s <- getLine
    t <- getLine
    print (solve k s t)