During the loading of the game "Dungeons and Candies" you are required to get descriptions of k levels from the server. Each description is a map of an n × m checkered rectangular field. Some cells of the field contain candies (each cell has at most one candy). An empty cell is denoted as "." on the map, but if a cell has a candy, it is denoted as a letter of the English alphabet. A level may contain identical candies, in this case the letters in the corresponding cells of the map will be the same.  When you transmit information via a network, you want to minimize traffic — the total size of the transferred data. The levels can be transmitted in any order. There are two ways to transmit the current level A:  You can transmit the whole level A. Then you need to transmit n·m bytes via the network.  You can transmit the difference between level A and some previously transmitted level B (if it exists); this operation requires to transmit dA, B·w bytes, where dA, B is the number of cells of the field that are different for A and B, and w is a constant. Note, that you should compare only the corresponding cells of levels A and B to calculate dA, B. You cannot transform the maps of levels, i.e. rotate or shift them relatively to each other. Your task is to find a way to transfer all the k levels and minimize the traffic.

The first line contains four integers n, m, k, w (1 ≤ n, m ≤ 10; 1 ≤ k, w ≤ 1000). Then follows the description of k levels. Each level is described by n lines, each line contains m characters. Each character is either a letter of the English alphabet or a dot ("."). Please note that the case of the letters matters.

In the first line print the required minimum number of transferred bytes. Then print k pairs of integers x1, y1, x2, y2, ..., xk, yk, describing the way to transfer levels. Pair xi, yi means that level xi needs to be transferred by way yi. If yi equals 0, that means that the level must be transferred using the first way, otherwise yi must be equal to the number of a previously transferred level. It means that you will transfer the difference between levels yi and xi to transfer level xi. Print the pairs in the order of transferring levels. The levels are numbered 1 through k in the order they follow in the input. If there are multiple optimal solutions, you can print any of them.

import Data.Array.IO
import Data.IORef
import Control.Monad
import Data.Tuple
import Data.List
import Data.Char
import qualified Data.ByteString.Lazy as B

dist :: IOUArray Int Char -> IOUArray Int Char -> IO Int
dist a b = do
	r <- newIORef 0
	bounds <- getBounds a
	forM_ (range bounds) $ \i -> do
		aa <- readArray a i
		bb <- readArray b i
		if aa /= bb then do
			c <- readIORef r
			writeIORef r (c + 1)
		else return ()
	readIORef r

type SNM = IOArray Int (Int,Int)

snm_get :: SNM -> Int -> IO Int
snm_get snm i = do
	(p,r) <- readArray snm i
	if p == i then return i
	else do
		pp <- snm_get snm p
		writeArray snm i (pp,r)
		return pp

snm_union :: SNM -> Int -> Int -> IO ()
snm_union snm a b = do
	(va,ra) <- readArray snm a
	(vb,rb) <- readArray snm b
	if ra < rb then writeArray snm a (vb,ra)
	else if ra > rb then writeArray snm b (va,rb)
	else do
		writeArray snm a (vb,ra)
		writeArray snm b (vb,rb+1)

dfs :: IOUArray Int Bool -> IOArray Int [Int] -> IORef [(Int, Int)] -> Int -> IO ()
dfs fs g path i = do
	e <- readArray g i
	forM_ e $ \j-> do
		f <- readArray fs j
		if not f then do
			writeArray fs j True
			dfs fs g path j
			modifyIORef path $ \p-> (j,i+1):p
		else return ()

main :: IO ()
main = do
	n:m:k:w:_ <- liftM ((map read) . words) getLine
	levels <- ((newArray_ (0,k-1)) :: IO (IOArray Int (IOUArray Int Char)))
	forM_ [0..(k-1)] $ \k -> do
		content <- liftM concat $ forM [0..(n-1)] $ \_ -> getLine
		l <- newListArray (0,n*m-1) content
		writeArray levels k l
	el <- getElems levels
	--liftM show (mapM getElems el) >>= putStrLn
	edges <- newIORef []
	forM_ [0..(k-1)] $ \i -> do
		a <- readArray levels i
		forM_ [(i+1)..(k-1)] $ \j -> do
			b <- readArray levels j
			d <- dist a b
			if d * w >= (n*m) then return ()
			else do
				e <- readIORef edges
				writeIORef edges ((d * w,i,j):e)
	sedges <- liftM sort $ readIORef edges
	--putStrLn $ show sedges
	snm <- newListArray (0,k-1) $ zip [0..(k-1)] $ replicate k 0
	r <- newIORef 0
	g <- newArray (0,k-1) []
	forM_ sedges $ \(d,i,j) -> do
		pi <- snm_get snm i
		pj <- snm_get snm j
		if pi /= pj then do
			snm_union snm pi pj
			modifyIORef r $ \r->r+d
			ig <- readArray g i
			writeArray g i (j:ig)
			jg <- readArray g j
			writeArray g j (i:jg)
		else return ()
	fs <- ((newArray (0,k-1) False) :: IO (IOUArray Int Bool))
	path <- newIORef []
	forM_ [0..(k-1)] $ \i -> do
		f <- readArray fs i
		if not f then do
			writeArray fs i True
			dfs fs g path i
			modifyIORef path $ \p-> (i,0):p
			modifyIORef r $ \r->r+n*m
		else return ()
	res <- readIORef r
	putStrLn $ show res
	ps <- readIORef path
	forM_ ps $ \(i,j)-> putStrLn $ (show (i + 1)) ++ " " ++ (show j)


A robot cleaner is placed on the floor of a rectangle room, surrounded by walls. The floor consists of $$$n$$$ rows and $$$m$$$ columns. The rows of the floor are numbered from $$$1$$$ to $$$n$$$ from top to bottom, and columns of the floor are numbered from $$$1$$$ to $$$m$$$ from left to right. The cell on the intersection of the $$$r$$$-th row and the $$$c$$$-th column is denoted as $$$(r,c)$$$. The initial position of the robot is $$$(r_b, c_b)$$$.In one second, the robot moves by $$$dr$$$ rows and $$$dc$$$ columns, that is, after one second, the robot moves from the cell $$$(r, c)$$$ to $$$(r + dr, c + dc)$$$. Initially $$$dr = 1$$$, $$$dc = 1$$$. If there is a vertical wall (the left or the right walls) in the movement direction, $$$dc$$$ is reflected before the movement, so the new value of $$$dc$$$ is $$$-dc$$$. And if there is a horizontal wall (the upper or lower walls), $$$dr$$$ is reflected before the movement, so the new value of $$$dr$$$ is $$$-dr$$$.Each second (including the moment before the robot starts moving), the robot cleans every cell lying in the same row or the same column as its position. There is only one dirty cell at $$$(r_d, c_d)$$$. The job of the robot is to clean that dirty cell.  Illustration for the first example. The blue arc is the robot. The red star is the target dirty cell. Each second the robot cleans a row and a column, denoted by yellow stripes. Given the floor size $$$n$$$ and $$$m$$$, the robot's initial position $$$(r_b, c_b)$$$ and the dirty cell's position $$$(r_d, c_d)$$$, find the time for the robot to do its job.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 10^4$$$). Description of the test cases follows. A test case consists of only one line, containing six integers $$$n$$$, $$$m$$$, $$$r_b$$$, $$$c_b$$$, $$$r_d$$$, and $$$c_d$$$ ($$$1 \le n, m \le 100$$$, $$$1 \le r_b, r_d \le n$$$, $$$1 \le c_b, c_d \le m$$$) — the sizes of the room, the initial position of the robot and the position of the dirt cell.

For each test case, print an integer — the time for the robot to clean the dirty cell. We can show that the robot always cleans the dirty cell eventually.

NoteIn the first example, the floor has the size of $$$10\times 10$$$. The initial position of the robot is $$$(6, 1)$$$ and the position of the dirty cell is $$$(2, 8)$$$. See the illustration of this example in the problem statement.In the second example, the floor is the same, but the initial position of the robot is now $$$(9, 9)$$$, and the position of the dirty cell is $$$(1, 1)$$$. In this example, the robot went straight to the dirty cell and clean it.   In the third example, the floor has the size $$$9 \times 8$$$. The initial position of the robot is $$$(5, 6)$$$, and the position of the dirty cell is $$$(2, 1)$$$.   In the fourth example, the floor has the size $$$6 \times 9$$$. The initial position of the robot is $$$(2, 2)$$$ and the position of the dirty cell is $$$(5, 8)$$$.   In the last example, the robot was already standing in the same column as the dirty cell, so it can clean the cell right away.

processLine :: [String] -> [Int]
processLine args = do
    nums <- words <$> args

    let [n, m, rb, cb, rd, cd] = read <$> nums :: [Int]

    let {
        _go cur_r cur_c dr dc acc
        | cur_r == rd || cur_c == cd = acc
        | otherwise = _go (cur_r + new_dr) (cur_c + new_dc) new_dr new_dc (acc + 1)
        where new_dr = if cur_r == n then -dr else dr
              new_dc = if cur_c == m then -dc else dc
        }

    return (_go rb cb 1 1 0)

main = do
    input <- processLine . tail . lines <$> getContents

    mapM_ print input

module Main where

import Control.Monad ( void, replicateM )

main :: IO ()
main = getLine >>= void . flip replicateM runAction . read

runAction :: IO ()
runAction = getLine >>= print . (\[n,m,rb,cb,rd,cd] -> calculate n m rb cb rd cd) . map read . words

calculate :: Int -> Int -> Int -> Int -> Int -> Int -> Int
calculate n m rb cb rd cd =
    let dr = if rb > rd then (n - rb) + (n - rd) else rd - rb
        dc = if cb > cd then (m - cb) + (m - cd) else cd - cb
    in min dr dc

import Data.List

data Config = Config
  { floorSize :: (Int, Int)
  , initialPos :: (Int, Int)
  , dirtyPos :: (Int, Int)
  }

data Dir = NE | SE | NW | SW
  deriving (Show, Eq)

direction :: (Int, Int) -> Dir
direction (dr, dc)
  | dr < 0 && dc < 0 = NW
  | dr < 0 && dc > 0 = NE
  | dr > 0 && dc < 0 = SW
  | otherwise = SE

data Robot = Robot
  { robotPos :: (Int, Int)
  , robotDir :: (Int, Int)
  }

modifyRobotDir :: ((Int, Int) -> (Int, Int)) -> Robot -> Robot
modifyRobotDir f robot = let dir = robotDir robot
                         in robot{ robotDir = f dir }

moveRobot :: Robot -> Robot
moveRobot (Robot (r,c) dir@(dr, dc)) = Robot (r + dr, c + dc) dir

main :: IO ()
main = interact robotCleaner

readTestCase :: String -> Config
readTestCase testCase =
  Config
    { floorSize = (n, m)
    , initialPos = (rb, cb)
    , dirtyPos = (rd, cd)
    }
  where
    [n, m, rb, cb, rd, cd] = read <$> words testCase

robotCleaner :: String -> String
robotCleaner = unlines . map (clean . readTestCase) . tail . lines

clean :: Config -> String
clean cfg = show $ length $ unfoldr go $ Robot (initialPos cfg) (1,1)
  where
    go :: Robot -> Maybe ((), Robot)
    go robot
      | checkClean (robotPos robot) (dirtyPos cfg) = Nothing
      | otherwise = Just ((), step (floorSize cfg) robot)

step :: (Int, Int) -> Robot -> Robot
step (n,m) robot@(Robot pos@(r,c) dir) = moveRobot $ modifyRobotDir adjust robot
  where
    adjust :: (Int, Int) -> (Int, Int)
    adjust
      | corner    = reflectH . reflectV
      | vert      = reflectH
      | horz      = reflectV
      | otherwise = id
      where
        dir' = direction dir
        corner =    (pos == (1,1) && dir' == NW)
                 || (pos == (1,m) && dir' == NE)
                 || (pos == (n,1) && dir' == SW)
                 || (pos == (n,m) && dir' == SE)
        vert =    (c == 1 && (dir' == NW || dir' == SW))
               || (c == m && (dir' == NE || dir' == SE))
        horz =    (r == 1 && (dir' == NE || dir' == NW))
               || (r == n && (dir' == SE || dir' == SW))

reflectH :: (Int, Int) -> (Int, Int)
reflectH (dr, dc) = (dr, negate dc)

reflectV :: (Int, Int) -> (Int, Int)
reflectV (dr, dc) = (negate dr, dc)

checkClean ::
  -- robot position
  (Int, Int) ->
  -- dirt position
  (Int, Int) ->
  Bool
checkClean (rr, rc) (dr, dc) = rr == dr || rc == dc


You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.For instance, if we are given an array $$$[10, 20, 30, 40]$$$, we can permute it so that it becomes $$$[20, 40, 10, 30]$$$. Then on the first and the second positions the integers became larger ($$$20>10$$$, $$$40>20$$$) and did not on the third and the fourth, so for this permutation, the number that Vasya wants to maximize equals $$$2$$$. Read the note for the first example, there is one more demonstrative test case.Help Vasya to permute integers in such way that the number of positions in a new array, where integers are greater than in the original one, is maximal.

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array.

Print a single integer — the maximal number of the array's elements which after a permutation will stand on the position where a smaller element stood in the initial array.

NoteIn the first sample, one of the best permutations is $$$[1, 5, 5, 3, 10, 1, 1]$$$. On the positions from second to fifth the elements became larger, so the answer for this permutation is 4.In the second sample, there is no way to increase any element with a permutation, so the answer is 0.

import Data.List as List

toint s = (read s) :: Integer

comb (s,r) c =
    let ss = min s c in
    (s-ss+c,r+ss)

doit :: [Integer] -> (Integer,Integer) -> Integer -> Integer -> Integer

doit [] t a q =
    let (x,y) = comb t q in
    y

doit (x:xs) t a q =
    if x == a then
        doit xs t a (q+1)
    else
        doit xs (comb t q) x 1

solve::String -> String
solve ss =
    let s = List.sort $ map toint (tail (words ss)) in
    let r = doit s (0,0) (-1) 0 in
    (show r) ++ "\n"

main = do
  interact $ solve

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

import Data.Array.IArray
import Data.Array.Unboxed
import Data.Char
import Data.Functor
import Data.List
import Data.Int
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import Control.Monad

getInts :: IO [Int]
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

solve :: [Int] -> Int
solve = maximum . map length . group . sort

main :: IO ()
main = do [n] <- getInts
          a <- getInts
          print (n - (solve a))


Wherever the destination is, whoever we meet, let's render this song together.On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage.On the sides of the stage stand n dancers. The i-th of them falls into one of the following groups:   Vertical: stands at (xi, 0), moves in positive y direction (upwards);  Horizontal: stands at (0, yi), moves in positive x direction (rightwards).   According to choreography, the i-th dancer should stand still for the first ti milliseconds, and then start moving in the specified direction at 1 unit per millisecond, until another border is reached. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.When two dancers collide (i.e. are on the same point at some time when both of them are moving), they immediately exchange their moving directions and go on.  Dancers stop when a border of the stage is reached. Find out every dancer's stopping position.

The first line of input contains three space-separated positive integers n, w and h (1 ≤ n ≤ 100 000, 2 ≤ w, h ≤ 100 000) — the number of dancers and the width and height of the stage, respectively. The following n lines each describes a dancer: the i-th among them contains three space-separated integers gi, pi, and ti (1 ≤ gi ≤ 2, 1 ≤ pi ≤ 99 999, 0 ≤ ti ≤ 100 000), describing a dancer's group gi (gi = 1 — vertical, gi = 2 — horizontal), position, and waiting time. If gi = 1 then pi = xi; otherwise pi = yi. It's guaranteed that 1 ≤ xi ≤ w - 1 and 1 ≤ yi ≤ h - 1. It is guaranteed that no two dancers have the same group, position and waiting time at the same time.

Output n lines, the i-th of which contains two space-separated integers (xi, yi) — the stopping position of the i-th dancer in the input.

NoteThe first example corresponds to the initial setup in the legend, and the tracks of dancers are marked with different colours in the following figure.  In the second example, no dancers collide.

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

import qualified Data.ByteString as B (getLine, getContents)
import qualified Data.ByteString.Char8 as C (readInt, words, lines)
import qualified Data.Maybe as M (fromJust)
import qualified Data.Function as F (on)
import qualified Data.List as L (sort, sortBy, groupBy, intercalate)

readInt = fst . M.fromJust . C.readInt
cor (i, [g, p, t]) | g == 1 = ((p, -t), i) | g == 2 = ((-t, p), i)
diff = uncurry (+) . fst

solve w h xs = zip (g ++ p) f where
    f = map snd $ L.sortBy (compare `F.on` (fst . fst)) xs
    g = L.sort [[x, h] | ((x, y), _) <- xs, y <= 0]
    p = reverse $ L.sort [[w, y] | ((x, y), _) <- xs, x <= 0]

main :: IO ()
main = do
    (map readInt . C.words -> [_, w, h]) <- B.getLine
    (map cor . zip [1..] . map (map readInt . C.words) . C.lines -> xs) <- B.getContents
    let gs = L.groupBy ((==) `F.on` diff) $ L.sortBy (compare `F.on` diff) xs
        ans = (map fst . L.sortBy (compare `F.on` snd) . concat . map (solve w h)) gs
    putStrLn $ L.intercalate "\n" $ map (L.intercalate " " . map show) ans


Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon. The dragon has a hit point of $$$x$$$ initially. When its hit point goes to $$$0$$$ or under $$$0$$$, it will be defeated. In order to defeat the dragon, Kana can cast the two following types of spells.  Void Absorption Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will become $$$\left\lfloor \frac{h}{2} \right\rfloor + 10$$$. Here $$$\left\lfloor \frac{h}{2} \right\rfloor$$$ denotes $$$h$$$ divided by two, rounded down. Lightning Strike This spell will decrease the dragon's hit point by $$$10$$$. Assume that the dragon's current hit point is $$$h$$$, after casting this spell its hit point will be lowered to $$$h-10$$$.Due to some reasons Kana can only cast no more than $$$n$$$ Void Absorptions and $$$m$$$ Lightning Strikes. She can cast the spells in any order and doesn't have to cast all the spells. Kana isn't good at math, so you are going to help her to find out whether it is possible to defeat the dragon.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$)  — the number of test cases. The next $$$t$$$ lines describe test cases. For each test case the only line contains three integers $$$x$$$, $$$n$$$, $$$m$$$ ($$$1\le x \le 10^5$$$, $$$0\le n,m\le30$$$)  — the dragon's intitial hit point, the maximum number of Void Absorptions and Lightning Strikes Kana can cast respectively.

If it is possible to defeat the dragon, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can print each letter in any case (upper or lower).

NoteOne possible casting sequence of the first test case is shown below: Void Absorption $$$\left\lfloor \frac{100}{2} \right\rfloor + 10=60$$$. Lightning Strike $$$60-10=50$$$. Void Absorption $$$\left\lfloor \frac{50}{2} \right\rfloor + 10=35$$$. Void Absorption $$$\left\lfloor \frac{35}{2} \right\rfloor + 10=27$$$. Lightning Strike $$$27-10=17$$$. Lightning Strike $$$17-10=7$$$. Lightning Strike $$$7-10=-3$$$.

import Control.Arrow

main = interact $
  lines >>> drop 1
  >>> map (words >>> map read)
  >>> process
  >>> map (\b -> if b then "YES" else "NO") >>> unlines

process :: [[Int]] -> [Bool]
process [] = []
process ([x,n,m]:ps) = (solve x n m <= 0) : process ps

solve x n m
  | x <= 0 = 0
  | n > 0 && x >= 20 = solve (x `div` 2 + 10) (n - 1) m
  | otherwise = x - m * 10

module Main where

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = words <$> getLine

getIntList :: IO [Int]
getIntList = map read <$> getStrList

printStrList :: [String] -> IO ()
printStrList = putStrLn . intercalate " "

printList :: (Show a) => [a] -> IO ()
printList = printStrList . map show

yesOrNo :: Bool -> String
yesOrNo True = "YES"
yesOrNo False = "NO"

(|>) :: a -> (a -> b) -> b
(|>) = flip ($)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [x, n, m] <- getIntList
        putStrLn . yesOrNo $ f x n m

voidA :: Int -> Int
voidA = (+ 10) . (`div` 2)

f :: Int -> Int -> Int -> Bool
f x n m = x |> iterate voidA |> take (n + 1) |> filter (<= (10 * m)) |> (/= [])

module Main where

import Control.Monad
import Data.List

getStrList :: IO [String]
getStrList = words <$> getLine

getIntList :: IO [Int]
getIntList = map read <$> getStrList

printStrList :: [String] -> IO ()
printStrList = putStrLn . intercalate " "

printList :: (Show a) => [a] -> IO ()
printList = printStrList . map show

yesOrNo :: Bool -> String
yesOrNo True = "YES"
yesOrNo False = "NO"

(-->) :: a -> (a -> b) -> b
(-->) = flip ($)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [x, n, m] <- getIntList
        putStrLn . yesOrNo $ f x n m

voidA :: Int -> Int
voidA = (+ 10) . (`div` 2)

f :: Int -> Int -> Int -> Bool
f x n m = x
          --> iterate voidA
          --> take (n + 1)
          --> filter (<= (10 * m))
          --> (/= [])

main = getLine >>= test . read

test 0 = return ()
test i = do
    (x:n:m:_) <- map read . words <$> getLine
    let x' = minimum $ take (n + 1) $ iterate va x
    if minimum (take (m + 1) $ iterate ls x') <= 0
        then putStrLn "YES"
        else putStrLn "NO"
    test (i - 1)

va h = div h 2 + 10

ls h = h - 10

import Control.Monad
main :: IO ()
main = do
    n <- readLn
    replicateM_ n routine

routine :: IO ()
routine = do
    [x,n,m] <- (map (read ::String -> Int).words) <$> getLine
    putStrLn $ if solve x n m
      then "YES"
      else "NO"

solve :: Int -> Int -> Int -> Bool
solve x n m
  |x<=0 = True
  |x <=20 = x - (10*m) <= 0
  |n>0 = solve ((x `div` 2)+10) (n-1) (m)
  |otherwise = x - (10*m) <= 0

yn :: Bool -> String
yn True = "YES"
yn False = "NO"

a :: Int -> Int -> Int
a 0 x = x
a n x = a (n - 1) (div x 2 + 10)

solve :: [Int] -> Bool
solve [x, n, m] = m * 10 >= min x (a n x)

io :: String -> String
io s = unlines $ map (yn . solve . map (read :: String -> Int) . words) $ drop 1 $ lines s

main :: IO ()
main = do
  interact io

import Control.Monad (forM_)

solve h abs strike = (iterate (\h -> if h >= 20 then h `div` 2 + 10 else h) h !! abs - 10*strike) <= 0

main = do
	t <- fmap read getLine
	forM_ [1..t] $ \i -> do
		[h, abs, strike] <- fmap (map read.words) getLine :: IO [Int]
		putStrLn $ if solve h abs strike then "YES" else "NO"

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

process a b c | a<=0 ="YES"
              | a<=20 = if c*10 >= a then "YES" else "NO"
	      | b==0 = if c*10 >=a then "YES" else "NO"
              | otherwise = process ((div a 2)+10) (b-1) c

onecase = do
		[a,b,c]<-map read <$> words <$> getLine ::IO [Integer]
		putStrLn $ process a b c

main = do
		n<-read <$> getLine ::IO Int
		replicateM_ n onecase

process :: Int -> Int -> Int -> Bool
process x n m = (iterate (\x -> x - 10) (min x (iterate (\x -> x `div` 2 + 10) x !! n)) !! m) <= 0

readInt :: String -> Int
readInt = read

run :: Int -> IO ()
run 0 = return ()
run t = do
    [x,n,m] <- fmap (map readInt.words) getLine
    if process x n m
        then putStrLn "YES"
        else putStrLn "NO"
    run (t-1)

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

absorption :: Int -> Int -> Int
absorption x n
  | x <= 20 = x
  | n == 0 = x
  | otherwise = absorption ((div x 2) + 10) (n-1)

solve :: Int -> Int -> Int -> Bool
solve x n m = afterAbsorption - (m*10) <= 0
  where afterAbsorption = absorption x n

parse :: String -> String
parse input
  | solve x n m = "YES"
  | otherwise = "NO"
  where [x, n, m] = map (\z -> read z :: Int) $ words input

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


As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lowercase English letter.  Max and Lucas are playing the game. Max goes first, then Lucas, then Max again and so on. Each player has a marble, initially located at some vertex. Each player in his/her turn should move his/her marble along some edge (a player can move the marble from vertex v to vertex u if there's an outgoing edge from v to u). If the player moves his/her marble from vertex v to vertex u, the "character" of that round is the character written on the edge from v to u. There's one additional rule; the ASCII code of character of round i should be greater than or equal to the ASCII code of character of round i - 1 (for i > 1). The rounds are numbered for both players together, i. e. Max goes in odd numbers, Lucas goes in even numbers. The player that can't make a move loses the game. The marbles may be at the same vertex at the same time.Since the game could take a while and Lucas and Max have to focus on finding Dart, they don't have time to play. So they asked you, if they both play optimally, who wins the game?You have to determine the winner of the game for all initial positions of the marbles.

The first line of input contains two integers n and m (2 ≤ n ≤ 100, ). The next m lines contain the edges. Each line contains two integers v, u and a lowercase English letter c, meaning there's an edge from v to u written c on it (1 ≤ v, u ≤ n, v ≠ u). There's at most one edge between any pair of vertices. It is guaranteed that the graph is acyclic.

Print n lines, a string of length n in each one. The j-th character in i-th line should be 'A' if Max will win the game in case her marble is initially at vertex i and Lucas's marble is initially at vertex j, and 'B' otherwise.

NoteHere's the graph in the first sample test case:  Here's the graph in the second sample test case:

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.Array.Unboxed
import Data.Bool

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  m <- poi
  g <- accumArray (flip const) '\0' ((1, 1), (n, n)) `fmap` replicateM m (liftM3 (\u v c -> ((u, v), B.head c)) poi poi pop)
  return $ unlines $ map (map (bool 'B' 'A')) $ solve n g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n g = [[tbl!(i, j, 'a') | j <- [1..n]] | i <- [1..n]]
  where
  _ = g :: UArray (Int, Int) Char
  tbl = listArray rng $ map go $ range rng :: Array (Int, Int, Char) Bool
    where
    rng = ((1, 1, 'a'), (n, n, 'z'))
    go (u, v, c) = or [not $ tbl!(v, w, c') | w <- [1..n], let c' = g!(u, w), c' >= c]

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Strict
import Data.Array.Unboxed
import Data.Bool

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  m <- poi
  g <- accumArray (flip const) '\0' ((1, 1), (n, n)) `fmap` replicateM m (liftM3 (\u v c -> ((u, v), B.head c)) poi poi pop)
  return $ unlines $ map (map (bool 'B' 'A')) $ solve n g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n g = [[tbl!(i, j, 'a') | j <- [1..n]] | i <- [1..n]]
  where
  _ = g :: UArray (Int, Int) Char
  tbl = listArray rng $ map go $ range rng :: Array (Int, Int, Char) Bool
    where
    rng = ((1, 1, 'a'), (n, n, 'z'))
    go (u, v, c) = or [not $ tbl!(v, w, c') | w <- [1..n], let c' = g!(u, w), c' >= c]

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.Array.Unboxed
import Data.Bool

main = B.interact exec
exec = B.pack . evalState app . B.words
app = do
  n <- poi
  m <- poi
  g <- accumArray (flip const) '\0' ((1, 1), (n, n)) `fmap` replicateM m (liftM3 (\u v c -> ((u, v), B.head c)) poi poi pop)
  return $ unlines $ map (map (bool 'B' 'A')) $ solve n g
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n g = [[tbl!(i, j, 'a') | j <- [1..n]] | i <- [1..n]]
  where
  _ = g :: UArray (Int, Int) Char
  tbl = listArray rng $ map go $ range rng :: Array (Int, Int, Char) Bool
    where
    rng = ((1, 1, 'a'), (n, n, 'z'))
    go (u, v, c) = or [not $ tbl!(v, w, c') | w <- [1..n], let c' = g!(u, w), c' >= c]


Eugeny loves listening to music. He has n songs in his play list. We know that song number i has the duration of ti minutes. Eugeny listens to each song, perhaps more than once. He listens to song number i ci times. Eugeny's play list is organized as follows: first song number 1 plays c1 times, then song number 2 plays c2 times, ..., in the end the song number n plays cn times.Eugeny took a piece of paper and wrote out m moments of time when he liked a song. Now for each such moment he wants to know the number of the song that played at that moment. The moment x means that Eugeny wants to know which song was playing during the x-th minute of his listening to the play list.Help Eugeny and calculate the required numbers of songs.

The first line contains two integers n, m (1 ≤ n, m ≤ 105). The next n lines contain pairs of integers. The i-th line contains integers ci, ti (1 ≤ ci, ti ≤ 109) — the description of the play list. It is guaranteed that the play list's total duration doesn't exceed 109 . The next line contains m positive integers v1, v2, ..., vm, that describe the moments Eugeny has written out. It is guaranteed that there isn't such moment of time vi, when the music doesn't play any longer. It is guaranteed that vi < vi + 1 (i < m). The moment of time vi means that Eugeny wants to know which song was playing during the vi-th munite from the start of listening to the playlist.

Print m integers — the i-th number must equal the number of the song that was playing during the vi-th minute after Eugeny started listening to the play list.

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

readInt :: C.ByteString -> Int
readInt = fst . fromJust . C.readInt

main :: IO ()
main = do
  n <- head <$> readA
  a <- scanl1 (+) <$> replicateM n (product <$> readA)
  b <- readA
  putStr $ unlines $ map show $ gao (zip [(1::Int)..] a) b
  where
    readA = map readInt . C.words <$> C.getLine
    gao [] _ = []
    gao _ [] = []
    gao a@((i,e):t) b@(u:v)
      | u <= e    = i: gao a v
      | otherwise = gao t b

import qualified Data.ByteString.Char8 as B

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

solve :: [[Int]] -> [Int]
solve ([n, m] : xs) = map (fst . head) $ tail $ scanl f ts ms
  where
  (ls, ms : _) = splitAt n xs
  ts = zip [1..] $ scanl1 (+) $ map (foldl1 (*)) ls
  f is@((i, t) : is') m
    | m <= t = is
    | otherwise = f is' m

import Control.Monad

cumsum :: (Num a) => [a] -> [a]
cumsum = cumsum_ 0
    where
        cumsum_ _ [] = []
        cumsum_ a (x:xs) = (x + a):cumsum_ (x + a) xs

outputSongs :: (Num a, Ord a, Show a) => a -> [a] -> [a] -> IO ()
outputSongs _ _ [] = return ()
outputSongs _ [] _ = error ""
outputSongs idx (x:xs) (m:ms) =
    if m <= x then do
        print idx
        outputSongs idx (x:xs) ms
    else
        outputSongs (idx + 1) xs (m:ms)

main :: IO ()
main = do
    [n, _] <- (map read . words) `fmap` getLine
    times <- replicateM n $ do
        [ci, ti] <- (map read . words) `fmap` getLine
        return (ci * ti :: Integer)

    let cumTimes = cumsum times

    ms <- (map read . words) `fmap` getLine
    outputSongs 1 cumTimes ms

import Control.Monad (liftM, replicateM)
import Data.Char (ord)
import Data.List (intercalate)

solve :: [(Int, Int)] -> [Int] -> [Int]
solve as vs =  solve' 1 (zip [1..] as) vs
  where
    solve' _ _ []  =  []
    solve' t ((i, (ci, ti)) : xs) (v:vs)
      | t' <= v  =  solve' t' xs (v:vs)
      | otherwise  =  i : solve' t ((i, (ci, ti)) : xs) vs
      where
        t'  =  t + ci * ti

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

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

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

    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' a' s
          where
            a'  =  10 * a + fromIntegral (ord c - ord '0')

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

main = do
  [n, m] <- getList
  a <- replicateM n getList
  let b = scanl (+) 1 (map (\[c, t] -> c*t) a)
  v <- getList
  mapM (print) (f b v 0 [])
  where
    f _ [] _ acc = reverse acc
    f (b:bs) (v:vs) number acc = if v < b then f (b:bs) vs number (number:acc) else f bs (v:vs) (number+1) acc
    getList = fmap (map (fst . fromJust . C.readInt) . C.words) C.getLine

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

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

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

main :: IO ()
main = do
  [n,m] <- map read.words <$> getLine
  (cts,vs) <- splitAt(2*n).map readInt.B.words <$> B.getContents
  putStr.unlines.map show $ solve cts vs

solve :: [Int] -> [Int] -> [Int]
solve cts vs= go 1 0 cts vs
   where
     go !i !time (c:t:cts) (v:vs)
       | time < v && v <=time + c*t = i : go i time (c:t:cts) vs
       | otherwise = go (i+1) (time+c*t) cts (v:vs)
     go _ _ _ _ = []


There are $$$n$$$ bags with candies, initially the $$$i$$$-th bag contains $$$i$$$ candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: Choose $$$m$$$ such that $$$1 \le m \le 1000$$$Perform $$$m$$$ operations. In the $$$j$$$-th operation, you will pick one bag and add $$$j$$$ candies to all bags apart from the chosen one.Your goal is to find a valid sequence of operations after which all the bags will contain an equal amount of candies. It can be proved that for the given constraints such a sequence always exists.You don't have to minimize $$$m$$$.If there are several valid sequences, you can output any.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of each test case contains one integer $$$n$$$ ($$$2 \le n\le 100$$$).

For each testcase, print two lines with your answer.  In the first line print $$$m$$$ ($$$1\le m \le 1000$$$) — the number of operations you want to take.  In the second line print $$$m$$$ positive integers $$$a_1, a_2, \dots, a_m$$$ ($$$1 \le a_i \le n$$$), where $$$a_j$$$ is the number of bag you chose on the $$$j$$$-th operation.

NoteIn the first case, adding $$$1$$$ candy to all bags except of the second one leads to the arrangement with $$$[2, 2]$$$ candies.In the second case, firstly you use first three operations to add $$$1+2+3=6$$$ candies in total to each bag except of the third one, which gives you $$$[7, 8, 3]$$$. Later, you add $$$4$$$ candies to second and third bag, so you have $$$[7, 12, 7]$$$, and $$$5$$$ candies to first and third bag  — and the result is $$$[12, 12, 12]$$$.

import Control.Arrow ((>>>))

main :: IO ()
main =
  interact $
  words >>>
  drop 1 >>>
  map (read >>> solve >>> showWithLen >>> map show >>> unwords) >>> unlines
  where
    showWithLen xs = length xs : xs

solve :: Int -> [Int]
solve n = [1 .. n]

import Data.List
import System.IO

main :: IO ()
main = do
    input <- getContents
    let output = solve input
    putStr output

solve :: String -> String
solve input = let num_list = map read (words input)
                  t = head num_list
                  n_list = tail num_list
                  ans_list = map (\x -> x:[1..x]) n_list
                  all = foldl (++) [] ans_list
                  all_char = map show all
                  ans = foldl (\x y->x++y++" ") "" all_char
              in ans

solve :: String -> String
solve = concat . map go . tail . words
  where go s = unlines [s, unwords $ map show [1..read s]]

main = interact solve


Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.Recently, she was presented with an array $$$a$$$ of the size of $$$10^9$$$ elements that is filled as follows:   $$$a_1 = -1$$$  $$$a_2 = 2$$$  $$$a_3 = -3$$$  $$$a_4 = 4$$$  $$$a_5 = -5$$$  And so on ... That is, the value of the $$$i$$$-th element of the array $$$a$$$ is calculated using the formula $$$a_i = i \cdot (-1)^i$$$.She immediately came up with $$$q$$$ queries on this array. Each query is described with two numbers: $$$l$$$ and $$$r$$$. The answer to a query is the sum of all the elements of the array at positions from $$$l$$$ to $$$r$$$ inclusive.Margarita really wants to know the answer to each of the requests. She doesn't want to count all this manually, but unfortunately, she couldn't write the program that solves the problem either. She has turned to you — the best programmer.Help her find the answers!

The first line contains a single integer $$$q$$$ ($$$1 \le q \le 10^3$$$) — the number of the queries. Each of the next $$$q$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le 10^9$$$) — the descriptions of the queries.

Print $$$q$$$ lines, each containing one number — the answer to the query.

NoteIn the first query, you need to find the sum of the elements of the array from position $$$1$$$ to position $$$3$$$. The sum is equal to $$$a_1 + a_2 + a_3 = -1 + 2 -3 = -2$$$.In the second query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$5$$$. The sum is equal to $$$a_2 + a_3 + a_4 + a_5 = 2 -3 + 4 - 5 = -2$$$.In the third query, you need to find the sum of the elements of the array from position $$$5$$$ to position $$$5$$$. The sum is equal to $$$a_5 = -5$$$.In the fourth query, you need to find the sum of the elements of the array from position $$$4$$$ to position $$$4$$$. The sum is equal to $$$a_4 = 4$$$.In the fifth query, you need to find the sum of the elements of the array from position $$$2$$$ to position $$$3$$$. The sum is equal to $$$a_2 + a_3 = 2 - 3 = -1$$$.

import           Data.Int

sum' :: Int64 -> Int64
sum' r | r `mod` 2 == 0 = r `div` 2
       | otherwise      = r `div` 2 - r

solve :: IO ()
solve = do
    [l, r] <- map read . words <$> getLine
    print $ sum' r - sum' (l - 1)

ntimes :: Int -> IO () -> IO ()
ntimes 0 _  = return ()
ntimes n io = io >> ntimes (n - 1) io

main :: IO ()
main = do
    t <- readLn
    ntimes t solve

module Main where
import Data.Int
default (Int64)
main = interact exec
exec = unlines . map (\(l, r) -> show $ nsum r - nsum (l - 1)) . pairs . tail . map read . words
nsum n | s <- sgn n = (2 * s * n + s - 1) `quot` 4
pairs (x1:x2:xs) = (x1, x2):pairs xs
pairs _ = []
sgn n | odd n = -1
      | otherwise = 1

f :: Integer->Integer
f n=let a=(n-1) `div` 2
        b=n `div` 2
    in -a*a-2*a-1+b*(b+1)

f2::[String]->[String]
f2 []=[]
f2 (s:str)=let (a:b:[])=map read (words s)::[Integer]
           in (show ((f b)-(f (a-1)))):f2 str

main = do
       e<-getLine
       es<-getContents
       let xs=lines es
       mapM_ putStrLn $ f2 xs

g x = if rem x 2 > 0 then -div (x+1) 2 else div x 2
s [x,y] = g y - g (x-1)

main = interact $ unlines.map(show.s.map read.words).tail.lines


You are given two binary square matrices $$$a$$$ and $$$b$$$ of size $$$n \times n$$$. A matrix is called binary if each of its elements is equal to $$$0$$$ or $$$1$$$. You can do the following operations on the matrix $$$a$$$ arbitrary number of times (0 or more):   vertical xor. You choose the number $$$j$$$ ($$$1 \le j \le n$$$) and for all $$$i$$$ ($$$1 \le i \le n$$$) do the following: $$$a_{i, j} := a_{i, j} \oplus 1$$$ ($$$\oplus$$$ — is the operation xor (exclusive or)).  horizontal xor. You choose the number $$$i$$$ ($$$1 \le i \le n$$$) and for all $$$j$$$ ($$$1 \le j \le n$$$) do the following: $$$a_{i, j} := a_{i, j} \oplus 1$$$. Note that the elements of the $$$a$$$ matrix change after each operation.For example, if $$$n=3$$$ and the matrix $$$a$$$ is: $$$$$$ \begin{pmatrix} 1 & 1 & 0 \\ 0 & 0 & 1 \\ 1 & 1 & 0 \end{pmatrix} $$$$$$ Then the following sequence of operations shows an example of transformations:   vertical xor, $$$j=1$$$. $$$$$$ a= \begin{pmatrix} 0 & 1 & 0 \\ 1 & 0 & 1 \\ 0 & 1 & 0 \end{pmatrix} $$$$$$  horizontal xor, $$$i=2$$$. $$$$$$ a= \begin{pmatrix} 0 & 1 & 0 \\ 0 & 1 & 0 \\ 0 & 1 & 0 \end{pmatrix} $$$$$$  vertical xor, $$$j=2$$$. $$$$$$ a= \begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \end{pmatrix} $$$$$$ Check if there is a sequence of operations such that the matrix $$$a$$$ becomes equal to the matrix $$$b$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the size of the matrices. The following $$$n$$$ lines contain strings of length $$$n$$$, consisting of the characters '0' and '1' — the description of the matrix $$$a$$$. An empty line follows. The following $$$n$$$ lines contain strings of length $$$n$$$, consisting of the characters '0' and '1' — the description of the matrix $$$b$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$1000$$$.

For each test case, output on a separate line:    "YES", there is such a sequence of operations that the matrix $$$a$$$ becomes equal to the matrix $$$b$$$;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

NoteThe first test case is explained in the statements.In the second test case, the following sequence of operations is suitable:   horizontal xor, $$$i=1$$$;  horizontal xor, $$$i=2$$$;  horizontal xor, $$$i=3$$$; It can be proved that there is no sequence of operations in the third test case so that the matrix $$$a$$$ becomes equal to the matrix $$$b$$$.

-- Trying to use only ByteString I/O with a state monad this contest

import Control.Monad
import Control.Monad.Trans.State.Lazy
import qualified Data.ByteString.Lazy.Char8 as P

import Control.Monad.ST
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Bits

newSTUArray :: (Int, Int) -> Bool -> ST s (STUArray s Int Bool)
newSTUArray = newArray

-- How has CRLF not killed me sooner?
getSLine :: Monad m => StateT P.ByteString m P.ByteString
getSLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.tail . snd $ P.break (== '\n') next
  pure out

readInts :: Monad m => StateT P.ByteString m [Int]
readInts = do
  currLine <- getSLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

-- There has to be a combinator for this. But where?
outLine :: P.ByteString -> StateT P.ByteString IO ()
outLine v = StateT $ \s -> ((), s) <$ P.putStrLn v

solve :: Int -> UArray (Int, Int) Bool -> Bool
solve n arr = runST $ do
  rows <- newSTUArray (1, n) False
  cols <- newSTUArray (1, n) False
  let  locs = do { i <- [1..n]; (i, i) : [(i + 1, i) | i < n] }
  forM_ locs $ \(i, j) -> do
    rs <- readArray rows i
    cs <- readArray cols j
    when (arr ! (i, j) `xor` rs `xor` cs) $ if  i == j
      then  writeArray cols j (not cs)
      else  writeArray rows i (not rs)
  fmap and . forM [1..n] $ \i ->
    fmap and . forM [1..n] $ \j -> do
      rs <- readArray rows i
      cs <- readArray cols j
      pure . not $ arr ! (i, j) `xor` rs `xor` cs

main :: IO ()
main = (P.getContents >>=) $ evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n] <- readInts
    a <- replicateM n getSLine
    _ <- getSLine -- empty line!!
    b <- replicateM n getSLine
    let
      delta = uncurry (P.zipWith (/=)) <$> zip a b
      arr :: UArray (Int, Int) Bool
      arr = listArray ((1,1), (n,n)) $ concat delta
      ans = solve n arr
    outLine . P.pack $ if  ans
      then  "YES"
      else  "NO"

-- Trying to use only ByteString I/O with a state monad this contest

import Control.Monad
import Control.Monad.Trans.State.Lazy
import qualified Data.ByteString.Lazy.Char8 as P

import Control.Monad.ST
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Bits

newSTUArray :: (Int, Int) -> Bool -> ST s (STUArray s Int Bool)
newSTUArray = newArray

getSLine :: Monad m => StateT P.ByteString m P.ByteString
getSLine = do
  (out, next) <- P.break (== '\n') <$> get
  put $ P.tail next
  pure out

readInts :: Monad m => StateT P.ByteString m [Int]
readInts = do
  currLine <- getSLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

-- There has to be a combinator for this. But where?
outLine :: P.ByteString -> StateT P.ByteString IO ()
outLine v = StateT $ \s -> ((), s) <$ P.putStrLn v

solve :: Int -> UArray (Int, Int) Bool -> Bool
solve n arr = runST $ do
  rows <- newSTUArray (1, n) False
  cols <- newSTUArray (1, n) False
  let  locs = do { i <- [1..n]; (i, i) : [(i + 1, i) | i < n] }
  forM_ locs $ \(i, j) -> do
    rs <- readArray rows i
    cs <- readArray cols j
    when (arr ! (i, j) `xor` rs `xor` cs) $ if  i == j
      then  writeArray cols j (not cs)
      else  writeArray rows i (not rs)
  fmap and . forM [1..n] $ \i ->
    fmap and . forM [1..n] $ \j -> do
      rs <- readArray rows i
      cs <- readArray cols j
      pure . not $ arr ! (i, j) `xor` rs `xor` cs

main :: IO ()
main = (P.getContents >>=) $ evalStateT $ do
  [t] <- readInts
  replicateM_ t $ do
    [n] <- readInts
    a <- replicateM n getSLine
    _ <- getSLine -- empty line!!
    b <- replicateM n getSLine
    let
      delta = uncurry (P.zipWith (/=)) <$> zip a b
      arr :: UArray (Int, Int) Bool
      arr = listArray ((1,1), (n,n)) $ concat delta
      ans = solve n arr
    outLine . P.pack $ if  ans
      then  "YES"
      else  "NO"


You are given a program that consists of $$$n$$$ instructions. Initially a single variable $$$x$$$ is assigned to $$$0$$$. Afterwards, the instructions are of two types:   increase $$$x$$$ by $$$1$$$;  decrease $$$x$$$ by $$$1$$$. You are given $$$m$$$ queries of the following format:   query $$$l$$$ $$$r$$$ — how many distinct values is $$$x$$$ assigned to if all the instructions between the $$$l$$$-th one and the $$$r$$$-th one inclusive are ignored and the rest are executed without changing the order?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of testcases. Then the description of $$$t$$$ testcases follows. The first line of each testcase contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of instructions in the program and the number of queries. The second line of each testcase contains a program — a string of $$$n$$$ characters: each character is either '+' or '-' — increment and decrement instruction, respectively. Each of the next $$$m$$$ lines contains two integers $$$l$$$ and $$$r$$$ ($$$1 \le l \le r \le n$$$) — the description of the query. The sum of $$$n$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$. The sum of $$$m$$$ over all testcases doesn't exceed $$$2 \cdot 10^5$$$.

For each testcase print $$$m$$$ integers — for each query $$$l$$$, $$$r$$$ print the number of distinct values variable $$$x$$$ is assigned to if all the instructions between the $$$l$$$-th one and the $$$r$$$-th one inclusive are ignored and the rest are executed without changing the order.

NoteThe instructions that remain for each query of the first testcase are:   empty program — $$$x$$$ was only equal to $$$0$$$;  "-" — $$$x$$$ had values $$$0$$$ and $$$-1$$$;  "---+" — $$$x$$$ had values $$$0$$$, $$$-1$$$, $$$-2$$$, $$$-3$$$, $$$-2$$$ — there are $$$4$$$ distinct values among them;  "+--+--+" — the distinct values are $$$1$$$, $$$0$$$, $$$-1$$$, $$$-2$$$.

{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE OverloadedStrings #-}

import           Control.Monad
import qualified Data.Array      as A
import qualified Data.List       as L
import qualified Data.Map.Strict as M
import qualified Data.Set        as S
import           System.IO       (BufferMode (..), hSetBuffering, stdin, stdout)

--
-- UTILITIES
--
import qualified Data.ByteString.Char8 as C8
import           Data.Maybe            (fromJust)

getInt :: IO Int
getInt = parseInt <$> C8.getLine

getInts :: IO [Int]
getInts = parseInts <$> C8.getLine

parseInt :: C8.ByteString -> Int
parseInt = fst . fromJust . C8.readInt

parseInts :: C8.ByteString -> [Int]
parseInts = fmap parseInt . C8.words

getInteger :: IO Integer
getInteger = read <$> getLine

getIntegers :: IO [Integer]
getIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine

--
-- MAIN
--

main :: IO ()
main = do
    hSetBuffering stdin NoBuffering
    hSetBuffering stdout NoBuffering
    input <- C8.getContents
    output <- solveProblem input
    C8.putStrLn output

solveProblem :: C8.ByteString -> IO (C8.ByteString)
solveProblem str = pure $ C8.unlines $ getAns <$> preparedInput
  where
    (_:input) = C8.lines str
    preparedInput = prepareInput input

    getAns :: (C8.ByteString, [(Int, Int)]) -> C8.ByteString
    getAns (prog, ixs) = C8.intercalate "\n" $ C8.pack . show <$> results
      where
        !arrays = buildArrays prog
        !results = (\(l, r) -> solve arrays l r) <$> ixs

prepareInput :: [C8.ByteString] -> [(C8.ByteString, [(Int, Int)])]
prepareInput [] = []
prepareInput (nums:prog:lst) = (prog, (\[x, y] -> (x, y)) . parseInts <$> ixs) : prepareInput rest
  where
    [n, m] = parseInts nums
    (ixs, rest) = L.splitAt m lst

buildArrays :: C8.ByteString -> (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int))
buildArrays str = (left2right, right2left)
  where
    nums = fmap c2n $ C8.unpack str

    c2n :: Char -> Int
    c2n c | c == '+' = 1
          | c == '-' = -1
          | otherwise = 0

    left2right :: A.Array Int (Int, Int, Int)
    left2right = A.listArray (0, length nums) $ L.scanl' minMaxFinal (0, 0, 0) nums
    right2left :: A.Array Int (Int, Int, Int)
    right2left = A.listArray (0, length nums) $ reverse $ L.scanl' minMaxFinal (0, 0, 0) $ reverse $ negate <$> nums

minMaxFinal :: (Int, Int, Int) -> Int -> (Int, Int, Int)
minMaxFinal (oldmin, oldmax, oldfin) n =
    let newfin = oldfin + n
    in (min oldmin newfin, max oldmax newfin, newfin)

solve :: (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int)) -> Int -> Int -> Int
solve (left2right, right2left) l r = ansmax - ansmin + 1
  where
    (lmin, lmax, lfin) = left2right A.! (l - 1)
    (rmin, rmax, rfin) = right2left A.! r

    diff = lfin - rfin
    ansmin = min lmin (rmin + diff)
    ansmax = max lmax (rmax + diff)

{-# LANGUAGE BangPatterns #-}

import           Control.Monad
import qualified Data.Array      as A
import qualified Data.List       as L
import qualified Data.Map.Strict as M
import qualified Data.Set        as S
import System.IO (hSetBuffering, stdin, stdout, BufferMode (..))

--
-- UTILITIES
--
import qualified Data.ByteString.Char8 as C8
import           Data.Maybe            (fromJust)

getInt :: IO Int
getInt = parseInt <$> C8.getLine

getInts :: IO [Int]
getInts = parseInts <$> C8.getLine

parseInt :: C8.ByteString -> Int
parseInt = fst . fromJust . C8.readInt

parseInts :: C8.ByteString -> [Int]
parseInts = fmap parseInt . C8.words

getInteger :: IO Integer
getInteger = read <$> getLine

getIntegers :: IO [Integer]
getIntegers = fmap (fst . fromJust . C8.readInteger) . C8.words <$> C8.getLine

--
-- MAIN
--

main :: IO ()
main = do
    hSetBuffering stdin NoBuffering
    hSetBuffering stdout NoBuffering
    t:input <- C8.lines <$> C8.getContents
    forM_ (prepareInput input) $ \(prog, ixs) -> do
        let !arrays = buildArrays prog
        let results =  (\(l, r) -> solve arrays l r) <$> ixs
        C8.putStr . C8.unlines $ C8.pack . show <$> results

prepareInput :: [C8.ByteString] -> [(C8.ByteString, [(Int, Int)])]
prepareInput [] = []
prepareInput (nums:prog:lst) = (prog, (\[x, y] -> (x, y)) . parseInts <$> ixs) : prepareInput rest
  where
    [n, m] = parseInts nums
    (ixs, rest) = L.splitAt m lst

buildArrays :: C8.ByteString -> (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int))
buildArrays str = (left2right, right2left)
  where
    nums = fmap c2n $ C8.unpack str

    c2n :: Char -> Int
    c2n c | c == '+' = 1
          | c == '-' = -1
          | otherwise = 0

    left2right :: A.Array Int (Int, Int, Int)
    left2right = A.listArray (0, length nums) $ L.scanl' minMaxFinal (0, 0, 0) nums
    right2left :: A.Array Int (Int, Int, Int)
    right2left = A.listArray (0, length nums) $ reverse $ L.scanl' minMaxFinal (0, 0, 0) $ reverse $ negate <$> nums

minMaxFinal :: (Int, Int, Int) -> Int -> (Int, Int, Int)
minMaxFinal (oldmin, oldmax, oldfin) n =
    let newfin = oldfin + n
    in (min oldmin newfin, max oldmax newfin, newfin)

solve :: (A.Array Int (Int, Int, Int), A.Array Int (Int, Int, Int)) -> Int -> Int -> Int
solve (left2right, right2left) l r = ansmax - ansmin + 1
  where
    (lmin, lmax, lfin) = left2right A.! (l - 1)
    (rmin, rmax, rfin) = right2left A.! r

    diff = lfin - rfin
    ansmin = min lmin (rmin + diff)
    ansmax = max lmax (rmax + diff)

{-# LANGUAGE LambdaCase #-}

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

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

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

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

input :: Scanner Input
input = do
  n <- int
  m <- int
  s <- str
  qs <- m >< pair int int
  return (s, qs)

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

solve :: Input -> Output
solve (s, qs) = map query qs
  where
    query (l, r) = max mxl mxr - min mnl mnr + 1
      where
        mxl = preMax ! (l - 1)
        mnl = preMin ! (l - 1)
        delta = (preSum ! (l - 1)) - (preSum ! r)
        mxr = (sufMax ! (r + 1)) + delta
        mnr = (sufMin ! (r + 1)) + delta

    psum = scanl (+) 0 . map conv $ s

    inf = 10^9
    preSum, preMin, sufMin, preMax, sufMax :: UArray Int Int
    preSum = listArray (0, length s) psum
    preMin = listArray (0, length s) $ scanl min inf psum
    preMax = listArray (0, length s) $ scanl max (-inf) psum
    sufMin = listArray (1, length s + 1) $ scanr min inf psum
    sufMax = listArray (1, length s + 1) $ scanr max (-inf) psum

    conv :: Char -> Int
    conv '+' = 1
    conv '-' = -1

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

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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

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

{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE Safe                #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             guard, join, replicateM,
                                             replicateM_)
import qualified Control.Monad.ST.Strict    as ST
import qualified Control.Monad.State.Strict as S
import qualified Data.Array                 as A
import qualified Data.Array.MArray.Safe     as MA
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.Function              (on)
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             intersect, isPrefixOf, nub, sort,
                                             sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           GHC.IO.Handle              (hDuplicateTo)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             openFile, stdin, stdout)
import           Text.Printf                (printf)

-- import Debug.Trace (trace)
-- debug = flip trace

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

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

type Range = (Int, Int)
type CombineFunc a = a -> a -> a
type Instruction = Int
type Program = (Int, Int, Int)

defaultProgram :: (Int, Int, Int)
defaultProgram = (0, 0, 0)

combinePrograms :: Program -> Program -> Program
(aDeltaI, aDeltaL, aDeltaR) `combinePrograms` (bDeltaI, bDeltaL, bDeltaR) = (aDeltaI + bDeltaI, fst resultRange, snd resultRange)
    where
        aRange = (aDeltaL, aDeltaR)
        bRange = (bDeltaL + aDeltaI, bDeltaR + aDeltaI)
        resultRange = ((min `on` fst) aRange bRange, (max `on` snd) aRange bRange)

type ProgramArray = UA.Array Int Program
presolve :: Int -> String -> (ProgramArray, ProgramArray)
presolve n instructionsStr = (prefixes, suffixes)
        -- `debug` ("presolve \n\t" ++ show n ++ "\n\t" ++ show instructions ++ "\n\t" ++ show prefixes ++ "\n\t" ++ show suffixes)
    where
        instructions = map (\c -> if c == '+' then 1 else -1) instructionsStr
        programs = map (\i -> (i, min 0 i, max 0 i)) instructions
        prefixes = UA.listArray (0, n) (scanl combinePrograms defaultProgram programs)
        suffixes = UA.listArray (0, n) (scanr combinePrograms defaultProgram programs)

solve :: (ProgramArray, ProgramArray) -> Range -> Int
solve (prefixes, suffixes) (l, r) = resultR - resultL + 1
    where
        lProgram = prefixes UA.! (l - 1)
        rProgram = suffixes UA.! r
        rangeProgram@(_, resultL, resultR) = lProgram `combinePrograms` rProgram

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [n, q] <- B8.getLine <&> map readIntB8 . B8.words
        s <- B8.getLine <&> head . B8.words <&> B8.unpack
        let preAnswer = presolve n s

        replicateM_ q $ do
            [l, r] <- B8.getLine <&> map readIntB8 . B8.words
            let answer = solve preAnswer (l, r)
            printf "%d\n" answer


Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number of winning squares. To determine if the particular square is winning you should do the following. Calculate the sum of all numbers on the squares that share this column (including the given square) and separately calculate the sum of all numbers on the squares that share this row (including the given square). A square is considered winning if the sum of the column numbers is strictly greater than the sum of the row numbers.For instance, lets game was ended like is shown in the picture. Then the purple cell is winning, because the sum of its column numbers equals 8 + 3 + 6 + 7 = 24, sum of its row numbers equals 9 + 5 + 3 + 2 = 19, and 24 > 19.

The first line contains an integer n (1 ≤ n ≤ 30). Each of the following n lines contain n space-separated integers. The j-th number on the i-th line represents the number on the square that belongs to the j-th column and the i-th row on the board. All number on the board are integers from 1 to 100.

Print the single number — the number of the winning squares.

NoteIn the first example two upper squares are winning.In the third example three left squares in the both middle rows are winning:5 7 8 49 5 3 21 6 6 49 5 7 3

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

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

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

main = do
  n <- readLn
  a <- replicateM n getInts

  let
    ss1 = map sum a
    ss2 = map sum $ transpose a

  print $ length [(s1, s2) | s1 <- ss1, s2 <- ss2, s1 < s2]

import Data.List (transpose, sum)

main = interact $ show . solve . lines where

solve (ns:ss) = cnt where
    n = read ns
    xs = map (map read . take n . words) (take n ss)
    ys = transpose xs
    sx = map sum xs
    sy = map sum ys
    cnt = length [(x, y) | x <- sx, y <- sy, x < y]

--    ghc --make -O Main.hs
import Data.List (transpose)

parse_input :: String -> [[Int]]
parse_input str =
  let strs = lines str
      n = (read::String->Int) $ head $ words $ head strs       -- read n from first line
  in map (map (read::String->Int).words) (take n $ tail strs ) -- read [[Int]] from n next lines

solve :: String -> String
solve in_str =
  let l = parse_input in_str        -- [[Int]] of size n x n
      rSum = map sum l              -- sum by rows
      cSum = map sum $ transpose l  -- sum by columns
  in show $ length $ [True | r <- rSum, c <- cSum, c > r]
  -- show [ (r, c) | r <- rSum, c <- cSum, c > r]

main :: IO ()
main = do interact $ solve

import Array

test :: Array (Int, Int) Int
test = array ((0, 0), (n, n)) ([((0, j), 100) | j <- [0..n]] ++ [((i, j), 1) | i <- [1..n], j <- [0..n]])
  where
    n = 29

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

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

readArray :: Read e => (Int, Int) -> IO (Array (Int, Int) e)
readArray (n, m) = do
    xss <- sequence (replicate n Main.reads)
    return (array ((0, 0), (n-1, m-1))
        [((i, j), xss !! i !! j) | i <- [0..n-1], j <- [0..m-1]])

solve :: Array (Int, Int) Int -> Int
solve a  =  length [(c, r) | c <- sumInCols, r <- sumInRows, c > r]
  where
    ((i0, j0), (i1, j1)) = bounds a
    sumInRows  =  map (\i -> sum (map (\j -> a ! (i, j)) [j0..j1])) [i0..i1]
    sumInCols  =  map (\j -> sum (map (\i -> a ! (i, j)) [i0..i1])) [j0..j1]

main :: IO ()
main  =  do
    n <- readLn
    a <- readArray (n, n)
    print $ solve a

module Main where
main :: IO ()
main = do
    n <- readLn :: IO Int
    let readSquares :: [Int] -> [Int] -> IO ([Int],[Int])
        readSquares rowSums colSums =
            if length rowSums == n
            then do return (rowSums,colSums)
            else do l <- getLine
                    let squares = map (read :: String -> Int) (words l)
                        s = sum squares
                        colSums' = zipWith (+) squares colSums
                    readSquares (s:rowSums) colSums'
    (rowSums, colSums) <- readSquares [] (repeat 0)
    putStrLn (show (sum [1 | rSum <- rowSums, cSum <- colSums, cSum > rSum]))

import Data.Array (listArray, (!))

solve :: [[Int]] -> Int
solve x =
  length $ filter (\[a, b] -> b > a) $ sequence [rowSums, colSums]
  where
    n = length x
    x' = listArray ((1,1), (n, n)) $ concat x
    rowSums = [sum [x' ! (i, j) | j <- [1..n]] | i <- [1..n]] :: [Int]
    colSums = [sum [x' ! (i, j) | i <- [1..n]] | j <- [1..n]] :: [Int]

main = do
  putStrLn . show . solve . map (map read . words) . tail . lines =<< getContents

import Data.List
import Data.Char
import Control.Monad
main = do
  n <- readLn
  g <- replicateM n $ fmap (map read . words) getLine
  let a = map sum g
      b = map sum $ transpose g
      k = [1 | a1 <- a, b1 <- b, a1 < b1]
      in print $ length k

import Data.List
import Control.Monad
main = do
  n <- readLn
  g <- replicateM n $ fmap (map read . words) getLine
  let rs = map sum g
      cs = foldr1 (zipWith (+)) g
  print $ length [ () | r <- rs, c <- cs, c > r ]

import Control.Applicative
import Data.List

main = do
    n <- read <$> getLine
    table <- mapM (\_ -> map read . words <$> getLine) [1..n]
    print $ winnerCount table

winnerCount :: [[Int]] -> Int
winnerCount tbl = length $ filter (isWinner tbl) possibleCoords
    where possibleCoords = [(x, y) | x <- [0..length tbl-1], y <- [0..length tbl-1]]

isWinner :: [[Int]] -> (Int, Int) -> Bool
isWinner tbl (x, y) = sumVertical > sumHorizontal
    where sumVertical = sum $ (transpose tbl) !! x
          sumHorizontal = sum $ tbl !! y

import Data.List
import Control.Applicative

main = getLine >> do
  ss <- map (map read . words) . lines <$> getContents
  print $ solve ss

solve :: [[Int]] -> Int
solve ss = length [(x,y) | x<-xs, y<-ys, x<y]
   where xs = map sum ss
         ys = map sum $ transpose ss

import Data.List ( transpose )

main = do
    input <- getContents
    let process = putStrLn . show . winningSquares
    mapM_ process $ readLines $ lines input

readLines :: [String] -> [[[Int]]]
readLines [] = []
readLines input = (cases $ take numLines rest):(readLines $ drop numLines rest)
    where
        numLines = (read $ head input)::Int
        rest = tail input

cases :: [String] -> [[Int]]
cases [] = []
cases (x:xs) = list:cases xs
    where
        list = (map read $ words x)::[Int]

winningSquares :: [[Int]] -> Int
winningSquares board = countSquares board 0 0
    where
        lines = map sum board
        columns = map sum (transpose board)

        countSquares :: [[Int]] -> Int -> Int -> Int
        countSquares [] _ _ = 0
        countSquares ([]:ys) i j = countSquares ys (i+1) 0
        countSquares ((x:xs):ys) i j
            | columnSum > lineSum = 1 + rec
            | otherwise           = rec
            where
                columnSum = columns !! j
                lineSum = lines !! i
                rec = countSquares (xs:ys) i (j+1)

import List
m=map sum
s t=length[0|a<-m t,b<-m$transpose t,b>a]
main=interact$show.s.map(map read.words).tail.lines

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

main :: IO ()
main = do
	nn <- getLine
	inp <- getContents
	let
		n = read nn :: Int
		arr1 = map (\x -> map(\x -> read x :: Int). words $ x). lines $ inp
		arr2 = transpose arr1
		s = sum [if sum (arr1 !! i) < sum (arr2 !! j) then 1 else 0 | i <- [0..n-1], j <- [0..n-1]]
	print s

import Data.List
main = do
    s <- getLine
    let n = read s
    c <- getContents
    let ns = take n $ map (\x -> map read $ words x) $ lines c
    print $ sum.map (\z -> f z (n-1) ns (transpose ns) 0) $ [0..(n-1)]
f z (-1) ns ns' acc = acc
f z n ns ns' acc
    |((sum $ (ns')!!z) > (sum $ ns!!n)) = f z (n-1) ns ns' (acc+1)
    | True = f z (n-1) ns ns' acc

import Data.List
import Control.Monad

sums :: [[Int]] -> [Int]
sums = map sum

solve :: [[Int]] -> Int
solve l =
    let rows = sums l
        cols = sums $ transpose l
    in
      sum [if x < y then 1 else 0 | x <- rows, y <- cols]

main = do
  n <- getLine >>= (return . (read::String->Int))
  rows <- forM [1..n] (\_ -> getLine >>= (return . map (read::String->Int) . words))
  print $ solve rows

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

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

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

main = do
  n <- readLn
  a <- replicateM n getInts

  let
    ss1 = map sum a
    ss2 = map sum $ transpose a

  print $ length [(s1, s2) | s1 <- ss1, s2 <- ss2, s1 > s2]

import Data.List (transpose)

parse_input :: String -> [[Int]]
parse_input str = tail $ map (map (read::String->Int).words) (lines str)

solve :: String -> String
solve in_str =
  let l = parse_input in_str
      r = map sum l              -- sum by rows
      c = map sum $ transpose l  -- sum by columns
      in show $ length $ [1::Int | rSum <- r, cSum <- c, rSum > cSum]

main :: IO ()
main = do interact $ solve

import Array

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

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

readArray :: Read e => (Int, Int) -> IO (Array (Int, Int) e)
readArray (n, m) = do
    xss <- sequence (replicate n Main.reads)
    return (array ((0, 0), (n-1, m-1))
        [((i, j), xss !! i !! j) | i <- [0..n-1], j <- [0..m-1]])

solve :: Array (Int, Int) Int -> Int
solve a  =  length [(c, r) | c <- sumInCols, r <- sumInRows, c > r]
  where
    ((i0, j0), (i1, j1)) = bounds a
    sumInCols  =  map (\i -> sum (map (\j -> a ! (i, j)) [j0..j1])) [j0..j1]
    sumInRows  =  map (\j -> sum (map (\i -> a ! (i, j)) [i0..i1])) [j0..j1]

main :: IO ()
main  =  do
    n <- readLn
    a <- readArray (n, n)
    print $ solve a

import Data.List
import Data.Char
import Control.Monad
main = do
  n <- readLn
  g <- replicateM n $ fmap (map read . words) getLine
  let a = map sum g
      b = map sum $ transpose g
      k = [1 | a1 <- a, b1 <- b, a1 > b1]
      in print $ length k

import Data.List
import Control.Applicative

main = getLine >> do
  ss <- map (map read . words) . lines <$> getContents
  print $ solve ss

solve :: [[Int]] -> Int
solve ss = length [(x,y) | x<-xs, y<-ys, x<y]
   where ys = map sum ss
         xs = map sum $ transpose ss

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

main :: IO ()
main = do
	nn <- getLine
	inp <- getContents
	let
		n = read nn :: Int
		arr1 = map (\x -> map(\x -> read x :: Int). words $ x). lines $ inp
		arr2 = transpose arr1
		s = sum [if sum (arr1 !! i) > sum (arr2 !! j) then 1 else 0 | i <- [0..n-1], j <- [0..n-1]]
	print s

import Data.List
import Control.Monad

sums :: [[Int]] -> [Int]
sums = map sum

solve :: [[Int]] -> Int
solve l =
    let rows = sums l
        cols = sums $ transpose l
    in
      sum [if x > y then 1 else 0 | x <- rows, y <- cols]

main = do
  n <- getLine >>= (return . (read::String->Int))
  rows <- forM [1..n] (\_ -> getLine >>= (return . map (read::String->Int) . words))
  print $ solve rows