One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, 1 ≤ k ≤ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7).

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.

Print the single number — the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7).

NoteIn the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB".

import Data.List

main = interact $ show . solve . getInput . lines

getInput :: [String] -> [String]
getInput (s:ss) = map (take m) (take n ss) where
    [n, m] = map read (words s)

solve :: [String] -> Integer
solve ss = solve' (transpose ss) 1 where
    solve' []     n = n
    solve' (s:ss) n = solve' ss (n * cnt `mod` 1000000007) where
        cnt = (toInteger . length . group . sort) s

import Data.List (nub, transpose)

solve :: String -> String
solve  =  show . (flip mod 1000000007) . product . map (fromIntegral . length . nub) . transpose . tail . lines

main :: IO ()
main  =  interact solve

import List

solve :: [[Char]] -> Integer
solve = foldl (\a x -> mod (a * x) (10 ^ 9 + 7)) 1 . map (genericLength . group . sort) . transpose
main = interact $ show . solve . tail . lines

import Data.List

main:: IO()
main = interact work

work :: String -> String
work = show . flip mod 1000000007 . solve . tail . lines

solve :: [String] -> Integer
solve = product . map (fromIntegral . length . group . sort) . transpose

import Data.List
import Control.Applicative

main = do
  _ <- getLine
  cs <- lines <$> getContents
  print $ solve cs

solve :: [String] -> Integer
solve cs = flip mod 1000000007 $ foldl1' (*) $ map (toInteger.length.nub) $ transpose cs

import Data.List

result::[String]->Integer
result = foldl1 f.map (fromIntegral.length.nub)
	where f a b = (a*b)`mod`1000000007

main=interact$show.result.transpose.tail.lines

import Data.List

main :: IO()
main = interact work

work :: String -> String
work = show . solve . tail . lines

solve :: [String] -> Integer
solve strings = (product . map (fromIntegral . length . group . sort) . transpose $ strings) `mod` 1000000007

import System.IO
import Data.List

readL :: Int -> IO [String]
readL n = sub n []
  where sub 0 l = return l
        sub n l = do ll <- getLine
                     sub (n-1) (l ++ [ll])

flatten :: [[a]] -> [a]
flatten [[]] = []
flatten ([]:ys) = flatten ys
flatten ((x:xs):ys) = x:(flatten (xs:ys))

rotate :: [String] -> [String]
rotate l = sub l []
  where sub l acc
          | flatten l == [] = acc
          | otherwise       = sub (map tail l) ((foldl (\ac x -> (head x):ac) "" l):acc)

modInt :: Integer
modInt = 1000000007

main :: IO ()
main = do
  f <- getLine
  cs <- readL . head $ map read (words f)
  let rcs = rotate cs
      ans = foldl (\ac x -> ac * ((genericLength $ nub x)::Integer) `mod` modInt) (1::Integer) rcs
  putStrLn $ show ans

import Data.List
import Control.Monad

find_best grades =
    [i | (i, x) <- zip [1..] grades, x == best]
    where best = maximum grades

solve :: Ord a => [[a]] -> Integer
solve grades =
    foldl mul 1 (map count grades)
    where count = toInteger . length . group . sort
          mul a b = (a * b) `mod` (10^9 + 7)

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

import Data.List (nub, transpose)

solve :: String -> String
solve  =  show . product . map (fromIntegral . length . nub) . transpose . tail . lines

main :: IO ()
main  =  interact solve

import List

solve :: [[Char]] -> Integer
solve = foldl (\a x -> mod (a * x) (10 ^ 9 + 1)) 1 . map (genericLength . group . sort) . transpose
main = interact $ show . solve . tail . lines

import List

solve :: [[Char]] -> Integer
solve = product . map (genericLength . group . sort) . transpose
main = interact $ show . solve . tail . lines

import Data.List

result = foldl1 f.map (length.nub)
	where f a b = (a*b)`mod`1000000007

main=interact$show.result.transpose.tail.lines

import Data.List

main :: IO()
main = interact work

work :: String -> String
work = show . product . map (length . group . sort) . transpose . tail . lines

import System.IO
import Data.List

readL :: Int -> IO [String]
readL n = sub n []
  where sub 0 l = return l
        sub n l = do ll <- getLine
                     sub (n-1) (l ++ [ll])

flatten :: [[a]] -> [a]
flatten [[]] = []
flatten ([]:ys) = flatten ys
flatten ((x:xs):ys) = x:(flatten (xs:ys))

rotate :: [String] -> [String]
rotate l = sub l []
  where sub l acc
          | flatten l == [] = acc
          | otherwise       = sub (map tail l) ((foldl (\ac x -> (head x):ac) "" l):acc)

modInt :: Int
modInt = 1000000007

main :: IO ()
main = do
  f <- getLine
  cs <- readL . head $ map read (words f)
  let rcs = rotate cs
      ans = foldl (\ac x -> ac * (length $ nub x) `mod` modInt) 1 rcs
  putStrLn $ show ans

import Data.List
import Control.Monad

find_best grades =
    [i | (i, x) <- zip [1..] grades, x == best]
    where best = maximum grades

solve :: Ord a => [[a]] -> Int
solve grades =
    foldl mul 1 (map count grades)
    where count = length . group . sort
          mul a b = (a * b) `mod` (10^9 + 7)

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


Limak is a little bear who learns to draw. People usually start with houses, fences and flowers but why would bears do it? Limak lives in the forest and he decides to draw a tree.Recall that tree is a connected graph consisting of n vertices and n - 1 edges.Limak chose a tree with n vertices. He has infinite strip of paper with two parallel rows of dots. Little bear wants to assign vertices of a tree to some n distinct dots on a paper so that edges would intersect only at their endpoints — drawn tree must be planar. Below you can see one of correct drawings for the first sample test.  Is it possible for Limak to draw chosen tree?

The first line contains single integer n (1 ≤ n ≤ 105). Next n - 1 lines contain description of a tree. i-th of them contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) denoting an edge between vertices ai and bi. It's guaranteed that given description forms a tree.

Print "Yes" (without the quotes) if Limak can draw chosen tree. Otherwise, print "No" (without the quotes).

module Main(main) where
import qualified Data.ByteString.Char8 as B
import Data.Functor
import Data.List
import Data.Array
import Data.Maybe
import qualified Data.Map.Strict as Map
import Control.Monad

getNums :: B.ByteString -> [Int]
getNums =
	let
		f1 = (map ((fst.fromJust) . B.readInt))
		f2 = (B.split ' ')
	in f1.f2
readInts :: IO [Int]
readInts = getNums <$> B.getLine

cpy [] = []
cpy ([a, b]:xs) = (a,b):(b,a):(cpy xs)

handle :: [Int] -> Int
handle [] = 0
handle (7:_) = 7
handle (5:_) = 7
handle (4:[]) = 4
handle (4:0:[]) = 5
handle (4:_) = 7
handle (3:3:_) = 7
handle (3:2:_) = 7
handle (3:1:_) = 7
handle (3:[]) = 4
handle (3:0:[]) = 4
handle (3:0:0:[]) = 5
handle (3:_) = 7
handle (2:2:2:_) = 7
handle (2:2:_) = 3
handle (2:_) = 2
handle (1:_) = 2
handle (0:0:0:_) = 2
handle (0:0:_) = 1
handle (0:_) = 0

dfs tree = go where
	go parent me =
		let
			ch = reverse $ sort $ map (go me) $ filter (/= parent) $ tree ! me
		in
			handle ch

main = do
	n <- (read <$> getLine)::IO Int
	tree <-((accumArray (flip (:)) [] (1, n)) .cpy) <$> replicateM (n-1) readInts
	let res = (dfs tree 0 1)::Int
	putStrLn $ if res<7 then "Yes" else "No"
	return ()


In Morse code, an letter of English alphabet is represented as a string of some length from $$$1$$$ to $$$4$$$. Moreover, each Morse code representation of an English letter contains only dots and dashes. In this task, we will represent a dot with a "0" and a dash with a "1".Because there are $$$2^1+2^2+2^3+2^4 = 30$$$ strings with length $$$1$$$ to $$$4$$$ containing only "0" and/or "1", not all of them correspond to one of the $$$26$$$ English letters. In particular, each string of "0" and/or "1" of length at most $$$4$$$ translates into a distinct English letter, except the following four strings that do not correspond to any English alphabet: "0011", "0101", "1110", and "1111".You will work with a string $$$S$$$, which is initially empty. For $$$m$$$ times, either a dot or a dash will be appended to $$$S$$$, one at a time. Your task is to find and report, after each of these modifications to string $$$S$$$, the number of non-empty sequences of English letters that are represented with some substring of $$$S$$$ in Morse code.Since the answers can be incredibly tremendous, print them modulo $$$10^9 + 7$$$.

The first line contains an integer $$$m$$$ ($$$1 \leq m \leq 3\,000$$$) — the number of modifications to $$$S$$$.  Each of the next $$$m$$$ lines contains either a "0" (representing a dot) or a "1" (representing a dash), specifying which character should be appended to $$$S$$$.

Print $$$m$$$ lines, the $$$i$$$-th of which being the answer after the $$$i$$$-th modification to $$$S$$$.

NoteLet us consider the first sample after all characters have been appended to $$$S$$$, so S is "111".As you can see, "1", "11", and "111" all correspond to some distinct English letter. In fact, they are translated into a 'T', an 'M', and an 'O', respectively. All non-empty sequences of English letters that are represented with some substring of $$$S$$$ in Morse code, therefore, are as follows.  "T" (translates into "1")  "M" (translates into "11")  "O" (translates into "111")  "TT" (translates into "11")  "TM" (translates into "111")  "MT" (translates into "111")  "TTT" (translates into "111") Although unnecessary for this task, a conversion table from English alphabets into Morse code can be found here.

{-# LANGUAGE CPP #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE RankNTypes #-}

import Control.Applicative
import Control.Monad
import Data.Bits
import Data.Char
import Data.Functor
import Data.Maybe
import Data.Monoid hiding ((<>))
import Data.Semigroup

import qualified Data.ByteString.Lazy.Char8 as BS

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

import Control.Monad.ST.Safe
import Data.Function
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Int
import Data.STRef
import qualified Data.List as List
import qualified Data.Array as Arr

-- {{{ Functors

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

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

-- }}}

-- {{{ Monads

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

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

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

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

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

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

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

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

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

-- }}}

-- {{{ Lens

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

#if __GLASGOW_HASKELL__ < 713
infix 1 &
#endif

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

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

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

-- }}}

-- {{{ Common used lens

class Has1 m a | m -> a where
  _1 :: CylLens' a m

class Has2 m a | m -> a where
  _2 :: CylLens' a m

class Has3 m a | m -> a where
  _3 :: CylLens' a m

class Has4 m a | m -> a where
  _4 :: CylLens' a m

class Has5 m a | m -> a where
  _5 :: CylLens' a m

class Has6 m a | m -> a where
  _6 :: CylLens' a m

instance Has1 ((,) a b) a where
  _1 = lens fst $ \(a, b) c -> (c, b)
  {-# INLINE _1 #-}

instance Has1 ((,,) a b c) a where
  _1 = lens (\(a, _, _) -> a) $ \(a, b, c) d -> (d, b, c)
  {-# INLINE _1 #-}

instance Has1 ((,,,) a b c d) a where
  _1 = lens (\(a, _, _, _) -> a) $ \(a, b, c, d) e -> (e, b, c, d)
  {-# INLINE _1 #-}

instance Has1 ((,,,,) a b c d e) a where
  _1 = lens (\(a, _, _, _, _) -> a) $ \(a, b, c, d, e) f -> (f, b, c, d, e)
  {-# INLINE _1 #-}

instance Has1 ((,,,,,) a b c d e f) a where
  _1 = lens (\(a, _, _, _, _, _) -> a) $ \(a, b, c, d, e, f) g -> (g, b, c, d, e, f)
  {-# INLINE _1 #-}

instance Has2 ((,) a b) b where
  _2 = lens snd $ \(a, b) c -> (a, c)
  {-# INLINE _2 #-}

instance Has2 ((,,) a b c) b where
  _2 = lens (\(_, b, _) -> b) $ \(a, b, c) d -> (a, d, c)
  {-# INLINE _2 #-}

instance Has2 ((,,,) a b c d) b where
  _2 = lens (\(_, b, _, _) -> b) $ \(a, b, c, d) e -> (a, e, c, d)
  {-# INLINE _2 #-}

instance Has2 ((,,,,) a b c d e) b where
  _2 = lens (\(_, b, _, _, _) -> b) $ \(a, b, c, d, e) f -> (a, f, c, d, e)
  {-# INLINE _2 #-}

instance Has2 ((,,,,,) a b c d e f) b where
  _2 = lens (\(_, b, _, _, _, _) -> b) $ \(a, b, c, d, e, f) g -> (a, g, c, d, e, f)
  {-# INLINE _2 #-}

instance Has3 ((,,) a b c) c where
  _3 = lens (\(_, _, c) -> c) $ \(a, b, c) d -> (a, b, d)
  {-# INLINE _3 #-}

instance Has3 ((,,,) a b c d) c where
  _3 = lens (\(_, _, c, _) -> c) $ \(a, b, c, d) e -> (a, b, e, d)
  {-# INLINE _3 #-}

instance Has3 ((,,,,) a b c d e) c where
  _3 = lens (\(_, _, c, _, _) -> c) $ \(a, b, c, d, e) f -> (a, b, f, d, e)
  {-# INLINE _3 #-}

instance Has3 ((,,,,,) a b c d e f) c where
  _3 = lens (\(_, _, c, _, _, _) -> c) $ \(a, b, c, d, e, f) g -> (a, b, g, d, e, f)
  {-# INLINE _3 #-}

instance Has4 ((,,,) a b c d) d where
  _4 = lens (\(_, _, _, d) -> d) $ \(a, b, c, d) e -> (a, b, c, e)
  {-# INLINE _4 #-}

instance Has4 ((,,,,) a b c d e) d where
  _4 = lens (\(_, _, _, d, _) -> d) $ \(a, b, c, d, e) f -> (a, b, c, f, e)
  {-# INLINE _4 #-}

instance Has4 ((,,,,,) a b c d e f) d where
  _4 = lens (\(_, _, _, d, _, _) -> d) $ \(a, b, c, d, e, f) g -> (a, b, c, g, e, f)
  {-# INLINE _4 #-}

instance Has5 ((,,,,) a b c d e) e where
  _5 = lens (\(_, _, _, _, e) -> e) $ \(a, b, c, d, e) f -> (a, b, c, d, f)
  {-# INLINE _5 #-}

instance Has5 ((,,,,,) a b c d e f) e where
  _5 = lens (\(_, _, _, _, e, _) -> e) $ \(a, b, c, d, e, f) g -> (a, b, c, d, g, f)
  {-# INLINE _5 #-}

instance Has6 ((,,,,,) a b c d e f) f where
  _6 = lens (\(_, _, _, _, _, f) -> f) $ \(a, b, c, d, e, f) g -> (a, b, c, d, e, g)
  {-# INLINE _6 #-}

-- }}}

-- {{{ Handy IO

type StringReader a = State BS.ByteString a

readContents :: StringReader a -> IO a
readContents reader = do
  contents <- BS.getContents
  return $ readFrom contents reader

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

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

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

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

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

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

-- }}}

-- {{{ Suffix Array

newtype SuffixArray = SA { runSA :: UArray Int32 Int32}

data SALcp  = SALcp {
  _sa :: UArray Int32 Int32,
  _sarank :: UArray Int32 Int32,
  -- | salcp[i] = lcp(sa[i], sa[i + 1]) 0 <= i < n - 1
  _salcp :: UArray Int32 Int32
} deriving (Show)

mkSaDoubling :: (Ord a, Eq a) => [a] -> SuffixArray
mkSaDoubling xs = case xs of
  [] -> SA $ array (0, -1) []
  _ -> let extendedSa = runST mk
       in extendedSa & tail & listArray (0, n - 1) & SA
  where
    n = fromIntegral $ length xs :: Int32
    newArr :: ST s (STUArray s Int32 Int32)
    newArr = newArray (0, n) 0

    mk = do
      rank1 <- newArr
      rank2 <- newArr
      radixArr <- newArray (0, n) [] :: ST s (STArray s Int32 [Int32])
      maxr0 <- rerank (return . (initXs!)) initSa rank1
      if maxr0 == n
        then return initSa
        else do
          let c sa' i = do
                idxs <- readArray radixArr i
                writeArray radixArr i []
                return $ List.foldl' (flip (:)) sa' idxs
              radixSort rankFn sa = do
                forM_ sa $ \sidx -> do
                  ridx <- rankFn sidx
                  stack <- readArray radixArr ridx
                  writeArray radixArr ridx (sidx:stack)
                foldM c [] [n, n - 1..0]
              goSa rollingRanks step sa = do
                let (sRank, tRank) = rollingRanks
                    dRankFn d x = let y = x + d
                      in if (y > n) then return 0 else readArray sRank y
                    dRankFn2 i = (,) <$> dRankFn 0 i <*> dRankFn step i
                sa' <- radixSort (dRankFn step) sa
                sa'' <- radixSort (dRankFn 0) sa'
                maxRank <- rerank dRankFn2 sa'' tRank
                if maxRank == n
                  then return sa''
                  else goSa (tRank, sRank) (step + step) sa''
          goSa (rank1, rank2) 1 initSa

    initSa :: [Int32]
    initSa = zip [0..n - 1] xs & List.sortOn snd & map fst & (n:)

    mkArr :: [a] -> Arr.Array Int32 a
    mkArr zs = listArray (0, n - 1) zs
    initXs = mkArr xs

    rerank :: Eq b => (Int32 -> ST s b) -> [Int32] -> (STUArray s Int32 Int32) -> ST s Int32
    rerank valFn inds target = do
      writeArray target headInd 0
      counter <- newSTRef (0 :: Int32)
      forM_ indPairs $ \(pi, i) -> do
        if pi == headInd
          then modifySTRef counter (+1)
          else do
              pv <- valFn pi
              iv <- valFn i
              when (pv /= iv) $ modifySTRef counter (+1)
        c <- readSTRef counter
        writeArray target i c
      readSTRef counter
      where
        headInd = head inds
        indPairs = zip inds (tail inds)

getSaLcp :: (Eq a,  Ord a) => ([a] -> SuffixArray) -> [a] -> SALcp
getSaLcp saFn xs = SALcp sa rank saLcp
  where
    sa = runSA $ saFn xs
    n = (bounds sa & snd) + 1

    rank :: UArray Int32 Int32
    rank = array (0, n - 1) $ map (\(x, y) -> (y, x)) $ assocs sa

    mkArr :: [a] -> Arr.Array Int32 a
    mkArr zs = listArray (0, n - 1) zs
    initXs = mkArr xs

    saLcp = scanl lcp' (-1, 0) [0..n - 1]
      & filter (inRange (0, n - 2) . fst)
      & array (0, n - 2)

    lcp' (r, prevLcp) suffixIdx =
      if thisRk == n - 1 then (n - 1, 0)
      else (thisRk, lcp')
      where
        thisRk = rank ! suffixIdx
        largerSuffixIdx = sa ! (thisRk + 1)
        lcp' = goLcp (max 0 (prevLcp - 1))

        goLcp l = l + (fromIntegral $ length $ takeWhile g [l..])
          where
            g l' =
              let thisEnd = suffixIdx + l'
                  thatEnd = largerSuffixIdx + l'
              in (thisEnd < n) && (thatEnd < n)
                && (initXs ! thisEnd) == (initXs ! thatEnd)

-- }}}

-- {{{ DSU

class Monoid m => Group m where
  groupNegate :: m -> m

-- a is of commutative Monoid
class (Group m, Monoid a) => Ring m a where
  ringMul :: m -> a -> a

instance Group () where
  groupNegate = id
  {-# INLINE groupNegate #-}

instance Group a => Ring a () where
  ringMul _ _ = ()
  {-# INLINE ringMul #-}

data DsuCell i r e =
  DsuRoot {
    componentSize :: Int,
    componentState :: r
  }
  | DsuChild {
    dsuFatherIndex :: i,
    dsuRelation :: e
  }

newtype STDsu s i r e = STDsu {_runDsu :: STArray s i (DsuCell i r e)}

newSTDsu :: Ix i => (i, i) -> [r] -> ST s (STDsu s i r e)
newSTDsu bnds rs = do
  newArr <- newListArray bnds $ map (DsuRoot 1)  rs
  return $ STDsu newArr

readDsuCell :: Ix i => STDsu s i r e -> i -> ST s (DsuCell i r e)
readDsuCell dsu idx = flip readArray idx . _runDsu $ dsu

isRootCell :: DsuCell i r e -> Bool
isRootCell DsuRoot{} = True
isRootCell _ = False

dsuImmeidateRelation :: (Ix i, Monoid e) => i -> STDsu s i r e-> ST s e
dsuImmeidateRelation idx dsuST = do
  cell <- readDsuCell dsuST idx
  case cell of
    DsuChild _ rel -> return rel
    DsuRoot{} -> return mempty

dsuFather :: Ix i => i -> STDsu s i r e -> ST s i
dsuFather idx dsuST = do
  cell <- readDsuCell dsuST idx
  case cell of
    DsuChild f _ -> return f
    DsuRoot{} -> return idx

writeDsuCell :: Ix i => STDsu s i r e -> i -> DsuCell i r e -> ST s ()
writeDsuCell = writeArray . _runDsu

modifyDsuCell :: Ix i => STDsu s i r e -> i -> (DsuCell i r e -> DsuCell i r e) -> ST s ()
modifyDsuCell dsuST i f = do
  cell <- readDsuCell dsuST i
  writeDsuCell dsuST i (f cell)

dsuUpToRootAndCompress :: (Ix i, Monoid e) => i -> STDsu s i r e -> ST s (i, e)
dsuUpToRootAndCompress idx dsuST = do
  fa <- dsuFather idx dsuST
  if fa == idx
    then return (idx, mempty)
    else do
      (rootIdx, faRel) <- dsuUpToRootAndCompress fa dsuST
      thisRel <- dsuImmeidateRelation idx dsuST
      let newRel = thisRel `mappend` faRel
      writeDsuCell dsuST idx (DsuChild rootIdx newRel)
      return (rootIdx, newRel)

dsuUnion :: (Ix i, Ring e r, Group e) => i -> i -> e -> STDsu s i r e -> ST s ()
dsuUnion from to rel dsuST = when (from /= to) $ do
  (fromRoot, fromRel) <- dsuUpToRootAndCompress from dsuST
  (toRoot, toRel) <- dsuUpToRootAndCompress to dsuST
  DsuRoot sFrom _ <- readDsuCell dsuST fromRoot
  DsuRoot sTo _ <- readDsuCell dsuST toRoot
  if sFrom <= sTo
  then connect fromRoot toRoot $
    groupNegate fromRel `mappend` rel `mappend` toRel
  else connect toRoot fromRoot $
    groupNegate toRel `mappend` groupNegate rel `mappend` fromRel
  where
    connect f newRoot newRel = do
      (DsuRoot sf cf) <- readDsuCell dsuST f
      writeDsuCell dsuST f $ DsuChild newRoot newRel
      modifyDsuCell dsuST newRoot $ \(DsuRoot sR cR) ->
        DsuRoot (sR + sf) (ringMul newRel cf `mappend` cR)
-- }}}

instance Ring () (Min Int32) where
  ringMul m a = a

type SolveState = (Int32, [Int])

data PrefixSolveState = PSS {
  _total :: Int
}

solve :: [Int] -> [Int]
solve xs = zipWith go prefixes (elems getDupLen) & scanl1 addMod
  where
    modulo = 1000000007

    addMod x y = (x + y) `mod` modulo

    asArr :: Array i e -> Array i e
    asArr = id

    revSaLcp = getSaLcp mkSaDoubling $ reverse xs

    getDupLen =
      let SALcp sa _ salcp = revSaLcp
          n = (+1) . snd $ bounds sa
      in
      runSTUArray $ do
        dupLen <- newArray (0, n - 1) 0 :: ST s (STUArray s Int32 Int32)
        stackRef <- newSTRef []
        let reorderedLcp = assocs sa
              & map (\(rk, sidx) ->
                let l = if rk == n - 1 then 0 else salcp ! rk
                in (sidx, Min l))
              & array (0, n - 1)
              & asArr
              & elems
        dsu <- newSTDsu (0, n - 1) reorderedLcp :: ST s (STDsu s Int32 (Min Int32) ())
        let popAndMerge y [] = return []
            popAndMerge y stack'@(z:_) = do
              dsuUnion y z () dsu
              return stack'
            updateMaxFrom f t = do
              (r, _) <- dsuUpToRootAndCompress f dsu
              Min l' <- (readDsuCell dsu r <&> componentState)
              l <- readArray dupLen (n - 1 - t)
              writeArray dupLen (n - 1 - t) (max l l')
            popCloserToEnd _ [] = return []
            popCloserToEnd x stack'@(y:ys) =
              if (y > x)
                then do
                  updateMaxFrom y x
                  return stack'
                else do
                  updateMaxFrom y y
                  stack'' <- popAndMerge y ys
                  popCloserToEnd x stack''

        forM_ (elems sa) $ \sidx -> do
          stack <- readSTRef stackRef
          stack' <- popCloserToEnd sidx stack
          writeSTRef stackRef (sidx:stack')
        return dupLen

    -- blacklist = map (map (\c -> (ord c) - (ord '0')))
    --   ["0011", "0101", "1110", "1111"]
    blacklist :: [Int32]
    blacklist = map (+(bit 4)) [12, 10, 7, 15]

    prefixes = xs & scanl (flip (:)) [] & tail

    lastDigits :: CylLens' Int32 SolveState
    lastDigits = _1

    lastCounts :: CylLens' [Int] SolveState
    lastCounts = _2

    p a x = a .|. (if x >= (bit 4)
        then x & (`clearBit` 4) & (`shiftL` 1) & (`setBit` 4)
        else x `shiftL` 1)

    app1 :: Int -> State SolveState Int
    app1 digit = do
      lastDigits %= (p $ fromIntegral digit)
      (ds, cs) <- get
      let numLastCs = if ds `elem` blacklist then 3 else 4
          newCount = (foldl addMod 0 $ take numLastCs cs)
      lastCounts %= (newCount:) . take 3
      return newCount

    go :: [Int] -> Int32 -> Int
    go prefix dupLen =
      mapM app1 prefix
      & flip runState (1, [1])
      & fst
      & drop (fromIntegral dupLen)
      & List.foldl' addMod 0

main :: IO ()
main = do
  s <- readContents $ do
     m <- getInt
     replicateM m getInt
  solve s & map show & unlines & putStrLn
  return ()

{-# LANGUAGE CPP #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE RankNTypes #-}

{-# OPTIONS_GHC -O2 #-}

import Control.Applicative
import Control.Monad
import Data.Bits
import Data.Char
import Data.Functor
import Data.Maybe
import Data.Monoid hiding ((<>))
import Data.Semigroup

import qualified Data.ByteString.Lazy.Char8 as BS

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

import Control.Monad.ST.Safe
import Data.Function
import Data.Array.IArray
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
import Data.Array.Unboxed
import Data.Int
import Data.STRef
import qualified Data.List as List
import qualified Data.Array as Arr

-- {{{ Functors

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

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

-- }}}

-- {{{ Monads

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

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

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

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

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

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

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

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

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

-- }}}

-- {{{ Lens

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

#if __GLASGOW_HASKELL__ < 713
infix 1 &
#endif

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

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

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

-- }}}

-- {{{ Common used lens

class Has1 m a | m -> a where
  _1 :: CylLens' a m

class Has2 m a | m -> a where
  _2 :: CylLens' a m

class Has3 m a | m -> a where
  _3 :: CylLens' a m

class Has4 m a | m -> a where
  _4 :: CylLens' a m

class Has5 m a | m -> a where
  _5 :: CylLens' a m

class Has6 m a | m -> a where
  _6 :: CylLens' a m

instance Has1 ((,) a b) a where
  _1 = lens fst $ \(a, b) c -> (c, b)
  {-# INLINE _1 #-}

instance Has1 ((,,) a b c) a where
  _1 = lens (\(a, _, _) -> a) $ \(a, b, c) d -> (d, b, c)
  {-# INLINE _1 #-}

instance Has1 ((,,,) a b c d) a where
  _1 = lens (\(a, _, _, _) -> a) $ \(a, b, c, d) e -> (e, b, c, d)
  {-# INLINE _1 #-}

instance Has1 ((,,,,) a b c d e) a where
  _1 = lens (\(a, _, _, _, _) -> a) $ \(a, b, c, d, e) f -> (f, b, c, d, e)
  {-# INLINE _1 #-}

instance Has1 ((,,,,,) a b c d e f) a where
  _1 = lens (\(a, _, _, _, _, _) -> a) $ \(a, b, c, d, e, f) g -> (g, b, c, d, e, f)
  {-# INLINE _1 #-}

instance Has2 ((,) a b) b where
  _2 = lens snd $ \(a, b) c -> (a, c)
  {-# INLINE _2 #-}

instance Has2 ((,,) a b c) b where
  _2 = lens (\(_, b, _) -> b) $ \(a, b, c) d -> (a, d, c)
  {-# INLINE _2 #-}

instance Has2 ((,,,) a b c d) b where
  _2 = lens (\(_, b, _, _) -> b) $ \(a, b, c, d) e -> (a, e, c, d)
  {-# INLINE _2 #-}

instance Has2 ((,,,,) a b c d e) b where
  _2 = lens (\(_, b, _, _, _) -> b) $ \(a, b, c, d, e) f -> (a, f, c, d, e)
  {-# INLINE _2 #-}

instance Has2 ((,,,,,) a b c d e f) b where
  _2 = lens (\(_, b, _, _, _, _) -> b) $ \(a, b, c, d, e, f) g -> (a, g, c, d, e, f)
  {-# INLINE _2 #-}

instance Has3 ((,,) a b c) c where
  _3 = lens (\(_, _, c) -> c) $ \(a, b, c) d -> (a, b, d)
  {-# INLINE _3 #-}

instance Has3 ((,,,) a b c d) c where
  _3 = lens (\(_, _, c, _) -> c) $ \(a, b, c, d) e -> (a, b, e, d)
  {-# INLINE _3 #-}

instance Has3 ((,,,,) a b c d e) c where
  _3 = lens (\(_, _, c, _, _) -> c) $ \(a, b, c, d, e) f -> (a, b, f, d, e)
  {-# INLINE _3 #-}

instance Has3 ((,,,,,) a b c d e f) c where
  _3 = lens (\(_, _, c, _, _, _) -> c) $ \(a, b, c, d, e, f) g -> (a, b, g, d, e, f)
  {-# INLINE _3 #-}

instance Has4 ((,,,) a b c d) d where
  _4 = lens (\(_, _, _, d) -> d) $ \(a, b, c, d) e -> (a, b, c, e)
  {-# INLINE _4 #-}

instance Has4 ((,,,,) a b c d e) d where
  _4 = lens (\(_, _, _, d, _) -> d) $ \(a, b, c, d, e) f -> (a, b, c, f, e)
  {-# INLINE _4 #-}

instance Has4 ((,,,,,) a b c d e f) d where
  _4 = lens (\(_, _, _, d, _, _) -> d) $ \(a, b, c, d, e, f) g -> (a, b, c, g, e, f)
  {-# INLINE _4 #-}

instance Has5 ((,,,,) a b c d e) e where
  _5 = lens (\(_, _, _, _, e) -> e) $ \(a, b, c, d, e) f -> (a, b, c, d, f)
  {-# INLINE _5 #-}

instance Has5 ((,,,,,) a b c d e f) e where
  _5 = lens (\(_, _, _, _, e, _) -> e) $ \(a, b, c, d, e, f) g -> (a, b, c, d, g, f)
  {-# INLINE _5 #-}

instance Has6 ((,,,,,) a b c d e f) f where
  _6 = lens (\(_, _, _, _, _, f) -> f) $ \(a, b, c, d, e, f) g -> (a, b, c, d, e, g)
  {-# INLINE _6 #-}

-- }}}

-- {{{ Handy IO

type StringReader a = State BS.ByteString a

readContents :: StringReader a -> IO a
readContents reader = do
  contents <- BS.getContents
  return $ readFrom contents reader

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

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

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

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

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

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

-- }}}

-- {{{ Suffix Array

newtype SuffixArray = SA { runSA :: UArray Int32 Int32}

data SALcp  = SALcp {
  _sa :: UArray Int32 Int32,
  _sarank :: UArray Int32 Int32,
  -- | salcp[i] = lcp(sa[i], sa[i + 1]) 0 <= i < n - 1
  _salcp :: UArray Int32 Int32
} deriving (Show)

mkSaDoubling :: (Ord a, Eq a) => [a] -> SuffixArray
mkSaDoubling xs = case xs of
  [] -> SA $ array (0, -1) []
  _ -> let extendedSa = runST mk
       in extendedSa & tail & listArray (0, n - 1) & SA
  where
    n = fromIntegral $ length xs :: Int32
    newArr :: ST s (STUArray s Int32 Int32)
    newArr = newArray (0, n) 0

    mk = do
      rank1 <- newArr
      rank2 <- newArr
      radixArr <- newArray (0, n) [] :: ST s (STArray s Int32 [Int32])
      maxr0 <- rerank (return . (initXs!)) initSa rank1
      if maxr0 == n
        then return initSa
        else do
          let c sa' i = do
                idxs <- readArray radixArr i
                writeArray radixArr i []
                return $ List.foldl' (flip (:)) sa' idxs
              radixSort rankFn sa = do
                forM_ sa $ \sidx -> do
                  ridx <- rankFn sidx
                  stack <- readArray radixArr ridx
                  writeArray radixArr ridx (sidx:stack)
                foldM c [] [n, n - 1..0]
              goSa rollingRanks step sa = do
                let (sRank, tRank) = rollingRanks
                    dRankFn d x = let y = x + d
                      in if (y > n) then return 0 else readArray sRank y
                    dRankFn2 i = (,) <$> dRankFn 0 i <*> dRankFn step i
                sa' <- radixSort (dRankFn step) sa
                sa'' <- radixSort (dRankFn 0) sa'
                maxRank <- rerank dRankFn2 sa'' tRank
                if maxRank == n
                  then return sa''
                  else goSa (tRank, sRank) (step + step) sa''
          goSa (rank1, rank2) 1 initSa

    initSa :: [Int32]
    initSa = zip [0..n - 1] xs & List.sortOn snd & map fst & (n:)

    mkArr :: [a] -> Arr.Array Int32 a
    mkArr zs = listArray (0, n - 1) zs
    initXs = mkArr xs

    rerank :: Eq b => (Int32 -> ST s b) -> [Int32] -> (STUArray s Int32 Int32) -> ST s Int32
    rerank valFn inds target = do
      writeArray target headInd 0
      counter <- newSTRef (0 :: Int32)
      forM_ indPairs $ \(pi, i) -> do
        if pi == headInd
          then modifySTRef counter (+1)
          else do
              pv <- valFn pi
              iv <- valFn i
              when (pv /= iv) $ modifySTRef counter (+1)
        c <- readSTRef counter
        writeArray target i c
      readSTRef counter
      where
        headInd = head inds
        indPairs = zip inds (tail inds)

getSaLcp :: (Eq a,  Ord a) => ([a] -> SuffixArray) -> [a] -> SALcp
getSaLcp saFn xs = SALcp sa rank saLcp
  where
    sa = runSA $ saFn xs
    n = (bounds sa & snd) + 1

    rank :: UArray Int32 Int32
    rank = array (0, n - 1) $ map (\(x, y) -> (y, x)) $ assocs sa

    mkArr :: [a] -> Arr.Array Int32 a
    mkArr zs = listArray (0, n - 1) zs
    initXs = mkArr xs

    saLcp = scanl lcp' (-1, 0) [0..n - 1]
      & filter (inRange (0, n - 2) . fst)
      & array (0, n - 2)

    lcp' (r, prevLcp) suffixIdx =
      if thisRk == n - 1 then (n - 1, 0)
      else (thisRk, lcp')
      where
        thisRk = rank ! suffixIdx
        largerSuffixIdx = sa ! (thisRk + 1)
        lcp' = goLcp (max 0 (prevLcp - 1))

        goLcp l = l + (fromIntegral $ length $ takeWhile g [l..])
          where
            g l' =
              let thisEnd = suffixIdx + l'
                  thatEnd = largerSuffixIdx + l'
              in (thisEnd < n) && (thatEnd < n)
                && (initXs ! thisEnd) == (initXs ! thatEnd)

-- }}}

-- {{{ DSU

class Monoid m => Group m where
  groupNegate :: m -> m

-- a is of commutative Monoid
class (Group m, Monoid a) => Ring m a where
  ringMul :: m -> a -> a

instance Group () where
  groupNegate = id
  {-# INLINE groupNegate #-}

instance Group a => Ring a () where
  ringMul _ _ = ()
  {-# INLINE ringMul #-}

data DsuCell i r e =
  DsuRoot {
    componentSize :: Int,
    componentState :: r
  }
  | DsuChild {
    dsuFatherIndex :: i,
    dsuRelation :: e
  }

newtype STDsu s i r e = STDsu {_runDsu :: STArray s i (DsuCell i r e)}

newSTDsu :: Ix i => (i, i) -> [r] -> ST s (STDsu s i r e)
newSTDsu bnds rs = do
  newArr <- newListArray bnds $ map (DsuRoot 1)  rs
  return $ STDsu newArr

readDsuCell :: Ix i => STDsu s i r e -> i -> ST s (DsuCell i r e)
readDsuCell dsu idx = flip readArray idx . _runDsu $ dsu

isRootCell :: DsuCell i r e -> Bool
isRootCell DsuRoot{} = True
isRootCell _ = False

dsuImmeidateRelation :: (Ix i, Monoid e) => i -> STDsu s i r e-> ST s e
dsuImmeidateRelation idx dsuST = do
  cell <- readDsuCell dsuST idx
  case cell of
    DsuChild _ rel -> return rel
    DsuRoot{} -> return mempty

dsuFather :: Ix i => i -> STDsu s i r e -> ST s i
dsuFather idx dsuST = do
  cell <- readDsuCell dsuST idx
  case cell of
    DsuChild f _ -> return f
    DsuRoot{} -> return idx

writeDsuCell :: Ix i => STDsu s i r e -> i -> DsuCell i r e -> ST s ()
writeDsuCell = writeArray . _runDsu

modifyDsuCell :: Ix i => STDsu s i r e -> i -> (DsuCell i r e -> DsuCell i r e) -> ST s ()
modifyDsuCell dsuST i f = do
  cell <- readDsuCell dsuST i
  writeDsuCell dsuST i (f cell)

dsuUpToRootAndCompress :: (Ix i, Monoid e) => i -> STDsu s i r e -> ST s (i, e)
dsuUpToRootAndCompress idx dsuST = do
  fa <- dsuFather idx dsuST
  if fa == idx
    then return (idx, mempty)
    else do
      (rootIdx, faRel) <- dsuUpToRootAndCompress fa dsuST
      thisRel <- dsuImmeidateRelation idx dsuST
      let newRel = thisRel `mappend` faRel
      writeDsuCell dsuST idx (DsuChild rootIdx newRel)
      return (rootIdx, newRel)

dsuUnion :: (Ix i, Ring e r, Group e) => i -> i -> e -> STDsu s i r e -> ST s ()
dsuUnion from to rel dsuST = when (from /= to) $ do
  (fromRoot, fromRel) <- dsuUpToRootAndCompress from dsuST
  (toRoot, toRel) <- dsuUpToRootAndCompress to dsuST
  DsuRoot sFrom _ <- readDsuCell dsuST fromRoot
  DsuRoot sTo _ <- readDsuCell dsuST toRoot
  if sFrom <= sTo
  then connect fromRoot toRoot $
    groupNegate fromRel `mappend` rel `mappend` toRel
  else connect toRoot fromRoot $
    groupNegate toRel `mappend` groupNegate rel `mappend` fromRel
  where
    connect f newRoot newRel = do
      (DsuRoot sf cf) <- readDsuCell dsuST f
      writeDsuCell dsuST f $ DsuChild newRoot newRel
      modifyDsuCell dsuST newRoot $ \(DsuRoot sR cR) ->
        DsuRoot (sR + sf) (ringMul newRel cf `mappend` cR)
-- }}}

instance Ring () (Min Int32) where
  ringMul m a = a

type SolveState = (Int32, [Int])

solve :: [Int] -> [Int]
solve xs = zipWith go prefixes (elems getDupLen) & scanl1 addMod
  where
    modulo = 1000000007

    addMod x y = (x + y) `mod` modulo

    asArr :: Array i e -> Array i e
    asArr = id

    revSaLcp = getSaLcp mkSaDoubling $ reverse xs

    getDupLen =
      let SALcp sa _ salcp = revSaLcp
          n = (+1) . snd $ bounds sa
      in
      runSTUArray $ do
        dupLen <- newArray (0, n - 1) 0 :: ST s (STUArray s Int32 Int32)
        stackRef <- newSTRef []
        let reorderedLcp = assocs sa
              & map (\(rk, sidx) ->
                let l = if rk == n - 1 then 0 else salcp ! rk
                in (sidx, Min l))
              & array (0, n - 1)
              & asArr
              & elems
        dsu <- newSTDsu (0, n - 1) reorderedLcp :: ST s (STDsu s Int32 (Min Int32) ())
        let popAndMerge y [] = return []
            popAndMerge y stack'@(z:_) = do
              dsuUnion y z () dsu
              return stack'
            updateMaxFrom f t = do
              (r, _) <- dsuUpToRootAndCompress f dsu
              Min l' <- (readDsuCell dsu r <&> componentState)
              l <- readArray dupLen (n - 1 - t)
              writeArray dupLen (n - 1 - t) (max l l')
            popCloserToEnd _ [] = return []
            popCloserToEnd x stack'@(y:ys) =
              if (y > x)
                then do
                  updateMaxFrom y x
                  return stack'
                else do
                  updateMaxFrom y y
                  stack'' <- popAndMerge y ys
                  popCloserToEnd x stack''

        forM_ (elems sa) $ \sidx -> do
          stack <- readSTRef stackRef
          stack' <- popCloserToEnd sidx stack
          writeSTRef stackRef (sidx:stack')
        return dupLen

    blacklist :: [Int32]
    blacklist = map (+(bit 4)) [12, 10, 7, 15]

    prefixes = xs & scanl (flip (:)) [] & tail

    lastDigits :: CylLens' Int32 SolveState
    lastDigits = _1

    lastCounts :: CylLens' [Int] SolveState
    lastCounts = _2

    p a x = a .|. (if x >= (bit 4)
        then x & (`clearBit` 4) & (`shiftL` 1) & (`setBit` 4)
        else x `shiftL` 1)

    app1 :: Int -> State SolveState Int
    app1 digit = do
      lastDigits %= (p $ fromIntegral digit)
      (ds, cs) <- get
      let numLastCs = if ds `elem` blacklist then 3 else 4
          newCount = (foldl addMod 0 $ take numLastCs cs)
      lastCounts %= (newCount:) . take 3
      return newCount

    go :: [Int] -> Int32 -> Int
    go prefix dupLen =
      mapM app1 prefix
      & flip runState (1, [1])
      & fst
      & drop (fromIntegral dupLen)
      & List.foldl' addMod 0

main :: IO ()
main = do
  s <- readContents $ do
     m <- getInt
     replicateM m getInt
  solve s & map show & unlines & putStrLn
  return ()

{-# LANGUAGE CPP #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}

import Control.Applicative
import Control.Monad
import Data.Char
import Data.Function
import Data.Functor

import qualified Data.Map.Strict as Map
import qualified Data.ByteString.Lazy.Char8 as BS

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

-- {{{ Functors

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

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

-- }}}

-- {{{ Monads

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

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

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

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

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

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

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

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

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

-- }}}

-- {{{ Lens

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

#if __GLASGOW_HASKELL__ < 713
infix 1 &
#endif

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

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

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

-- }}}

-- {{{ Common used lens

class Has1 m a | m -> a where
  _1 :: CylLens' a m

class Has2 m a | m -> a where
  _2 :: CylLens' a m

class Has3 m a | m -> a where
  _3 :: CylLens' a m

class Has4 m a | m -> a where
  _4 :: CylLens' a m

class Has5 m a | m -> a where
  _5 :: CylLens' a m

class Has6 m a | m -> a where
  _6 :: CylLens' a m

instance Has1 ((,) a b) a where
  _1 = lens fst $ \(a, b) c -> (c, b)
  {-# INLINE _1 #-}

instance Has1 ((,,) a b c) a where
  _1 = lens (\(a, _, _) -> a) $ \(a, b, c) d -> (d, b, c)
  {-# INLINE _1 #-}

instance Has1 ((,,,) a b c d) a where
  _1 = lens (\(a, _, _, _) -> a) $ \(a, b, c, d) e -> (e, b, c, d)
  {-# INLINE _1 #-}

instance Has1 ((,,,,) a b c d e) a where
  _1 = lens (\(a, _, _, _, _) -> a) $ \(a, b, c, d, e) f -> (f, b, c, d, e)
  {-# INLINE _1 #-}

instance Has1 ((,,,,,) a b c d e f) a where
  _1 = lens (\(a, _, _, _, _, _) -> a) $ \(a, b, c, d, e, f) g -> (g, b, c, d, e, f)
  {-# INLINE _1 #-}

instance Has2 ((,) a b) b where
  _2 = lens snd $ \(a, b) c -> (a, c)
  {-# INLINE _2 #-}

instance Has2 ((,,) a b c) b where
  _2 = lens (\(_, b, _) -> b) $ \(a, b, c) d -> (a, d, c)
  {-# INLINE _2 #-}

instance Has2 ((,,,) a b c d) b where
  _2 = lens (\(_, b, _, _) -> b) $ \(a, b, c, d) e -> (a, e, c, d)
  {-# INLINE _2 #-}

instance Has2 ((,,,,) a b c d e) b where
  _2 = lens (\(_, b, _, _, _) -> b) $ \(a, b, c, d, e) f -> (a, f, c, d, e)
  {-# INLINE _2 #-}

instance Has2 ((,,,,,) a b c d e f) b where
  _2 = lens (\(_, b, _, _, _, _) -> b) $ \(a, b, c, d, e, f) g -> (a, g, c, d, e, f)
  {-# INLINE _2 #-}

instance Has3 ((,,) a b c) c where
  _3 = lens (\(_, _, c) -> c) $ \(a, b, c) d -> (a, b, d)
  {-# INLINE _3 #-}

instance Has3 ((,,,) a b c d) c where
  _3 = lens (\(_, _, c, _) -> c) $ \(a, b, c, d) e -> (a, b, e, d)
  {-# INLINE _3 #-}

instance Has3 ((,,,,) a b c d e) c where
  _3 = lens (\(_, _, c, _, _) -> c) $ \(a, b, c, d, e) f -> (a, b, f, d, e)
  {-# INLINE _3 #-}

instance Has3 ((,,,,,) a b c d e f) c where
  _3 = lens (\(_, _, c, _, _, _) -> c) $ \(a, b, c, d, e, f) g -> (a, b, g, d, e, f)
  {-# INLINE _3 #-}

instance Has4 ((,,,) a b c d) d where
  _4 = lens (\(_, _, _, d) -> d) $ \(a, b, c, d) e -> (a, b, c, e)
  {-# INLINE _4 #-}

instance Has4 ((,,,,) a b c d e) d where
  _4 = lens (\(_, _, _, d, _) -> d) $ \(a, b, c, d, e) f -> (a, b, c, f, e)
  {-# INLINE _4 #-}

instance Has4 ((,,,,,) a b c d e f) d where
  _4 = lens (\(_, _, _, d, _, _) -> d) $ \(a, b, c, d, e, f) g -> (a, b, c, g, e, f)
  {-# INLINE _4 #-}

instance Has5 ((,,,,) a b c d e) e where
  _5 = lens (\(_, _, _, _, e) -> e) $ \(a, b, c, d, e) f -> (a, b, c, d, f)
  {-# INLINE _5 #-}

instance Has5 ((,,,,,) a b c d e f) e where
  _5 = lens (\(_, _, _, _, e, _) -> e) $ \(a, b, c, d, e, f) g -> (a, b, c, d, g, f)
  {-# INLINE _5 #-}

instance Has6 ((,,,,,) a b c d e f) f where
  _6 = lens (\(_, _, _, _, _, f) -> f) $ \(a, b, c, d, e, f) g -> (a, b, c, d, e, g)
  {-# INLINE _6 #-}

-- }}}

-- {{{ Handy IO

type StringReader a = State BS.ByteString a

readContents :: StringReader a -> IO a
readContents reader = do
  contents <- BS.getContents
  return $ readFrom contents reader

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

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

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

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

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

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

-- }}}

type SolveState = ([Int], [Int])
type SolveStateMap = Map.Map Int SolveState

data PrefixSolveState = PSS {
  _ssm :: SolveStateMap,
  _total :: Int
}
_pssIso :: CylLens' (SolveStateMap, Int) PrefixSolveState
_pssIso = iso (uncurry PSS) (\(PSS a b) -> (a, b))
ssm :: CylLens' SolveStateMap PrefixSolveState
ssm = _pssIso . _1
total :: CylLens' Int PrefixSolveState
total = _pssIso . _2

solve :: [Int] -> [Int]
solve xs = scanl1 addMod $ fst $ runState resultM (Map.singleton 0 ([], [1]))
  where
    modulo = 1000000007
    factor = 7919

    addMod x y = (x + y) `mod` modulo

    blacklist = map (map (\c -> (ord c) - (ord '0')))
      ["0011", "0101", "1110", "1111"]

    prefixes = xs & scanl (flip (:)) [] & drop 1
    resultM = forM prefixes app

    lastDigits :: CylLens' [Int] SolveState
    lastDigits = _1

    lastCounts :: CylLens' [Int] SolveState
    lastCounts = _2

    p a = (a:) . take 3

    app1 :: Int -> State SolveState ()
    app1 digit = do
      lastDigits %= (p digit)
      (ds, cs) <- get
      let numLastCs = if ds `elem` blacklist then 3 else 4
          newCount = (foldl addMod 0 $ take numLastCs cs)
      lastCounts %= (p newCount)
      return ()

    hashSeq :: [Int] -> [Int]
    hashSeq = drop 1 . scanl (\ph x -> (ph * factor + x + 1) `mod` modulo) 0

    app :: [Int] -> State SolveStateMap Int
    app prefix = prefixResult
      where
        hs = hashSeq prefix

        getPhs :: SolveStateMap -> [(Int, Int, Int)]
        getPhs ssm = prefix
          & zip hs
          & zipWith (\prevH (h, p) -> (prevH, h, p)) (0:hs)

        app' :: (Int, Int, Int) -> State PrefixSolveState ()
        app' (prevH, h, c) = do
          stateMap <- use ssm
          let prevS = stateMap Map.! prevH
              newS = execState (app1 c) prevS
          ssm %= Map.insert h newS
          let cnt = newS ^. lastCounts & head
          total %=  (addMod cnt)

        prefixResult :: State SolveStateMap Int
        prefixResult = do
          stateMap <- get
          let phs = getPhs stateMap
                & filter (not . (`Map.member` stateMap) . (^. _2))
              m = forM_ phs app'
              pss = execState m (PSS stateMap 0)
          put (pss ^. ssm)
          return (pss ^. total)

main :: IO ()
main = do
  s <- readContents $ do
     m <- getInt
     replicateM m getInt
  solve s & map show & unlines & putStrLn
  return ()

{-# LANGUAGE CPP #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}

import Control.Applicative
import Control.Monad
import Data.Char
import Data.Function
import Data.Functor

import qualified Data.Map.Strict as Map
import qualified Data.ByteString.Lazy.Char8 as BS

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

-- {{{ Functors

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

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

-- }}}

-- {{{ Monads

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

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

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

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

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

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

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

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

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

-- }}}

-- {{{ Lens

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

#if __GLASGOW_HASKELL__ < 713
infix 1 &
#endif

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

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

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

-- }}}

-- {{{ Common used lens

class Has1 m a | m -> a where
  _1 :: CylLens' a m

class Has2 m a | m -> a where
  _2 :: CylLens' a m

class Has3 m a | m -> a where
  _3 :: CylLens' a m

class Has4 m a | m -> a where
  _4 :: CylLens' a m

class Has5 m a | m -> a where
  _5 :: CylLens' a m

class Has6 m a | m -> a where
  _6 :: CylLens' a m

instance Has1 ((,) a b) a where
  _1 = lens fst $ \(a, b) c -> (c, b)
  {-# INLINE _1 #-}

instance Has1 ((,,) a b c) a where
  _1 = lens (\(a, _, _) -> a) $ \(a, b, c) d -> (d, b, c)
  {-# INLINE _1 #-}

instance Has1 ((,,,) a b c d) a where
  _1 = lens (\(a, _, _, _) -> a) $ \(a, b, c, d) e -> (e, b, c, d)
  {-# INLINE _1 #-}

instance Has1 ((,,,,) a b c d e) a where
  _1 = lens (\(a, _, _, _, _) -> a) $ \(a, b, c, d, e) f -> (f, b, c, d, e)
  {-# INLINE _1 #-}

instance Has1 ((,,,,,) a b c d e f) a where
  _1 = lens (\(a, _, _, _, _, _) -> a) $ \(a, b, c, d, e, f) g -> (g, b, c, d, e, f)
  {-# INLINE _1 #-}

instance Has2 ((,) a b) b where
  _2 = lens snd $ \(a, b) c -> (a, c)
  {-# INLINE _2 #-}

instance Has2 ((,,) a b c) b where
  _2 = lens (\(_, b, _) -> b) $ \(a, b, c) d -> (a, d, c)
  {-# INLINE _2 #-}

instance Has2 ((,,,) a b c d) b where
  _2 = lens (\(_, b, _, _) -> b) $ \(a, b, c, d) e -> (a, e, c, d)
  {-# INLINE _2 #-}

instance Has2 ((,,,,) a b c d e) b where
  _2 = lens (\(_, b, _, _, _) -> b) $ \(a, b, c, d, e) f -> (a, f, c, d, e)
  {-# INLINE _2 #-}

instance Has2 ((,,,,,) a b c d e f) b where
  _2 = lens (\(_, b, _, _, _, _) -> b) $ \(a, b, c, d, e, f) g -> (a, g, c, d, e, f)
  {-# INLINE _2 #-}

instance Has3 ((,,) a b c) c where
  _3 = lens (\(_, _, c) -> c) $ \(a, b, c) d -> (a, b, d)
  {-# INLINE _3 #-}

instance Has3 ((,,,) a b c d) c where
  _3 = lens (\(_, _, c, _) -> c) $ \(a, b, c, d) e -> (a, b, e, d)
  {-# INLINE _3 #-}

instance Has3 ((,,,,) a b c d e) c where
  _3 = lens (\(_, _, c, _, _) -> c) $ \(a, b, c, d, e) f -> (a, b, f, d, e)
  {-# INLINE _3 #-}

instance Has3 ((,,,,,) a b c d e f) c where
  _3 = lens (\(_, _, c, _, _, _) -> c) $ \(a, b, c, d, e, f) g -> (a, b, g, d, e, f)
  {-# INLINE _3 #-}

instance Has4 ((,,,) a b c d) d where
  _4 = lens (\(_, _, _, d) -> d) $ \(a, b, c, d) e -> (a, b, c, e)
  {-# INLINE _4 #-}

instance Has4 ((,,,,) a b c d e) d where
  _4 = lens (\(_, _, _, d, _) -> d) $ \(a, b, c, d, e) f -> (a, b, c, f, e)
  {-# INLINE _4 #-}

instance Has4 ((,,,,,) a b c d e f) d where
  _4 = lens (\(_, _, _, d, _, _) -> d) $ \(a, b, c, d, e, f) g -> (a, b, c, g, e, f)
  {-# INLINE _4 #-}

instance Has5 ((,,,,) a b c d e) e where
  _5 = lens (\(_, _, _, _, e) -> e) $ \(a, b, c, d, e) f -> (a, b, c, d, f)
  {-# INLINE _5 #-}

instance Has5 ((,,,,,) a b c d e f) e where
  _5 = lens (\(_, _, _, _, e, _) -> e) $ \(a, b, c, d, e, f) g -> (a, b, c, d, g, f)
  {-# INLINE _5 #-}

instance Has6 ((,,,,,) a b c d e f) f where
  _6 = lens (\(_, _, _, _, _, f) -> f) $ \(a, b, c, d, e, f) g -> (a, b, c, d, e, g)
  {-# INLINE _6 #-}

-- }}}

-- {{{ Handy IO

type StringReader a = State BS.ByteString a

readContents :: StringReader a -> IO a
readContents reader = do
  contents <- BS.getContents
  return $ readFrom contents reader

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

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

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

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

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

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

-- }}}

type SolveState = ([Int], [Int])
type SolveStateMap = Map.Map Int SolveState

data PrefixSolveState = PSS {
  _ssm :: SolveStateMap,
  _total :: Int
}
_pssIso :: CylLens' (SolveStateMap, Int) PrefixSolveState
_pssIso = iso (uncurry PSS) (\(PSS a b) -> (a, b))
ssm :: CylLens' SolveStateMap PrefixSolveState
ssm = _pssIso . _1
total :: CylLens' Int PrefixSolveState
total = _pssIso . _2

solve :: [Int] -> [Int]
solve xs = scanl1 (\x y -> (x + y) `mod` modulo)
  $ fst $ runState resultM (Map.singleton 0 ([], [1]))
  where
    modulo = 1000000007
    factor = 1337

    blacklist = map (map (\c -> (ord c) - (ord '0')))
      ["0011", "0101", "1110", "1111"]

    prefixes = xs & scanl (flip (:)) [] & drop 1
    resultM = forM prefixes app

    lastDigits :: CylLens' [Int] SolveState
    lastDigits = _1

    lastCounts :: CylLens' [Int] SolveState
    lastCounts = _2

    p a = (a:) . take 3

    app1 :: Int -> State SolveState ()
    app1 digit = do
      lastDigits %= (p digit)
      (ds, cs) <- get
      let numLastCs = if ds `elem` blacklist then 3 else 4
          newCount = (sum $ take numLastCs cs) `mod` modulo
      lastCounts %= (p newCount)
      return ()

    hashSeq :: [Int] -> [Int]
    hashSeq = drop 1 . scanl (\ph x -> (ph * factor + x + 1) `mod` modulo) 0

    app :: [Int] -> State SolveStateMap Int
    app prefix = prefixResult
      where
        hs = hashSeq prefix

        getPhs :: SolveStateMap -> [(Int, Int, Int)]
        getPhs ssm = prefix
          & zip hs
          & zipWith (\prevH (h, p) -> (prevH, h, p)) (0:hs)

        app' :: (Int, Int, Int) -> State PrefixSolveState ()
        app' (prevH, h, c) = do
          stateMap <- use ssm
          let prevS = stateMap Map.! prevH
              newS = execState (app1 c) prevS
          ssm %= Map.insert h newS
          let cnt = newS ^. lastCounts & head
          total %= (`mod` modulo) . (+cnt)

        prefixResult :: State SolveStateMap Int
        prefixResult = do
          stateMap <- get
          let phs = getPhs stateMap
                & filter (not . (`Map.member` stateMap) . (^. _2))
              m = forM_ phs app'
              pss = execState m (PSS stateMap 0)
          put (pss ^. ssm)
          return (pss ^. total)

main :: IO ()
main = do
  s <- readContents $ do
     m <- getInt
     replicateM m getInt
  solve s & map show & unlines & putStrLn
  return ()

{-# LANGUAGE CPP #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}

import Control.Applicative
import Control.Monad
import Data.Char
import Data.Function
import Data.Functor

import qualified Data.Map.Strict as Map
import qualified Data.ByteString.Lazy.Char8 as BS

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

-- {{{ Functors

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

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

-- }}}

-- {{{ Monads

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

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

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

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

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

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

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

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

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

-- }}}

-- {{{ Lens

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

#if __GLASGOW_HASKELL__ < 713
infix 1 &
#endif

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

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

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

-- }}}

-- {{{ Common used lens

class Has1 m a | m -> a where
  _1 :: CylLens' a m

class Has2 m a | m -> a where
  _2 :: CylLens' a m

class Has3 m a | m -> a where
  _3 :: CylLens' a m

class Has4 m a | m -> a where
  _4 :: CylLens' a m

class Has5 m a | m -> a where
  _5 :: CylLens' a m

class Has6 m a | m -> a where
  _6 :: CylLens' a m

instance Has1 ((,) a b) a where
  _1 = lens fst $ \(a, b) c -> (c, b)
  {-# INLINE _1 #-}

instance Has1 ((,,) a b c) a where
  _1 = lens (\(a, _, _) -> a) $ \(a, b, c) d -> (d, b, c)
  {-# INLINE _1 #-}

instance Has1 ((,,,) a b c d) a where
  _1 = lens (\(a, _, _, _) -> a) $ \(a, b, c, d) e -> (e, b, c, d)
  {-# INLINE _1 #-}

instance Has1 ((,,,,) a b c d e) a where
  _1 = lens (\(a, _, _, _, _) -> a) $ \(a, b, c, d, e) f -> (f, b, c, d, e)
  {-# INLINE _1 #-}

instance Has1 ((,,,,,) a b c d e f) a where
  _1 = lens (\(a, _, _, _, _, _) -> a) $ \(a, b, c, d, e, f) g -> (g, b, c, d, e, f)
  {-# INLINE _1 #-}

instance Has2 ((,) a b) b where
  _2 = lens snd $ \(a, b) c -> (a, c)
  {-# INLINE _2 #-}

instance Has2 ((,,) a b c) b where
  _2 = lens (\(_, b, _) -> b) $ \(a, b, c) d -> (a, d, c)
  {-# INLINE _2 #-}

instance Has2 ((,,,) a b c d) b where
  _2 = lens (\(_, b, _, _) -> b) $ \(a, b, c, d) e -> (a, e, c, d)
  {-# INLINE _2 #-}

instance Has2 ((,,,,) a b c d e) b where
  _2 = lens (\(_, b, _, _, _) -> b) $ \(a, b, c, d, e) f -> (a, f, c, d, e)
  {-# INLINE _2 #-}

instance Has2 ((,,,,,) a b c d e f) b where
  _2 = lens (\(_, b, _, _, _, _) -> b) $ \(a, b, c, d, e, f) g -> (a, g, c, d, e, f)
  {-# INLINE _2 #-}

instance Has3 ((,,) a b c) c where
  _3 = lens (\(_, _, c) -> c) $ \(a, b, c) d -> (a, b, d)
  {-# INLINE _3 #-}

instance Has3 ((,,,) a b c d) c where
  _3 = lens (\(_, _, c, _) -> c) $ \(a, b, c, d) e -> (a, b, e, d)
  {-# INLINE _3 #-}

instance Has3 ((,,,,) a b c d e) c where
  _3 = lens (\(_, _, c, _, _) -> c) $ \(a, b, c, d, e) f -> (a, b, f, d, e)
  {-# INLINE _3 #-}

instance Has3 ((,,,,,) a b c d e f) c where
  _3 = lens (\(_, _, c, _, _, _) -> c) $ \(a, b, c, d, e, f) g -> (a, b, g, d, e, f)
  {-# INLINE _3 #-}

instance Has4 ((,,,) a b c d) d where
  _4 = lens (\(_, _, _, d) -> d) $ \(a, b, c, d) e -> (a, b, c, e)
  {-# INLINE _4 #-}

instance Has4 ((,,,,) a b c d e) d where
  _4 = lens (\(_, _, _, d, _) -> d) $ \(a, b, c, d, e) f -> (a, b, c, f, e)
  {-# INLINE _4 #-}

instance Has4 ((,,,,,) a b c d e f) d where
  _4 = lens (\(_, _, _, d, _, _) -> d) $ \(a, b, c, d, e, f) g -> (a, b, c, g, e, f)
  {-# INLINE _4 #-}

instance Has5 ((,,,,) a b c d e) e where
  _5 = lens (\(_, _, _, _, e) -> e) $ \(a, b, c, d, e) f -> (a, b, c, d, f)
  {-# INLINE _5 #-}

instance Has5 ((,,,,,) a b c d e f) e where
  _5 = lens (\(_, _, _, _, e, _) -> e) $ \(a, b, c, d, e, f) g -> (a, b, c, d, g, f)
  {-# INLINE _5 #-}

instance Has6 ((,,,,,) a b c d e f) f where
  _6 = lens (\(_, _, _, _, _, f) -> f) $ \(a, b, c, d, e, f) g -> (a, b, c, d, e, g)
  {-# INLINE _6 #-}

-- }}}

-- {{{ Handy IO

type StringReader a = State BS.ByteString a

readContents :: StringReader a -> IO a
readContents reader = do
  contents <- BS.getContents
  return $ readFrom contents reader

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

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

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

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

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

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

-- }}}

type SolveState = ([Int], [Int])
type SolveStateMap = Map.Map Int SolveState

data PrefixSolveState = PSS {
  _ssm :: SolveStateMap,
  _total :: Int
}
_pssIso :: CylLens' (SolveStateMap, Int) PrefixSolveState
_pssIso = iso (uncurry PSS) (\(PSS a b) -> (a, b))
ssm :: CylLens' SolveStateMap PrefixSolveState
ssm = _pssIso . _1
total :: CylLens' Int PrefixSolveState
total = _pssIso . _2

solve :: [Int] -> [Int]
solve xs = scanl1 addMod $ fst $ runState resultM (Map.singleton 0 ([], [1]))
  where
    modulo = 1000000007
    factor = 1337

    addMod x y = (x + y) `mod` modulo

    blacklist = map (map (\c -> (ord c) - (ord '0')))
      ["0011", "0101", "1110", "1111"]

    prefixes = xs & scanl (flip (:)) [] & drop 1
    resultM = forM prefixes app

    lastDigits :: CylLens' [Int] SolveState
    lastDigits = _1

    lastCounts :: CylLens' [Int] SolveState
    lastCounts = _2

    p a = (a:) . take 3

    app1 :: Int -> State SolveState ()
    app1 digit = do
      lastDigits %= (p digit)
      (ds, cs) <- get
      let numLastCs = if ds `elem` blacklist then 3 else 4
          newCount = (foldl addMod 0 $ take numLastCs cs) `mod` modulo
      lastCounts %= (p newCount)
      return ()

    hashSeq :: [Int] -> [Int]
    hashSeq = drop 1 . scanl (\ph x -> (ph * factor + x + 1) `mod` modulo) 0

    app :: [Int] -> State SolveStateMap Int
    app prefix = prefixResult
      where
        hs = hashSeq prefix

        getPhs :: SolveStateMap -> [(Int, Int, Int)]
        getPhs ssm = prefix
          & zip hs
          & zipWith (\prevH (h, p) -> (prevH, h, p)) (0:hs)

        app' :: (Int, Int, Int) -> State PrefixSolveState ()
        app' (prevH, h, c) = do
          stateMap <- use ssm
          let prevS = stateMap Map.! prevH
              newS = execState (app1 c) prevS
          ssm %= Map.insert h newS
          let cnt = newS ^. lastCounts & head
          total %= (`mod` modulo) . (+cnt)

        prefixResult :: State SolveStateMap Int
        prefixResult = do
          stateMap <- get
          let phs = getPhs stateMap
                & filter (not . (`Map.member` stateMap) . (^. _2))
              m = forM_ phs app'
              pss = execState m (PSS stateMap 0)
          put (pss ^. ssm)
          return (pss ^. total)

main :: IO ()
main = do
  s <- readContents $ do
     m <- getInt
     replicateM m getInt
  solve s & map show & unlines & putStrLn
  return ()


In this problem we consider a very simplified model of Barcelona city.Barcelona can be represented as a plane with streets of kind $$$x = c$$$ and $$$y = c$$$ for every integer $$$c$$$ (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal which can be represented as a the set of points $$$(x, y)$$$ for which $$$ax + by + c = 0$$$.One can walk along streets, including the avenue. You are given two integer points $$$A$$$ and $$$B$$$ somewhere in Barcelona. Find the minimal possible distance one needs to travel to get to $$$B$$$ from $$$A$$$.

The first line contains three integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$-10^9\leq a, b, c\leq 10^9$$$, at least one of $$$a$$$ and $$$b$$$ is not zero) representing the Diagonal Avenue. The next line contains four integers $$$x_1$$$, $$$y_1$$$, $$$x_2$$$ and $$$y_2$$$ ($$$-10^9\leq x_1, y_1, x_2, y_2\leq 10^9$$$) denoting the points $$$A = (x_1, y_1)$$$ and $$$B = (x_2, y_2)$$$.

Find the minimum possible travel distance between $$$A$$$ and $$$B$$$. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.

NoteThe first example is shown on the left picture while the second example us shown on the right picture below. The avenue is shown with blue, the origin is shown with the black dot.

import Data.List

toint s = (read s) :: Double

dist x1 y1 x2 y2 = sqrt ((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))

f0 a b c x1 y1 x2 y2 = abs(x1-x2)+abs(y1-y2)

f1 a b c x1 y1 x2 y2 = -- x,x
	let yy1 = (-c-a*x1)/b in
	let yy2 = (-c-a*x2)/b in
	abs(y1-yy1)+abs(y2-yy2)+dist x1 yy1 x2 yy2

f2 a b c x1 y1 x2 y2 =
	let yy1 = (-c-a*x1)/b in
	let xx2 = (-c-b*y2)/a in
	abs(y1-yy1)+abs(x2-xx2)+dist x1 yy1 xx2 y2

f3 a b c x1 y1 x2 y2 =
	let xx1 = (-c-b*y1)/a in
	let yy2 = (-c-a*x2)/b in
	abs(x1-xx1)+abs(y2-yy2)+dist xx1 y1 x2 yy2

f4 a b c x1 y1 x2 y2 =
	let xx1 = (-c-b*y1)/a in
	let xx2 = (-c-b*y2)/a in
	abs(x1-xx1)+abs(x2-xx2)+dist xx1 y1 xx2 y2

solve::String -> String
solve ss =
	let a:b:c:x1:y1:x2:y2:_ = map toint $ words ss in
	if abs(b)<0.5 || abs(a)<0.5 then
		show(minimum [f0 a b c x1 y1 x2 y2])++"\n"
	else
		show(minimum [f0 a b c x1 y1 x2 y2, f1 a b c x1 y1 x2 y2, f2 a b c x1 y1 x2 y2, f3 a b c x1 y1 x2 y2, f4 a b c x1 y1 x2 y2])++"\n"

main = do
  interact $ solve


Ivan has $$$n$$$ songs on his phone. The size of the $$$i$$$-th song is $$$a_i$$$ bytes. Ivan also has a flash drive which can hold at most $$$m$$$ bytes in total. Initially, his flash drive is empty.Ivan wants to copy all $$$n$$$ songs to the flash drive. He can compress the songs. If he compresses the $$$i$$$-th song, the size of the $$$i$$$-th song reduces from $$$a_i$$$ to $$$b_i$$$ bytes ($$$b_i < a_i$$$).Ivan can compress any subset of the songs (possibly empty) and copy all the songs to his flash drive if the sum of their sizes is at most $$$m$$$. He can compress any subset of the songs (not necessarily contiguous).Ivan wants to find the minimum number of songs he needs to compress in such a way that all his songs fit on the drive (i.e. the sum of their sizes is less than or equal to $$$m$$$).If it is impossible to copy all the songs (even if Ivan compresses all the songs), print "-1". Otherwise print the minimum number of songs Ivan needs to compress.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^5, 1 \le m \le 10^9$$$) — the number of the songs on Ivan's phone and the capacity of Ivan's flash drive. The next $$$n$$$ lines contain two integers each: the $$$i$$$-th line contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$, $$$a_i > b_i$$$) — the initial size of the $$$i$$$-th song and the size of the $$$i$$$-th song after compression.

If it is impossible to compress a subset of the songs in such a way that all songs fit on the flash drive, print "-1". Otherwise print the minimum number of the songs to compress.

NoteIn the first example Ivan can compress the first and the third songs so after these moves the sum of sizes will be equal to $$$8 + 7 + 1 + 5 = 21 \le 21$$$. Also Ivan can compress the first and the second songs, then the sum of sizes will be equal $$$8 + 4 + 3 + 5 = 20 \le 21$$$. Note that compressing any single song is not sufficient to copy all the songs on the flash drive (for example, after compressing the second song the sum of sizes will be equal to $$$10 + 4 + 3 + 5 = 22 > 21$$$).In the second example even if Ivan compresses all the songs the sum of sizes will be equal $$$8 + 4 + 1 + 4 = 17 > 16$$$.

{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Function (fix)
import Data.Array (Array, array, (!))
import System.IO
import Data.ByteString.Lazy.Builder
import Data.ByteString.Lazy.Builder.ASCII
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

construct :: BS.ByteString -> [Integer]
construct str
    | BS.null str = []
    | isSpace (BS8.head str) = construct (BS8.tail str)
    | otherwise = let Just (i, other) = BS8.readInteger str in i : construct other

getInts :: IO [Integer]
getInts = construct `fmap` BS.getLine

fastPrint :: Char -> [Int] -> IO ()
fastPrint mid arr = hPutBuilder stdout  $ build arr
    where build = foldr (\n b -> intDec n <> charUtf8 mid <> b) mempty

solve songs capa = reduce sorted (total-capa) 0
    where sorted = sortBy (\[a,b] [c,d] -> compare (b-a) (d-c)) songs
          total = sum $ map head songs
          reduce [] now r = if now > 0 then -1 else r
          reduce ([a,b]:xs) now r = if now <= 0 then r else reduce xs (now - (a-b)) (r+1)

main = do
    [n,m] <- getInts
    songs <- replicateM (fromIntegral n) getInts
    print (solve songs m)

{-# LANGUAGE BangPatterns #-}
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Function (fix)
import Data.Array (Array, array, (!))
import System.IO
import Data.ByteString.Lazy.Builder
import Data.ByteString.Lazy.Builder.ASCII
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

construct :: BS.ByteString -> [Int]
construct str
    | BS.null str = []
    | isSpace (BS8.head str) = construct (BS8.tail str)
    | otherwise = let Just (i, other) = BS8.readInt str in i : construct other

getInts :: IO [Int]
getInts = construct `fmap` BS.getLine

fastPrint :: Char -> [Int] -> IO ()
fastPrint mid arr = hPutBuilder stdout  $ build arr
    where build = foldr (\n b -> intDec n <> charUtf8 mid <> b) mempty

solve songs capa = reduce sorted (total-capa) 0
    where sorted = sortBy (\[a,b] [c,d] -> compare (b-a) (d-c)) songs
          total = sum $ map head songs
          reduce [] now r = if now > 0 then -1 else r
          reduce ([a,b]:xs) now r = if now <= 0 then r else reduce xs (now - (a-b)) (r+1)

main = do
    [n,m] <- getInts
    songs <- replicateM n getInts
    print (solve songs m)


You are given three positive integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$a < b < c$$$). You have to find three positive integers $$$x$$$, $$$y$$$, $$$z$$$ such that:$$$$$$x \bmod y = a,$$$$$$ $$$$$$y \bmod z = b,$$$$$$ $$$$$$z \bmod x = c.$$$$$$Here $$$p \bmod q$$$ denotes the remainder from dividing $$$p$$$ by $$$q$$$. It is possible to show that for such constraints the answer always exists.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10\,000$$$) — the number of test cases. Description of the test cases follows. Each test case contains a single line with three integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a < b < c \le 10^8$$$).

For each test case output three positive integers $$$x$$$, $$$y$$$, $$$z$$$ ($$$1 \le x, y, z \le 10^{18}$$$) such that $$$x \bmod y = a$$$, $$$y \bmod z = b$$$, $$$z \bmod x = c$$$. You can output any correct answer.

parse :: String -> [(Int, Int, Int)]
parse input =  case lines input of
    [] -> undefined
    (w:ws) -> parseN (read w) ws
    where
        parseLine :: String -> (Int, Int, Int)
        parseLine = (\[a, b, c] -> (a, b, c)) . map read . take 3 . words
        parseN :: Int -> [String] -> [(Int, Int, Int)]
        parseN t = map parseLine . take t

solve :: [(Int, Int, Int)] -> [(Int, Int, Int)]
solve = map (\(a, b, c) -> (a+b+c, b+c, c))

format :: [(Int, Int, Int)] -> String
format = unlines . map (unwords . (\(x, y, z) -> [show x, show y, show z]))

main :: IO ()
main = interact (format . solve . parse)

import Control.Monad (replicateM_)

solve :: Integer -> Integer -> Integer -> [Integer]
solve a b c = [a + b + c, b + c, c]

main = do
    n <- readLn :: IO Int
    replicateM_ n $ do
        [a, b, c] <- map read . words <$> getLine :: IO [Integer]
        putStrLn $ unwords $ map show $ solve a b c

-- https://codeforces.com/contest/1679/problem/D
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}

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

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

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

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

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

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

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace

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

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

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

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

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

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

{- END OF GENERAL -}

solve :: (Int, Int, Int) -> (Int, Int, Int)
solve (a, b, c) = (a + b + c, b + c, c)

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [a, b, c] <- B8.getLine <&> readIntB8s
        let (x, y, z) = solve (a, b, c)
        printf "%d %d %d\n" x y z

mainLoop 0 = return ()
mainLoop t = do line <- getLine
                let [a, b, c] = map (read :: String -> Int) (words line)
                putStrLn (unwords [show (a + b + c), show (b + c), show c])
                mainLoop (t - 1)

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

main :: IO ()
main = do
	n <- getLine
	let number = read n :: Int
	solve number number
	return ()

solve :: Int -> Int -> IO ()
solve number 0 = return ()
solve number current = 	do
				line <- getLine
				let ws = words line
				let a = (read $ head ws) :: Int
				let b = (read $ head $ tail ws) :: Int
				let c = (read $ head $ tail $ tail ws) :: Int
				let x = a + b + c
				let y = b + c
				let z = c
				putStrLn $ (show x) ++ " " ++ (show y) ++ " " ++ (show z)
				solve number (current - 1)

import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import System.IO

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

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

putInts :: [Int] -> Builder
putInts [] = charUtf8 '\n'
putInts (x : xs) = intDec x <> charUtf8 ' ' <> putInts xs

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    [a, b, c] <- getInts
    let k = (c - a) `div` b + 1
    return $ putInts [k * b + a, b, c]
  hPutBuilder stdout output

parse :: String -> [(Int, Int, Int)]
parse input =  case lines input of
    [] -> undefined
    (w:ws) -> parseN (read w) ws
    where
        parseLine :: String -> (Int, Int, Int)
        parseLine = (\[a, b, c] -> (a, b, c)) . map read . take 3 . words
        parseN :: Int -> [String] -> [(Int, Int, Int)]
        parseN t = map parseLine . take t

solve :: [(Int, Int, Int)] -> [(Int, Int, Int)]
solve = map (\(a, b, c) -> (a+b+c, a+b, c))

format :: [(Int, Int, Int)] -> String
format = unlines . map (unwords . (\(x, y, z) -> [show x, show y, show z]))

main :: IO ()
main = interact (format . solve . parse)

parse :: String -> (Int, Int, Int)
parse = (\[a, b, c] -> (a, b, c)) . map read . take 3 . words

solve :: (Int, Int, Int) -> (Int, Int, Int)
solve (a, b, c) = (a+b+c, a+b, c)

format :: (Int, Int, Int) -> String
format (x, y, z) = unwords $ map show [x, y, z]

main :: IO ()
main = interact (format . solve . parse)

import Control.Monad (replicateM_)

solve :: Int -> Int -> Int -> [Int]
solve a b c = [a + b + c, b + c, c]

main = do
    n <- readLn :: IO Int
    replicateM_ n $ do
        [a, b, c] <- map read . words <$> getLine :: IO [Int]
        print $ unwords $ map show $ solve a b c