Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix.The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is defined as the sum of n dot products. The i-th of them is the dot product of the i-th row vector and the i-th column vector in the matrix A.Fortunately for Chris, he has to work only in GF(2)! This means that all operations (addition, multiplication) are calculated modulo 2. In fact, the matrix A is binary: each element of A is either 0 or 1. For example, consider the following matrix A:  The unusual square of A is equal to (1·1 + 1·0 + 1·1) + (0·1 + 1·1 + 1·0) + (1·1 + 0·1 + 0·0) = 0 + 1 + 1 = 0.However, there is much more to the homework. Chris has to process q queries; each query can be one of the following:   given a row index i, flip all the values in the i-th row in A;  given a column index i, flip all the values in the i-th column in A;  find the unusual square of A. To flip a bit value w means to change it to 1 - w, i.e., 1 changes to 0 and 0 changes to 1.Given the initial matrix A, output the answers for each query of the third type! Can you solve Chris's homework?

The first line of input contains an integer n (1 ≤ n ≤ 1000), the number of rows and the number of columns in the matrix A. The next n lines describe the matrix: the i-th line contains n space-separated bits and describes the i-th row of A. The j-th number of the i-th line aij (0 ≤ aij ≤ 1) is the element on the intersection of the i-th row and the j-th column of A. The next line of input contains an integer q (1 ≤ q ≤ 106), the number of queries. Each of the next q lines describes a single query, which can be one of the following:    1 i — flip the values of the i-th row;  2 i — flip the values of the i-th column;  3 — output the unusual square of A.  Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.

Let the number of the 3rd type queries in the input be m. Output a single string s of length m, where the i-th symbol of s is the value of the unusual square of A for the i-th query of the 3rd type as it appears in the input.

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

import Control.Monad (replicateM,forM_,forM,foldM_)
import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Data.List (foldl')
import System.IO (hFlush,stdout)
import Data.Char (isDigit,isSpace)

readDiagonal :: Int -> IO [Bool]
readDiagonal n = do
  forM [0..n-1] $ \i -> do
    line <- BS.getLine
    let ws = BS.words line
    return $ (ws !! i) == "1"

readDiagonal' :: Int -> IO [Bool]
readDiagonal' n = do
  forM [0..n-1] $ \i -> do
    line <- BS.getLine
    let ind = BS.findIndices isDigit line
    let ch = BS.index line (ind !! i)
    return $ ch == '1'

nthWord :: Int -> ByteString -> Maybe Int
nthWord n bs = skip 0 >>= go n
  where
    len = BS.length bs
    skip :: Int -> Maybe Int -- skip spaces
    skip k = if isSpace (BS.index bs k)
               then if k+1 < len then skip (k+1) else Nothing
               else Just k
    skip' :: Int -> Maybe Int -- skip non-spaces
    skip' k = if not (isSpace (BS.index bs k))
                then if k+1 < len then skip (k+1) else Nothing
                else Just k
    go 0  !k = Just k
    go !n !k = skip' k >>= go (n-1)

readDiagonal'' :: Int -> IO [Bool]
readDiagonal'' n = do
  forM [0..n-1] $ \i -> do
    line <- BS.getLine
    let Just ind = nthWord i line
    let ch = BS.index line ind
    return $ ch == '1'

xor :: Bool -> Bool -> Bool
xor True False = True
xor False True = True
xor _ _        = False

(-->) = flip fmap

main = do
  n <- getLine --> read :: IO Int
  diag <- readDiagonal'' n
  let sq = foldl' xor False diag

  q <- getLine --> read :: IO Int

  let doit !sq' i = do
        if i `mod` 1000 == 0
          then hFlush stdout
          else return ()
        line <- BS.getLine
        if BS.null line
          then return sq'
          else case BS.head line of
                '1' -> return $ not sq'
                '2' -> return $ not sq'
                '3' -> do putChar $ if sq' then '1' else '0'
                          return sq'
                _   -> return sq'
  foldM_ doit sq [1..q]
  BS.putStrLn ""

{-# LANGUAGE BangPatterns #-}

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

import Control.Exception

bool :: a -> a -> Bool -> a
bool t f b=if b then t else f

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

main = catch main_ (\err ->print (err :: SomeException))

main_ = do
  n <- readLn
  diag <- forM [0..n-1] $ \i -> do
    b <- ('1'==).flip B.index (2*i) <$> B.getLine
    return $! b
  _ <- getLine
  qs <- map readInt.B.words <$> B.getContents
  putStrLn . map (bool '1' '0') $ solve (foldl' (/=) False diag) qs

solve :: Bool -> [Int] -> [Bool]
solve !res (3:qs) = res : solve res qs
solve !res (_:_:qs) = solve (res /= True) qs
solve _ _ = []

{-# LANGUAGE BangPatterns #-}
import Data.Bits (xor)
import Data.Word (Word8)
import Data.Maybe (fromJust)
import Data.Foldable (foldl')
import Control.Applicative ((<$>))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Control.Monad (sequence, replicateM)

solve :: [[Word8]] -> [[Word8]] -> [Word8]
solve a q = val `seq` foldr loop (`seq` []) (map head q) (val, 0)
    where
    !val = foldl' xor 0 $ zipWith (!!) a [0..]

    loop x f (i, j)
        | x == 3 = i' `seq` i':f (i', 0)
        | otherwise = j' `seq` f (i, j `xor` 1)
        where
        !i' = i `xor` j
        !j' = j `xor` 1

parse :: Num a => ByteString -> [a]
parse line = fromIntegral . fst . fromJust . C.readInt <$> C.words line

main = do
    [n] <- parse <$> B.getLine
    a <- fmap parse <$> replicateM n B.getLine
    [m] <- parse <$> B.getLine
    q <- fmap parse <$> replicateM m B.getLine
    mapM_ (putStr . show) $ solve a q

{-# LANGUAGE BangPatterns #-}
import Data.List (transpose)
import Data.Bits ((.&.), xor)
import Data.Word (Word8)
import Data.Maybe (fromJust)
import Data.Foldable (foldl')
import Control.Applicative ((<$>))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Control.Monad (sequence, replicateM)

solve :: [[Word8]] -> [[Word8]] -> [Word8]
solve a q = val `seq` foldr loop (`seq` []) (map head q) (val, 0)
    where
    !val = foldl' xor 0 . concat $ zipWith (zipWith (.&.)) a (transpose a)

    loop x f (i, j)
        | x == 3 = i' `seq` i':f (i', 0)
        | otherwise = j' `seq` f (i, j `xor` 1)
        where
        !i' = i `xor` j
        !j' = j `xor` 1

parse :: Num a => ByteString -> [a]
parse line = fromIntegral . fst . fromJust . C.readInt <$> C.words line

main = do
    [n] <- parse <$> B.getLine
    a <- fmap parse <$> replicateM n B.getLine
    [m] <- parse <$> B.getLine
    q <- fmap parse <$> replicateM m B.getLine
    mapM_ (putStr . show) $ solve a q

{-# LANGUAGE BangPatterns #-}
import Data.Bits (xor)
import Data.Word (Word8)
import Data.Maybe (fromJust)
import Data.Foldable (foldl')
import Control.Applicative ((<$>))
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Control.Monad (sequence, replicateM)

solve :: [[Word8]] -> [[Word8]] -> [Word8]
solve a q = val `seq` foldr loop (`seq` []) (map head q) (val, 0)
    where
    !val = foldl' xor 0 . map head $ zipWith drop [0..] a

    loop x f (i, j)
        | x == 3 = i' `seq` i':f (i', 0)
        | otherwise = j' `seq` f (i, j `xor` 1)
        where
        !i' = i `xor` j
        !j' = j `xor` 1

parse :: Num a => ByteString -> [a]
parse line = fromIntegral . fst . fromJust . C.readInt <$> C.words line

main = do
    [n] <- parse <$> B.getLine
    a <- fmap parse <$> replicateM n B.getLine
    [m] <- parse <$> B.getLine
    q <- fmap parse <$> replicateM m B.getLine
    mapM_ (putStr . show) $ solve a q

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

import Control.Exception

bool :: a -> a -> Bool -> a
bool t f b=if b then t else f

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

main = catch main_ (\err ->print (err :: SomeException))

main_ = do
  n <- readLn
  diag <- forM [0..n-1] $ \i -> do
    b <- ('1'==).flip B.index (2*i) <$> B.getLine
    return $! b
  _ <- getLine
  qs <- map readInt.B.words <$> B.getContents
  putStrLn . map (bool '1' '0') $ solve (foldl' (/=) False diag) qs

solve :: Bool -> [Int] -> [Bool]
solve res (3:qs) = res : solve res qs
solve res (_:_:qs) = solve (res /= True) qs
solve _ _ = []


The mobile application store has a new game called "Subway Roller".The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmost column. Some number of trains rides towards the hero. Each train consists of two or more neighbouring cells in some row of the field.All trains are moving from right to left at a speed of two cells per second, and the hero runs from left to right at the speed of one cell per second. For simplicity, the game is implemented so that the hero and the trains move in turns. First, the hero moves one cell to the right, then one square up or down, or stays idle. Then all the trains move twice simultaneously one cell to the left. Thus, in one move, Philip definitely makes a move to the right and can move up or down. If at any point, Philip is in the same cell with a train, he loses. If the train reaches the left column, it continues to move as before, leaving the tunnel.Your task is to answer the question whether there is a sequence of movements of Philip, such that he would be able to get to the rightmost column.

Each test contains from one to ten sets of the input data. The first line of the test contains a single integer t (1 ≤ t ≤ 10 for pretests and tests or t = 1 for hacks; see the Notes section for details) — the number of sets. Then follows the description of t sets of the input data.  The first line of the description of each set contains two integers n, k (2 ≤ n ≤ 100, 1 ≤ k ≤ 26) — the number of columns on the field and the number of trains. Each of the following three lines contains the sequence of n character, representing the row of the field where the game is on. Philip's initial position is marked as 's', he is in the leftmost column. Each of the k trains is marked by some sequence of identical uppercase letters of the English alphabet, located in one line. Distinct trains are represented by distinct letters. Character '.' represents an empty cell, that is, the cell that doesn't contain either Philip or the trains.

For each set of the input data print on a single line word YES, if it is possible to win the game and word NO otherwise.

NoteIn the first set of the input of the first sample Philip must first go forward and go down to the third row of the field, then go only forward, then go forward and climb to the second row, go forward again and go up to the first row. After that way no train blocks Philip's path, so he can go straight to the end of the tunnel.Note that in this problem the challenges are restricted to tests that contain only one testset.

import qualified Data.List as L
answer::[Int] -> Int -> [String] -> Int -> Bool
answer [] j ds n = False
answer is j d@(d0:d1:d2:ds) n | j<n = answer (L.nub [nexti|i<- is,nexti<-[i-1,i,i+1],isok0 i j nexti d]) (j+3) ds n
                              | otherwise = True
answer is j ds n = (null [nexti|i<- is,nexti<-[i-1,i,i+1],isok0 i j nexti ds]) == False

isok0::Int -> Int -> Int -> [String] -> Bool
isok0 i j nexti [] = True
isok0 i j nexti (d0:d1:d2:ds) = 0 <= nexti && nexti < 3 && (d0 !! i)=='.' && (d0 !! nexti) == '.' && (d1 !! nexti) == '.' && (d2 !! nexti) == '.'
isok0 i j nexti (d0:d1:ds) = 0 <= nexti && nexti < 3 && (d0 !! i)=='.' && (d0 !! nexti) == '.' && (d1 !! nexti) == '.'
isok0 i j nexti (d0:ds) = 0 <= nexti && nexti < 3 && (d0 !! i)=='.' && (d0 !! nexti) == '.'
trans [[],[],[]] = []
trans a = (map head a):(trans (map tail a))
readInput 0 = return []
readInput n = do
  w0 <- getLine
  next <- readInput (n-1)
  return (w0:next)
execTest 0 = return ()
execTest t = do
  w0 <- getLine
  let [n,k] = [read n::Int|n<-(words w0)]
  d <- readInput 3
  let dt = trans d
  let h = head dt
  let Just i = L.elemIndex 's' h
  let res=answer [i] 0 (tail dt) n
  putStrLn $ if res then "YES" else "NO"
  execTest (t-1)
main=do
  w0 <- getLine
  let t = read w0::Int
  execTest t

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

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

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

solve = do
  [n, _] <- map read . words <$> getLine
  a <- replicateM 3 getLine

  bs :: IOUArray (Int, Int) Bool <- newArray ((1, 1), (3, n)) False

  let
    aa :: UArray (Int, Int) Char = listArray ((1, 1), (3, n)) $ concat a

    dfs (i, j)
      | j >= n = return True
      | otherwise = do
      b <- readArray bs (i, j)
      if not b
        then do
          writeArray bs (i, j) True

          if j > n || aa!(i, j+1) /= '.'
            then return False
            else
              or <$> (forM [max (i-1) 1..min (i+1) 3] $ \i ->
                if all (== '.') [aa!(i, j) | j <- [j+1..j+3], j <= n]
                  then dfs (i, j+3)
                  else return False)

        else
          return False

  let si = (fromJust $ elemIndex 's' $ map (!!0) a) + 1
  r <- dfs (si, 1)

  putStrLn $ if r then "YES" else "NO"

main = do
  t <- readLn
  replicateM t solve


Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato.Vanya has n pieces of potato, the height of the i-th piece is equal to ai. He puts them in the food processor one by one starting from the piece number 1 and finishing with piece number n. Formally, each second the following happens:  If there is at least one piece of potato remaining, Vanya puts them in the processor one by one, until there is not enough space for the next piece.  Processor smashes k centimeters of potato (or just everything that is inside). Provided the information about the parameter of the food processor and the size of each potato in a row, compute how long will it take for all the potato to become smashed.

The first line of the input contains integers n, h and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ h ≤ 109) — the number of pieces of potato, the height of the food processor and the amount of potato being smashed each second, respectively. The second line contains n integers ai (1 ≤ ai ≤ h) — the heights of the pieces.

Print a single integer — the number of seconds required to smash all the potatoes following the process described in the problem statement.

NoteConsider the first sample.   First Vanya puts the piece of potato of height 5 into processor. At the end of the second there is only amount of height 2 remaining inside.  Now Vanya puts the piece of potato of height 4. At the end of the second there is amount of height 3 remaining.  Vanya puts the piece of height 3 inside and again there are only 3 centimeters remaining at the end of this second.  Vanya finally puts the pieces of height 2 and 1 inside. At the end of the second the height of potato in the processor is equal to 3.  During this second processor finally smashes all the remaining potato and the process finishes. In the second sample, Vanya puts the piece of height 5 inside and waits for 2 seconds while it is completely smashed. Then he repeats the same process for 4 other pieces. The total time is equal to 2·5 = 10 seconds.In the third sample, Vanya simply puts all the potato inside the processor and waits 2 seconds.

import Data.Functor

main :: IO()
main = do
    let readInts = map read . words
    [n, h, k] <- readInts <$> getLine
    a <- readInts <$> getLine
    print $ solve h k a 0

solve :: Integer -> Integer -> [Integer] -> Integer -> Integer
solve _ k []    m = (m + k - 1) `div` k
solve h k (a:s) m | m + a <= h = solve h k s (m + a)
                  | otherwise = let x = (a + m - h + k - 1) `div` k
                                in x + solve h k (a:s) (max 0 (m - k * x))

import Control.Monad
import Control.Applicative

main = do
  [_, h, k] <- map read . words <$> getLine
  as <- map read . words <$> getLine
  print $ solve h k as

solve :: Integer -> Integer -> [Integer] -> Integer
solve h k [a0] = (a0 + k - 1) `div` k
solve h k (a0:(a1:as)) =
    if a0 `mod` k + a1 <= h
    then (a0 + a1) `div` k + solve h k (((a0 + a1) `mod` k):as)
    else (a0 + k - 1) `div` k + solve h k (a1:as)

import Control.Applicative( (<$>))
main = do
    tokens <- return . words =<< getContents
    let n:capacity:lengthPerSec:hights = read <$> tokens
	sendfull buf [] = (buf,[])
	sendfull buf (p:ps) = if buf+p <= capacity
				then sendfull (buf+p) ps
				else (buf,p:ps)
	smash buf = buf `divMod` lengthPerSec
	process::(Int,[Int]) -> Integer -> Integer
	process (0,[]) sec = sec
	process (buf,potatoes) sec = process (sendfull potatoRest potatoes) (sec+toInteger timeplus)
	    where
		(times, pmod) = smash buf
		judge = times == 0 && pmod /= 0
		timeplus = if judge then 1 else times
		potatoRest = if judge then 0 else pmod
    print $ process (0,take n hights) 0

import Control.Monad
import Control.Applicative

main = do
  [_, h, k] <- map read . words <$> getLine
  as <- map read . words <$> getLine
  print $ solve h k as

solve :: Int -> Int -> [Int] -> Int
solve h k [a0] = (a0 + k - 1) `div` k
solve h k (a0:(a1:as)) =
    if a0 `mod` k + a1 <= h
    then (a0 + a1) `div` k +  solve h k (((a0 + a1) `mod` k):as)
    else (a0 + k - 1) `div` k + solve h k (a1:as)

import Control.Applicative( (<$>))
main = do
    tokens <- return . words =<< getContents
    let n:capacity:lengthPerSec:hights = read <$> tokens
	sendfull buf [] = (buf,[])
	sendfull buf (p:ps) = if buf+p <= capacity
				then sendfull (buf+p) ps
				else (buf,p:ps)
	smash buf = buf `divMod` lengthPerSec
	process (0,[]) sec = sec
	process (buf,potatoes) sec = process (sendfull potatoRest potatoes) (sec+timeplus)
	    where
		(times, pmod) = smash buf
		judge = times == 0 && pmod /= 0
		timeplus = if judge then 1 else times
		potatoRest = if judge then 0 else pmod
    print $ process (0,take n hights) 0


Sereja is a coder and he likes to take part in Codesorfes rounds. However, Uzhland doesn't have good internet connection, so Sereja sometimes skips rounds.Codesorfes has rounds of two types: Div1 (for advanced coders) and Div2 (for beginner coders). Two rounds, Div1 and Div2, can go simultaneously, (Div1 round cannot be held without Div2) in all other cases the rounds don't overlap in time. Each round has a unique identifier — a positive integer. The rounds are sequentially (without gaps) numbered with identifiers by the starting time of the round. The identifiers of rounds that are run simultaneously are different by one, also the identifier of the Div1 round is always greater.Sereja is a beginner coder, so he can take part only in rounds of Div2 type. At the moment he is taking part in a Div2 round, its identifier equals to x. Sereja remembers very well that he has taken part in exactly k rounds before this round. Also, he remembers all identifiers of the rounds he has taken part in and all identifiers of the rounds that went simultaneously with them. Sereja doesn't remember anything about the rounds he missed.Sereja is wondering: what minimum and what maximum number of Div2 rounds could he have missed? Help him find these two numbers.

The first line contains two integers: x (1 ≤ x ≤ 4000) — the round Sereja is taking part in today, and k (0 ≤ k < 4000) — the number of rounds he took part in. Next k lines contain the descriptions of the rounds that Sereja took part in before. If Sereja took part in one of two simultaneous rounds, the corresponding line looks like: "1 num2 num1" (where num2 is the identifier of this Div2 round, num1 is the identifier of the Div1 round). It is guaranteed that num1 - num2 = 1. If Sereja took part in a usual Div2 round, then the corresponding line looks like: "2 num" (where num is the identifier of this Div2 round). It is guaranteed that the identifiers of all given rounds are less than x.

Print in a single line two integers — the minimum and the maximum number of rounds that Sereja could have missed.

NoteIn the second sample we have unused identifiers of rounds 1, 6, 7. The minimum number of rounds Sereja could have missed equals to 2. In this case, the round with the identifier 1 will be a usual Div2 round and the round with identifier 6 will be synchronous with the Div1 round. The maximum number of rounds equals 3. In this case all unused identifiers belong to usual Div2 rounds.

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

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

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i
    where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
inf = maxBound `div` 2 :: Int

main = do
    (x,k) <- readIntPair
    l <- concat . map tail <$> replicateM k readInts
    let unused = S.toList $ S.fromList [1..x-1] S.\\ S.fromList l
        maxM = length unused
        minM = go unused
        go (a:b:l) | a + 1 == b = 1 + go l
        go (a:l) = 1 + go l
        go [] = 0
    putStrLn $ unwords $ map show $ [minM,maxM]

{-# LANGUAGE BangPatterns #-}
import Data.List
main=interact$unwords.map show.f.map read.words
f(x:k:xs)=[go 0 ys, length ys]
   where
     ys = unused [1..x-1] $ sort $ parse xs
     go !res (x:y:xs)
       | x+1==y = go (res+1) xs
       | otherwise = go (res+1) (y:xs)
     go res [x] = res+1
     go res [] = res

unused (x:xs) (y:ys)
  | x == y = unused xs ys
  | x < y = x : unused xs (y:ys)
unused xs _ = xs

parse (1:x:y:xs) = x : y : parse xs
parse (2:x:xs) = x : parse xs
parse _ = []

import Data.List
main = interact$f.map read.words
f (a:b:xs) = (show $foldl (\acc x-> acc + div (x+1) 2) 0 list) ++ " " ++ (show $ sum list)
	where list = map length $ groupBy (\a b->b-a==1)$ [1..(a-1)] \\ (g xs)
g [] = []
g (1:a:b:xs) = [a, b] ++ (g xs)
g (2:a:xs) = a:(g xs)


The Little Elephant enjoys recursive functions.This time he enjoys the sorting function. Let a is a permutation of an integers from 1 to n, inclusive, and ai denotes the i-th element of the permutation. The Little Elephant's recursive function f(x), that sorts the first x permutation's elements, works as follows:  If x = 1, exit the function.  Otherwise, call f(x - 1), and then make swap(ax - 1, ax) (swap the x-th and (x - 1)-th elements of a). The Little Elephant's teacher believes that this function does not work correctly. But that-be do not get an F, the Little Elephant wants to show the performance of its function. Help him, find a permutation of numbers from 1 to n, such that after performing the Little Elephant's function (that is call f(n)), the permutation will be sorted in ascending order.

A single line contains integer n (1 ≤ n ≤ 1000) — the size of permutation.

In a single line print n distinct integers from 1 to n — the required permutation. Numbers in a line should be separated by spaces. It is guaranteed that the answer exists.

main :: IO ()
main = do str <- getLine
          let n = read str
          putStrLn . unwords . map show $ n:[1..(n-1)]

import Data.List (intercalate)

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

main :: IO ()
main  =  do
    n  <-  readLn
    prints $ n : [1 .. (n-1)]

import Control.Applicative

main :: IO ()
main = do
  n <- read <$> getLine
  putStrLn $ unwords $ map show $ n:[1..n-1]

main = interact $ (++ "\n") . unwords . map show . (\n -> n:[1..n-1]) . read . head . lines

main :: IO ()
main = readLn >>= putStrLn . unwords . map show . solve

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

main = do
  n <- readLn
  putStrLn $ unwords $ map show $ n : [1..n-1]

import Data.List

main :: IO ()
main = do
  n <- readLn
  putStrLn $ intercalate " "
           $ map show
           $ (if n == 1 then (1 :) else ([n, 1] ++)) [2..n-1]

import qualified Data.List as L

main :: IO()
main = do
	(w:ws) <- words `fmap` getContents
	putStrLn $ L.foldl' (\s num-> s ++ (show num) ++ " ") "" $ readInt(w):[1..((readInt(w))-1)]

readInt :: String -> Int
readInt = read

calc :: Int -> [Int]
calc 1 = [1]
calc 2 = [2, 1]
calc n = [n, 1] ++ [2..n-1]

main = do s <- getLine
          putStrLn $ unwords $ map show $ calc $ read s

import Data.List

work n = intercalate " " (map show (n : [1 .. n - 1]))

main = do
	line <- getLine
	putStrLn(work (read line :: Int))

import Control.Applicative
import Data.List

main= do
 	x<-read <$> getLine
	putStrLn $ unwords $ map show (x:[1..(x-1)])

main = getLine >>= mapM_ (\x -> putStr (show x ++ " ")). (\x -> x:[1..(x-1)]). (\x -> read x :: Int) . head. words

main=(shw.slv.read=<<getLine) >> putStrLn ""
slv :: Int -> [Int]
slv n = n:[1..n-1]
shw xs=mapM_ (\c->putStr(' ':show c)) $ xs

main = interact $ (++ "\n") . unwords . map show . reverse . (\n -> [1..n]) . read . head . lines

main = do
  n <- readLn
  putStrLn $ unwords $ map show $ [n,1..n-1]

import Data.List

main :: IO ()
main = do
  n <- readLn
  putStrLn $ intercalate " "
           $ map show
           $ [2..n] ++ [1]

import Data.Array
import Data.List

f :: Int -> Array Int Int -> Array Int Int
f 1 arr = arr
f x arr = arr' // [(x, arr' ! (x - 1)), (x - 1, arr' ! x)]
  where arr' = f (x - 1) arr

(|>) :: a -> (a -> b) -> b
x |> f = f x
infixl 0 |>

main :: IO ()
main = do
  n <- readLn
  listArray (1, n) [1..n]
    |> f n
    |> elems
    |> map show
    |> intercalate " "
    |> putStrLn

import Data.List

main :: IO ()
main = do
  n <- readLn
  putStrLn $ intercalate " "
           $ map show
           $ n : 1 : [2..n-1]

import qualified Data.List as L

main :: IO()
main = do
	(w:ws) <- words `fmap` getContents
	putStrLn $ L.foldl' (\s num-> s ++ (show num) ++ " ") "" $ [2..(readInt w)] ++ [1]

readInt :: String -> Int
readInt = read

calc :: Int -> [Int]
calc n = [2..n] ++ [1]

main = do s <- getLine
          putStrLn $ unwords $ map show $ calc $ read s


This is the easy version of the problem. The only difference is that in this version $$$n \leq 2000$$$. You can make hacks only if both versions of the problem are solved.There are $$$n$$$ potions in a line, with potion $$$1$$$ on the far left and potion $$$n$$$ on the far right. Each potion will increase your health by $$$a_i$$$ when drunk. $$$a_i$$$ can be negative, meaning that potion will decrease will health.You start with $$$0$$$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.What is the largest number of potions you can drink?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 2000$$$) — the number of potions.  The next line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, ... ,$$$a_n$$$ ($$$-10^9 \leq a_i \leq 10^9$$$) which represent the change in health after drinking that potion.

Output a single integer, the maximum number of potions you can drink without your health becoming negative.

NoteFor the sample, you can drink $$$5$$$ potions by taking potions $$$1$$$, $$$3$$$, $$$4$$$, $$$5$$$ and $$$6$$$. It is not possible to drink all $$$6$$$ potions because your health will go negative at some point

import Data.Maybe
import Data.Int
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import qualified Data.IntMap.Strict as IM
import System.IO

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

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = do
  _ <- getInts
  as <- getInts
  let (result, _, _) = foldl' acc (0, 0, IM.empty) as
      acc :: (Int, Int64, IM.IntMap Int) -> Int -> (Int, Int64, IM.IntMap Int)
      acc (num, hp, mp) a
        | a >= 0 = (num + 1, hp + fromIntegral a, mp)
        | hp + fromIntegral a < 0 = (num, hp', IM.alter dec a' mp')
        | otherwise = (num + 1, hp + fromIntegral a, IM.alter inc a mp)
        where Just (a', _) = IM.lookupMin mp'
              mp' = IM.alter inc a mp
              hp' = hp + fromIntegral a - fromIntegral a'
              inc Nothing = Just 1
              inc (Just x) = Just (x + 1)
              dec Nothing = Nothing
              dec (Just 1) = Nothing
              dec (Just x) = Just (x - 1)
  hPutBuilder stdout $ intDec result `mappend` charUtf8 '\n'

import Data.Int (Int64)
import qualified Data.Set as S

main = do
    n <- read <$> getLine
    a <- map read . words <$> getLine
    print $ solve S.empty 0 $ zip a [1..n]

solve :: S.Set (Int64, Int) -> Int64 -> [(Int64, Int)] -> Int
solve s h [] = S.size s
solve s h (x:xs)
    | h' >= 0 = solve s' h' xs
    | otherwise =
        let (y, s'') = S.deleteFindMin s'
         in solve s'' (h' - fst y) xs
  where
    s' = S.insert x s
    h' = h + fst x

import Data.Maybe
import Data.Int
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import qualified Data.IntMap.Strict as IM
import System.IO

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

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = do
  _ <- getInts
  as <- getInts
  let (result, _, _) = foldl' acc (0, 0, IM.empty) as
      acc :: (Int, Int64, IM.IntMap Int) -> Int -> (Int, Int64, IM.IntMap Int)
      acc (num, hp, mp) a
        | a >= 0 = (num + 1, hp + fromIntegral a, mp)
        | hp + fromIntegral a < 0 = (num, hp', IM.alter dec a' mp')
        | otherwise = (num + 1, hp + fromIntegral a, IM.alter inc a mp)
        where Just ((a', _), mp') = IM.minViewWithKey $ IM.alter inc a mp
              hp' = hp + fromIntegral a - fromIntegral a'
              inc Nothing = Just 1
              inc (Just x) = Just (x + 1)
              dec Nothing = Nothing
              dec (Just 1) = Nothing
              dec (Just x) = Just (x - 1)
  hPutBuilder stdout $ intDec result `mappend` charUtf8 '\n'

import Data.Maybe
import Data.Int
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import qualified Data.IntSet as IS
import System.IO

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

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = do
  _ <- getInts
  as <- getInts
  let (result, _, _) = foldl' acc (0, 0, IS.empty) as
      acc :: (Int64, Int64, IS.IntSet) -> Int -> (Int64, Int64, IS.IntSet)
      acc (num, hp, set) a
        | a >= 0 = (num + 1, hp + fromIntegral a, set)
        | hp + fromIntegral a < 0 = (num, hp', set')
        | otherwise = (num + 1, hp + fromIntegral a, IS.insert a set)
        where Just (a', set') = IS.minView $ IS.insert a set
              hp' = hp + fromIntegral a - fromIntegral a'
  hPutBuilder stdout $ int64Dec result `mappend` charUtf8 '\n'

import Data.Int (Int64)
import qualified Data.Set as S

main = do
    _ <- getLine
    a <- map read . words <$> getLine
    print $ solve S.empty 0 a

solve :: S.Set Int64 -> Int64 -> [Int64] -> Int
solve s h [] = 0
solve s h (x:xs)
    | h' >= 0 = 1 + solve s' h' xs
    | otherwise =
        let (y, s'') = S.deleteFindMin s'
         in solve s'' (h' - y) xs
  where
    s' = S.insert x s
    h' = h + x


Vasya is currently at a car rental service, and he wants to reach cinema. The film he has bought a ticket for starts in t minutes. There is a straight road of length s from the service to the cinema. Let's introduce a coordinate system so that the car rental service is at the point 0, and the cinema is at the point s.There are k gas stations along the road, and at each of them you can fill a car with any amount of fuel for free! Consider that this operation doesn't take any time, i.e. is carried out instantly.There are n cars in the rental service, i-th of them is characterized with two integers ci and vi — the price of this car rent and the capacity of its fuel tank in liters. It's not allowed to fuel a car with more fuel than its tank capacity vi. All cars are completely fueled at the car rental service.Each of the cars can be driven in one of two speed modes: normal or accelerated. In the normal mode a car covers 1 kilometer in 2 minutes, and consumes 1 liter of fuel. In the accelerated mode a car covers 1 kilometer in 1 minutes, but consumes 2 liters of fuel. The driving mode can be changed at any moment and any number of times.Your task is to choose a car with minimum price such that Vasya can reach the cinema before the show starts, i.e. not later than in t minutes. Assume that all cars are completely fueled initially.

The first line contains four positive integers n, k, s and t (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 2·105, 2 ≤ s ≤ 109, 1 ≤ t ≤ 2·109) — the number of cars at the car rental service, the number of gas stations along the road, the length of the road and the time in which the film starts.  Each of the next n lines contains two positive integers ci and vi (1 ≤ ci, vi ≤ 109) — the price of the i-th car and its fuel tank capacity. The next line contains k distinct integers g1, g2, ..., gk (1 ≤ gi ≤ s - 1) — the positions of the gas stations on the road in arbitrary order.

Print the minimum rent price of an appropriate car, i.e. such car that Vasya will be able to reach the cinema before the film starts (not later than in t minutes). If there is no appropriate car, print -1.

NoteIn the first sample, Vasya can reach the cinema in time using the first or the third cars, but it would be cheaper to choose the first one. Its price is equal to 10, and the capacity of its fuel tank is 8. Then Vasya can drive to the first gas station in the accelerated mode in 3 minutes, spending 6 liters of fuel. After that he can full the tank and cover 2 kilometers in the normal mode in 4 minutes, spending 2 liters of fuel. Finally, he drives in the accelerated mode covering the remaining 3 kilometers in 3 minutes and spending 6 liters of fuel.

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

import           Control.Applicative
import           Control.Monad
import           Control.Monad.State.Strict
import           Data.Array.Unboxed
import           Data.Bits
import           Data.Bool
import qualified Data.ByteString.Char8      as B
import           Data.Char
import           Data.Function
import           Data.Int
import qualified Data.IntMap.Strict         as IM
import qualified Data.IntSet                as IS
import           Data.List
import           Data.List.Split
import qualified Data.Map.Strict            as M
import           Data.Monoid
import           Data.Ord
import qualified Data.Set                   as S
import           Data.Tuple
import           Data.Word

readInt :: B.ByteString -> Int
readInt bs=case B.readInt bs of{Just(n,_)->n;_->error$"readInt error : bs = "++show bs;}
readInteger :: B.ByteString -> Integer
readInteger bs=case B.readInteger bs of{Just(n,_)->n;_->error$"readInteger error : bs = "++show bs;}

lowerBound :: (Integral i) => i -> i -> (i -> Bool) -> i
lowerBound low high p = go low high
  where
    go !low !high
        | high <= low = high
        | p mid       = go low       mid
        | otherwise   = go (mid + 1) high
      where
        mid = (low + high) `quot` 2

main :: IO ()
main = do
    [n,k,s,t] <- map read.words <$> getLine
    (cvs, gs) <- splitAt(2*n).map readInt.B.words <$> B.getContents
    print . maybe (-1) id $ solve s t (parse cvs) $ sort gs

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

solve :: Int -> Int -> [(Int, Int)] -> [Int] -> Maybe Int
solve s t cvs gs
  | isValid maxV = Just $ minimum . map fst $ filter ((>=needV).snd) cvs
  | otherwise = Nothing
  where
    maxV = maximum $ map snd cvs
    needV = lowerBound 0 maxV isValid
    isValid :: Int -> Bool
    isValid v = go 0 0 $ gs ++ [s]
      where
        go !cur !time (g:rest)
          | d > v = False
          | otherwise = go g (time + t') rest
          where
            d = g - cur
            r = min d $ v - d
            t' = 2 * (max 0 $ d - r) + r
        go _ !time [] = time <= t


Consider the decimal presentation of an integer. Let's call a number d-magic if digit d appears in decimal presentation of the number on even positions and nowhere else.For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic, 34 is 4-magic and 71 is 1-magic.Find the number of d-magic numbers in the segment [a, b] that are multiple of m. Because the answer can be very huge you should only find its value modulo 109 + 7 (so you should find the remainder after dividing by 109 + 7).

The first line contains two integers m, d (1 ≤ m ≤ 2000, 0 ≤ d ≤ 9) — the parameters from the problem statement. The second line contains positive integer a in decimal presentation (without leading zeroes). The third line contains positive integer b in decimal presentation (without leading zeroes). It is guaranteed that a ≤ b, the number of digits in a and b are the same and don't exceed 2000.

Print the only integer a — the remainder after dividing by 109 + 7 of the number of d-magic numbers in segment [a, b] that are multiple of m.

NoteThe numbers from the answer of the first example are 16, 26, 36, 46, 56, 76, 86 and 96.The numbers from the answer of the second example are 2, 4, 6 and 8.The numbers from the answer of the third example are 1767, 2717, 5757, 6707, 8797 and 9747.

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

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM_, mapM)
import Data.Array.IArray (listArray, (!))
import Data.Array.MArray.Safe (newArray, readArray, writeArray)
import Data.Array.ST.Safe (runSTUArray)
import Data.Array.Unboxed (UArray)
import Data.List (foldl')
import Data.Char (ord)

modulo :: Int
modulo = 10^9+7

a +. b = let c = a + b in if c >= modulo then c - modulo else c

a -. b = a +. (modulo - b)

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `mod` m) 1 :: UArray Int Int

    prev j d i = (j - d*ps!i `mod` m + m) `mod` m

    cs :: UArray (Int, Int) Int
    cs = runSTUArray $ do
      a <- newArray ((0, 0), (n, m-1)) 0
      writeArray a (0, 0) 1

      forM_ [1..n] $ \i ->
        forM_ [0..m-1] $ \j ->
          let
            ds = if odd n == odd i then filter (/= d) [0..9] else [d]
            f' d = readArray a (i-1, j') where j' = prev j d (i-1)
          in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)

      return a

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f _ _ [] = 0
        f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) +. (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = match && r == 0
      where
        ds = map (\c -> ord c - 48) s
        match = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
        r = foldl1 (\a b -> (a + b) `mod` m) $ zipWith (\x i -> x*ps!(n-i) `mod` m) ds [1..]

  -- print cs
  -- print $ check b
  print $ count b -. count a +. (if check b then 1 else 0)

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

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM_, mapM)
import Data.Array.IArray (listArray, (!))
import Data.Array.MArray.Safe (newArray, readArray, writeArray)
import Data.Array.ST.Safe (runSTUArray)
import Data.Array.Unboxed (UArray)
import Data.List (foldl')
import Data.Char (ord)

remulo :: Int
remulo = 10^9+7

a +. b = let c = a + b in if c >= remulo then c - remulo else c

a -. b = a +. (remulo - b)

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    mplus a b = let c = a+b in if c >= m then c-m else c
    mminus a b = a `mplus` (m-b)
    mmul a b = a*b `rem` m

    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `rem` m) 1 :: UArray Int Int

    prev j d i = j `mminus` (d `mmul` (ps!i))

    cs :: UArray (Int, Int) Int
    cs = runSTUArray $ do
      a <- newArray ((0, 0), (n, m-1)) 0
      writeArray a (0, 0) 1

      forM_ [1..n] $ \i -> forM_ [0..m-1] $ \j ->
        let
          ds = if odd n == odd i then filter (/= d) [0..9] else [d]
          f' d = readArray a (i-1, j') where j' = prev j d (i-1)
        in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)

      return a

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f _ _ [] = 0
        f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) +. (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = match && r == 0
      where
        ds = map (\c -> ord c - 48) s
        match = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
        r = foldl1 mplus $ zipWith (\x i -> x `mmul` (ps!(n-i))) ds [1..]

  print $ count b -. count a +. (if check b then 1 else 0)

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

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM_, mapM)
import Data.Array.IArray (listArray, (!))
import Data.Array.MArray.Safe (newArray, readArray, writeArray)
import Data.Array.ST.Safe (runSTUArray)
import Data.Array.Unboxed (UArray)
import Data.List (foldl')
import Data.Char (ord)

remulo :: Int
remulo = 10^9+7

a +. b = if c >= remulo then c - remulo else c where c = a+b
a -. b = a +. (remulo - b)

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    mplus a b = if c >= m then c-m else c where c = a+b
    mminus a b = a `mplus` (m-b)
    mmul a b = a*b `rem` m

    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `rem` m) 1 :: UArray Int Int

    prev j d i = j `mminus` (d `mmul` (ps!i))

    cs :: UArray (Int, Int) Int
    cs = runSTUArray $ do
      a <- newArray ((0, 0), (n, m-1)) 0
      writeArray a (0, 0) 1

      forM_ [1..n] $ \i -> forM_ [0..m-1] $ \j ->
        let
          ds = if odd n == odd i then filter (/= d) [0..9] else [d]
          f' d = readArray a (i-1, j') where j' = prev j d (i-1)
        in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)

      return a

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f _ _ [] = 0
        f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) +. (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = match && r == 0
      where
        ds = map (\c -> ord c - 48) s
        match = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
        r = foldl1 mplus $ zipWith (\x i -> x `mmul` (ps!(n-i))) ds [1..]

  print $ count b -. count a +. (if check b then 1 else 0)

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

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM_, mapM)
import Data.Array.IArray (listArray, (!))
import Data.Array.MArray.Safe (newArray, readArray, writeArray)
import Data.Array.ST.Safe (runSTUArray)
import Data.Array.Unboxed (UArray)
import Data.List (foldl')
import Data.Char (ord)

modulo :: Int
modulo = 10^9+7

a +. b = let c = a + b in if c >= modulo then c - modulo else c

a -. b = a +. (modulo - b)

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    mplus a b = let c = a+b in if c >= m then c-m else c
    mminus a b = a `mplus` (m-b)
    mmul a b = a*b `mod` m

    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `mod` m) 1 :: UArray Int Int

    prev j d i = j `mminus` (d `mmul` (ps!i))

    cs :: UArray (Int, Int) Int
    cs = runSTUArray $ do
      a <- newArray ((0, 0), (n, m-1)) 0
      writeArray a (0, 0) 1

      forM_ [1..n] $ \i -> forM_ [0..m-1] $ \j ->
        let
          ds = if odd n == odd i then filter (/= d) [0..9] else [d]
          f' d = readArray a (i-1, j') where j' = prev j d (i-1)
        in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)

      return a

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f _ _ [] = 0
        f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) +. (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = match && r == 0
      where
        ds = map (\c -> ord c - 48) s
        match = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
        r = foldl1 mplus $ zipWith (\x i -> x `mmul` (ps!(n-i))) ds [1..]

  print $ count b -. count a +. (if check b then 1 else 0)

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

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM_, mapM)
import Data.Array (Array)
import Data.Array.IArray (listArray, (!))
import Data.Array.MArray.Safe (newArray, readArray, writeArray)
import Data.Array.ST.Safe (runSTUArray, runSTArray)
import Data.Array.Unboxed (UArray)
import Data.List (foldl')
import Data.Char (ord)

modulo :: Int
modulo = 10^9+7

a +. b = if c >= modulo then c - modulo else c where c = a+b
a -. b = a +. (modulo - b)

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    mplus a b = if c >= m then c-m else c where c = a+b
    mminus a b = a `mplus` (m-b)
    mmul a b = a*b `mod` m

    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `mod` m) 1 :: UArray Int Int

    prev j d i = j `mminus` (d `mmul` (ps!i))

    -- cs :: UArray (Int, Int) Int
    cs = runSTUArray $ do
      a <- newArray ((0, 0), (n, m-1)) 0
      writeArray a (0, 0) 1

      forM_ [1..n] $ \i -> forM_ [0..m-1] $ \j ->
        let
          ds = if odd n == odd i then filter (/= d) [0..9] else [d]
          f' d = readArray a (i-1, j') where j' = prev j d (i-1)
        in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)

      return a

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f _ _ [] = 0
        f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) +. (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = match && r == 0
      where
        ds = map (\c -> ord c - 48) s
        match = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
        r = foldl1 mplus $ zipWith (\x i -> x `mmul` (ps!(n-i))) ds [1..]

  print $ count b -. count a +. (if check b then 1 else 0)

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

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM_, mapM)
import Data.Array.IArray (listArray, (!))
import Data.Array.MArray.Safe (newArray, readArray, writeArray)
import Data.Array.ST.Safe (runSTUArray)
import Data.Array.Unboxed (UArray)
import Data.List (foldl')
import Data.Char (ord)

modulo :: Int
modulo = 10^9+7

a +. b = let c = a + b in if c >= modulo then c - modulo else c

a -. b = a +. (modulo - b)

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `mod` m) 1 :: UArray Int Int

    prev j d i = (j - d*ps!i `mod` m + m) `mod` m

    cs :: UArray (Int, Int) Int
    cs = runSTUArray $ do
      a <- newArray ((0, 0), (n, m-1)) 0
      writeArray a (0, 0) 1

      forM_ [1..n] $ \i ->
        forM_ [0..m-1] $ \j ->
          let
            ds = if odd n == odd i then filter (/= d) [0..9] else [d]
            f' d = readArray a (i-1, j') where j' = prev j d (i-1)
          in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)

      return a

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f _ _ [] = 0
        f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = match && r == 0
      where
        ds = map (\c -> ord c - 48) s
        match = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
        r = foldl1 (\a b -> (a + b) `mod` m) $ zipWith (\x i -> x*ps!i `mod` m) ds [1..]

  -- print cs
  print $ count b -. count a +. (if check b then 1 else 0)

import Control.Applicative ((<$>), (<*>))
import Data.Array (listArray, (!))
import Data.Int (Int64)
import Data.Char (ord)

newtype MInt = MInt Int64

modulo :: Int64
modulo = 10^9+7

instance Num MInt where
  MInt a + MInt b = let c = a + b in MInt $ if c >= modulo then c - modulo else c
  MInt a * MInt b = MInt $ a * b `mod` modulo
  negate (MInt a) = MInt $ modulo - a
  abs = id
  signum (MInt a) = if a == 0 then 0 else 1
  fromInteger a = MInt $ fromInteger $ a `mod` toInteger modulo

instance Show MInt where show (MInt a) = show a

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `mod` m) 1

    prev j d i = (j - d*ps!i `mod` m + m) `mod` m

    cs = listArray ((0, 0), (n, m-1)) $ map (uncurry f) $ ((,) <$> [0..n] <*> [0..m-1])
      where
        f :: Int -> Int -> MInt
        f 0 0 = 1
        f 0 _ = 0
        f i j = sum $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]
          where f' d = cs!(i-1, j') where j' = prev j d (i-1)

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f :: Int -> Int -> [Int] -> MInt
        f _ _ [] = 0 :: MInt
        f i j (x:xs) = (sum $ map f' ds) + (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
      where
        ds = map (\c -> ord c - 48) s

  print $ count b - count a + (if check b then 1 else 0)

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

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM_, mapM)
import Control.Monad.ST.Safe (ST)
import Data.Array (Array)
import Data.Array.IArray (listArray, (!))
import Data.Array.MArray.Safe (newArray, readArray, writeArray)
import Data.Array.ST.Safe (runSTUArray, STUArray)
import Data.Array.Unboxed (UArray)
import Data.Int (Int64)
import Data.List (foldl')
import Data.Char (ord)

modulo :: Int64
modulo = 10^9+7

a +. b = let c = a + b in if c >= modulo then c - modulo else c
a *. b = a * b `mod` modulo

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `mod` m) 1 :: UArray Int Int

    prev j d i = (j - d*ps!i `mod` m + m) `mod` m

    cs = runSTUArray $ do
      a <- newArray ((0, 0), (n, m-1)) 0 :: ST s (STUArray s (Int, Int) Int64)
      writeArray a (0, 0) 1

      forM_ [1..n] $ \i ->
        forM_ [0..m-1] $ \j ->
          let
            ds = if odd n == odd i then filter (/= d) [0..9] else [d]
            f' d = readArray a (i-1, j') where j' = prev j d (i-1)
          in (sum <$> mapM f' ds) >>= writeArray a (i, j)

      return a

    -- cs = listArray ((0, 0), (n, m-1)) $ map (f) $ ((,) <$> [0..n] <*> [0..m-1]) :: Array (Int, Int) Int64
    --   where
    --     f (0, 0) = 1
    --     f (0, _) = 0
    --     f (i, j) = foldl' (+.) 0 $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]
    --       where f' d = cs!(i-1, j') where j' = prev j d (i-1)

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f :: Int -> Int -> [Int] -> Int64
        f _ _ [] = 0
        f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = match && r == 0
      where
        ds = map (\c -> ord c - 48) s
        match = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
        r = foldl1 (\a b -> (a + b) `mod` m) $ zipWith (\x i -> x*ps!(i-1) `mod` m) ds [1..]

  -- print cs
  print $ count b - count a + (if check b then 1 else 0)

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

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM_, mapM)
import Data.Array.IArray (listArray, (!))
import Data.Array.MArray.Safe (newArray, readArray, writeArray)
import Data.Array.ST.Safe (runSTUArray)
import Data.Array.Unboxed (UArray)
import Data.List (foldl')
import Data.Char (ord)

modulo :: Int
modulo = 10^9+7

a +. b = let c = a + b in if c >= modulo then c - modulo else c

a -. b = a +. (modulo - b)

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `mod` m) 1 :: UArray Int Int

    prev j d i = (j - d*ps!i `mod` m + m) `mod` m

    cs :: UArray (Int, Int) Int
    cs = runSTUArray $ do
      a <- newArray ((0, 0), (n, m-1)) 0
      writeArray a (0, 0) 1

      forM_ [1..n] $ \i ->
        forM_ [0..m-1] $ \j ->
          let
            ds = if odd n == odd i then filter (/= d) [0..9] else [d]
            f' d = readArray a (i-1, j') where j' = prev j d (i-1)
          in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)

      return a

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f _ _ [] = 0
        f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = match && r == 0
      where
        ds = map (\c -> ord c - 48) s
        match = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
        r = foldl1 (\a b -> (a + b) `mod` m) $ zipWith (\x i -> x*ps!(n-i) `mod` m) ds [1..]

  -- print cs
  -- print $ check b
  print $ count b -. count a +. (if check b then 1 else 0)

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

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM_, mapM)
import Control.Monad.ST.Safe (ST)
import Data.Array (Array)
import Data.Array.IArray (listArray, (!))
import Data.Array.MArray.Safe (newArray, readArray, writeArray)
import Data.Array.ST.Safe (runSTUArray, STUArray)
import Data.Array.Unboxed (UArray)
import Data.Int (Int64)
import Data.List (foldl')
import Data.Char (ord)

modulo :: Int64
modulo = 10^9+7

a +. b = let c = a + b in if c >= modulo then c - modulo else c
a -. b = let c = modulo + a - b in if c >= modulo then c- modulo else c

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `mod` m) 1 :: UArray Int Int

    prev j d i = (j - d*ps!i `mod` m + m) `mod` m

    cs = runSTUArray $ do
      a <- newArray ((0, 0), (n, m-1)) 0 :: ST s (STUArray s (Int, Int) Int64)
      writeArray a (0, 0) 1

      forM_ [1..n] $ \i ->
        forM_ [0..m-1] $ \j ->
          let
            ds = if odd n == odd i then filter (/= d) [0..9] else [d]
            f' d = readArray a (i-1, j') where j' = prev j d (i-1)
          in (sum <$> mapM f' ds) >>= writeArray a (i, j)

      return a

    -- cs = listArray ((0, 0), (n, m-1)) $ map (f) $ ((,) <$> [0..n] <*> [0..m-1]) :: Array (Int, Int) Int64
    --   where
    --     f (0, 0) = 1
    --     f (0, _) = 0
    --     f (i, j) = foldl' (+.) 0 $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]
    --       where f' d = cs!(i-1, j') where j' = prev j d (i-1)

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f :: Int -> Int -> [Int] -> Int64
        f _ _ [] = 0
        f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = match && r == 0
      where
        ds = map (\c -> ord c - 48) s
        match = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
        r = foldl1 (\a b -> (a + b) `mod` m) $ zipWith (\x i -> x*ps!(i-1) `mod` m) ds [1..]

  -- print cs
  print $ count b -. count a +. (if check b then 1 else 0)

import Control.Applicative ((<$>), (<*>))
import Data.Array (listArray, (!))
import Data.Int (Int64)
import Data.Char (ord)

newtype MInt = MInt Int64

modulo :: Int64
modulo = 10^9+7

instance Num MInt where
  MInt a + MInt b = let c = a + b in MInt $ if c >= modulo then c - modulo else c
  MInt a * MInt b = MInt $ a * b `mod` modulo
  negate (MInt a) = MInt $ modulo - a
  abs = id
  signum (MInt a) = if a == 0 then 0 else 1
  fromInteger a = MInt $ fromInteger $ a `mod` toInteger modulo

instance Show MInt where show (MInt a) = show a

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `mod` m) 1

    prev j d i = (j - d*ps!i `mod` m + m) `mod` m

    cs = listArray ((0, 0), (n, m-1)) $ map (uncurry f) $ ((,) <$> [0..n] <*> [0..m-1])
      where
        f :: Int -> Int -> MInt
        f 0 0 = 1
        f 0 _ = 0
        f i j = sum $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]
          where f' d = cs!(i-1, j') where j' = prev j d (i-1)

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f :: Int -> Int -> [Int] -> MInt
        f _ _ [] = 0 :: MInt
        f i j (x:xs) = (sum $ map f' ds) + (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = and $ zipWith (\x i -> if odd i then x == d else x /= d) ds [1..]
      where
        ds = map (\c -> ord c - 48) s

  print $ count b - count a + (if check b then 1 else 0)

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

import Control.Applicative ((<$>), (<*>))
import Control.Monad (forM_, mapM)
import Data.Array.IArray (listArray, (!))
import Data.Array.MArray.Safe (newArray, readArray, writeArray)
import Data.Array.ST.Safe (runSTUArray)
import Data.Array.Unboxed (UArray)
import Data.List (foldl')
import Data.Char (ord)

modulo :: Int
modulo = 10^9+7

a +. b = let c = a + b in if c >= modulo then c - modulo else c

a -. b = a +. (modulo - b)

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `mod` m) 1 :: UArray Int Int

    prev j d i = (j - d*ps!i `mod` m + m) `mod` m

    cs :: UArray (Int, Int) Int
    cs = runSTUArray $ do
      a <- newArray ((0, 0), (n, m-1)) 0
      writeArray a (0, 0) 1

      forM_ [1..n] $ \i ->
        forM_ [0..m-1] $ \j ->
          let
            ds = if odd n == odd i then filter (/= d) [0..9] else [d]
            f' d = readArray a (i-1, j') where j' = prev j d (i-1)
          in (foldl (+.) 0 <$> mapM f' ds) >>= writeArray a (i, j)

      return a

    -- cs = listArray ((0, 0), (n, m-1)) $ map (f) $ ((,) <$> [0..n] <*> [0..m-1]) :: Array (Int, Int) Int64
    --   where
    --     f (0, 0) = 1
    --     f (0, _) = 0
    --     f (i, j) = foldl' (+.) 0 $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]
    --       where f' d = cs!(i-1, j') where j' = prev j d (i-1)

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f _ _ [] = 0
        f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = match && r == 0
      where
        ds = map (\c -> ord c - 48) s
        match = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
        r = foldl1 (\a b -> (a + b) `mod` m) $ zipWith (\x i -> x*ps!(i-1) `mod` m) ds [1..]

  -- print cs
  print $ count b -. count a +. (if check b then 1 else 0)

{-# OPTIONS_GHC -O2 #-}

import Control.Applicative ((<$>), (<*>))
import Data.Array (Array)
import Data.Array.IArray (listArray, (!))
import Data.Array.Unboxed (UArray)
import Data.Int (Int64)
import Data.List (foldl')
import Data.Char (ord)

modulo :: Int64
modulo = 10^9+7

a +. b = let c = a + b in if c >= modulo then c - modulo else c
a *. b = a * b `mod` modulo

main = do
  [m, d] <- map read . words <$> getLine
  a <- getLine
  b <- getLine

  let
    n = length a

    ps = listArray (0, n) $ iterate (\x -> x*10 `mod` m) 1 :: UArray Int Int

    prev j d i = (j - d*ps!i `mod` m + m) `mod` m

    cs = listArray ((0, 0), (n, m-1)) $ map (uncurry f) $ ((,) <$> [0..n] <*> [0..m-1]) :: Array (Int, Int) Int64
      where
        f :: Int -> Int -> Int64
        f 0 0 = 1
        f 0 _ = 0
        f i j = foldl' (+.) 0 $ map f' $ if odd n == odd i then filter (/= d) [0..9] else [d]
          where f' d = cs!(i-1, j') where j' = prev j d (i-1)

    count s = f 1 0 ds
      where
        ds = map (\c -> ord c - 48) s

        f :: Int -> Int -> [Int] -> Int64
        f _ _ [] = 0
        f i j (x:xs) = (foldl' (+.) 0 $ map f' ds) + (if b then f (i+1) j' xs else 0)
          where
            ds
              | i == 1 = filter (/= d) [1..x-1]
              | odd i = filter (/=d) [0..x-1]
              | even i = filter (== d) [0..x-1]

            f' d = cs!(n-i, j') where j' = prev j d (n-i)

            b = if odd i then x /= d else d == x
            j' = prev j x (n-i)

    check s = match && r == 0
      where
        ds = map (\c -> ord c - 48) s
        match = and $ zipWith (\x i -> if odd i then x /= d else x == d) ds [1..]
        r = foldl1 (\a b -> (a + b) `mod` m) $ zipWith (\x i -> x*ps!(i-1) `mod` m) ds [1..]

  print cs
  print $ count b - count a + (if check b then 1 else 0)


You are given a string $$$s$$$ of length $$$n$$$ consisting only of the characters 0 and 1.You perform the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue the remaining two parts together (any of them can be empty) in the same order. For example, if you erase the substring 111 from the string 111110, you will get the string 110. When you delete a substring of length $$$l$$$, you get $$$a \cdot l + b$$$ points.Your task is to calculate the maximum number of points that you can score in total, if you have to make the given string empty.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains three integers $$$n$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n \le 100; -100 \le a, b \le 100$$$) — the length of the string $$$s$$$ and the parameters $$$a$$$ and $$$b$$$. The second line contains the string $$$s$$$. The string $$$s$$$ consists only of the characters 0 and 1.

For each testcase, print a single integer — the maximum number of points that you can score.

NoteIn the first example, it is enough to delete the entire string, then we will get $$$2 \cdot 3 + 0 = 6$$$ points.In the second example, if we delete characters one by one, then for each deleted character we will get $$$(-2) \cdot 1 + 5 = 3$$$ points, i. e. $$$15$$$ points in total.In the third example, we can delete the substring 00 from the string 100111, we get $$$1 \cdot 2 + (-4) = -2$$$ points, and the string will be equal to 1111, removing it entirely we get $$$1 \cdot 4 + (-4) = 0$$$ points. In total, we got $$$-2$$$ points for $$$2$$$ operations.

count :: Integer -> Integer ->Integer -> String -> Integer
count n a b string
    | b >= 0 = (a + b) * n
    | otherwise = (((flips string) `div` 2) + ((flips string) `mod` 2) + 1)* b + n * a -- for deleting the first prefix
        where
            flips:: String -> Integer
            flips [] = 0
            flips [_] = 0
            flips (x:(y:xs))
                | x == y = flips (y:xs)
                | otherwise = flips (y:xs) + 1

main = do
    int <- getLine
    let t = read int::Integer
    repeat t
        where
            repeat 0 = return ()
            repeat m = do
                nab <- getLine
                let arr = map (\a -> read a::Integer) $ words nab
                string <- getLine
                print $ count (arr!!0) (arr!!1) (arr!!2) string
                repeat $ m - 1

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

solve :: IO ()
solve = do
    [n, a, b] <- readMany :: IO [Int]
    s <- getLine
    let oneByOne = n * (a + b)
        g = length $ group s
        greedy = a * n + b * (g `div` 2 + 1)
    print $ if b < 0 then greedy else oneByOne

readMany :: Read a => IO [a]
readMany = map read . words <$> getLine

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

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as C
import Data.List (group)
import Data.Maybe (fromJust, fromMaybe)

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

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

testCase :: Scanner Int
testCase = do
  nab <- three int
  s <- C.unpack <$> str
  return $ solve nab s

solve [n, a, b] s
  | b >= 0 = n * (a + b)
  | otherwise = n * a + m * b
  where
    g = length $ group s
    m = 1 + (g `div` 2)

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

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

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

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

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

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

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

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

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

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

(><) = times

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

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

{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Prelude as P
import Data.List as L
import Data.Int (Int64)
import Data.Bits as B
import System.IO as Io
--import Data.Char as C
--import Data.IntSet as S

cnt :: String -> Int -> Char -> Int
cnt [] k _ = div k 2 + 1
cnt (x:xs) k ch
  | x == ch = cnt xs k x
  | otherwise = cnt xs (k+1) x

solve :: IO ()
solve = do
  s_ <- getLine
  s <- getLine
  let [n,a,b] = map read $ words s_ :: [Int]
      total = (if b >= 0 then n * (a + b) else
                  n*a + (cnt s 0 '2')*b)
    in print total

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

import Control.Monad

count = sum . map fromEnum

main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [n, a, b] <- map read . words <$> getLine
    s <- getLine
    let len = length s
    print $ a * len + b * if b >= 0
                             then len
                             else (1 + count (zipWith (/=) s (tail s))) `div` 2 + 1

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

solve [x] = 1
solve (x:xs) = solve xs + if x /= head xs then 1 else 0

printResult = do
    [n,a,b] <- readInts
    s <- getLine
    if b > 0 then print $ n*(a+b)
    else do
        let r = solve s
        print $ n * a + (div r 2 + 1) * b

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

count :: Integer -> Integer ->Integer -> String -> Integer
count n a b string
    | b >= 0 = (a + b) * n
    | otherwise = (((flips string) `div` 2) + ((flips string) `mod` 2)) * b + n * a
        where
            flips:: String -> Integer
            flips [] = 0
            flips [_] = 1
            flips (x:(y:xs))
                | x == y = flips (y:xs)
                | otherwise = flips (y:xs) + 1

main = do
    int <- getLine
    let t = read int::Integer
    repeat t
        where
            repeat 0 = return ()
            repeat m = do
                nab <- getLine
                let arr = map (\a -> read a::Integer) $ words nab
                string <- getLine
                print $ count (arr!!0) (arr!!1) (arr!!2) string
                repeat $ m - 1

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

solve :: IO ()
solve = do
    [n, a, b] <- readMany :: IO [Int]
    s <- getLine
    let oneByOne = n * (a + b)
        n' = length $ group s
        greedy = a * n + b * ((n' + 1) `div` 2)
    print $ if b <= 0 then greedy else oneByOne

readMany :: Read a => IO [a]
readMany = map read . words <$> getLine

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

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad.State
import qualified Data.ByteString.Lazy.Char8 as C
import Data.List (group)
import Data.Maybe (fromJust, fromMaybe)

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

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

testCase :: Scanner Int
testCase = do
  nab <- three int
  s <- C.unpack <$> str
  return $ solve nab s

solve [n, a, b] s
  | b >= 0 = n * (a + b)
  | otherwise = n * a + m * b
  where
    m = (1 + length (group s)) `div` 2

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

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

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

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

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

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


You are given a function $$$f$$$ written in some basic language. The function accepts an integer value, which is immediately written into some variable $$$x$$$. $$$x$$$ is an integer variable and can be assigned values from $$$0$$$ to $$$2^{32}-1$$$. The function contains three types of commands:  for $$$n$$$ — for loop;  end — every command between "for $$$n$$$" and corresponding "end" is executed $$$n$$$ times;  add — adds 1 to $$$x$$$. After the execution of these commands, value of $$$x$$$ is returned.Every "for $$$n$$$" is matched with "end", thus the function is guaranteed to be valid. "for $$$n$$$" can be immediately followed by "end"."add" command can be outside of any for loops.Notice that "add" commands might overflow the value of $$$x$$$! It means that the value of $$$x$$$ becomes greater than $$$2^{32}-1$$$ after some "add" command. Now you run $$$f(0)$$$ and wonder if the resulting value of $$$x$$$ is correct or some overflow made it incorrect.If overflow happened then output "OVERFLOW!!!", otherwise print the resulting value of $$$x$$$.

The first line contains a single integer $$$l$$$ ($$$1 \le l \le 10^5$$$) — the number of lines in the function. Each of the next $$$l$$$ lines contains a single command of one of three types:   for $$$n$$$ ($$$1 \le n \le 100$$$) — for loop;  end — every command between "for $$$n$$$" and corresponding "end" is executed $$$n$$$ times;  add — adds 1 to $$$x$$$.

If overflow happened during execution of $$$f(0)$$$, then output "OVERFLOW!!!", otherwise print the resulting value of $$$x$$$.

9
add
for 43
end
for 10
for 15
add
end
add
end

11
for 100
for 100
for 100
for 100
for 100
add
end
end
end
end
end

NoteIn the first example the first "add" is executed 1 time, the second "add" is executed 150 times and the last "add" is executed 10 times. Note that "for $$$n$$$" can be immediately followed by "end" and that "add" can be outside of any for loops.In the second example there are no commands "add", thus the returning value is 0.In the third example "add" command is executed too many times, which causes $$$x$$$ to go over $$$2^{32}-1$$$.

module Main where

import Control.Monad
import System.IO
import Data.Maybe
import Data.Char
import Data.List

data Token a = Add | End | For a
    deriving Show

isAdd :: Token a -> Bool
isAdd Add = True
isAdd _ = False

isEnd :: Token a -> Bool
isEnd End = True
isEnd _ = False

fromFor :: Token a -> a
fromFor Add = undefined
fromFor End = undefined
fromFor (For count) = count

parseToken :: String -> Maybe (Token Integer)
parseToken s
    | s == "add" = Just Add
    | s == "end" = Just End
    | otherwise =
        let ws = words s
            maybe_for = length ws == 2 && head ws == "for"
        in if maybe_for
            then Just $ For (read (head (tail ws)) :: Integer)
            else Nothing

topBound = 4294967295 :: Integer

progCalc :: [Token Integer] -> Maybe Integer
progCalc toks = progCalc' (Just 0) [] toks

progCalc' :: Maybe Integer -> [Maybe Integer] -> [Token Integer] -> Maybe Integer
progCalc' x _ [] = x
progCalc' Nothing _ _ = Nothing
progCalc' (Just x) levels (tok : resttoks)
    | isAdd tok && null levels =
        let z = x + 1
        in if z > topBound then Nothing
            else progCalc' (Just z) levels resttoks
    | isAdd tok =
        let lev = head levels
        in if isNothing lev then Nothing
            else let z = x + (fromJust lev)
            in if z > topBound then Nothing
                else progCalc' (Just z) levels resttoks
    | isEnd tok = progCalc' (Just x) (tail levels) resttoks
    | otherwise =
        let count = fromFor tok
            prevLev = if null levels then (Just 1) else head levels
        in if isNothing prevLev
            then progCalc' (Just x) (Nothing : levels) resttoks
            else let lev = (fromJust prevLev) * count
                in if lev > topBound
                    then progCalc' (Just x) (Nothing : levels) resttoks
                    else progCalc' (Just x) ((Just lev) : levels) resttoks

main :: IO()
main = do

    q <- readLn :: IO Int
    lines <- forM [1..q] $ \q_nxt -> do
        line <- getLine
        return line

    let toks = map (fromJust . parseToken) lines
    let result = progCalc toks
    let resultstr = if (isNothing result)
        then "OVERFLOW!!!"
        else show $ fromJust result

    putStrLn resultstr

import qualified Data.List as List

data Command = For Integer | Add | End
            deriving (Eq, Show)

data Instr =
    One Command
  | More [Instr]
  deriving (Eq, Show)

{- reduce the stack -}
turnOutermost :: [Instr] -> [Instr] -> [Instr]
turnOutermost [] acc = acc
turnOutermost (One End : rest) acc = turnOutermost rest (One End : acc)
turnOutermost (One Add : rest) acc  = turnOutermost rest (One Add : acc)
turnOutermost (More x : rest) acc = turnOutermost rest (More x : acc)
turnOutermost (One (For n) : rest) acc = More (One (For n) : acc) : rest

{- Shift and reduce -}
parseCommand :: [Command] -> [Instr] -> [Instr]
parseCommand [] stack = stack
parseCommand (Add : rest) stack
  | stack == [] =  One Add : parseCommand rest stack
  | otherwise = parseCommand rest (One Add : stack)
parseCommand(For n : rest) stack = parseCommand rest (One (For n) : stack)
parseCommand (End : rest) stack = ret where
    tw = turnOutermost (One End : stack) []
    ret = case tw of
           [x] -> x : parseCommand rest []
           _ -> parseCommand rest tw

evalCommand :: [Instr] -> Integer
evalCommand [] = 0
evalCommand (One Add : xs) = 1 + evalCommand xs
evalCommand (One End : xs) = evalCommand xs
evalCommand (One (For n) : xs) = n * evalCommand xs
evalCommand (More t : xs) = evalCommand t + evalCommand xs

solve :: [Command] -> String
solve xs = ret where
  rt = evalCommand (parseCommand xs [])
  ret = if rt > 4294967295 then "OVERFLOW!!!" else show rt

strCommand :: [String] -> Command
strCommand ["add"] = Add
strCommand ["end"] = End
strCommand ["for", n] = For (read n :: Integer)

main :: IO ()
main = interact $  solve . map (strCommand . words) . tail . lines


Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time when all the people who stand in the queue in front of him are served. Susie thought that if we swap some people in the queue, then we can decrease the number of people who are disappointed. Help Susie find out what is the maximum number of not disappointed people can be achieved by swapping people in the queue.

The first line contains integer n (1 ≤ n ≤ 105). The next line contains n integers ti (1 ≤ ti ≤ 109), separated by spaces.

Print a single number — the maximum number of not disappointed people in the queue.

NoteValue 4 is achieved at such an arrangement, for example: 1, 2, 3, 5, 15. Thus, you can make everything feel not disappointed except for the person with time 5.

-- http://codeforces.com/problemset/problem/545/D

import Data.List

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

takeFirst :: (a -> Bool) -> [a] -> Maybe a
takeFirst f [] = Nothing
takeFirst f (x:xs)
	| f x = Just x
	| otherwise = takeFirst f xs

main = do
	n <- fmap read getLine :: IO Int
	people <-	fmap sort $
				fmap (map read) $
				fmap (take n) $
				fmap words getLine :: IO [Int]

	let
		not_dissapointed = notDissapointed people

	putStrLn $ show not_dissapointed

notDissapointed :: [Int] -> Int
notDissapointed xs = notDissapointed' 0 xs
	where
		notDissapointed' :: Int -> [Int] -> Int
		notDissapointed' acc people
			| not_dissapointed == 0 = 0
			| otherwise = 1 + notDissapointed' (acc + not_dissapointed) rest
			where
				not_dissapointed = eliminate 0 $ takeFirst (>=acc) people
				rest = delete not_dissapointed people
				eliminate :: a -> Maybe a -> a
				eliminate fallback Nothing = fallback
				eliminate _ (Just x) = x

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

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

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

main = do
  getLine
  xs <- getInts

  let
    c = count (0 :: Int64) $ sort xs
      where
        count _ [] = 0
        count c (x:xs)
          | c > x' = count c xs
          | otherwise = 1 + count (c+x') xs
          where
            x' = fromIntegral x :: Int64

  print c

import Data.List (sort)
import System.IO

f (suma, ans) x =
    if suma <= x
       then (suma + x, ans + 1)
       else (suma, ans)

solve list =
    foldl f (0, 0) (sort list)

solution list = snd $ solve list

makeItInt a =
    read a :: Int

makeListGreatAgain l =
    map makeItInt $ lines $ map (\c -> if c == ' ' then '\n' else c) l

main = do
    n <- getLine
    l <- getLine
    putStrLn $ show (solution $ makeListGreatAgain l)

import Data.List (sort)
getNum [] waitTime = 0
getNum (ha:ta) waitTime | ha >= waitTime = 1+(getNum ta (waitTime+ha))
                        | otherwise = getNum ta waitTime
main = do
  w0 <- getLine
  w1 <- getLine
  let a = [read n::Int|n <-(words w1)]
  print $ getNum (sort a) 0

module Main where
import Data.List
-- import Debug.Trace

solve _ n [] = n
solve w n (t:ts) = -- trace ("t=" ++ show t ++ " w=" ++ show w ++ " n=" ++ show n) $
    if t >= w
        then solve (w+t) (n+1) ts
        else solve w n ts

main = do
    getLine
    is <- map (read :: String -> Int) .words <$> getLine
    print $ solve 0 0 $ sort is

import Data.List

foo :: [Int] -> Int -> Int -> Int
foo [] _ n = n
foo (x:xs) t n = if x<t then foo xs t n else foo xs (t+x) (n+1)

main :: IO ()
main = do
  n <- return . (read::String->Int) =<< getLine
  xs <- return . sort . map (read::String->Int) . words =<< getLine
  print $ foo xs 0 0

import Control.Applicative
import Data.List

process n s [] = n
process n s a |  b==[] = n
              |  otherwise = process (n+1) (s+ (head b)) (tail b)
    where b = dropWhile (<s) a
main::IO ()
main=do
    n<- read <$> getLine::IO Int
    a1<- sort <$>  map read <$>   words   <$> getLine:: IO [Int]
    print $ process 0 0 a1

import Data.List

main = do
	getLine
	l <- getLine >>= return.(map read).words
	putStrLn $ show $ solve (sort l) 0

solve :: [Int] -> Int -> Int
solve [] _ = 0
solve (x:xs) n
	| n > x		= solve xs n
	| otherwise = 1 + solve xs (n+x)

import Control.Applicative ((<*>))
import Data.List (sort)

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

solve :: [Int] -> Int
solve = snd . foldl (\(a, b) c -> if a <= c then (a + c, b + 1) else (a, b)) (0, 0) . sort

import Data.List
main = interact $ show . solve 0 . sort . map read . tail . words
solve t (a:as) | t <= a = 1 + solve (t+a) as
               | otherwise = solve t as
solve _ [] = 0

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

process [] n u= n
process (s:ss) n u| u<=s = process ss (n+1) (u+s)
                  | otherwise= process ss n u
main= do
	getLine
	s<- sort . map (fst.fromJust.C.readInt). C.words <$> C.getLine :: IO [Int]
	print $ process s 0 0

import Data.List

main = interact $ show . sol 0 . sort . tail . map read . words

sol _ [] = 0
sol t (x:xs)
    | t <= x = 1 + sol (t+x) xs
    | otherwise = sol t xs

-- http://codeforces.com/problemset/problem/545/D

import Data.List

getLines :: Int -> IO [String]
getLines 0 = return []
getLines n = do
	x <- getLine
	xs <- getLines (n-1)
	return (x:xs)

takeFirst :: (a -> Bool) -> [a] -> Maybe a
takeFirst f [] = Nothing
takeFirst f (x:xs)
	| f x = Just x
	| otherwise = takeFirst f xs

main = do
	n <- fmap read getLine :: IO Int
	people <-	fmap sort $
				fmap (map read) $
				fmap (take n) $
				fmap words getLine :: IO [Int]

	let
		not_dissapointed = notDissapointed people

	putStrLn $ show not_dissapointed

notDissapointed :: [Int] -> Int
notDissapointed xs = notDissapointed' 0 xs
	where
		notDissapointed' :: Int -> [Int] -> Int
		notDissapointed' acc people
			| not_dissapointed == 0 = 0
			| otherwise = 1 + notDissapointed' (acc + not_dissapointed) rest
			where
				not_dissapointed = eliminate 0 $ takeFirst (>acc) people
				rest = delete not_dissapointed people
				eliminate :: a -> Maybe a -> a
				eliminate fallback Nothing = fallback
				eliminate _ (Just x) = x

module Main where
import Data.List

main = do
    getLine
    is <- map (read :: String -> Int) .words <$> getLine
    let ss = sort is
        ts = scanl' (+) 0 ss
    print $ length $ filter (\(a,b) -> a >= b) $ zip ss ts

module Main where
import Data.List

main = do
    getLine
    is <- map (read :: String -> Int) .words <$> getLine
    let patience = sort is
        waiting = scanl' (+) 0 patience
    --print $  zip patience waiting
    print $ succ $ length $ filter (\(p,w) -> p >= w) $ zip (tail patience) (tail waiting)

import Control.Applicative
import Data.List

main::IO ()
main=do
    n<- read <$> getLine::IO Int
    a1<- sort <$>  map read <$>   words   <$> getLine:: IO [Int]
    let a2 = scanl1 (+) a1
    print $ (+1)$ length $ filter (\(z1,z2)-> z1<=z2)  $ zip a2 (tail a1)

import Control.Applicative ((<*>))
import Data.List (sort)

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

solve :: [Int] -> Int
solve = length . filter id . (zipWith (>=) <*> scanl (+) 0) . sort

import Data.List
main = interact $ show . solve . sort . map read . tail . words
solve as = sum $ zipWith ((fromEnum .) . (<=)) (scanl (+) 0 as) as

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

main= do
	getLine
	s<- sort . map (fst.fromJust.C.readInt). C.words <$> C.getLine :: IO [Int]
	let t = scanl (+) 0 s
	print $ length $ filter (\z-> fst z >= snd z) $ zip s t


Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, and crust around the main part of the width d. Pieces of sausage are also circles. The radius of the i -th piece of the sausage is ri, and the center is given as a pair (xi, yi).Gleb asks you to help determine the number of pieces of sausage caught on the crust. A piece of sausage got on the crust, if it completely lies on the crust.

First string contains two integer numbers r and d (0 ≤ d < r ≤ 500) — the radius of pizza and the width of crust. Next line contains one integer number n — the number of pieces of sausage (1 ≤ n ≤ 105). Each of next n lines contains three integer numbers xi, yi and ri ( - 500 ≤ xi, yi ≤ 500, 0 ≤ ri ≤ 500), where xi and yi are coordinates of the center of i-th peace of sausage, ri — radius of i-th peace of sausage.

Output the number of pieces of sausage that lay on the crust.

NoteBelow is a picture explaining the first example. Circles of green color denote pieces of sausage lying on the crust.

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

main = putStr . evalState app . B.words =<< B.getContents

app = do
  r <- poi
  d <- poi
  n <- poi
  ss <- replicateM n $ liftM3 (,,) poi poi poi
  return $ show $ solve r d ss
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve r d = length . filter ok
  where
  ok (x, y, r') = o <= (r - r')^2 && o >= (r - d + r')^2
    where o = x*x + y*y

import Data.List
import Data.Ord

{-

solve l r x y k
	|l/y<=k && r/x>=k = solve1 l r x y k
	|otherwise = "NO"
solve1 l r x y k
	|or (map (\a->bin a x y k) [l..r] ) = "YES"
	|otherwise = "NO"

bin a x y k
	|x>y = False
	|a/x==k = True
	|a/y==k = True
	|2*a/(y+x)<k = bin a x ((y+x)/2) k
	|otherwise = bin a ((y+x)/2) y k

main=do
	word<-getLine
	let [l,r,x,y,k]=map (\x->read x::Float) $ words word
	putStrLn (solve l r x y k)

-}

fi=fromIntegral

hip x y=sqrt ((fi x)^2 + (fi y)^2)
check r d x y r1 = ((h-fi r1)>=fi (r-d)) && ((h+fi r1)<=fi r) where
 h=hip x y

toNArr x = map (\x->read x::Int) $ words x

extract (x:y:xs)=(r,d,circles) where
	[r,d]=toNArr x
	n=read y::Int
	circles=map toNArr $ take n xs

solve (r,d,circles)=length $ filter (\(x:y:r1:_)->check r d x y r1) circles

main=interact$show.solve.extract.lines

sqrtm = sqrt . (fromIntegral :: Int -> Double)

fun :: Int -> Int -> [Int] -> Int
fun _ _ [] = 0
fun r l x@(a : b : c :xz) = do
				let n = sqrtm (a * a + b * b)

				if n - fromIntegral c >= fromIntegral l && n + fromIntegral c <= fromIntegral r then 1 + fun r l xz else fun r l xz

main = do
	str <- getContents
	let cont = (map (\x -> read x :: Int). words) str
	let (r:l:n) = take 3 cont
	let newcont = drop 3 cont
	print $ fun r (r - l) newcont

import Control.Applicative( (<$>))
import Control.Monad( replicateM)

main = do
    [r_, d_] <- map read . words <$> getLine
    n_ <- readLn::IO Int
    sausageInfos_ <- replicateM n_ (map read . words <$> getLine)
    let

	disSq x y = x^2 + y^2

	check [x,y,ri] = let
			    dis2 = disSq x y
			in
			    (r_-d_+ri)^2 <= dis2 &&
				dis2 <= (r_-ri)^2

    print . length $ filter check sausageInfos_

import           Control.Monad

crust :: (Int, Int) -> (Int, Int, Int) -> Bool
crust (r, d) (x, y, r') = fromIntegral (r - d) <= dist - fromIntegral r' && fromIntegral r >= dist + fromIntegral r'
  where dist = sqrt (fromIntegral (x^2 + y^2) :: Double)

main :: IO ()
main = do
  [r, d] <- map (read :: String -> Int) . words <$> getLine
  n <- (read :: String -> Int) <$> getLine
  print =<< length . filter (crust (r, d)) . map((\[x,y,r]->(x,y,r)) . map (read :: String -> Int) . words) <$> replicateM n getLine

sqrtm = sqrt . (fromIntegral :: Int -> Double)

fun :: Int -> Int -> [Int] -> Int
fun _ _ [] = 0
fun r l x@(a : b : c :xz) = do
				let n = sqrtm (a * a + b * b)

				if n - fromIntegral c >= fromIntegral l && n + fromIntegral c <= fromIntegral r then 1 + fun r l xz else fun r l xz

main = do
	str <- getContents
	let cont = (map (\x -> read x :: Int). words) str
	let (r:l:n) = take 3 cont
	let newcont = drop 3 cont
	print $ fun r l newcont