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

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

data ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil

main :: IO ()
main = do
  [n,s] <- map read . words <$> getLine :: IO [Int]
  vals <- valencies n <$> BSL.getContents
  print $ (fromIntegral (2*s) /)
    (fromIntegral $ length $ filter (==1) $ A.elems $ vals ::Double)

valencies :: Int -> BSL.ByteString -> UArray Int Int
valencies n bstr = runSTUArray $ do
  valencies_ <- A.newArray (1,n) (0::Int)
  forM_ (take (2*n-2) $ unfoldr (BSL.readInt . BSL.dropWhile (<'-')) bstr)
    $ \ v -> A.readArray valencies_ v >>= A.writeArray valencies_ v . (+1)
  return valencies_

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

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

data ListInt = Cons {-# UNPACK #-} !Int !ListInt | Nil

main :: IO ()
main = do
  [n,s] <- map read . words <$> getLine :: IO [Int]
  codd <- preprocess n <$> BSL.getContents
  print $ (fromIntegral (2*s) /) (fromIntegral $ valency1 codd ::Double)
    where
      {-# INLINE processInt #-}
      processInt = \(!i,!bs) -> do
        (!e,!bs1) <- BS.readInt $ BS.dropWhile (< '-') bs
        return $! ((i,e),(i+1,bs1))

{-# INLINE children_ #-}
children_ :: UArray Int Int -> Int -> Int -> [Int]
children_ codd parent this =
  filter (/= parent)
  $ map (codd A.!) [codd A.! (this-1) .. codd A.! this - 1]

valency1 :: UArray Int Int -> Int
valency1 !codd = leaves codd (-1) 1 + if length children <= 1 then 1 else 0
  where
    children = children_ codd (-1) 1

leaves :: UArray Int Int -> Int -> Int -> Int
leaves !codd parent this
  | null children = 1
  | otherwise     = sum $ map (leaves codd this) children
  where
    children = children_ codd parent this

{-# INLINE preprocess #-}
preprocess :: Int -> BSL.ByteString -> UArray Int Int
preprocess n bstr = codd
  where
    {-# INLINE processInt #-}
    processInt = \(!i,!bs) -> do
      (!e,!bs1) <- BSL.readInt $ BSL.dropWhile (< '-') bs
      return $! ((i,e),(i+1,bs1))
    -- domcods :: UArray Int Int
    -- domcods = A.array (0, 2*n - 3) $ unfoldr processInt (0,bstr)
    codd :: UArray Int Int
    codd = runSTUArray $ do
      domcods_ <- A.newArray_ (0,2*n-3) :: ST s (STUArray s Int Int)
      arr <- A.newArray (0,3*n-2) 0
      forM_ (take (2*n-2) $ unfoldr processInt (0,bstr)) $ \ (!i,!e) -> do
        A.writeArray domcods_ i e
      forM_ [0..2*n-3] $ \ !i -> do
        j <- A.readArray domcods_ i
        when (j < n) $ do
          x <- A.readArray arr (j+1)
          A.writeArray arr (j+1) (x+1)
      A.writeArray arr 0 (n+1)
      forM_ [1..n] $ \ !i -> do
        x <- A.readArray arr (i-1)
        y <- A.readArray arr i
        A.writeArray arr i (x+y)
      forM_ [0,2..2*(n-2)] $ \ !i -> do
        dom <- A.readArray domcods_ i
        cod <- A.readArray domcods_ (i+1)
        j_dom <- A.readArray arr dom
        A.writeArray arr dom (j_dom+1)
        A.writeArray arr j_dom cod
        j_cod <- A.readArray arr cod
        A.writeArray arr cod (j_cod+1)
        A.writeArray arr j_cod dom
      return arr


import Control.Applicative
main = do
  n <- readLn
  a <- map read . words <$> getLine
  print $ solve a (0, 0) (101, 0) 0 n

solve [] (_, a) (_, b) _ n = a + n - b - 1 - if a > b then 1 else 0
solve (a:as) (ma, maxp) (mi, minp) p n =
  solve as (if ma < a then (a, p) else (ma, maxp)) (if mi >= a then (a, p) else (mi, minp)) (p+1) n

import Data.List
import Control.Monad

placemax list =
    let
        (list0, list1) = span (> minimum list) (reverse list)

    in length list0

placemin list =
    let
        (list0, list1) = span (< maximum list) list
        list' = head list1 : (list0 ++ tail list1)

    in (length list0, list')

main = do
    n <- liftM read getLine :: IO Int
    list <- liftM (map read . words) getLine :: IO [Int]

    let (ans1, list') = placemin list
        ans2 = placemax list'

    putStrLn $ show $ ans1 + ans2

m=minimum
x=maximum
s(_:h)=q(n+m(l$x h)-x(l$m h)-1)where n=length h;q x|x<n=x|1>0=x-1;l k=[i|i<-[0..n-1],h!!i==k]
main=interact$show.s.map read.words

m=minimum
x=maximum
s(c:h)=q$n+m(l$x h)-x(l$m h)where n=c-1;q x|x>n=x-1|1>0=x;l k=[i|i<-[0..n],h!!i==k]
main=interact$show.s.map read.words

m=minimum
x=maximum
s(n:h)|r<n=r|1>0=r-1 where r=n+m(l$x h)-1-x(l$m h);l k=[i|i<-[0..n-1],h!!i==k]
main=interact$show.s.map read.words

m=minimum
x=maximum
s(n:h)=q$n+m(l$x h)-1-x(l$m h)where q x|x<n=x|1>0=x-1;l k=[i|i<-[0..n-1],h!!i==k]
main=interact$show.s.map read.words

import Control.Applicative
import Data.List

main= do
	n<- read <$> getLine ::IO Int
	x<- map read. words <$> getLine ::IO [Int]
	let x1 = minimum x
	let p1 = last $ elemIndices x1 x
	let x2 = maximum x
	let p2 = head $ elemIndices x2 x
	print $ p2 + n-p1-1 + if (p2>p1) then (-1) else 0

{-
A. Arrival of the General
==========================
time limit per test: 2 seconds
memory limit per test: 256 megabytes
input: standard input
output: standard output

A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.

By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.

For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.

Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

Input
-----
The first input line contains the only integer n (2 ≤ n ≤ 100) which represents the number of soldiers in the line. The second line contains integers a1, a2, ..., an (1 ≤ ai ≤ 100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1, a2, ..., an are not necessarily different.

Output
------
Print the only integer — the minimum number of seconds the colonel will need to form a line-up the general will like.

Sample test(s)
--------------
input
4
33 44 11 22
output
2

input
7
10 10 58 31 63 40 76
output
10

Note
------
In the first sample the colonel will need to swap the first and second soldier and then the third and fourth soldier. That will take 2 seconds. The resulting position of the soldiers is (44, 33, 22, 11).

In the second sample the colonel may swap the soldiers in the following sequence:

(10, 10, 58, 31, 63, 40, 76)
(10, 58, 10, 31, 63, 40, 76)
(10, 58, 10, 31, 63, 76, 40)
(10, 58, 10, 31, 76, 63, 40)
(10, 58, 31, 10, 76, 63, 40)
(10, 58, 31, 76, 10, 63, 40)
(10, 58, 31, 76, 63, 10, 40)
(10, 58, 76, 31, 63, 10, 40)
(10, 76, 58, 31, 63, 10, 40)
(76, 10, 58, 31, 63, 10, 40)
(76, 10, 58, 31, 63, 40, 10)
-}
import Data.List (elemIndices)

swapNumber :: [Int] -> Int
swapNumber xs = (posMax - 1 + lenXS - posMin) + if (posMax > posMin) then -1 else 0
  where
    lenXS  = length xs
    posMax = (head $ elemIndices (maximum xs) xs) + 1 :: Int -- count from 1
    posMin = (last $ elemIndices (minimum xs) xs) + 1 :: Int -- count from 1

reader :: String -> [Int]
reader s = map read $ words ss
  where _:ss:_ = lines s

main = do
  input <- getContents
  let xs = reader input
  print $ swapNumber xs

import Data.List
main = interact $ show . f . map read . words . (!! 1) . lines
         where f :: [Int] -> Int
               f x = length x - 1 - mini + maxi - if maxi > mini then 1 else 0
                 where maxi = head $ elemIndices (maximum x) x
                       mini = last $ elemIndices (minimum x) x

import Data.List
main = getLine >> getLine >>= putStrLn.show.solve.map read.words

solve :: [Int] -> Int
solve soldiers = tallest + shortest - crossed
  where find f set = maybe 0 (+0) $ findIndex (==f set) set
        tallest    = find maximum soldiers
        shortest   = find minimum $ reverse soldiers
        crossed    = if tallest + shortest < length soldiers then 0 else 1

import Data.List (maximumBy, minimumBy)
import Data.Ord (comparing)

maxIndex ::  Ord a => [a] -> Int
maxIndex = fst . maximumBy (comparing snd) . zip [0..]

minIndex :: Ord a => [a] -> Int
minIndex = fst . minimumBy (comparing snd) . zip [0..]

process :: [Int] -> Int
process xs
    | imax + imin > n-1 = imax + imin - 1
    | otherwise = imax + imin
    where
        n = length xs
        xs' = reverse xs
        imax = n-1 - maxIndex xs'
        imin = minIndex xs'

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    xs <- fmap (map readInt.words) getLine
    print $ process xs

import Data.List
import Data.Char

ans xs = if mi>ma then ma+(length xs) -mi-1 else ma+(length xs)-mi-2
    where (mi,ma)=(last $ elemIndices (minimum xs) xs,head $ elemIndices (maximum xs) xs)

main = do
    getLine
    n<-getLine
    let input = map (\x->read x::Int) $ words n
    print $ ans input

import Data.List

main = interact $ show . s . map read . tail . words

s :: [Int] -> Int
s xs = length xs + maxIn xs - minIn xs - if maxIn xs > minIn xs then 2 else 1 where
    maxIn t = head (elemIndices (maximum t) t)
    minIn t = last (elemIndices (minimum t) t)

import Data.List
import Data.Maybe

cost :: [Int] -> Int
cost sq =
    let mx = maximum sq
        mn = minimum sq
        leftTall = fromJust $ elemIndex mx sq
        rightShort = last $ elemIndices mn sq
        len = length sq
        extraDecrement = if (leftTall > rightShort) then 1 else 0
    in leftTall + len - rightShort - 1 - extraDecrement

solve :: String -> String
solve = show . cost . map read . tail. words

main :: IO ()
main = interact $ solve

module Main (main)
    where

import Data.List (elemIndices)

readInts :: String -> [Int]
readInts = map read . words

indices :: [Int] -> (Int, Int, Int)
indices xs = let (a,b) = (minimum xs, maximum xs)
                 n = length xs
              in (n,
                  last $ a `elemIndices` xs,
                  head $ b `elemIndices` xs)

main :: IO ()
main = print . steps . indices . map read . words =<< (getLine >> getLine)
    where steps (n,a,b) = let i = if a < b then -1 else 0
                           in i + n + b - a - 1

import Data.List
import Data.Maybe

-- Snippet: readItems
readItems = do
    line <- getLine
    return $ map read $ words line

main = do
    n <- readLn
    a <- readItems :: IO [Int]
    let diffMin = fromJust $ findIndex (== (minimum a)) (reverse a)
    let diffMax = fromJust $ findIndex (== (maximum a)) a
    let diff = diffMin + diffMax
    putStrLn $ show $ if diff < n then diff else diff - 1

minIndex :: [Int] -> (Int, Int)
minIndex [x] = (0, x)
minIndex (x:l) =
  let (i, y) = minIndex l
  in if x < y then (0, x) else (i+1, y)

maxIndex :: [Int] -> (Int, Int)
maxIndex [x] = (0, x)
maxIndex (x:l) =
  let (i, y) = maxIndex l
  in if x >= y then (0, x) else (i+1, y)

main = do
  getLine
  line <- getLine
  let soldiers = map read $ words line
      min = fst $ minIndex soldiers
      max = fst $ maxIndex soldiers
      len = length soldiers
      secs = max + (len - 1 - min) - if max > min then 1 else 0
  putStrLn $ show secs

import Data.List
import Data.Maybe

main = do
  getLine
  as <- fmap (map read . words) getLine :: IO [Int]
  let
    n = length as
    i = fromJust (elemIndex (maximum as) as)
    j = n-1 - (fromJust $ elemIndex (minimum as) (reverse as))

  print $ if i < j then i + (n-1-j) else i + (n-1-j) - 1

import Data.List
import Data.List.Split

(|>) x f = f x
main = interact solve

solve contents = let
  nums = contents |> lines |> (!! 1) |> words |> map read :: [Int]
  in swaps nums |> show

swaps nums = let
  mx = maximum nums
  (before, after) = span (/= mx) nums
  nums' = (head after):(before ++ tail after)
  mn = minimum nums'
  lastMinIndex = nums' |> findIndices (== mn) |> last
  in length before + length nums - 1 - lastMinIndex

import Data.List

main = interact $ show . solve . input

input :: String -> [Int]
input = (map read) . words

solve (n:xs) = posMax + (n - posMin - 1) - swapMaxMin where
    posMax = minimum (maximum xs `elemIndices` xs)
    posMin = maximum (minimum xs `elemIndices` xs)
    swapMaxMin = if posMin < posMax then 1 else 0

import Control.Applicative
main = do
  n <- readLn
  a <- map read . words <$> getLine
  print $ solve a (0, 0) (101, 0) 0 n

solve [] (_, a) (_, b) _ n = a+n-b-1-(if a > b then 1 else 0)
solve (a:as) (ma, maxp) (mi, minp) p n =
  solve as (if ma < a then (a, p) else (ma, maxp)) (if mi >= a then (a, p) else (mi, minp)) (p+1) n

getminTail ::[Int] ->Int
getminTail a = fst$last$filter (\x -> snd x == minimum a) (zip [1..(length a)] a)
getmaxHead ::[Int] ->Int
getmaxHead a = fst$head$filter (\x -> snd x == maximum a) (zip [1..(length a)] a)
calc ::Int ->Int -> Int -> Int
calc n mt mh |mt < mh = (n-mt)+(mh-2)
             |otherwise =(n-mt)+(mh-1)
getAns ::[Int] -> Int
getAns a = calc (length a) (getminTail a) (getmaxHead a)
main=interact$show.getAns.(map read).tail.words

import Data.List
import Data.Maybe
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ show.solve . concat.map (map read.words).take 2 . lines
solve :: [Int]->Int
solve (x:xs) = let  minidx = last $ elemIndices  (minimum xs) xs  ; maxidx = fromJust $ elemIndex  (maximum xs) xs in if maxidx<minidx then maxidx +x-minidx-1 else maxidx +x-minidx-2

import List

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

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

firstMaximum :: [Int] -> Int
firstMaximum xs = head (elemIndices (maximum xs) xs)

lastMinimum :: [Int] -> Int
lastMinimum xs = head (elemIndices (minimum xs) (reverse xs))

solve :: Int -> [Int] -> Int
solve n xs
  | (a + b) >= n  =  a + b - 1
  | otherwise     =  a + b
  where
    a = firstMaximum xs
    b = lastMinimum xs

main :: IO ()
main = do
    n <- readLn
    xs <- Main.reads
    print (solve n xs)

import Control.Applicative
import Data.List (elemIndices)

main = do
  n <- read <$> getLine
  xs <- map read . words <$> getLine :: IO [Int]
  let mn = minimum xs
      mx = maximum xs
      mxi = head . elemIndices mx $ xs
      mni = last . elemIndices mn $ xs
  print $ n-1-mni + mxi - if mxi > mni then 1 else 0

rightMostMin nos = snd $ foldl newMin (101, 0) (zip nos [0..])
  where newMin (a, b) (x, y) = if a >= x
                               then (x, y)
                               else (a, b)

leftMostMax nos = snd $ foldr newMax (-1, 0) (zip nos [0..])
  where newMax (x, y) (a, b) = if x >= a
                               then (x, y)
                               else (a, b)

getMinTime :: Int -> [Int] -> Int
getMinTime n nos | minPos > maxPos = (n - 1 - minPos) + maxPos
                 | otherwise = (n - 1 - minPos) + maxPos - 1
                   where minPos = rightMostMin nos
                         maxPos = leftMostMax nos

main = do
  line <- getLine
  let n = read line :: Int
  line <- getLine
  let nos = map (\x -> read x :: Int) (words line)
      ans = getMinTime n nos
  putStrLn $ show ans

import Control.Monad
import Data.Array
import Data.Char
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
-- import qualified Data.Text as T
import qualified Data.ByteString.Char8 as B
getList :: Read a => IO [a]
getList = fmap (map (read . B.unpack) . B.words) B.getLine
getIntList :: IO [Int]
getIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine

solve :: [Int] -> Int
solve a = maxH + (n - 1 - minL) + (if maxH < minL then 0 else -1)
    where n    = length a
          maxi = maximum a
          mini = minimum a
          maxH = head $ elemIndices maxi a
          minL = last $ elemIndices mini a

main :: IO ()
main = do
        _ <- getLine
        a <- getIntList
        print $ solve a

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

process a  = pma  +  pmi  + if pma >=(length a- pmi) then (-1) else 0
    where mi = minimum a
          ma = maximum a
          pmi = fromJust $ elemIndex mi (reverse a)
          pma = fromJust $ elemIndex ma a

main=do
    getLine
    a<-map read <$> words <$> getLine ::IO [Int]
    print $ process a

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph

parseInput = do
    n <- readInt
    seq <- replicateM n readInt
    return seq
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

main = print =<< solve . evalState parseInput <$> BS.getContents

solve seq = ans
  where
    maxv = maximum seq
    minv = minimum seq

    n = length seq

    ans = minimum [ i + (n - 1 - j) - if j < i then 1 else 0
                  | (i, ai) <- zip [0..] seq
                  , (j, aj) <- zip [0..] seq
                  , ai == maxv && aj == minv && i /= j
                  ]

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

class (Monad m) => MonadState s m | m -> s where
	get :: m s
	put :: s -> m ()

modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
	s <- get
	put (f s)

gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
	s <- get
	return (f s)

newtype State s a = State { runState :: s -> (a, s) }

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

instance Applicative (State s) where
    pure = return
    (<*>) = ap

instance Monad (State s) where
	return a = State $ \s -> (a, s)
	m >>= k  = State $ \s -> let
		(a, s') = runState m s
		in runState (k a) s'

instance MonadState s (State s) where
	get   = State $ \s -> (s, s)
	put s = State $ \_ -> ((), s)

evalState :: State s a -> s -> a
evalState m s = fst (runState m s)

execState :: State s a -> s -> s
execState m s = snd (runState m s)

mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m

withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f

state = State

import Data.List ((\\), elemIndex)
import Data.Maybe (fromJust)

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

solve :: [Int] -> Int
solve xs = fromJust (elemIndex (maximum xs) xs) + fromJust (elemIndex (minimum xs) xs')
  where xs' = reverse (xs \\ [maximum xs])

import Data.List
main = do
  n <- readLn
  as <- fmap (map read . words) getLine :: IO [Int]
  let i = head (elemIndices (maximum as) as)
      j = last (elemIndices (minimum as) as)
  print $ i + n - j - 1 - if i > j then 1 else 0

import Data.List
solve :: [Int] -> Int
solve xs | ok xs = 0
         | otherwise = solve (step xs) + 1
ok :: [Int] -> Bool
ok xs = head xs == maximum xs && last xs == minimum xs
step :: [Int] -> [Int]
step xs | head xs == maximum xs = exchange2 xs minIndex
        | otherwise = exchange2 xs $ maxIndex-1
    where minIndex = last $ elemIndices (minimum xs) xs
          maxIndex = head $ elemIndices (maximum xs) xs
exchange2 :: [a] -> Int -> [a]
exchange2 (x:y:ys) 0 = y:x:ys
exchange2 (x:xs) l = x : exchange2 xs (l-1)
main = getLine >> fmap (map read . words) getLine >>= print . solve

-- Vicfred
-- https://codeforces.com/problemset/problem/144/A

import Data.List
import Data.Char
import qualified Data.ByteString.Char8 as B

getIntList :: IO [Int]
getIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine

solve :: [Int] -> Int
solve a = maxH + (n - 1 - minL) + (if maxH < minL then 0 else -1)
    where n     = length a
          maxi  = maximum a
          mini  = minimum a
          maxH  = head $ elemIndices maxi a
          minL  = last $ elemIndices mini a

main :: IO ()
main = do
    _ <- getLine
    a <- getIntList
    print $ solve a

import Control.Applicative

main = do n <- read <$> getLine
          xs <- map read . words <$> getLine
          print $ solve n xs

solve :: Int -> [Int] -> Int
solve n xs
 | l == h    = 0
 | l < h     = (n-l) + (h-1) -1
 | otherwise = (n-l) + (h-1)
   where h = succ $ (n-) $ snd $ maximum $ zip xs [n,(n-1)..1]
         l = succ $ (n-) $ snd $ minimum $ zip xs [n,(n-1)..1]

import Data.Function
import Data.List

moveMax xs = [x] ++ takeWhile (<x) xs ++ (tail.dropWhile (<x)$xs)
	where x = maximum xs

findMax xs = head.findIndices (==x)$xs
	where x = maximum xs

findMin xs = length xs - 1 - (last.findIndices (==x)$xs)
	where x = minimum xs

findAll :: [Int]->Int
findAll xs = findMax xs + findMin (moveMax xs)

result [n,xs] = findAll.map read.words$xs

main=interact$show.result.lines

import Data.List
import Data.Maybe

main = do
  getLine
  as <- fmap (map read . words) getLine :: IO [Int]
  let
    n = length as
    i = fromJust $ elemIndex (maximum as) as
    j = n - (fromJust $ elemIndex (minimum as) (reverse as)) + 1

  print $ if i < j then i + (n-j+1) else i+n-j

import Data.List ((\\), elemIndex)
import Data.Maybe (fromJust)

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

solve :: [Int] -> Int
solve xs = fromJust (elemIndex (maximum xs) xs) + fromJust (elemIndex (minimum xs) xs')
  where xs' = reverse xs \\ [maximum xs]

-- Vicfred
-- https://codeforces.com/problemset/problem/144/A

import Data.List
import Data.Char
import qualified Data.ByteString.Char8 as B

getIntList :: IO [Int]
getIntList = fmap (unfoldr (B.readInt . B.dropWhile isSpace)) B.getLine

solve :: [Int] -> Int
solve a = maxH + (n-1-minL) + (if maxH < minL then 0 else -1)
    where n     = length a
          maxi  = maximum a
          mini  = minimum a
          maxH  = head $ elemIndices maxi a
          minL  = head $ elemIndices mini a

main :: IO ()
main = do
    getLine
    a <- getIntList
    print $ solve a

import Data.List
main = getLine >> getLine >>= putStrLn.show.solve.map read.words

solve :: [Int] -> Int
solve soldiers = pred $ tallest + shortest
  where find f set = maybe 0 (+0) $ findIndex (==f set) set
        tallest    = find maximum soldiers
        shortest   = find minimum $ reverse soldiers

import Data.List (maximumBy, minimumBy)
import Data.Ord (comparing)

maxIndex ::  Ord a => [a] -> Int
maxIndex = fst . maximumBy (comparing snd) . zip [0..]

minIndex :: Ord a => [a] -> Int
minIndex = fst . minimumBy (comparing snd) . zip [0..]

process :: [Int] -> Int
process xs
    | imax + imin > n-1 = imax + imin - 1
    | otherwise = imax + imin
    where
        n = length xs
        imax = maxIndex xs
        imin = minIndex (reverse xs)

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    n <- fmap readInt getLine
    xs <- fmap (map readInt.words) getLine
    print $ process xs


import Data.List
import Data.Array
import Data.Ord

extract (x:xs)=take (read x::Int) xs
calc x=length (filter (=='1') x)
solve x=maximum $ map calc $ map (\k->(map (\y->y!!k) x)) [0..6]

main=interact$show.solve.extract.lines

{-
	fmap (map (\x->read x::Int).words)  $ getLine
-}

import Control.Monad
import Data.Char
-- import Data.List

main = do
    n <- readLn :: IO Int
    print =<< maximum . foldr (zipWith (+)) (replicate 7 0) <$> replicateM n ( map digitToInt <$> getLine)


--prewritten code: https://github.com/antma/algo
{-# LANGUAGE BangPatterns, Safe #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char
import Data.Bits

getSeed = return . fromInteger . (`mod` 999983) . diffTimeToPicoseconds . utctDayTime =<< getCurrentTime :: IO Int

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

solve :: [C.ByteString] -> Builder
solve (sn:sx:sy:s:_) = intDec res <> char7 '\n'
  where
    !n = ri sn
    !x = ri sx
    !y = ri sy
    !res = sum $ zipWith xor (replicate y 0 ++ (1 : repeat 0)) $  map (subtract 48 .  ord) $ C.unpack $ C.take x $ C.reverse s

main :: IO ()
main = hPutBuilder stdout . solve . C.words =<< C.getContents

module Main where

main :: IO ()
main = do
  params <- (fmap read . words) <$> getLine
  digits <- getLine
  print $ minOps params digits

minOps :: [Int] -> String -> Int
minOps [n, x, y] digits = let
  digits' = drop (n-x) digits
  digits'' = take (x -y -1) digits' ++
    [case digits' !! (x -y-1) of
      '0' -> '1'
      '1' -> '0'] ++ drop  (x-y) digits'
  in
  length $ filter (=='1') digits''

import Data.Char

main = do
    header <- getLine
    l <- getLine
    putStrLn . show $ solve header l

solve :: String -> String -> Int
solve header l_ =
    let [n, x, y] = (map read . words) header in
    let l = (take x . reverse) l_ in
    let f (pos, val) =
            if pos == y then
                (if val == '0' then 1 else 0)
            else
                (if val == '1' then 1 else 0)
    in
    sum $ map f (zip [0..] l)

import Data.List
import qualified Data.ByteString as B

main = do
    zz <- fmap (map read . words) getLine :: IO [Int]
    let n = zz !! 0
    let x = zz !! 1
    let y = zz !! 2
    s <- fmap (map (== '1') . reverse) getLine
    let t = take x s
    let ans = (foldl' (\s x -> if x then s + 1 else s) 0 t) - (if t !! y then 1 else (-1))
    putStrLn $ show ans
    return ()


getList :: Int -> Int -> Int -> Int -> [Int] -> [Int]
getList cur sub n k a
	| cur == n * k		= []
	| mod cur n == 0 	= (a !! (div cur n)) : (getList (cur + 1) sub n k a)
	| contain sub a		= getList cur (sub + 1) n k a
	| otherwise			= sub : (getList (cur + 1) (sub + 1) n k a)

contain :: Int -> [Int] -> Bool
contain _ [] = False
contain c (x:xs) = (x == c) || (contain c xs)

printList :: [Int] -> IO()
printList [] = do
	putStrLn ""
printList (x:xs) = do
	putStr ((show x) ++ " ")
	printList xs

main :: IO()
main = do
	str1 <- getLine
	str2 <- getLine
	let n = read ((words str1) !! 0)
	let k = read ((words str1) !! 1)
	let a = map read (words str2)
	printList (getList 0 1 n k a)

{-# 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 . (,)

main = do
    (n,k) <- readIntPair
    as <- readInts
    let oranges = [1..n*k] \\ as
    let go [] _ = return ()
        go (a:as) l  = do
            let (l1,l2) = splitAt (n-1) l
            putStrLn $ unwords $ map show $ (a:l1)
            go as l2
    go as oranges

module Main where
import Data.List
import Control.Applicative

main = do
    [n,k] <- map (read :: String -> Int) . words <$> getLine
    ks <- map (read :: String -> Int) . words <$> getLine
    let a = [1..n*k] \\ ks
        m = n-1
        b =  if null a then replicate k [] else unfoldr (\x -> if null x then Nothing else Just (take m x, drop m x)) a
    putStrLn $ concat $ intersperse "\n" $ map (concat . intersperse " " . map show) $ zipWith (:) ks b

import Control.Monad (liftM)
import Data.List ((\\), intercalate)
import Prelude hiding (reads)

reads :: Read a => IO [a]
reads  =  liftM (map read . words) getLine

solve :: Int -> Int -> [Int] -> [[Int]]
solve n k xs  =  solve' xs ([1..n*k] \\ xs)
  where
    solve' [] _  =  []
    solve' (x:xs) ys  =  (x : take (n-1) ys) : solve' xs (drop (n - 1) ys)

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

main :: IO ()
main  =  do
    [n, k]  <-  reads
    xs  <-  reads
    mapM_ prints $ solve n k xs

-- Codeforces 244A

import Data.List

main :: IO ()
main = getContents >>= putStrLn . solve . map read . words

solve :: [Int] -> String
solve (n:k:xs) = intercalate "\n" $ map (intercalate " " . map show . sort) $ transpose $ (xs:) $ map (\i -> take k $ drop ((i-1)*k) other) [1..n-1] where other = filter (`notElem` xs) [1..n*k]

import Control.Applicative
import Data.List

main = do
       [n,k] <- map read.words <$> getLine
       xs <- map read.words <$> getLine
       let rest = [1..n*k]\\xs
           ans = transpose $ xs:slices k rest
       putStr.unlines.map (unwords.map show) $ ans

slices :: Int -> [a] -> [[a]]
slices _ [] = []
slices n xs = let (ys,zs) = splitAt n xs in ys:slices n zs

import Data.List

main = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines
solve [[n, k], xs]  =  solve' xs ([1..n*k] \\ xs)
  where
    solve' [] _  =  []
    solve' (x:xs) ys  =  (x : take (n-1) ys) : solve' xs (drop (n - 1) ys)

module Main where
import Data.List
import Control.Applicative

main = do
    [n,k] <- map (read :: String -> Int) . words <$> getLine
    ks <- map (read :: String -> Int) . words <$> getLine
    let a = [1..n*k] \\ ks
        m = n-1
        b =  unfoldr (\x -> if null x then Nothing else Just (take m x, drop m x)) a
    putStrLn $ concat $ intersperse "\n" $ map (concat . intersperse " " . map show) $ zipWith (:) ks b

import Data.List

main = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines
solve [[n, 1], a] = [[1..n]]
solve [[n, k], a] = zipWith (:) a $ splitEvery (k-1) $ [1..n*k] \\ a
    where
        splitEvery _ [] = []
        splitEvery x ys = take x ys : splitEvery x (drop x ys)

import Data.List

main = interact $ unlines . map (unwords . map show) . solve . map (map read . words) . lines
solve [[1, k], a] = map (\x -> [x]) a
solve [[n, 1], a] = [[1..n]]
solve [[n, k], a] = zipWith (:) a $ splitEvery (k-1) $ [1..n*k] \\ a
    where
        splitEvery _ [] = []
        splitEvery x ys = take x ys : splitEvery x (drop x ys)


import Control.Applicative
import Data.List

lis = [div ((i-2)*180) i  | i<-[3..1000], mod ((i-2)*180) i==0 ]
process s | elem s lis = "YES"
          | otherwise = "NO"

main = do
  getLine
  s<-    map read  <$> lines  <$> getContents ::IO [Int]
  mapM_ putStrLn   $  map process s

main=interact$unlines.map (f.read).tail.words
f n
	| n >= 180 = "NO"
	| mod 360 (180-n) == 0 = "YES"
	| otherwise = "NO"

isPolyAngle :: Int -> Bool
isPolyAngle a = mod 360 b == 0
    where b = 180 - a

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

printList :: [String] -> IO()
printList (a:b) = do
    putStrLn a
    printList b
printList _ = do
    putStr ""

main :: IO()
main = do
    str <- getContents
    let a = map read (words str) :: [Int]
    printList (map (boolMap . isPolyAngle) (tail a))

conv lst kk
  | (null lst) = reverse kk
  | otherwise = conv (tail lst) (((read (head lst))::Int) : kk)

yesno lst oo
  | (null lst) = reverse oo
  | (mod 360 (180 - (head lst))) == 0 = yesno (tail lst) ("YES" : oo)
  | otherwise = yesno (tail lst) ("NO" : oo)

main = do
  ff <- getLine
  let aa = (read ff)::Int
      hh = replicate aa (getLine)
  uu <- sequence hh

  let tests = conv uu []
      ans = yesno tests []

  mapM_ putStrLn ans

  -- putStrLn (show ans)

main = interact $
    unlines . map (s . read) . tail . words
    where
        s n | 360 `mod` (180-n) == 0 = "YES"
            | otherwise = "NO"

main = do
  getLine
  xs <- fmap (map read . lines) getContents

  let
    solve 60 = True
    solve x = 360 `mod` (180-x) == 0

  putStrLn $ unlines $ map (\x -> if x then "YES" else "NO") $ map solve xs

import Control.Monad

main :: IO ()
main = do
    n <- getLine >>= return .read
    replicateM_ n solve

solve :: IO ()
solve = do
    a <- getLine >>= return . read
    putStrLn $ if 360 `mod` (180 - a) == 0 then "YES" else "NO"

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint = readLn >>= \ n -> (solve =<< forM [1 .. n] ( \i -> fst.fromJust.C.readInt <$>C.getLine))
solve xs = forM_ xs $ \i-> if 360 `mod` (180-i) == 0 then putStrLn "YES" else putStrLn "NO"

(?) :: Bool -> a -> a -> a
(?) p a b  =  if p then a else b

main' :: IO ()
main'  =  do
    a  <-  readLn
    putStrLn $ (360 `mod` (180 - a) == 0) ? "YES" $ "NO"

main :: IO ()
main  =  do
    n  <-  readLn
    sequence_ (replicate n main')

main = interact $ unlines . f . lines
f (x:xs) = map (g . read) xs
g x | rem 360 (180-x) == 0 = "YES"
    | otherwise            = "NO"

an = 0 : [180-(360 `div` i) | i <- [1..360]]
main = interact $ unlines . f . lines
f (x:xs) = map (g . read) xs
g x | elem x an && (rem 360 (180-x) == 0) = "YES"
    | otherwise                           = "NO"

import Control.Monad

good :: Int -> Bool
good a = any (\n -> a * n == 180 * (n - 2)) [3..1000]

main = do
    n <- read `fmap` getLine
    a <- sequence $ take n $ repeat $ read `fmap` getLine
    forM a $ \i ->
        putStrLn (if good i
                        then "YES"
                        else "NO")

import Control.Monad (replicateM)

main :: IO ()
main = do
  test_number <- readLn :: IO Int
  angles <-  replicateM test_number readLn :: IO [Int]
  mapM_ (putStrLn . to_string . check) angles
 where
  check :: Int -> Bool
  check x = 360 `mod` (180 - x) == 0
  to_string True = "YES"
  to_string _ = "NO"

main :: IO ()
main = getContents >>= mapM_ (putStrLn . yesno . solve . read) . tail . lines

solve :: Int -> Bool
solve a = 360 `mod` (180 - a) == 0

yesno :: Bool -> String
yesno True = "YES"
yesno _ = "NO"

main = interact $ unlines . map (solve . read) . tail . words
solve n | 360 `mod` (180-n) == 0 = "YES"
        | otherwise = "NO"

yes_or_no x = if (360 `mod` (180-x) == 0) && (360 `div` (180-x) > 2) then "YES" else "NO"
mkOut = do
    x <- getLine
    putStrLn(yes_or_no(read x))

n_times x | x > 0 = do mkOut;
                       n_times(x-1)
          | otherwise = putStr ""
main = do
  n_input <- getLine
  n_times(read n_input)

fit a = 360 `mod` (180 - a) == 0

loop 0 = return ()
loop n = do
    a <- getLine
    putStrLn $ if fit (read a :: Int) then "YES" else "NO"
    loop (n-1)

main = do
    n <- getLine
    loop (read n :: Int)

import Control.Applicative
import Control.Monad

ans= [div x n | n<-[3..1000],let x = 180 *(n-2) , (div x n)*n ==x ]

check a | elem a ans = "YES"
	| otherwise = "NO"

main= do
	 getLine
	 s<-map read. words <$> getContents::IO [Int]
	 mapM_ putStrLn $ map check s

import Control.Monad

check a
  | 360 `mod` (180-a) == 0 = True
  | otherwise = False

solve a
  | check a == True = "YES"
  | otherwise = "NO"

solveCase = do
  input <- getLine
  let a = read input :: Int
  putStrLn(solve a)

main = do
  caseNumStr <- getLine
  let t = read caseNumStr :: Int
  replicateM_ t solveCase

main = do
  m <- readLn
  n <- sequence $ replicate m getLine
  let n2 = map read n
  mapM_ putStrLn $ map pol n2
pol :: Int -> String
pol x = if (x `elem` [quot (180 * n) (n+2) | n <- filter (\x -> mod 360 (x+2) == 0) [1..360]]) then "YES" else "NO"

go x
  | k == 0    = "YES"
  | otherwise = "NO"
  where k = mod 360 (180 - x)
solve :: Int -> IO ()
solve 0 = return ()
solve n = do
  readLn >>= putStrLn. go
  solve $ n - 1
main = do
  n <- readLn :: IO Int
  solve n

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

main :: IO ()
main = getContents >>= mapM_ putStrLn. map (\x -> if 360 `mod` (180-x) == 0 then "YES" else "NO"). map (\x -> read x :: Int). tail. words

process :: Int -> Bool
process a = 360 `mod` (180-a) == 0

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    t <- fmap readInt getLine
    as <- fmap (map readInt.words) getContents
    mapM_ putStrLn . map (\a -> ["NO","YES"] !! fromEnum (process a)) $ as

main = interact f
    where f = unlines . map (isFancy.read) . tail . lines

isFancy x = if (360 `mod` (180 - x)) == 0 then "YES" else "NO"

import Data.List as List
import Data.Maybe as Maybe

getStringAfterChar :: Char -> String -> String
getStringAfterChar c str = drop ((Maybe.fromJust $ c `elemIndex` str) + 1) str

isAppropriate :: Int -> Int -> Bool
isAppropriate n angle = 180 * (n - 2) == angle * n

repeatX :: Int -> IO ()
repeatX x
    | x > 0 = do
    	solveCase
    	repeatX $ x - 1
    | otherwise = return ()

solveCase :: IO ()
solveCase = do
	line <- getLine
	let intAngle = read line :: Int
	let floatAngle = fromIntegral intAngle
	let sideNum = round $ 2 / (1 - (floatAngle / 180))
	let result = if isAppropriate sideNum intAngle
		then "YES"
		else "NO"
	putStrLn result

main = do
	line <- getLine
	let testNumber = read line :: Int
	repeatX testNumber

main=interact$unlines.map (f.read).tail.words
f n
	| n >= 180 = "No"
	| mod 360 (180-n) == 0 = "Yes"
	| otherwise = "No"

isPolyAngle :: Int -> Bool
isPolyAngle a = mod 360 b == 0
    where b = 180 - a

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

printList :: [String] -> IO()
printList (a:b) = do
    putStrLn a
    printList b
printList _ = do
    putStr ""

main :: IO()
main = do
    str <- getContents
    let a = map read (words str) :: [Int]
    printList (map (show . boolMap . isPolyAngle) (tail a))

yes_or_no x = if (360 `mod` (180-x) == 0) && (360 `div` (180-x) > 2) then "YES" else "NO"
mkOut = do
    x <- getLine
    putStrLn(show(yes_or_no(read x)))

n_times x | x > 0 = do mkOut;
                       n_times(x-1)
          | otherwise = putStr ""
main = do
  n_input <- getLine
  n_times(read n_input)

fit a = 360 `mod` (180 - a) == 0

loop 0 = return ()
loop n = do
    a <- getLine
    putStrLn $ if fit (read a :: Int) then "YES" else "NO"

main = do
    n <- getLine
    loop (read n :: Int)

import Control.Monad

check a
  | 360 `mod` (180-a) == 0 = True
  | otherwise = False

solve a
  | check a == True = "YES"
  | otherwise = "No"

solveCase = do
  input <- getLine
  let a = read input :: Int
  putStrLn(solve a)

main = do
  caseNumStr <- getLine
  let t = read caseNumStr :: Int
  replicateM_ t solveCase

main = do
  m <- readLn
  n <- sequence $ replicate m getLine
  let n2 = map read n
  mapM_ putStrLn $ map pol n2
pol :: Int -> String
pol x = if (x `elem` [quot (180 * n) (n+2) | n <- filter (\x -> mod 360 x == 0) [1..360]]) then "YES" else "NO"


import Control.Monad
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as C
import qualified Data.IntMap.Strict as M
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

update :: Num a => a -> Maybe a -> Maybe a
update delta value = case value of
  Nothing -> Just delta
  Just x -> Just (x + delta)

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    _ <- getInts
    as <- getInts
    let counts = foldl' (flip $ M.alter $ update 1) M.empty $ map abs as
        result = M.foldl' (\total count -> total + min 2 count) 0 $ M.adjust (const 1) 0 counts
    return $ intDec result `mappend` charUtf8 '\n'
  hPutBuilder stdout output

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
import Data.Array.Unboxed

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    a <- map abs <$> getInts n
    let
      cts :: UArray Int Int
      cts = accumArray (+) 0 (0, maximum a) $ zip a (repeat 1)
      cts' = cts // [(0, min 1 (cts ! 0))]
      ans = foldl' (\acc x -> acc + min x 2) 0 $ elems cts'
    pure $ putInts [ans]

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun $ P.words inp
  P.putStr $ toLazyByteString outp

import Control.Monad
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as C
import qualified Data.IntMap.Strict as M
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

update :: Num a => a -> Maybe a -> Maybe a
update delta value = case value of
  Nothing -> Just delta
  Just x -> Just (x + delta)

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    _ <- getInts
    as <- getInts
    let counts = foldl' (flip $ M.alter $ update 1) M.empty as
        result = M.foldl' (\total count -> total + min 2 count) 0 $ M.adjust (const 1) 0 counts
    return $ intDec result `mappend` charUtf8 '\n'
  hPutBuilder stdout output


{-
Codeforces Round #332

Problem 599 B. Spongebob and Joke

@author yamaton
@date 2015-12-01
-}

import Control.Applicative
import Control.Monad
-- import Text.Printf (printf)
import Data.Maybe (fromJust)
-- import qualified Data.Binary as Bin
import qualified Data.ByteString.Char8 as B
-- import qualified Data.ByteString.Lazy as BL
-- import qualified System.IO as IO
import qualified Data.Map.Strict as M
import qualified Data.Set as S

solve :: [Int] -> [Int] -> (String, [Int])
solve fs bs
  | any (`S.notMember` setFs) bs        = ("Impossible", [])
  | length ys /= S.size (S.fromList ys) = ("Ambiguity", [])
  | otherwise                           = ("Possible", recovered)
  where
    setFs = S.fromList fs
    setBs = S.fromList bs
    ys = filter (`S.member` setBs) fs
    invFsPairs = map (\(i, f) -> (f, i)) $ filter (\(_, f) -> f `S.member` setBs) (zip [1..] fs)
    invFsDict = M.fromList invFsPairs
    recovered = map (\i -> fromJust (M.lookup i invFsDict)) bs

main :: IO ()
main = do
    _ <- B.getLine
    fs <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    bs <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    let (msg, lst) = solve fs bs
    putStrLn msg
    if (null lst)
      then return ()
      -- else (B.putStrLn . B.unwords . map (BL.toStrict . Bin.encode)) lst
      else (putStrLn . unwords . map show) lst
    --
    -- IO.hPutStrLn IO.stderr $ printf "xs = %s" (show xs)
    -- IO.hPutStrLn IO.stderr $ printf "result = %d" msg

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

main = do
    (n : _ : rest) <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getContents
    let (f, b) = splitAt n rest
    let invf = accumArray (flip (:)) [] (1, n) $ zip f [1 ..]
    either putStrLn ((putStrLn "Possible" >>) . putStrLn . concat . intersperse " " . map show) $ solve b invf

solve :: [Int] -> Array Int [Int] -> Either String [Int]
solve [] _ = Right []
solve (b : bs) invf =
    case invf ! b of
        [a] -> solve bs invf >>= Right . (a :)
        []  -> Left "Impossible"
        _   -> solve bs invf >>= (const $ Left "Ambiguity")

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

main = do
    (n : _ : rest) <- map fst . mapMaybe BS.readInt . BS.words <$> BS.getContents
    let (f, b) = splitAt n rest
    let invf = accumArray (flip (:)) [] (1, n) $ zip f [1 ..]
    either putStrLn ((putStrLn "Possible" >>) . putStrLn . concat . intersperse " " . map show) $ solve b invf

solve :: [Int] -> Array Int [Int] -> Either String [Int]
solve [] _ = Right []
solve (b : bs) invf =
    case invf ! b of
        [a] -> solve bs invf >>= Right . (a :)
        []  -> Left "Impossible"
        _   -> solve bs invf >> Left "Ambiguity"

{-
Codeforces Round #332

Problem 599 B. Spongebob and Joke

@author yamaton
@date 2015-12-01
-}

import Control.Applicative
import Control.Monad
import Text.Printf (printf)
import Data.Maybe (fromJust)
import qualified Data.Binary as Bin
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as BL
import qualified System.IO as IO
import qualified Data.Map.Strict as M
import qualified Data.Set as S

solve :: [Int] -> [Int] -> (String, [Int])
solve fs bs
  | any (`S.notMember` setFs) bs        = ("Impossible", [])
  | length ys /= S.size (S.fromList ys) = ("Ambiguity", [])
  | otherwise                           = ("Possible", recovered)
  where
    setFs = S.fromList fs
    setBs = S.fromList bs
    ys = filter (`S.member` setBs) fs
    invFsPairs = map (\(i, f) -> (f, i)) $ filter (\(_, f) -> f `S.member` setBs) (zip [1..] fs)
    invFsDict = M.fromList invFsPairs
    recovered = map (\i -> fromJust (M.lookup i invFsDict)) bs

main :: IO ()
main = do
    _ <- B.getLine
    fs <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    bs <- map (fst . fromJust . B.readInt) . B.words <$> B.getLine
    let (msg, lst) = solve fs bs
    putStrLn msg
    if (null lst)
      then return ()
      -- else (B.putStrLn . B.unwords . map (BL.toStrict . Bin.encode)) lst
      else (putStrLn . unwords . map show) lst
    --
    -- IO.hPutStrLn IO.stderr $ printf "xs = %s" (show xs)
    -- IO.hPutStrLn IO.stderr $ printf "result = %d" msg

{-
Codeforces Round #332

Problem 599 B. Spongebob and Joke

@author yamaton
@date 2015-12-01
-}

import Control.Applicative
import Control.Monad
-- import Text.Printf
-- import System.IO (hPutStrLn, stderr)
import qualified Data.Map.Strict as M
import qualified Data.Set as S
import Data.Maybe (fromJust)

solve :: [Int] -> [Int] -> (String, [Int])
solve fs bs
  | any (`S.notMember` setFs) bs        = ("Impossible", [])
  | length ys /= S.size (S.fromList ys) = ("Ambiguity", [])
  | otherwise                           = ("Possible", recovered)
  where
    setFs = S.fromList fs
    setBs = S.fromList bs
    ys = filter (`S.member` setBs) fs
    invFsPairs = map (\(i, f) -> (f, i)) $ filter (\(_, f) -> f `S.member` setBs) (zip [1..] fs)
    invFsDict = M.fromList invFsPairs
    recovered = map (\i -> fromJust (M.lookup i invFsDict)) bs

main :: IO ()
main = do
    [n, m] <- (map read . words) <$> getLine :: IO [Int]
    fs <- (map read . words) <$> getLine :: IO [Int]
    bs <- (map read . words) <$> getLine :: IO [Int]
    let (msg, lst) = solve fs bs
    putStrLn msg
    if (null lst)
      then return ()
      else ((putStrLn . unwords . map show) lst)
    --
    -- hPutStrLn stderr $ printf "xs = %s" (show xs)
    -- hPutStrLn stderr $ printf "result = %d" msg


import Data.Char
import Data.List
import Data.Array

numbers :: String -> [Int]
numbers = map read . words

gets :: Int -> IO [String]
gets n = mapM (\i -> getLine) [0 .. n - 1]

count :: Char -> [Char] -> Int
count a b = sum $ map check b
  where
    check x
      | x == a    = 1
      | otherwise = 0

toChar :: Int -> Char
toChar 0 = '.'
toChar a = chr (ord '0' + a)

calculate :: (Int, Int) -> [String] -> [String]
calculate (n, m) a =
  map update [0 .. n - 1]
  where
    update i = map (w i) [0 .. m - 1]
    w i j
      | index (i, j) == '*' = '*'
      | otherwise = toChar $ count '*' (map index [(i + x, j + y) | x <- [-1 .. 1], y <- [-1 .. 1]])
    index (u, v)
      | u == -1 || u == n = ' '
      | v == -1 || v == m = ' '
      | otherwise = a !! u !! v

infix 4 ??
(??) :: a -> a -> Bool -> a
a ?? b = \i -> if i then a
                     else b

main :: IO ()
main = do
  firstLine <- getLine
  let [n, m] = numbers firstLine
  input <- gets n
  putStrLn . ("YES" ?? "NO") . (== input) . calculate (n, m) $ input

{-# Language BangPatterns, ViewPatterns #-}
import Control.DeepSeq
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import qualified Data.Map as Map

main = do
    [n, m] <- fmap (map readInt . words) $ getLine
    board <- fmap (parseInput n m) $ getContents
    putStrLn $ solve n m board

solve n m board
    | result == True = "YES"
    | result == False = "NO"
    where
        result = and $ map (uncurry isGood) $ zip expected actual

        expected = map neighbors $ Map.keys board
        actual = Map.elems board
        isGood a '*' = True
        isGood a '.' = a == '0'
        isGood a b = a == b

        neighbors (a,b) = intToDigit $ length $ do
            x <- [a-1..a+1]
            y <- [b-1..b+1]
            guard $ (x,y) /= (a,b)
            guard $ (fromMaybe '0' $ Map.lookup (x,y) board) == '*'
            return 1

parseInput n m x = Map.fromList $ concat $ map (uncurry zip) $ zip grid $ lines x
    where
        grid = [[(x,y) | y <- [1..m]] | x <- [1..n]]

readInt x = (read x) :: Int

import Data.List
import Data.List.Split
import Data.Char

type Grid a = [[a]]

main :: IO ()
main = do
    content <- getContents
    let ls = lines content
        n_m :: [Int]
        n_m = map read $ splitOn " " $ head ls
        grid = tail ls
        grid_sum = gridSum grid
        resultPair = zipWith zip grid_sum grid
        pass = all checkValid resultPair
    --putStrLn.unlines $ map (concat.(map show)) $ grid_sum
    if pass then
        putStrLn "YES"
    else
        putStrLn "NO"

checkValid :: [(Int,Char)] -> Bool
checkValid = all pairValid
pairValid :: (Int,Char) -> Bool
pairValid (0,'.') = True
pairValid (_,'*') = True
pairValid (x,y) = x + (ord '0') == ord y

gridSum grid =
    let x = length grid
        y = length $ head grid
        boardCore =(map.map) (\ch -> if ch== '*' then 1::Int else 0::Int) grid
        boardShifts = [gridShift boardCore p | p <- nearCoords]
        zeroGrid = take (x+2) . repeat $ take (y+2) . repeat $ (0::Int)
        boardSum = init.tail $ foldr ((zipWith.zipWith) (+)) zeroGrid boardShifts
    in map (init.tail) boardSum

nearCoords :: [(Int,Int)]
nearCoords = [(1,0)
             ,(1,1)
             ,(0,1)
             ,(-1,1)
             ,(-1,0)
             ,(-1,-1)
             ,(0,-1)
             ,(1,-1)
             ]

gridShift :: Grid Int -> (Int, Int) -> Grid Int
gridShift grid _ | length grid == 0 = []
gridShift _ (x,y) | not.elem (x,y) $ nearCoords = []
gridShift gridCore (x,y) =
    let --oldx = length grid
        oldy = length.head $ gridCore
        rowUp = 1 + x
        rowDown = 1 - x
        colLeft = 1 + y
        colRight = 1 - y
        row_Up = take rowUp . repeat $ take (oldy + 2) . repeat $ (0::Int)
        row_Down = take rowDown . repeat $ take (oldy + 2) . repeat $ (0::Int)
        col_Left = take colLeft $ repeat (0::Int)
        col_Right = take colRight $ repeat (0::Int)
    in  row_Up
        ++  (map (\line -> col_Left ++ line ++ col_Right) gridCore)
        ++ row_Down

import Data.Char
import Data.List
import Data.Array

numbers :: String -> [Int]
numbers = map read . words

gets :: (Int, Int) -> IO [String]
gets (n, m) = mapM _getLine [0 .. n - 1]
  where
    _getLine :: Int -> IO String
    _getLine a = getLine

filterStar :: [String] -> [String]
filterStar = map (map replace)
  where
    replace '*' = '*'
    replace  _  = '.'

count :: Char -> [Char] -> Int
count a b = sum $ map check b
  where
    check x
      | x == a    = 1
      | otherwise = 0

toChar :: Int -> Char
toChar 0 = '.'
toChar a = chr (ord '0' + a)

calculate :: (Int, Int) -> [String] -> [String]
calculate (n, m) a =
  map update [0 .. n - 1]
  where
    update i = map (w i) [0 .. m - 1]
    w i j
      | index (i, j) == '*' = '*'
      | otherwise = toChar $ count '*' (map index [(i + x, j + y) | x <- [-1 .. 1], y <- [-1 .. 1]])
    index (u, v)
      | u == -1 || u == n = ' '
      | v == -1 || v == m = ' '
      | otherwise = a !! u !! v

infix 4 <?>
(<?>) :: a -> a -> Bool -> a
a <?> b = \i -> if i then a
                     else b

main :: IO ()
main = do
  firstLine <- getLine
  let [n, m] = numbers firstLine
  res <- gets (n, m)
  putStrLn $ ("YES" <?> "NO") $ (== res) $ calculate (n, m) $ filterStar res

{-# Language BangPatterns, ViewPatterns #-}
import Control.DeepSeq
import Control.Monad
import Control.Applicative
import Data.Char
import Data.List
import Data.Maybe
import qualified Data.Map as Map

main = do
    [n, m] <- fmap (map readInt . words) $ getLine
    board <- fmap (parseInput n m) $ getContents
    putStrLn $ solve n m board

solve n m board
    | result == True = "YES"
    | result == False = "NO"
    where
        result = and $ isGood <$> expected <*> actual

        expected = map neighbors $ Map.keys board
        actual = Map.elems board
        isGood a '*' = True
        isGood a '.' = a == '0'
        isGood a b = a == b

        neighbors (a,b) = intToDigit $ length $ do
            x <- [a-1..a+1]
            y <- [b-1..b+1]
            guard $ (fromMaybe '0' $ Map.lookup (x,y) board) == '*'
            return 1

parseInput n m x = Map.fromList $ concat $ map (uncurry zip) $ zip grid $ lines x
    where
        grid = [[(x,y) | y <- [1..m]] | x <- [1..n]]

readInt x = (read x) :: Int

import Data.List
import Data.List.Split
import Data.Char

type Grid a = [[a]]

main :: IO ()
main = do
    content <- getContents
    let ls = lines content
        n_m :: [Int]
        n_m = map read $ splitOn " " $ head ls
        grid = tail ls
        grid_sum = gridSum grid
        resultPair = zipWith zip grid_sum grid
        pass = all checkValid resultPair
    putStrLn.unlines $ map (concat.(map show)) $ grid_sum
    if pass then
        putStrLn "YES"
    else
        putStrLn "NO"

checkValid :: [(Int,Char)] -> Bool
checkValid = all pairValid
pairValid :: (Int,Char) -> Bool
pairValid (0,'.') = True
pairValid (_,'*') = True
pairValid (x,y) = x + (ord '0') == ord y

gridSum grid =
    let x = length grid
        y = length $ head grid
        boardCore =(map.map) (\ch -> if ch== '*' then 1::Int else 0::Int) grid
        boardShifts = [gridShift boardCore p | p <- nearCoords]
        zeroGrid = take (x+2) . repeat $ take (y+2) . repeat $ (0::Int)
        boardSum = init.tail $ foldr ((zipWith.zipWith) (+)) zeroGrid boardShifts
    in map (init.tail) boardSum

nearCoords :: [(Int,Int)]
nearCoords = [(1,0)
             ,(1,1)
             ,(0,1)
             ,(-1,1)
             ,(-1,0)
             ,(-1,-1)
             ,(0,-1)
             ,(1,-1)
             ]

gridShift :: Grid Int -> (Int, Int) -> Grid Int
gridShift grid _ | length grid == 0 = []
gridShift _ (x,y) | not.elem (x,y) $ nearCoords = []
gridShift gridCore (x,y) =
    let --oldx = length grid
        oldy = length.head $ gridCore
        rowUp = 1 + x
        rowDown = 1 - x
        colLeft = 1 + y
        colRight = 1 - y
        row_Up = take rowUp . repeat $ take (oldy + 2) . repeat $ (0::Int)
        row_Down = take rowDown . repeat $ take (oldy + 2) . repeat $ (0::Int)
        col_Left = take colLeft $ repeat (0::Int)
        col_Right = take colRight $ repeat (0::Int)
    in  row_Up
        ++  (map (\line -> col_Left ++ line ++ col_Right) gridCore)
        ++ row_Down

import Data.Char
import Data.List
import Data.Array

numbers :: String -> [Int]
numbers = map read . words

gets :: (Int, Int) -> IO [String]
gets (n, m) = mapM _getLine [0 .. n - 1]
  where
    _getLine :: Int -> IO String
    _getLine a = getLine

filterStar :: [String] -> [String]
filterStar = map (map replace)
  where
    replace '*' = '*'
    replace  _  = '.'

count :: Char -> [Char] -> Int
count a b = sum $ map check b
  where
    check x
      | x == a    = 1
      | otherwise = 0

toChar :: Int -> Char
toChar a = chr (ord '0' + a)

calculate :: (Int, Int) -> [String] -> [String]
calculate (n, m) a =
  map update [0 .. n - 1]
  where
    update i = map (w i) [0 .. m - 1]
    w i j
      | index (i, j) == '*' = '*'
      | otherwise = toChar $ count '*' (map index [(i + x, j + y) | x <- [-1 .. 1], y <- [-1 .. 1]])
    index (u, v)
      | u == -1 || u == n = ' '
      | v == -1 || v == m = ' '
      | otherwise = a !! u !! v

infix 4 <?>
(<?>) :: a -> a -> Bool -> a
a <?> b = \i -> if i then a
                     else b

main :: IO ()
main = do
  firstLine <- getLine
  let [n, m] = numbers firstLine
  res <- gets (n, m)
  putStrLn $ ("YES" <?> "NO") $ (== res) $ calculate (n, m) $ filterStar res


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

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

main :: IO ()
main = do
  [t] <- getInts
  replicateM_ t $ do
    [n] <- getInts
    ss <- replicateM 3 $ (take (2 * n) . C.unpack) <$> C.getLine
    let cs = [let (as, bs) = partition (== '0') str in (length as, length bs) | str <- ss]
        tt = length [() | (c0, c1) <- cs, c0 <= c1] >= 2
        cmp ((c0, c1), _) ((c0', c1'), _) = if tt then compare c0 c0' else compare c1 c1'
        (s1 : s2 : _) = map snd $ sortBy cmp $ filter (\((c0, c1), _) -> (c0 <= c1) == tt) $ zip cs ss
        (cc, ct) = (if tt then id else swap) ('0', '1')
        calc [] = []
        calc (_ : xs) = let (ls, rs) = span (== cc) xs in length ls : calc rs
        func xs [] = concat [ct : replicate x cc | x <- xs]
        func (x : xs) (y : ys) = ct : replicate (max x y) cc ++ func xs ys
        result = tail $ func (calc (ct : s1)) (calc (ct : s2))
    C.putStrLn $ C.pack result

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

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             guard, join, replicateM,
                                             replicateM_)
import qualified Control.Monad.ST.Strict    as ST
import qualified Control.Monad.State.Strict as S
import qualified Data.Array                 as A
import qualified Data.Array.MArray.Safe     as MA
import qualified Data.Array.ST.Safe         as STA
import qualified Data.Array.Unboxed         as UA
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Function              (on)
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             intersect, isPrefixOf, nub, sort,
                                             sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             hFlush, openFile, stdin, stdout)
import           Text.Printf                (printf)

import           Debug.Trace                (trace, traceM, traceShowM)

debug :: c -> String -> c
debug = flip trace
traced x = trace (show x) x

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

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

mergeWith :: Char -> (B8.ByteString, B8.ByteString) -> B8.ByteString
mergeWith c (a, b) =
        B8.pack $ traceMerge' (trim' $ B8.unpack a) (trim' $ B8.unpack b)
    where
        trim' :: String -> String
        trim' = filter (not . isSpace)

        traceMerge' :: String -> String -> String
        traceMerge' a b = r --debug r ("merge' " ++ show a ++ ", " ++ show b ++ " -> " ++ show r)
            where r = merge' a b

        merge' :: String -> String -> String
        merge' [] b = b
        merge' a [] = a
        merge' a@(ca : restA) b@(cb : restB)
            | ca == cb   = ca : traceMerge' restA restB
            | ca == c    = cb : traceMerge' a restB
            | cb == c    = ca : traceMerge' restA b

solve :: Int -> [B8.ByteString] -> B8.ByteString
solve n ss =
    if length with0 >= 2
        then mergeWith '0' (with0 !! 0, with0 !! 1)
        else mergeWith '1' (with1 !! 0, with1 !! 1)
    where
        with0 = filter (\s -> B8.count '0' s >= n) ss
        with1 = filter (\s -> B8.count '1' s >= n) ss

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    forM_ [1..t] $ \_ -> do
        n <- B8.getLine <&> readIntB8
        ss <- forM [1..3] . const $ B8.getLine
        let answer = solve n ss
        B8.putStrLn answer

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

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             guard, join, replicateM,
                                             replicateM_)
import qualified Control.Monad.ST.Strict    as ST
import qualified Control.Monad.State.Strict as S
import qualified Data.Array                 as A
import qualified Data.Array.MArray.Safe     as MA
import qualified Data.Array.ST.Safe         as STA
import qualified Data.Array.Unboxed         as UA
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Function              (on)
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             intersect, isPrefixOf, nub, sort,
                                             sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             hFlush, openFile, stdin, stdout)
import           Text.Printf                (printf)

import Debug.Trace (trace, traceM, traceShowM)
debug :: c -> String -> c
debug = flip trace
traced x = trace (show x) x

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

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

mergeWith :: Char -> (B8.ByteString, B8.ByteString) -> B8.ByteString
mergeWith c (a, b) =
        B8.pack $ traceMerge' (B8.unpack a) (B8.unpack b)
    where
        traceMerge' :: String -> String -> String
        traceMerge' a b = r --debug r ("merge' " ++ show a ++ ", " ++ show b ++ " -> " ++ show r)
            where r = merge' a b

        merge' :: String -> String -> String
        merge' [] b = b
        merge' a [] = a
        merge' a@(ca : restA) b@(cb : restB)
            | ca == cb   = ca : traceMerge' restA restB
            | ca == c    = cb : traceMerge' a restB
            | cb == c    = ca : traceMerge' restA b

solve :: Int -> [B8.ByteString] -> B8.ByteString
solve n ss =
    if length with0 >= 2
        then mergeWith '0' (with0 !! 0, with0 !! 1)
        else mergeWith '1' (with1 !! 0, with1 !! 1)
    where
        with0 = filter (\s -> B8.count '0' s >= n) ss
        with1 = filter (\s -> B8.count '1' s >= n) ss

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    forM_ [1..t] $ \_ -> do
        n <- B8.getLine <&> readIntB8
        ss <- forM [1..3] $ const B8.getLine
        let answer = solve n ss
        B8.putStrLn answer


import Control.Applicative
import Control.Monad
import Data.Char
import Data.Maybe
import Data.Int (Int64)
import Debug.Trace
import qualified Data.ByteString.Char8 as C

readInt :: Integral a => C.ByteString -> a
readInt = fromIntegral . fst . fromJust . C.readInt

getInts :: IO [Int64]
getInts = map readInt . C.words <$> C.getLine

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

newtype Mint = Mint Int64

mymod :: Int64
mymod = 1000000007

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

instance Num Mint where
  (+) (Mint a) (Mint b) = Mint $ let c = a + b in if c >= mymod then c - mymod else c
  (-) (Mint a) (Mint b) = Mint $ let c = a - b in if c < 0 then c + mymod else c
  (*) (Mint a) (Mint b) = Mint $ a * b `rem` mymod
  abs                   = id
  signum (Mint a)       = Mint $ signum a
  fromInteger a         = Mint $ fromInteger $ a `mod` toInteger mymod

myDiv :: Mint -> Mint -> Mint
myDiv (Mint a) (Mint b) = Mint $ (if odd a then (a-1) else a) `div` b

powMod :: Mint -> Mint -> Mint
powMod _ (Mint 0) = Mint 1
powMod p n@(Mint t)
  | odd t = p * tmp
  | otherwise = tmp
  where
  tmp = powMod (p * p) (n `myDiv` (Mint 2))

main :: IO ()
main = do
  n <- getLine
  k <- getInt
  let len = fromIntegral $ length n
      n' = [(Mint i) | (i,x) <- zip [0..] n, x == '5' || x == '0']
      d = powMod (Mint 2) $ Mint len
      x = (powMod d (Mint k)) - (Mint 1)
      x' = x * (powMod (d-(Mint 1)) $ Mint $ mymod - 2)
  --putStrLn $ show n''
  print $ x' * foldl (\t x -> t + (powMod (Mint 2) x)) (Mint 0) n'

import Data.Char
import Data.Int
import Data.Maybe
import qualified Data.ByteString.Char8 as C

newtype MInt = MInt Int64

m :: Int64
m = 1000000007

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

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

powSum :: (Num a, Integral b) => a -> b -> a
powSum a b
  | b == 0    = 0
  | odd b     = 1 + a * powSum a (b - 1)
  | otherwise = let b' = b `quot` 2 in (1 + a ^ b') * powSum a b'

main :: IO ()
main = do
  s <- fmap (C.filter isDigit) C.getLine
  k <- fmap (fst . fromJust . C.readInt) C.getLine
  let x = sum [b | (a, b) <- zip (C.unpack s) $ iterate (*2) 1, a == '0' || a == '5']
      y = powSum (2^C.length s) k
  print $ (x * y :: MInt)

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

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Bits
import Data.Int

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

extGcd :: (Integral a) => a -> a -> (a, a)
extGcd !a !b
  | b == 0    = (1, 0)
  | otherwise = (t, s - a `div` b * t)
   where
     (!s, !t) = extGcd b $ a `mod` b
{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}
{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}
{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}

#define MOD 1000000007

newtype IntMod = IntMod Int64 deriving (Eq, Ord)

instance Show IntMod where
  show (IntMod x) = show x

instance Num IntMod where
  (IntMod x) + (IntMod y) = case x + y of
                              xy | xy < MOD -> IntMod xy
                                 | otherwise -> IntMod $ xy - MOD
  (IntMod x) - (IntMod y) = case x - y of
                              xy | xy >= 0 -> IntMod xy
                                 | otherwise -> IntMod $ xy + MOD
  (IntMod x) * (IntMod y) = IntMod $ x * y `rem` MOD
  abs _ = undefined
  signum _ = undefined
  fromInteger x = IntMod $ fromInteger x

instance Fractional IntMod where
  (IntMod x) / (IntMod y) = IntMod $ x * fst (extGcd y MOD) `mod` MOD
  fromRational q = undefined

main :: IO ()
main = do
  [bs,kbs] <- B.lines <$> B.getContents
  let xs = B.findIndices (\c->c=='0'||c=='5') bs
      k = readInt kbs
      l = B.length bs - 1
  print $ foldl' (+) (0 :: IntMod) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))

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

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Bits
import Data.Int

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

extGcd :: (Integral a) => a -> a -> (a, a)
extGcd !a !b
  | b == 0    = (1, 0)
  | otherwise = (t, s - a `div` b * t)
   where
     (!s, !t) = extGcd b $ a `mod` b
{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}
{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}
{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}

modulus :: Int64
modulus = 1000000007

newtype IntMod = Mod Int64 deriving (Eq, Ord)

instance Show IntMod where
  show (Mod x) = show x

instance Num IntMod where
  (Mod x) + (Mod y) = case x + y of
                        xy | xy < modulus -> Mod xy
                           | otherwise    -> Mod $ xy - modulus
  (Mod x) - (Mod y) = case x - y of
                        xy | xy >= 0   -> Mod xy
                           | otherwise -> Mod $ xy + modulus
  (Mod x) * (Mod y) = Mod $ x * y `rem` modulus
  abs _ = undefined
  signum _ = undefined
  fromInteger x = Mod $ fromInteger x `mod` modulus

instance Fractional IntMod where
  (Mod x) / (Mod y) = Mod $ x * fst (extGcd y modulus) `mod` modulus
  fromRational _ = undefined

main :: IO ()
main = do
  [bs,kbs] <- B.lines <$> B.getContents
  let xs = B.findIndices (\c->c=='0'||c=='5') bs
      k = readInt kbs
      l = B.length bs - 1
  print $ foldl' (+) (Mod 0) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))

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

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

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

infixl 8 .<<. , .>>.
(.<<.), (.>>.) :: (Bits a, Num a) => a -> Int -> a
(.<<.) = unsafeShiftL
(.>>.) = unsafeShiftR
{-# INLINE (.<<.) #-}
{-# INLINE (.>>.) #-}

extGcd :: (Integral a) => a -> a -> (a, a)
extGcd !a !b
  | b == 0    = (1, 0)
  | otherwise = (t, s - a `div` b * t)
   where
     (!s, !t) = extGcd b $ a `mod` b
{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}
{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}

#define MOD 1000000007

type IntMod = Int

infixr 8  ^%
infixl 7  *%, /%
infixl 6  +%, -%

(+%) :: IntMod -> IntMod -> IntMod
x +% y = case x+y of
           xy | xy < MOD -> xy
              | otherwise -> xy - MOD
{-# INLINE (+%) #-}

(-%) :: IntMod -> IntMod -> IntMod
x -% y = case x-y of
           xy | xy >= 0   -> xy
              | otherwise -> xy + MOD
{-# INLINE (-%) #-}

(*%) :: IntMod -> IntMod -> IntMod
x *% y = fromInteger $ toInteger x * toInteger y `rem` MOD
{-# INLINE (*%) #-}

(/%) :: IntMod -> IntMod -> IntMod
x /% y = x *% (fst (extGcd y MOD) `mod` MOD)
{-# INLINE (/%) #-}

(^%) :: IntMod -> IntMod -> IntMod
x ^% 0 = 1
x ^% y = f (toInteger x) y
   where
     f !x !y
       | even y    = f (x * x `rem` MOD) (y .>>. 1)
       | y == 1    = fromIntegral $ x `rem` MOD
       | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) x
     g !x !y !z
       | even y    = g (x * x `rem` MOD) (y .>>. 1) z
       | y == 1    = fromIntegral $ x * z `rem` MOD
       | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) (x * z `rem` MOD)

main :: IO ()
main = do
  [bs,kbs] <- B.lines <$> B.getContents
  let xs = B.findIndices (\c->c=='0'||c=='5') bs
      k = readInt kbs
      l = B.length bs - 1
  print $ foldl' (+%) 0 (map (2^%) xs) *% (((2^%l)^%k-%1)/%(2^%l-%1))

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

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Bits
import Data.Int

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

extGcd :: (Integral a) => a -> a -> (a, a)
extGcd !a !b
  | b == 0    = (1, 0)
  | otherwise = (t, s - a `div` b * t)
   where
     (!s, !t) = extGcd b $ a `mod` b
{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}
{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}
{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}

modulus :: Int64
modulus = 1000000007
{-# INLINE modulus #-}

newtype IntMod = Mod Int64 deriving (Eq, Ord)

instance Show IntMod where
  show (Mod x) = show x

instance Num IntMod where
  (Mod x) + (Mod y) = case x + y of
                        xy | xy < modulus -> Mod xy
                           | otherwise    -> Mod $ xy - modulus
  (Mod x) - (Mod y) = case x - y of
                        xy | xy >= 0   -> Mod xy
                           | otherwise -> Mod $ xy + modulus
  (Mod x) * (Mod y) = Mod $ x * y `rem` modulus
  abs _ = undefined
  signum _ = undefined
  fromInteger x = Mod $ fromInteger x `mod` modulus

instance Fractional IntMod where
  (Mod x) / (Mod y) = Mod $ x * fst (extGcd y modulus) `mod` modulus
  fromRational _ = undefined

main :: IO ()
main = do
  [bs,kbs] <- B.lines <$> B.getContents
  let xs = B.findIndices (\c->c=='0'||c=='5') bs
      k = readInt kbs
      l = B.length bs - 1
  print $ foldl' (+) (Mod 0) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))

{-# OPTIONS_GHC -O2 -funbox-strict-fields -cpp #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}
{-# LANGUAGE MagicHash #-}

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Bits
import Data.Int

import GHC.Int (Int64(..))
import GHC.IntWord64 (timesInt64#, remInt64#)

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

extGcd :: (Integral a) => a -> a -> (a, a)
extGcd !a !b
  | b == 0    = (1, 0)
  | otherwise = (t, s - a `div` b * t)
   where
     (!s, !t) = extGcd b $ a `mod` b
{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}
{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}
{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}

modulus :: Int64
modulus = 1000000007
{-# INLINE modulus #-}

newtype IntMod = Mod Int64 deriving (Eq, Ord)

instance Show IntMod where
  show (Mod x) = show x

instance Num IntMod where
  (Mod x) + (Mod y) = case x + y of
                        xy | xy < modulus -> Mod xy
                           | otherwise    -> Mod $ xy - modulus
  (Mod x) - (Mod y) = case x - y of
                        xy | xy >= 0   -> Mod xy
                           | otherwise -> Mod $ xy + modulus
  (Mod (I64# x#)) * (Mod (I64# y#)) = case modulus of
                                        (I64# m#) -> Mod $ I64# (x# `timesInt64#` y# `remInt64#` m#)
  abs _ = undefined
  signum _ = undefined
  fromInteger x = Mod $ fromInteger x `mod` modulus

instance Fractional IntMod where
  (Mod x) / (Mod y) = Mod $ x * fst (extGcd y modulus) `mod` modulus
  fromRational _ = undefined

main :: IO ()
main = do
  [bs,kbs] <- B.lines <$> B.getContents
  let xs = B.findIndices (\c->c=='0'||c=='5') bs
      k = readInt kbs
      l = B.length bs - 1
  print $ foldl' (+) (Mod 0) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))

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

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Bits
import Data.Int

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

infixl 8 .<<. , .>>.
(.<<.), (.>>.) :: (Bits a, Num a) => a -> Int -> a
(.<<.) = unsafeShiftL
(.>>.) = unsafeShiftR
{-# INLINE (.<<.) #-}
{-# INLINE (.>>.) #-}

extGcd :: (Integral a) => a -> a -> (a, a)
extGcd !a !b
  | b == 0    = (1, 0)
  | otherwise = (t, s - a `div` b * t)
   where
     (!s, !t) = extGcd b $ a `mod` b
{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}
{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}
{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}

#define MOD 1000000007

type IntMod = Int64

infixr 8  ^%
infixl 7  *%, /%
infixl 6  +%, -%

(+%) :: IntMod -> IntMod -> IntMod
x +% y = case x+y of
           xy | xy < MOD -> xy
              | otherwise -> xy - MOD
{-# INLINE (+%) #-}

(-%) :: IntMod -> IntMod -> IntMod
x -% y = case x-y of
           xy | xy >= 0   -> xy
              | otherwise -> xy + MOD
{-# INLINE (-%) #-}

(*%) :: IntMod -> IntMod -> IntMod
x *% y = x * y `rem` MOD
{-# INLINE (*%) #-}

(/%) :: IntMod -> IntMod -> IntMod
x /% y = x *% (fst (extGcd y MOD) `mod` MOD)
{-# INLINE (/%) #-}

(^%) :: IntMod -> Int -> IntMod
x ^% 0 = 1
x ^% y = f (toInteger x) y
   where
     f !x !y
       | even y    = f (x * x `rem` MOD) (y .>>. 1)
       | y == 1    = fromIntegral $ x `rem` MOD
       | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) x
     g !x !y !z
       | even y    = g (x * x `rem` MOD) (y .>>. 1) z
       | y == 1    = fromIntegral $ x * z `rem` MOD
       | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) (x * z `rem` MOD)

main :: IO ()
main = do
  [bs,kbs] <- B.lines <$> B.getContents
  let xs = B.findIndices (\c->c=='0'||c=='5') bs
      k = readInt kbs
      l = B.length bs - 1
  print $ foldl' (+%) 0 (map (2^%) xs) *% (((2^%l)^%k-%1)/%(2^%l-%1))

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

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Bits
import Data.Int
import Unsafe.Coerce

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

extGcd :: (Integral a) => a -> a -> (a, a)
extGcd !a !b
  | b == 0    = (1, 0)
  | otherwise = (t, s - a `div` b * t)
   where
     (!s, !t) = extGcd b $ a `mod` b
{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}
{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}
{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}

#define MOD 1000000007

newtype IntMod = IntMod Int64 deriving (Eq, Ord)

instance Show IntMod where
  show (IntMod x) = show x

instance Num IntMod where
  (IntMod x) + (IntMod y) = case x + y of
                              xy | xy < MOD  -> unsafeCoerce xy
                                 | otherwise -> unsafeCoerce $ xy - MOD
  (IntMod x) - (IntMod y) = case x - y of
                              xy | xy >= 0   -> unsafeCoerce xy
                                 | otherwise -> unsafeCoerce $ xy + MOD
  (IntMod x) * (IntMod y) = unsafeCoerce $ x * y `rem` MOD
  abs _ = undefined
  signum _ = undefined
  fromInteger x = IntMod $ fromInteger x `mod` MOD

instance Fractional IntMod where
  (IntMod x) / (IntMod y) = unsafeCoerce $ x * fst (extGcd y MOD) `mod` MOD
  fromRational _ = undefined

main :: IO ()
main = do
  [bs,kbs] <- B.lines <$> B.getContents
  let xs = B.findIndices (\c->c=='0'||c=='5') bs
      k = readInt kbs
      l = B.length bs - 1
  print $ foldl' (+) (IntMod 0) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))

module Main where

ch2int c
    | c == '1' = 1
    | c == '2' = 2
    | c == '3' = 3
    | c == '4' = 4
    | c == '5' = 5
    | c == '6' = 6
    | c == '7' = 7
    | c == '8' = 8
    | c == '9' = 9
    | otherwise = 0

str2int [] = 0
str2int s = (str2int (init s)) * 10 + (ch2int (last s))

mod_exp a n m = exp n
    where exp n = if n == 0
            then 1
            else
                let b = exp (div n 2)
                    c = mod (b * b) m
                in  if mod n 2 == 0
                    then c
                    else mod (a * c) m

pow_sum a n m = ps n
    where ps n = if n == 0
            then 1
            else if mod n 2 == 0
                 then mod (1 + a * ps (n - 1)) m
                 else let k = div n 2
                      in  mod ((1 + (mod_exp a (k + 1) m)) * (ps k)) m

sub [] = [[]]
sub (x:y) =
    let w = sub y
    in  w ++ [x:z | z <- w]
-- magic seq = length [s | s <- sub seq, length s > 0, last s == '5' || last s == '0']

magic seq =
    mod (sum (map f (zip seq [0..]))) 1000000007
        where f (c, i) = if c == '0' || c == '5'
                then mod_exp 2 i 1000000007
                else 0

solve str k =
    mod ((pow_sum a (k - 1) 1000000007) * q) 1000000007
        where
            n = length str
            q = (magic str)
            a = mod (mod_exp 2 n 1000000007) 1000000007

main = do
    str <- getLine
    line <- getLine
    print $ solve str (str2int line)

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

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.List
import Data.Bits
import Data.Int

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

extGcd :: (Integral a) => a -> a -> (a, a)
extGcd !a !b
  | b == 0    = (1, 0)
  | otherwise = (t, s - a `div` b * t)
   where
     (!s, !t) = extGcd b $ a `mod` b
{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}
{-# SPECIALISE extGcd :: Int64 -> Int64 -> (Int64, Int64) #-}
{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}

#define MOD 1000000007

newtype IntMod = IntMod Int64 deriving (Eq, Ord)

instance Show IntMod where
  show (IntMod x) = show x

instance Num IntMod where
  (IntMod x) + (IntMod y) = case x + y of
                              xy | xy < MOD -> IntMod xy
                                 | otherwise -> IntMod $ xy - MOD
  (IntMod x) - (IntMod y) = case x - y of
                              xy | xy >= 0 -> IntMod xy
                                 | otherwise -> IntMod $ xy + MOD
  (IntMod x) * (IntMod y) = IntMod $ x * y `rem` MOD
  abs _ = undefined
  signum _ = undefined
  fromInteger x = IntMod $ fromInteger x

instance Fractional IntMod where
  (IntMod x) / (IntMod y) = IntMod $ x * (fst (extGcd y MOD) `mod` MOD)
  fromRational q = undefined

main :: IO ()
main = do
  [bs,kbs] <- B.lines <$> B.getContents
  let xs = B.findIndices (\c->c=='0'||c=='5') bs
      k = readInt kbs
      l = B.length bs - 1
  print $ foldl' (+) (0 :: IntMod) (map (2^) xs) * (((2^l)^k-1)/(2^l-1))

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

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

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

infixl 8 .<<. , .>>.
(.<<.), (.>>.) :: (Bits a, Num a) => a -> Int -> a
(.<<.) = unsafeShiftL
(.>>.) = unsafeShiftR
{-# INLINE (.<<.) #-}
{-# INLINE (.>>.) #-}

extGcd :: (Integral a) => a -> a -> (a, a)
extGcd !a !b
  | b == 0    = (1, 0)
  | otherwise = (t, s - a `div` b * t)
   where
     (!s, !t) = extGcd b $ a `mod` b
{-# SPECIALISE extGcd :: Int -> Int -> (Int, Int) #-}
{-# SPECIALISE extGcd :: Integer -> Integer -> (Integer, Integer) #-}

#define MOD 1000000007

type IntMod = Int

infixr 8  ^%
infixl 7  *%, /%
infixl 6  +%, -%

(+%) :: IntMod -> IntMod -> IntMod
x +% y = case x+y of
           xy | xy < MOD -> xy
              | otherwise -> xy - MOD
{-# INLINE (+%) #-}

(-%) :: IntMod -> IntMod -> IntMod
x -% y = case x-y of
           xy | xy >= 0   -> xy
              | otherwise -> xy + MOD
{-# INLINE (-%) #-}

(*%) :: IntMod -> IntMod -> IntMod
x *% y = fromInteger $ toInteger x * toInteger y `rem` MOD
{-# INLINE (*%) #-}

(/%) :: IntMod -> IntMod -> IntMod
x /% y = x *% (fst (extGcd y MOD) `mod` MOD)
{-# INLINE (/%) #-}

(^%) :: IntMod -> IntMod -> IntMod
x ^% 0 = 1
x ^% y = f (toInteger x) y
   where
     f !x !y
       | even y    = f (x * x `rem` MOD) (y .>>. 1)
       | y == 1    = fromIntegral $ x `rem` MOD
       | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) x
     g !x !y !z
       | even y    = g (x * x `rem` MOD) (y .>>. 1) z
       | y == 1    = fromIntegral $ x * z `rem` MOD
       | otherwise = g (x * x `rem` MOD) ((y-1) .>>. 1) (x * z `rem` MOD)

main :: IO ()
main = do
  [bs,kbs] <- B.lines <$> B.getContents
  let xs = B.findIndices (\c->c=='0'||c=='5') bs
      k = readInt kbs
      l = B.length bs - 1
  print $ foldl' (+%) 0 (map (2^%) xs) *% ((2^%(k*%l)-%1)/%(2^%l-%1))

import Control.Applicative
import Control.Monad
import Data.Char
import Data.Maybe
import Data.Int (Int64)
import Debug.Trace
import qualified Data.ByteString.Char8 as C

readInt :: Integral a => C.ByteString -> a
readInt = fromIntegral . fst . fromJust . C.readInt

getInts :: IO [Int64]
getInts = map readInt . C.words <$> C.getLine

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

newtype Mint = Mint Int64

mymod :: Int64
mymod = 1000000007

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

instance Num Mint where
  (+) (Mint a) (Mint b) = Mint $ let c = a + b in if c >= mymod then c - mymod else c
  (-) (Mint a) (Mint b) = Mint $ let c = a - b in if c < 0 then c + mymod else c
  (*) (Mint a) (Mint b) = Mint $ a * b `rem` mymod
  abs                   = id
  signum (Mint a)       = Mint $ signum a
  fromInteger a         = Mint $ fromInteger $ a `mod` toInteger mymod

myDiv :: Mint -> Mint -> Mint
myDiv (Mint a) (Mint b) = Mint $ a `div` b

powMod :: Mint -> Mint -> Mint
powMod _ (Mint 0) = Mint 1
powMod p n@(Mint t)
  | odd t = p * tmp
  | otherwise = tmp
  where
  tmp = powMod (p * p) (n `myDiv` (Mint 2))

calc :: Mint -> (Mint, (Mint, Mint)) -> Mint
calc s (x,(l,k)) =
  --trace (show x ++ " " ++ show l ++ " " ++ show k ++ " " ++ show t ++ " " ++ show p ++ " " ++ show d ++ " " ++ show t') $
  s + p - t
  where
  t = powMod (Mint 2) x
  p = powMod (Mint 2) (x + l * k)

main :: IO ()
main = do
  n <- getLine
  k <- getInt
  let len = fromIntegral $ length n
      n' = [(Mint i,(Mint len, Mint k)) | (i,x) <- zip [0..] n, x == '5' || x == '0']
      chu' = powMod (Mint 2) $ Mint len
      chu = powMod (chu' - (Mint 1)) $ Mint $ mymod - 2
  --putStrLn $ show n''
  print $ chu * (foldl calc (Mint 0) n')

import Control.Applicative
import Control.Monad
import Data.Char
import Data.Maybe
import Data.Int (Int64)
import Debug.Trace
import qualified Data.ByteString.Char8 as C

readInt :: Integral a => C.ByteString -> a
readInt = fromIntegral . fst . fromJust . C.readInt

getInts :: IO [Int64]
getInts = map readInt . C.words <$> C.getLine

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

mymod :: Int64
mymod = 1000000007

powMod :: Int64 -> Int64 -> Int64
powMod _ 0 = 1
powMod p n
  | odd n = (p * tmp) `rem` mymod
  | otherwise = tmp
  where
  tmp = powMod ((p*p) `rem` mymod) ((if odd n then n-1 else n) `div` 2)

calc :: (Int64, (Int64, Int64)) -> Int64
calc (x,(l,k)) =
  --trace (show x ++ " " ++ show l ++ " " ++ show k ++ " " ++ show t ++ " " ++ show p ++ " " ++ show d ++ " " ++ show t') $
  (((p + mymod - t) `rem` mymod) * t') `rem` mymod
  where
  t = powMod 2 x
  d = powMod 2 l
  p = powMod 2 $ x + l * k
  t' = powMod (d - 1) $ mymod - 2

main :: IO ()
main = do
  --n <- (\x -> [digitToInt c | c <- x]) <$> C.getLine
  n <- getLine
  k <- getInt
  let len = fromIntegral $ length n
      n' = [i | (i,x) <- zip [0..] n, x == '5' || x == '0']
      n'' = zip n' $ replicate (length n') (len,k)
  --putStrLn $ show n''
  print $ sum $ map calc n''

import Data.Int
import Data.Maybe
import qualified Data.ByteString.Char8 as C

newtype MInt = MInt Int64

m :: Int64
m = 1000000007

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

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

main :: IO ()
main = do
  s <- C.getLine
  k <- fmap (fst . fromJust . C.readInt) C.getLine
  let x = sum [b | (a, b) <- zip (C.unpack s) $ iterate (*2) 1, a == '0' || a == '5']
      y = sum $ take k $ iterate (*2^C.length s) 1
  print $ (x * y :: MInt)