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

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

app = do
  n <- poi
  xs <- replicateM n poi
  return $ if solve n xs then "yes" else "no"
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n xs = odd (head xs) && odd n && odd (last xs)

main = interact foo

foo :: String -> String
foo inp =
    let ns = map ((`mod` 2) . read) . words . (!! 1) . lines $ inp :: [Int]
    in if head ns == 1 && last ns == 1
        then if (length ns) `mod` 2 == 1
            then "Yes"
            else "No" --if bar ns False 0 then "Yes" else "No"
        else "No"

-- bar :: [Int] -> Bool -> Int -> Bool -- ns lastWas1 countSoFar
-- bar _ _ 3 = True
-- bar [] _ _ = False
-- bar (n:ns) lastWas1 count =
--     if n == 1
--         then if lastWas1
--             then bar ns True $ count + 1
--             else bar ns True count
--         else bar ns False count

main = do
    n <- readLn :: IO Int
    xs <- fmap (map read . words) getLine :: IO [Int]
    if mod n 2 == 1 && mod (head xs) 2 == 1 && mod (last xs) 2 == 1
        then putStrLn "Yes"
        else putStrLn "No"

main = do
  count <- getLine
  numbers <- getLine
  putStrLn $ magic_wrapper (magic (readNumber count) (readNumbers numbers))

readNumber :: String -> Int
readNumber = read

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

magic_wrapper :: Bool -> String
magic_wrapper True = "Yes"
magic_wrapper False = "no"

magic :: Int -> [Int] -> Bool
magic c xs
  | odd c = not (even (head xs)) && (not (even (last xs)))
  | otherwise = False

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

main :: IO ()
main = do
    _ <- getLine
    (map (read :: String -> Int) . words -> xs@(last -> x)) <- getLine
    putStrLn $ case (head xs) `mod` 2 == 1 && x `mod` 2 == 1 && (length xs) `mod` 2 == 1 of
        True  -> "Yes"
        False -> "No"

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

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

app = do
  n <- poi
  xs <- replicateM n poi
  return $ if solve n xs then "yes" else "no"
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n (x:xs) = odd x && odd n

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

main = putStr . unlines . map show . evalState app . B.words =<< B.getContents

app = do
  n <- poi
  xs <- replicateM n poi
  return $ if solve n xs then "yes" else "no"
  where
  pop = state $ \(x:xs) -> (x, xs)
  poi = fmap int pop
  int = maybe undefined fst . B.readInt

solve n (x:xs) = odd x && odd n

main = do
    n <- readLn :: IO Int
    xs <- fmap (map read . words) getLine :: IO [Int]
    if mod n 2 == 1 && mod (head xs) 2 == 1 && mod (last xs) 2 == 1
        then print "Yes"
        else print "No"


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

import qualified Data.ByteString as B (getLine)
import qualified Data.ByteString.Char8 as C (readInt, words, dropWhile, unpack, reverse)
import qualified Data.Maybe as M (fromJust)
import Data.Char (isSpace)

rstrip = C.reverse . C.dropWhile isSpace . C.reverse

run' ('V':'K':xs) ans = run' xs (ans + 1)
run' (x:xs) ans = run' xs ans
run' [] ans = ans

flipx 'V' = 'K'
flipx 'K' = 'V'

flipi i x = take i x ++ [flipx (x !! i)] ++ drop (i + 1) x

run x = max (run' x 0) $ maximum [ run' (flipi i x) 0 | i <- [0..length x - 1] ]

main = do
    (C.unpack . rstrip -> x) <- B.getLine
    putStrLn $ show $ run x

main = do
    inp <- getLine
    print (num inp + check inp)

num ('V':'K':xs) = 1 + num xs
num (_:xs) = num xs
num [] = 0

check [_] = 0
check (x:y:[]) = if x==y then 1 else 0
check inp@(x:y:xs)
    | x == y && x == 'K' = 1
    | otherwise = bonus inp

bonus (x:y:z:xs)
    | x == y && y == z = 1
    | xs == [] = if y == z && y == 'V' then 1 else 0
    | otherwise = bonus (y:z:xs)

-- comment

import qualified Data.Sequence as Seq
import qualified Data.Maybe as Maybe
import qualified Data.Foldable as Fold
import qualified Data.Functor as Func

main :: IO ()
main = interact (show . countVKs)

countVKs :: String -> Int
countVKs s =
  let
    sv = Seq.fromList s
    idxs = Seq.fromList [0..(length s - 1)]
    flip v i =
      if Seq.index v i == 'V' then Seq.update i 'K' v else Seq.update i 'V' v
    count v =
      let ind i = if Seq.index v i == 'V' && Seq.index v (i+1) == 'K'
                  then 1 else 0
      in (Fold.foldl (+) 0 . Func.fmap ind) (Seq.take (Seq.length sv - 1) idxs)
  in
    (Fold.foldl (max) 0 . Func.fmap (count . flip sv)) idxs

main :: IO ()
main = print . solve "" =<< getLine

solve :: String -> String -> Int
solve pre [] = solve' pre
solve pre (s:sx) = maximum [solve' (pre ++ "V" ++ sx), solve' (pre ++ "K" ++ sx), solve (pre ++ [s]) sx]

solve' :: String -> Int
solve' [] = 0
solve' ('V':'K':sx) = 1 + solve' sx
solve' (s:sx) = solve' sx

main = do
    inp <- getLine
    print (num inp + check inp)

num ('V':'K':xs) = 1 + num xs
num (_:xs) = num xs
num [] = 0

check inp
    | length inp == 1 = 0
    | otherwise = bonus ( (head inp:inp) ++ last inp:[])

bonus (x:y:z:xs)
    | x == y && y == z = 1
    | xs == [] = 0
    | otherwise = bonus (y:z:xs)

main = do
    inp <- getLine
    print (num inp + bonus ( (head inp:inp) ++ last inp:[]))

num ('v':'k':xs) = 1 + num xs
num (_:xs) = num xs
num [] = 0

bonus (x:y:z:xs)
    | x == y && y == z = 1
    | xs == [] = 0
    | otherwise = bonus (y:z:xs)

main = do
    inp <- getLine
    print (num inp + bonus ( (head inp:inp) ++ last inp:[]))

num ('V':'K':xs) = 1 + num xs
num (_:xs) = num xs
num [] = 0

bonus (x:y:z:xs)
    | x == y && y == z = 1
    | xs == [] = 0
    | otherwise = bonus (y:z:xs)


main = interact $ unlines . map (show . (`div` 3) . (+2) . read) . tail . lines

f::[Int]->[String]
f []=[]
f (x:xs)=let t=(x-1) `div` 6 +1
       in (show t):f xs

main = do
       e<-getLine
       ts<-getContents
       let xs=map read (lines ts)::[Int]
       mapM_ putStrLn $ f xs

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

process = do
		b<-read <$> getLine ::IO Int
		print $ 1+ div b 7

main= do
		a<- read <$> getLine ::IO Int
		replicateM_ a process

--ghc 7.10

countRolls :: Int -> Int
countRolls n = (n+6) `div` 7

main = do
    tStr <- getLine
    contents <- getContents
    let xs = map read . words $ contents :: [Int]
    let rs = map countRolls $ xs
    sequence (map print rs)

main = interact $ unlines . map (show . (`div` 3) . read) . tail . lines


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

main = do
	s <- getLine
	t <- getLine
	print $ solve s t 1

solve :: String -> String -> Int -> Int
solve [] _ cur = cur
solve _ [] cur = cur
solve s@(a:as) (b:bs) cur
	| a == b = solve as bs ( cur + 1 )
	| otherwise = solve s bs cur

main = do
  s <- getLine
  t <- getLine
  print $ solve s t 1

solve [] _ i = i
solve _ [] i = i
solve (x:xs) (t:ts) i
          | x == t    = solve xs ts (i + 1)
          | otherwise = solve (x:xs) ts i

import Data.Array;

main :: IO ()
main = do
  pos <- getLine
  let posArr = array (1, length pos) $ zip [1 ..] pos
  ins <- getLine
  let worker idx i
        | posArr ! idx == i = idx + 1
        | otherwise         = idx
  print $ foldl worker 1 ins

main :: IO ()
main = getContents >>= print . (\[s, t] -> solve (1, s) t) . lines

solve :: (Integer, String) -> String -> Integer
solve = (fst .) . foldl (\(k, s) t -> if head s == t then (k + 1, tail s) else (k, s))

main = interact $ show . solve . lines
solve [s,t] = go s t 1 where
  go _ [] i = i
  go s@(h:s') (t:tt) i | h == t = go s' tt $! i+1
                       | otherwise = go s tt i

main = do
    s <- getLine
    t <- getLine
    print $ solve s t 1
solve _ [] n = n
solve (s:ss) (t:ts) n = if s == t then solve ss ts $ n+1 else solve (s:ss) ts n

main = do
  s <- getLine
  t <- getLine
  print $ f 1 s t

f pos (x:xs) (y:ys)
  | x==y = f (pos+1) xs ys
  | otherwise = f pos (x:xs) ys
f pos _ _ = pos

main = do
  l1 <- getLine
  l2 <- getLine
  print $ slv l1 l2 1

slv _ [] n = n
slv xs'@(x:xs) (y:ys) n
  | x == y = slv xs ys (n+1)
  | otherwise = slv xs' ys n

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

process _ [] n = n
process (s1:s1s) (s2:s2s) n | s1==s2 = process s1s s2s (n+1)
                            |otherwise = process (s1:s1s) s2s n

main = do
	s1<- getLine
	s2<- getLine
	print  $ process s1 s2 1

solve :: String -> String -> Int
solve _ ""  =  1
solve (c1:s1) (c2:s2)
  | c1 == c2  =  1 + solve s1 s2
  | otherwise  =  solve (c1:s1) s2

main :: IO ()
main  =  do
    s1  <-  getLine
    s2  <-  getLine
    print $ solve s1 s2

process :: [Char] -> [Char] -> Int
process xs@(x:xss) (y:yss)
    | x == y = 1+process xss yss
    | otherwise = process xs yss
process _ _ = 1

main :: IO ()
main = do
    xs <- getLine
    ys <- getLine
    print $ process xs ys

import Data.List

f::String->String->Int->Int
f _ "" p=p
f "" _ p=p
f (x:xs) (y:ys) p
   |x==y=f xs ys (p+1)
   |otherwise=f xs (y:ys) p

main = do
       a<-getLine
       b<-getLine
       print $ f b a 1

main=interact$show.(\[s,t]->f(1,s)t).lines
f=(fst.).foldl(\(k,s)t->if head s==t then(k+1,tail s)else(k,s))

main :: IO ()
main = getContents >>= print . (\[s, t] -> solve 1 s t) . lines

solve :: Integer -> String -> String -> Integer
solve n sss@(s:ss) (t:ts) | s == t = solve (n + 1) ss ts
                          | otherwise = solve n sss ts
solve n _ _ = n


main = do
	n <- getLine >>= readIO :: IO Int
	if n `mod` 2 == 0 then do putStrLn "white\n1 2"
			  else putStrLn "black"

solve input =
  let n = read input
  in  if even n
      then "white\n1 2"
      else "black"

main = interact solve

main = do
    input <- getLine >>= (return . read)
    if odd input then
        putStrLn "black"
    else do
        putStrLn "white\n1 2"

main = getLine >>= putStrLn . solve . head . fmap read . words
    where solve x = if odd x then "black" else "white\n1 2"


data State = Class Int | Waiting Int | Home Int

main = interact $ schedule . prep

prep input =
  let (_:pairs:_) = lines input
  in map read $ words pairs

schedule = strip . foldl (\acc x -> case acc of
  Class y -> if x == 1 then Class (y + 1) else Waiting y
  Waiting y -> if x == 1 then Class (y + 2) else Home y
  Home y -> if x == 1 then Class (y + 1) else Home y) (Home 0)

strip (Class y) = show y
strip (Waiting y) = show y
strip (Home y) = show y

module Main (main)
    where

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

main :: IO ()
main = (getLine >> getLine) >>= print . solve . map read . words
    where solve = reduce 0 . map (head &&& length) . group
          reduce n [(0,_)] = n
          reduce n [(1,l)] = n + l
          reduce 0 ((0,_):xs) = reduce 0 xs
          reduce n ((1,l):xs) = reduce (n + l) xs
          reduce n ((0,l):xs)
            | l >= 2    = reduce n xs
            | otherwise = reduce (n + 1) xs

import Data.List

main = do
  getLine
  x <- (group.dropWhile(==0).reverse.dropWhile(==0).map read.words)`fmap`getLine
  putStrLn $ solve x 0

solve [] n = show n
solve ([x]:o) n = solve o (n+1)
solve ((0:0:xs):o) n = solve o n
solve (x:o) n = solve o (n+length x)

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

solve :: Bool -> Bool -> Int -> [Int] -> Int
solve _     False cnt []    = cnt
solve False True  cnt []    = cnt - 1
solve _     _     cnt (1:x) = solve False False (cnt + 1) x
solve True  False cnt (0:x) = solve True  False cnt       x
solve False True  cnt (0:x) = solve True  False (cnt - 1) x
solve False False cnt (0:x) = solve False True  (cnt + 1) x

main = do
    n <- readLn :: IO Int
    a <- fmap ((map read) . words) getLine :: IO [Int]
    let a1 = reverse . dropWhile (==0) . reverse . dropWhile (==0) $ a
    print $ solve a1

solve [] = 0
solve (1:[]) = 1
solve (x:xs)
 |and [x==0,head xs==0] = solve (dropWhile (==0) xs)
 |otherwise = 1+solve xs

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

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

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

main = do
  getLine
  xs <- getInts

  print $ length $ concat $ filter (\g -> not $ head g == 0 && length g >= 2) $ group $ dropWhile (== 0) $ reverse $ dropWhile (== 0) $ reverse xs

answer (a:[]) state = a
answer s state = if state == 0 then if h == 0 then answer t 0
                                              else 1 + (answer t 1)
                 else if (h == 0) && (hh==0) then answer t 0
                      else 1 + (answer t 1)
  where h=head s
        t=tail s
        hh=head t
main=do
  w1 <- getLine
  let n=read w1::Int
  w0 <- getLine
  let sl =[read n::Int|n<-(words w0)]
  print $ answer sl 0

f :: [Int] -> [Int]
f (x:y:z:zs) = if (y == 0) && (x == 1) && (z == 1) then x : 1 : f (z:zs)
                                  else x : f (y:z:zs)
f xs = xs

solve :: [Int] -> Int
solve = length . filter (==1) . f

main = getLine >> fmap (map read . words) getLine >>= print . solve

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

myfunc 0 0 =0
myfunc _ _ =1

main=do
	x<- read <$> getLine:: IO Int
	n<-  map read. words <$> getLine:: IO  [Int]
	let n1 =dropWhile (==0) $reverse $ dropWhile (==0) n
	let y= length n1
	let a=filter (\z-> head z==0) $ group $ zipWith myfunc n1 (tail n1)
	print $ y-(length a ) - sum (map length a)


t k = max 0 k * (k+1) `div` 2
s a b k = if a+b<k then a*b else t k - t(k-a) - t(k-b)
sol [n,x,y,c] = head [k | k<-[0..], c<=s x y (k+1) + s(n-x) y k + s x (n-y) k + s (n-x) (n-y) (k-1)]
main=interact $ show.sol.map read.words

bsearch f a b
  | b == a+1 = b
  | f c = bsearch f a c
  | otherwise = bsearch f c b where
  c = (a + b)`div`2

calc n x y i = (whole, walls, corners) where
   whole = (\i -> 2*i*i-2*i+1) (i+1)
   walls = wall x + wall y + wall (n-x+1) + wall (n-y+1)
   corners = sum [corner (dx+dy-1) | dx<-[x,(n-x+1)],dy<-[y,(n-y+1)]]
   wall dist = w (max 0 $ i - dist + 1) where
    w i = i*i
   corner dist = c (max 0 $ i - dist + 1) where
    c i = i*(i-1)`div`2
solve[n,x,y,c]=bsearch good (-1) (10^9+1 :: Integer) where
  good i = whole - walls + corners >= c where
    (whole, walls, corners) = calc n x y i
main=interact$show.solve.map read.words

tr k = max 0 k * (k+1) `div` 2
s a b k = if a+b<k then a*b else tr k - tr(k-a) - tr(k-b)
solve [n,x,y,c] = head [k | k<-[0..], c<=s x y (k+1) + s(n-x) y k + s x (n-y) k + s (n-x) (n-y) (k-1)]
main=interact $ show.solve.map read.words

a.-b = max 0 $ a-b
tr k = k*(k+1) `div` 2
s a b k = if a+b<=k+1 then a*b else tr k - tr (k.-a) - tr (k.-b)
solve [n,x,y,c] =  find 0 (2*n) where
  h k = c <= s x y (k+1) + s (n-x) y k + s x (n-y) k + s (n-x) (n-y) (k-1)
  find l r | l >= r = r
           | h m = find l m
           | otherwise = find (m+1) r
    where m=(l+r) `div` 2

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

import Data.Int

main :: IO ()
main = do [n,x,y,c] <- getLine >>= return . map read . words
          putStrLn $ show $solve n x y c

solve :: Int64 -> Int64 -> Int64 -> Int64 -> Int64
solve n x y 1 = 0
solve n x y c = binarySearch n x y c 0 (2 * n)

binarySearch n x y c a b
    | a + 1 == b = b
    | lighton n x y m >= c = binarySearch n x y c a m
    | otherwise            = binarySearch n x y c m b
    where m = (a+b) `div` 2

lighton n x y t = center t - side x t - side (n-x+1) t
                           - side y t - side (n-y+1) t
                           + corner x y t
                           + corner (n+1-x) y t
                           + corner x (n+1-y) t
                           + corner (n+1-x) (n+1-y) t

center t = 2 * t * t + 2 * t + 1

side x t
    | (1+t-x) > 0 = (1 + t - x) ^ 2
    | otherwise   = 0

r n x t
    | (x+t-n) > 0 = (x + t - n) ^ 2
    | otherwise   = 0

corner x y t
    | t - x - y + 1 > 0 = (t - x - y + 1)* (t-x-y+2) `div` 2
    | otherwise         = 0

bsearch f a b
  | b == a+1 = b
  | f c = bsearch f a c
  | otherwise = bsearch f c b where
  c = (a + b)`div`2

calc n x y i = (whole, walls, corners) where
   whole = (\i -> 2*i*i-2*i+1) (i+1)
   walls = wall x + wall y + wall (n-x+1) + wall (n-y+1)
   corners = sum [corner (dx+dy-1) | dx<-[x,(n-x+1)],dy<-[y,(n-y+1)]]
   wall dist = w (max 0 $ i - dist) where
    w i = i*i
   corner dist = c (max 0 $ i - dist) where
    c i = i*(i-1)`div`2
solve[n,x,y,c]=bsearch good (-1) (10^9+1 :: Integer) where
  good i = whole - walls + corners >= c where
    (whole, walls, corners) = calc n x y i
main=interact$show.solve.map read.words


module Main where

import Data.Int

main :: IO ()
main = do
    [n, m, a, b] <- fmap (fmap read . words)  getLine
    putStrLn $ show $ minCost n m a b

minCost :: Int64 -> Int64 -> Int64 -> Int64 -> Int64
minCost n m a b = min (demolish * b) (build * a)
                    where demolish  = n `mod` m
                          build     = m - demolish

main=interact$show.f.map read.words
f :: [Integer] -> Integer
f[n,m,a,b]
   | mod n m == 0 = 0
   | otherwise = minimum [a * (m - mod n m), b * mod n m]

module Main where

import System.IO
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8

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

import Control.Monad

input :: IO BS.ByteString
input = do
  handle <- return stdin --openFile "test.txt" ReadMode
  BS.hGetContents handle

readInts :: BS.ByteString -> [Int]
readInts = map parse . C8.words
  where parse s = let Just(x,_) = C8.readInt s in x

main :: IO ()
main = do
  [n,m,a,b] <- fmap (map read . words) getLine :: IO [Integer]
  let toRemove = n `mod` m
      toAdd = m - toRemove
  print $ min (toAdd * a) (toRemove * b)

calculateStuff :: [Integer] -> Integer
calculateStuff (n:m:a:b:tail)
    | (n `mod` m == 0)           = 0
    | constructing < demolishing = constructing
    | otherwise                  = demolishing
    where constructing = a * (m - n `mod` m)
          demolishing = b * (n `mod` m)

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

import Data.List
import Data.Int
import qualified Data.Array as A
import Data.Array((!))
import Numeric

fastRead :: String -> Int64
fastRead ('-':s) = case readDec s of [(n, "")] -> (-n)
fastRead s = case readDec s of [(n, "")] -> n

main = interact solve

solve input = show answer
    where
        (n:m:a:b:_) = map fastRead (words input)
        extra = mod n m
        whenadd = (m - extra) * a
        whenremove = extra * b
        answer = min whenadd whenremove

calculateStuff :: [Int] -> Int
calculateStuff (n:m:a:b:tail)
    | (n `mod` m == 0)           = 0
    | constructing < demolishing = constructing
    | otherwise                  = demolishing
    where constructing = a * (m - n `mod` m)
          demolishing = b * (n `mod` m)

main = interact $ show . calculateStuff . map read . words
-- why


{-# LANGUAGE ScopedTypeVariables #-}

import Text.Printf
import Data.List
import Data.Functor
import Data.Function
import Control.Monad
import Control.Applicative
import Data.Maybe
import Data.Foldable (foldl', foldr', foldr1)
import Prelude
import Control.Monad.State.Strict
import Data.Int
import qualified Data.ByteString.Char8 as B8
import qualified Data.Map.Strict as MapS
import qualified Data.Set as Set

readB8Int64 :: B8.ByteString -> Int64
readB8Int64 = fromInteger . fst . fromJust . B8.readInteger

limitedValid :: Int64 -> Int64 -> [Int64]
limitedValid k limit = takeWhile (<= limit) $ iterate (* k) 1

twoThreeValid :: Int64 -> [Int64]
twoThreeValid limit = do
    twoValid <- limitedValid 2 limit
    threeValid <- limitedValid 3 $ limit `div` twoValid
    return $ twoValid * threeValid

twoThreeLimitCount :: Int64 -> Int64
twoThreeLimitCount limit = fromIntegral . length $ twoThreeValid limit

twoThreeRangeCount :: Int64 -> Int64 -> Int64
twoThreeRangeCount l r = (twoThreeLimitCount r) - (twoThreeLimitCount $ l - 1)

main :: IO ()
main = do
    [l, r] <- (map readB8Int64) <$> B8.words <$> B8.getLine
    let answer = twoThreeRangeCount l r
    printf "%lld\n" $ answer

import Data.List (sort)

main= do
    inpt <- getLine
    let (a:b:_) = map read (words inpt)
    print $ f a b

f a b = length $ filter (\x -> x >= a && x <= b) genlist
genlist = sort . concat $ map (\x -> gen' x) (map (\y -> 3 ^ y) [0..33])
gen' a = map (\x -> (2 ^ x) * a) [0..33]

countNums :: Integer -> Integer -> Integer -> Int -> Int
countNums n p2 p3 cnt
  | p2 >= n       = cnt
  | p2*p3 >= n    = countNums n (p2*2) 1 cnt
  | otherwise     = countNums n p2 (p3*3) (cnt+1)

countLT :: Integer -> Int
countLT n = countNums n 1 1 0

main :: IO ()
main = do
    xs <- fmap (map (read :: String -> Integer) . words) getLine
    print $ countLT ((xs!!1) + 1) - countLT (head xs)

import qualified Data.List.Split as Spl

ptwo :: Integer -> Integer
ptwo 0 = 1
ptwo x = (ptwo $ x - 1) * 2

pth :: Integer -> Integer
pth 0 = 1
pth x = (pth $ x - 1) * 3

check :: Integer -> Integer -> Integer -> Integer -> Int

check l r x y =
    if ((((ptwo x) * (pth y)) >= l) && (((ptwo x) * (pth y)) <= r))
    then 1
    else 0

solveY :: Integer -> Integer -> Integer -> Integer -> Int

solveY l r x y =
    if y > 20 then 0
    else (solveY l r x (y + 1)) + (check l r x y)

solveX :: Integer -> Integer -> Integer -> Int

solveX l r x =
    if x > 32 then 0
    else (solveX l r (x + 1)) + (solveY l r x 0)

main = do
    input <- getLine
    let keks = Spl.splitOn " " input
    let l =  read (keks !! 0) :: Integer
    let r =  read (keks !! 1) :: Integer
    print $ solveX l r 0

import Data.List (sort)

main= do {
	inpt <- getLine
	; let (a:b:_) = map read (words inpt) :: [Int]
	; print $ f a b }

f a b = length $ filter (\x -> x >= a && x <= b) genlist
genlist = sort . concat $ map (\x -> gen' x) (map (\y -> 3 ^ y) [0..33])
gen' a = map (\x -> (2 ^ x) * a) [0..33]

{-# LANGUAGE ScopedTypeVariables #-}

import Text.Printf
import Data.List
import Data.Functor
import Data.Function
import Control.Monad
import Control.Applicative
import Data.Maybe
import Data.Foldable (foldl', foldr', foldr1)
import Prelude
import Control.Monad.State.Strict
import Data.Int
import qualified Data.ByteString.Char8 as B8
import qualified Data.Map.Strict as MapS
import qualified Data.Set as Set

readB8Int64 :: B8.ByteString -> Int64
readB8Int64 = fromInteger . fst . fromJust . B8.readInteger

limitedValid :: Int64 -> Int64 -> [Int64]
limitedValid k limit = takeWhile (<= limit) $ iterate (* k) 1

twoThreeValid :: Int64 -> [Int64]
twoThreeValid limit = do
    twoValid <- limitedValid 2 limit
    threeValid <- limitedValid 3 $ limit `div` twoValid
    return $ twoValid * threeValid

twoThreeLimitCount :: Int64 -> Int64
twoThreeLimitCount limit = limit - (fromIntegral . length $ twoThreeValid limit)

twoThreeRangeCount :: Int64 -> Int64 -> Int64
twoThreeRangeCount l r = (twoThreeLimitCount r) - (twoThreeLimitCount $ l - 1)

main :: IO ()
main = do
    [l, r] <- (map readB8Int64) <$> B8.words <$> B8.getLine
    let answer = twoThreeRangeCount l r
    printf "%lld\n" $ answer


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

solve :: Int -> [Int] -> Int
solve 200 _ = -1
solve i [a, b, c, d] | b == d    = b
                     | b < d     = solve (i + 1) [a, b + a, c, d]
                     | otherwise = solve (i + 1) [a, b, c, d + c]

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Char8 as B

main = do
  [a, b] <- fmap readInts B.getLine
  [c, d] <- fmap readInts B.getLine
  print $ solve a b c d

ee a b = go a b 1 0 0 1
  where
    go r0 r1 s0 s1 t0 t1
      | r == 0 = (s1, t1, r1)
      | otherwise = go r1 r s1 (s0 - q * s1) t1 (t0 - q * t1)
      where (q, r) = r0 `quotRem` r1

solve a b c d
  | r /= 0 = -1
  | otherwise = b + (x - t * c `div` g) * a
  where
    (x_, y_, g) = ee a c
    (q, r) = (d - b) `divMod` g
    (x, y) = (q * x_, q * y_)
    t = min (x * g `div` c) ((-y) * g `div` a)

readInt = maybe undefined fst . B.readInt
readInts = fmap readInt . B.words

-- b + na = d + mc
-- na - mc = d - b
-- xa + yc = gcd(a, c)
-- n = x - r * c/gcd(a, c) >= 0
-- r <= x * gcd(a,c) / c
-- r <=
-- m = y + r * c/gcd(a, c) <=

import           Control.Applicative
import           Control.Monad
import           Data.List           (intersect)

main = replicateM 2 (fmap read . words <$> getLine) >>= \[[a,b],[c,d]]-> print $ head $ intersect [d, d+c..d+ 100*c] [b,b+a..b+100*a] ++[-1]

import           Control.Applicative
import           Control.Monad
import           Data.List           (find)

main = replicateM 2 (fmap read . words <$> getLine) >>= \[[a,b],[c,d]]-> print $ head $ [k |i <- [0..100], j <-[0..100],
                                                                                let k = b + i * a, let l = d + j * c,
                                                                                k == l] ++ [-1]

main = getContents >>= print . solve . map read . words

solve [a, b, c, d] = (\ls -> if null ls then -1 else head ls)
                     [t | t <- [(max b d)..1000000], (t - b) `mod` a == 0, (t - d) `mod` c == 0]

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

import Data.List (sort, sortBy, nub, delete)

-- all primes
primes :: [Int]
primes = takeWhile (< 100) $ pr (2:[3,5..]) where
    pr (x:xs) = x:pr [ i | i <- xs, i `mod` x /= 0 ]

-- Extended Euclidean Algorithm
exgcd a 0 = (a, 1, 0)
exgcd a b = (ret, y, x - a `div` b * y) where
    (ret, x, y) = exgcd b (a `mod` b)

-- Multiplication Inverse
minv n p = let (_, x, _) = exgcd n p in x

-- 12 => [(2, 2), (3, 1)]
factors = ffold . sort . factors' where
    factors' 1 = []
    factors' x = let k = filter (\i -> x `mod` i == 0) primes
                 in k ++ factors' (foldl div x k)
    ffold [] = []
    ffold (x:[]) = [(x, 1)]
    ffold (x:xs) = ffold' x (ffold xs)
    ffold' x (p:prev) | fst p == x = (x, snd p + 1):prev
                      | otherwise  = (x, 1):p:prev

runone b c d | b <= d               = d
             | (b - d) `mod` c == 0 = ((b - d) `div` c) * c + d
             | otherwise            = (1 + ((b - d) `div` c)) * c + d

run a b c d | a == 1    = runone b c d
            | c == 1    = runone d a b
            | fi        = -1
            | fe /= 0   = -1
            | otherwise = fo where
    fe = (b - d) `mod` (gcd a c)
    fa = map (\x -> (x, b)) (factors a)
    fc = map (\x -> (x, d)) (factors c)
    ff = sortBy cmp (fa ++ fc)
    fx [] b = [b]
    fx (d@((a', b'), c'):xs) e@((a, b), c) | a == a' = e:xs
                                           | otherwise = e:d:xs
    fg = sortBy cmp2 $ nub $ map fh (foldl fx [] ff)
    fh ((a, b), c) = (a^b, c `mod` (a^b))
    fi = any (\((a, b), (a', b')) -> a == a' && b /= b') (zip fg (tail fg))
    fgf = map fst fg
    fgs = map snd fg
    fj = map (foldl (*) 1 . flip delete fgf) fgf
    fk = zipWith minv fj fgf
    fl a b c = a * b * c
    fm = foldl (*) 1 fgf
    fn = (sum (zipWith3 fl fgs fk fj)) `mod` fm
    fo = until (\x -> b <= x && d <= x) (+ fm) fn
    cmp ((a, b), c) ((a', b'), c') | a == a' = compare b b'
                                   | otherwise = compare a a'
    cmp2 (a, b) (a', b') | a == a' = compare b b'
                         | otherwise = compare a a'

main = do
    (map (read :: String -> Int) . words -> [a, b]) <- getLine
    (map (read :: String -> Int) . words -> [c, d]) <- getLine
    putStrLn $ show $ run a b c d

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

exgcd a 0 = (a, 1, 0)
exgcd a b = (ret, y, x - a `div` b * y) where
    (ret, x, y) = exgcd b (a `mod` b)

pmod x y = ((x `mod` y) + y) `mod` y

-- Bezout's Lemma -- min. ax+b s.t. ax+b = cy+d, x, y >= 0
run a b c d | r /= 0 = -1
            | otherwise = until (>= d) (+ (a * p)) (b + a * ((x * q) `pmod` p)) where
    p = c `div` g
    (q, r) = (d - b) `divMod` g
    (g, x, y) = exgcd a c

main = do
    (map (read :: String -> Int) . words -> [a, b]) <- getLine
    (map (read :: String -> Int) . words -> [c, d]) <- getLine
    putStrLn $ show $ run a b c d

import           Control.Applicative
import           Control.Monad
import           Data.List           (find)

main = replicateM 2 (fmap read . words <$> getLine) >>= \[[a,b],[c,d]]-> print $ maybe (-1) fst $ find (uncurry (==)) [(b + i * a, d + i * c)| i <- [0..a*c]]

import           Control.Applicative
import           Control.Monad
import           Data.List           (find)

main = replicateM 2 (fmap read . words <$> getLine) >>= \[[a,b],[c,d]]-> print $ maybe (-1) fst $ find (uncurry (==)) [(b + i * a, d + i * c)| i <- [0..100000]]

import           Control.Applicative
import           Control.Monad
import           Data.List           (find)

main = replicateM 2 (fmap read . words <$> getLine) >>= \[[a,b],[c,d]]-> print $ maybe (-1) fst $ find (uncurry (==)) [(a + i * b, c + i * d)| i <- [0..b*d]]

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

import Control.Monad (forM_, forM)

main = do
    (map (read :: String -> Int) . words -> [a, b]) <- getLine
    (map (read :: String -> Int) . words -> [c, d]) <- getLine
    let x = take (2 * c) [b, b + a..]
        y = take (2 * a) [d, d + c..]
        z = filter (`elem` x) y
    if z == [] then
        putStrLn $ show $ -1
    else
        putStrLn $ show $ head z

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

exgcd a 0 = (a, 1, 0)
exgcd a b = (ret, y, x - a `div` b * y) where
    (ret, x, y) = exgcd b (a `mod` b)

pmod x y = ((x `mod` y) + y) `mod` y

-- Bezout's Lemma -- min. (ax+b) s.t. ax+b = cy+d
run a b c d | r /= 0 = -1
            | otherwise = b + a * ((x * q) `pmod` (c `div` g)) where
    (q, r) = (d - b) `divMod` g
    (g, x, _) = exgcd a c

main = do
    (map (read :: String -> Int) . words -> [a, b]) <- getLine
    (map (read :: String -> Int) . words -> [c, d]) <- getLine
    putStrLn $ show $ run a b c d

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

import Data.List (sort, sortBy, nub, delete)

-- all primes
primes :: [Int]
primes = takeWhile (< 100) $ pr (2:[3,5..]) where
    pr (x:xs) = x:pr [ i | i <- xs, i `mod` x /= 0 ]

-- Extended Euclidean Algorithm
exgcd a 0 = (a, 1, 0)
exgcd a b = (ret, y, x - a `div` b * y) where
    (ret, x, y) = exgcd b (a `mod` b)

-- Multiplication Inverse
minv n p = let (_, x, _) = exgcd n p in x

-- 12 => [(2, 2), (3, 1)]
factors = ffold . sort . factors' where
    factors' 1 = []
    factors' x = let k = filter (\i -> x `mod` i == 0) primes
                 in k ++ factors' (foldl div x k)
    ffold [] = []
    ffold (x:[]) = [(x, 1)]
    ffold (x:xs) = ffold' x (ffold xs)
    ffold' x (p:prev) | fst p == x = (x, snd p + 1):prev
                      | otherwise  = (x, 1):p:prev

runone b c d | b <= d               = 1
             | (b - d) `mod` c == 0 = 1 + ((b - d) `div` c)
             | otherwise            = 2 + ((b - d) `div` c)

run a b c d | a == 1    = runone b c d
            | c == 1    = runone d a b
            | fi        = -1
            | fe /= 0   = -1
            | otherwise = fo where
    fe = (b - d) `mod` (gcd a c)
    fa = map (\x -> (x, b)) (factors a)
    fc = map (\x -> (x, d)) (factors c)
    ff = sortBy cmp (fa ++ fc)
    fx [] b = [b]
    fx (d@((a', b'), c'):xs) e@((a, b), c) | a == a' = e:xs
                                           | otherwise = e:d:xs
    fg = sortBy cmp2 $ nub $ map fh (foldl fx [] ff)
    fh ((a, b), c) = (a^b, c `mod` (a^b))
    fi = any (\((a, b), (a', b')) -> a == a' && b /= b') (zip fg (tail fg))
    fgf = map fst fg
    fgs = map snd fg
    fj = map (foldl (*) 1 . flip delete fgf) fgf
    fk = zipWith minv fj fgf
    fl a b c = a * b * c
    fm = foldl (*) 1 fgf
    fn = (sum (zipWith3 fl fgs fk fj)) `mod` fm
    fo = until (\x -> b <= x && d <= x) (+ fm) fn
    cmp ((a, b), c) ((a', b'), c') | a == a' = compare b b'
                                   | otherwise = compare a a'
    cmp2 (a, b) (a', b') | a == a' = compare b b'
                         | otherwise = compare a a'

main = do
    (map (read :: String -> Int) . words -> [a, b]) <- getLine
    (map (read :: String -> Int) . words -> [c, d]) <- getLine
    putStrLn $ show $ run a b c d


test str1 k =
	let
		dx = length str
		str = str1 ++ take k (repeat '?')
	in
		maximum [ j | i <- [0 .. dx - 1], j <- [2,4..dx - i], check (take j (drop i str)) ]

check str = all (\a -> a) (map (\(a, b) -> a == b || b == '?') (zip str (drop (length str `div` 2) str)))

main  = do
	str <- getLine
	k <- getLine
	putStrLn (show (test str (read k :: Int)))

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main = do
  [bs,_n] <- B.words <$> B.getContents
  print $ solve (readInt _n) bs

solve :: Int -> B.ByteString -> Int
solve !k bs = foldl' max (div k 2) [2 * f i j|i<-[0..n-1],j<-[i..n-1]]
   where
     !n = B.length bs
     subString i j bs = B.take (j-i+1) $ B.drop i bs
     f i j
       | B.length sub == B.length sub' = if sub == sub' then len else 0
       | B.length sub <= B.length sub' + k && sub' `B.isPrefixOf` sub = len
       | n <= k = div (n + k) 2
       | otherwise = 0
      where
        !sub  = subString i j bs
        !sub' = B.take len $ B.drop (j+1) bs
        !len = j - i + 1

{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Data.Array.IO
import           Data.Array.Unboxed
import qualified Data.ByteString.Char8 as C
import qualified Data.Foldable         as F
import           Data.Function
import           Data.Functor
import           Data.IORef
import           Data.List
import           Data.Maybe
import           Data.Monoid
import           Data.Traversable
import           Text.Printf           (printf)

import qualified Data.Set as S
import Data.Char

-- I/O

readInts :: C.ByteString -> [Int]
readInts = map fst . mapMaybe C.readInt . C.words

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

readNums :: Num a => C.ByteString -> [a]
readNums = map (fromIntegral . fst) . mapMaybe C.readInteger . C.words

getNums :: Num a => IO [a]
getNums = readNums <$> C.getLine

cast :: (Integral a, Integral b) => a -> b
cast = fromIntegral

-----

main :: IO ()
main = do
  s <- getLine
  k <- readLn

  print $ foldl' max 0 [ i * 2
                       | ss <- tails s
                       , let tt = ss ++ replicate k '$', i <- [1..200]
                       , let aa = take i tt
                             bb = take i (drop i tt)
                       , length bb == i && and (zipWith f aa bb)
                       ]

f '$' _ = True
f _ '$' = True
f a b = a == b

import Data.List (tails, inits, isPrefixOf)

main = do
  s <- getLine
  k <- readLn
  let
    longest s = maximum $ 0 : (map ((*2) . length . fst) . filter can $ zip (inits s) (tails s))
    can (as, bs) = (isPrefixOf as bs || isPrefixOf bs as) && abs (length as - length bs) <= k
    longest' s = maximum $ 0 : (map length . filter isRepeat $ inits s)
    isRepeat s = a == b
      where
        (a, b) = splitAt (length s `div` 2) s
    result = if k > length s then (k + length s) `div` 2 * 2 else max (maximum . map longest $ tails s) (maximum . map longest' $ tails s)
   in putStrLn . show $ result

check str k = foldl (\acc (a, b) -> acc && a == b) True (zip str (drop ((length str + k) `div` 2) str))
test str k = if (length str + k) `mod` 2 == 0 && check str k then length str + k else test (drop 1 str) k
main  = do
	str <- getLine
	k <- getLine
	putStrLn (show (test str (read k :: Int)))

import Data.List (tails, inits, isPrefixOf)

main = do
  s <- getLine
  k <- readLn
  let
    longest :: String -> Int
    longest s = maximum $ 0 : (map ((*2) . length . fst) . filter can $ zip (inits s) (tails s))
    can (as, bs) = (isPrefixOf as bs || isPrefixOf bs as) && abs (length as - length bs) <= k
   in putStrLn . show $ maximum . map longest $ tails s

import Data.List (tails, inits, isPrefixOf)

main = do
  s <- getLine
  k <- readLn
  let
    longest s = maximum $ 0 : (map ((*2) . length . fst) . filter can $ zip (inits s) (tails s))
    can (as, bs) = (isPrefixOf as bs || isPrefixOf bs as) && abs (length as - length bs) <= k
    result = if k > length s then (k + length s) `div` 2 * 2 else maximum . map longest $ tails s
   in putStrLn . show $ result

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main = do
  [bs,_n] <- B.words <$> B.getContents
  print $ solve (readInt _n) bs

solve :: Int -> B.ByteString -> Int
solve !k bs = foldl' max 0 [2 * f i j|i<-[0..n-1],j<-[i..n-1]]
   where
     !n = B.length bs
     subString i j bs = B.take (j-i+1) $ B.drop i bs
     f i j
       | sub == sub' = len
       | sub' `B.isPrefixOf` sub && B.length sub <= B.length sub' + k = len
       | otherwise = 0
      where
        !sub  = subString i j bs
        !sub' = B.take len $ B.drop (j+1) bs
        !len = j - i + 1

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray)
import Data.Bits
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.Function
import Data.Int
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.STRef
import GHC.Arr (Array, Ix, unsafeIndex)
bool :: a -> a -> Bool -> a
bool t f b=if b then t else f
readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n
rep, rev :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
rev !n f=go(n-1)where go !i=when(i>=0)$f i>>go(i-1)
{-# INLINE rep #-}
{-# INLINE rev #-}
modifyArray :: (MArray a e m, Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray a i f=readArray a i>>=writeArray a i.f
{-# INLINE modifyArray #-}
unsafeModify :: (MArray a e m, Ix i) => a i e -> Int -> (e -> e) -> m ()
unsafeModify a i f=unsafeRead a i>>=unsafeWrite a i.f
{-# INLINE unsafeModify #-}

main = do
  [bs,_n] <- B.words <$> B.getContents
  print $ solve (readInt _n) bs

solve :: Int -> B.ByteString -> Int
solve !k bs = foldl' max 0 [2 * f i j|i<-[0..n-1],j<-[i..n-1]]
   where
     !n = B.length bs
     subString i j bs = B.take (j-i+1) $ B.drop i bs
     f i j
       | B.length sub == B.length sub' = if sub == sub' then len else 0
       | B.length sub <= B.length sub' + k && sub' `B.isPrefixOf` sub = len
       | otherwise = 0
      where
        !sub  = subString i j bs
        !sub' = B.take len $ B.drop (j+1) bs
        !len = j - i + 1


findOne :: [Int] -> Int
findOne (a:b)
    | a == 1    = 0
    | otherwise = 1 + findOne b

main :: IO()
main = do
    str <- getContents
    let ind = findOne (map read (words str))
    (putStrLn . show) (abs ((mod ind 5) - 2) + abs ((div ind 5) - 2))

import Data.Char
import Data.List
import Data.Maybe

main = do
	mat <- getContents
	print $ solve $ fromJust $ findIndex (=="1") $ words mat

solve :: Int -> Int
solve pos = abs(x-2) + abs(y-2)
	where
		x = pos `div` 5;
		y = pos `mod` 5;

import Control.Monad

import Data.List (findIndex)

findy :: [[Int]] -> (Int, Int)
findy xs = head [(r, c) | (r, row) <- zip [1..] xs, (c, val) <- zip [1..] row, val == 1]

solve :: [[Int]] -> Int
solve grid =
  let (r, c) = findy grid
  in
  abs (r - 3) + abs (c - 3)

main = do
  grid <- replicateM 5 $ do
    fmap read <$> words <$> getLine
  print $ solve grid

main = interact $ show . calc cost . words
cost = map(\x -> abs(div x 5 - 2) + abs(mod x 5 - 2))[0..]
calc _ [] = 0
calc (c:cs) (x:xs) = calc cs xs + if x == "1" then c else 0

import Control.Applicative

main = do
  matrix <- map words . lines <$> getContents
  let pos = position matrix 0
  print $ abs (fst pos - 2) + abs (snd pos - 2)

position (x:xs) i
  | "1" `elem` x = pos' x 0
  | otherwise    = position xs (i+1)
  where pos' (x:xs) j
          | x == "1"  = (i, j)
          | otherwise = pos' xs (j+1)

import Data.List

inputNumMatrix r=sequence$replicate r(map read.words<$>getLine)

oneCoordinates :: [[Int]] -> (Int, Int)
oneCoordinates matrix@(r:rs) = case findIndex (==1) r of
  Just i -> (0, i)
  Nothing -> (fst nxt + 1, snd nxt)
    where nxt = oneCoordinates rs

distanceFromCenter :: (Int, Int) -> Int
distanceFromCenter (rowI, colI) = abs (rowI - 2) + abs (colI - 2)

main :: IO ()
main = (inputNumMatrix 5 :: IO [[Int]]) >>=
  \matrix -> print $ distanceFromCenter (oneCoordinates matrix)

module Main where

distance :: (Int, Int) -> (Int, Int) -> Int
distance (a,b) (c,d) = abs (a-c) + abs (b-d)

find :: Int -> [Int] -> Int
find k xs = find' 0 k xs
     where
     find' _ _ [] = -1
     find' k x (x':xs) = if x == x'
                         then k
                         else find' (k+1) x xs

extractCoords :: [Int] -> (Int, Int)
extractCoords = extractCoords' 0
              where
              extractCoords' n ((-1):xs) = extractCoords' (n+1) xs
              extractCoords' n (x:xs) = (n, x)

getCoords :: [[Int]] -> (Int, Int)
getCoords mat = extractCoords $ map (find 1) mat

solve :: [[Int]] -> Int
solve mat = distance (2,2) $ getCoords mat

main = do
     matrixStr <- getContents
     let matrixChr = map words $ lines matrixStr
         matrix = map (map (read :: String -> Int)) matrixChr
     print $ solve matrix

import Control.Applicative
import Data.List

main= do
	  s<- map read. words <$> getContents::IO [Int]
	  let x = length $ takeWhile (==0) s
	  let a= mod x 5
	  let b= div x 5
	  print $ abs (a-2) + abs (b-2)

{-
A. Beautiful Matrix
====================
time limit per test: 2 seconds
memory limit per test: 256 megabytes
input: standard input
output: standard output

You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:

Swap two neighboring matrix rows, that is, rows with indexes i and i + 1 for some integer i (1 ≤ i < 5).
Swap two neighboring matrix columns, that is, columns with indexes j and j + 1 for some integer j (1 ≤ j < 5).
You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.

Input
------
The input consists of five lines, each line contains five integers: the j-th integer in the i-th line of the input represents the element of the matrix that is located on the intersection of the i-th row and the j-th column. It is guaranteed that the matrix consists of 24 zeroes and a single number one.

Output
------
Print a single integer — the minimum number of moves needed to make the matrix beautiful.

Sample test(s)
---------------
input
0 0 0 0 0
0 0 0 0 1
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
output
3

input
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 0 0
output
1

-}

import Data.List (elemIndex, findIndex)
import Data.Maybe (Maybe, isJust)

stepsToBeautifulMatrix :: [[Int]] -> Int
stepsToBeautifulMatrix xxs = abs (i - 2) + abs (j - 2)
  where tmp = map (elemIndex 1) xxs
        Just i = findIndex isJust tmp
        Just j = tmp !! i

main = do
  input <- getContents
  let xxs = [map read (words line) | line <- lines input]
  print $ stepsToBeautifulMatrix xxs

import           Control.Monad                  ( replicateM )
main :: IO ()
main = do
    zeroes <- takeWhile ("1" /=) . concatMap words <$> replicateM 5 getLine
    let pos = length zeroes
    let (row, col) = (pos `div` 5, pos `mod` 5)
    let ans = abs (2 - row) + abs (2 - col)
    print ans

import Control.Monad.State
import Control.Monad (when)

centerCoords = (2,2)

metric::(Int, Int) ->(Int, Int) -> Int
metric (a,b) (c,d) = sum $ abs <$> [a-c, b-d]

getXCoord::[Int]-> Int
getXCoord cc = if all (==0) cc then -1 else length cc  - length (dropWhile (== 0) cc)

readCoords :: IO ()
readCoords = forM_ [0..4] $ \y-> do
    l <- getLine
    let x = getXCoord $  read <$> words l
    Control.Monad.when (x /= - 1) $ print (metric centerCoords (x, y))

someFunc :: IO()
someFunc = readCoords

main :: IO ()
main = someFunc

import Data.List

main :: IO ()
main = interact $ show . solve . elemIndex "1" . words

solve :: Maybe Int -> Int
solve Nothing = 0
solve (Just n) = (abs ((mod n 5) - 2)) + (abs ((div n 5) - 2))

import Data.List
import Data.Maybe

dist :: (Int, Int) -> Int
dist (a, b) =
  (abs (2 - a)) + (abs (2 - b))

extract2 :: [Maybe Int] -> (Int, Int)
extract2 xs =
  (fromJust a, fromJust(xs !! fromJust a)) where
    a = findIndex (isJust) xs

extract :: [String] -> Maybe Int
extract xs =
  findIndex (=="1") xs

lib :: String -> String
lib xs = (show . dist . extract2 . fmap (extract . words) . lines $ xs) ++ "\n"

main :: IO ()
main = interact lib

import Control.Monad
import Control.Applicative
main = replicateM 5 (getLine >>= return.words) >>= return.concat >>= putStrLn.show.fst.head.filter snd.zip distances.map (=="1")

distances = concat $ map (\i -> map (i+) s) s
  where s = map abs [-2..2]

--ghc 7.10

import Data.Maybe
import Data.Tuple

manhattanDistance :: (Num a) => (a,a) -> (a,a) -> a
manhattanDistance (x1,y1) (x2,y2) = (abs (x1-x2)) + (abs (y1-y2))

toMatrix :: Int -> Int -> [a] -> [((Int,Int),a)]
toMatrix n m a = zip indices a
    where indices = [(i,j) | i <- [0..(n-1)], j <- [0..(m-1)]]

beautifulDiff :: (Eq a) => Int -> Int -> a -> [a] -> Int
beautifulDiff n m x a = manhattanDistance mid idx
    where
        mid = (n `div` 2, m `div` 2)
        idx = fromJust $ lookup x (map swap matrix)
        matrix = toMatrix n m a

main = do
    contents <- getContents
    let a = map read . words $ contents :: [Int]
    print $ beautifulDiff 5 5 1 a

import Data.List
import Control.Applicative

main = do
  x <- head . elemIndices 1 . tail . (0:) . map read . words <$> getContents
  print (abs (x `mod` 5 - 2) + abs (x `div` 5 - 2))

import Data.Array
import Data.List
import Control.Applicative
main = do
    ar <- listArray ((1,1),(5,5)) . words <$> getContents :: IO (Array (Int,Int) [Char])
    let c = fst $ head $ filter (\(i,e) -> e=="1") $ assocs ar
    print (m c (3,3))
m (a,b) (c,d) = abs (a-c) + abs (b-d)

distance :: (Int, Int) -> Int
distance (row, column) = abs (row - 2) + abs (column -2)

oneLoc :: String -> (Int, Int)
oneLoc = (`quotRem` 5) . oneDimPos
    where oneDimPos =  length . takeWhile (=="0") . words

solve :: String -> String
solve = show . distance . oneLoc

main :: IO ()
main = interact solve

import Data.Maybe
import Data.List

parseLn = map read . words

findRow = fromJust . findIndex (elem 1)

dist = abs . (-) 2

solve m = dist row + dist col
  where
    row = findRow m
    col = findRow $ transpose m

main = print . solve . map parseLn . lines =<< getContents

import Data.List
f xs = let Just n = elemIndex "1" xs
           [p,q] = [div n 5, mod n 5]
       in abs(p-2)+abs(q-2)
main = interact $ show.f.words

import Control.Monad (replicateM)
import Data.List

main::IO()
main = do
    lst1 <- replicateM 5 getLine
    let lst = concatMap (filter (/=' ')) lst1
    let Just i = elemIndex '1' lst
    print $ abs (i `mod` 5 - 2) + abs (i `div` 5 - 2)

module Main
    where

main = do
    c <- coord
    print $ mini c
    where
        mini (x, y) =
            abs (3 - x) + abs (3 - y)
        coord =
            coord' 0 0
            where
                coord' 0 y = do
                    row <- getLine
                    coord' (getX row) (y + 1)
                    where
                        getX row =
                            case words row of
                                "1":_ -> 1
                                _:"1":_ -> 2
                                _:_:"1":_ -> 3
                                _:_:_:"1":_ -> 4
                                _:_:_:_:"1":_ -> 5
                                _ -> 0
                coord' x y =
                    return (x, y)

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

removeSpace :: String -> String
removeSpace xs = [ x | x <- xs, not (x `elem` " ") ]

main :: IO ()
main = do
  inputs <- replicateM 5 getLine :: IO [[Char]]
  let ninputs = map removeSpace inputs
  let res = map (\x -> (elemIndex '1' x)) ninputs
  let resm = map (\x -> (fromMaybe (-1) x)) res
  let conc = zip resm [0..(length res)]
  let [(x, y)] = filter (\(a, _) -> a /= -1) conc
  print ((abs (2 - x)) + (abs (2 - y)))

import Control.Applicative

main = do
  ls <- lines <$> getContents
  let vec = concat $ map words ls
  let (a,b) = head $ [ (i,j) | i <- [0..4], j <- [0..4], (vec !! (i*5+j)) == "1"]
  print $ abs (2-a) + (abs (2-b))

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

main :: IO ()
main = do
  a <- replicateM 5 $ fmap (elemIndex (1::Int) . map read . words) getLine
  let i = fromJust $ findIndex isJust a
      j = fromJust $ a!!i
  print $ abs (i - 2) + abs (j - 2)

main = do
	al<-getContents
	putStrLn $ show $ solve $ map read $ concat $map (words) $ lines al

solve m = abs(3-i)+abs(3-j )
   where i = 1+div (one-1) 5
         j = 1+mod (one-1) 5
         one =1+ length (takeWhile (==0) m)

import Control.Applicative ((<$>))
import Data.List (elemIndex)
import Data.Maybe (fromJust)

main = lines <$> getContents >>= return . solve 0 0 . map words >>= print
       where solve a b (x:xs)
               | "1" `elem` x = (abs $ 2-a) + (abs $ 2 - (fromJust $ "1" `elemIndex` x))
               | otherwise    = solve (a+1) b xs

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

main = (sequence $ take 5 $ repeat getLine) >>= return . solve (0,0) . map words >>= print
       where solve (a,b) (x:xs)
               | "1" `elem` x = (abs $ 2-a) + (abs $ 2 - (fromJust $ "1" `elemIndex` x))
               | otherwise    = solve (a+1, b) xs

import Data.Char
import Data.List

f n (x:xs) = case elemIndex '1' x of
             Just m -> sum $ map (abs . subtract 2) [m, n]
             Nothing -> f (n + 1) xs

main = interact $ show . f 0 . map (filter $ not . isSpace) . lines

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

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

main = do
    a <- replicateM 5 $ do
        ai <- readItems
        return $ elemIndex 1 ai
    let i1 = fromJust (findIndex isJust a)
    let i2 = fromJust (a !! i1)
    putStrLn $ show $ abs (i1 - 2) + abs (i2 - 2)

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

main :: IO ()
main = do
  vals <- sequence [getLine, getLine, getLine, getLine, getLine]
  print $ distance $ findOne (map words vals) 0

findOne :: Num t => [[[Char]]] -> t -> (t, Int)
findOne (x:xs) idx
  | elem "1" x = (idx, fromJust $ elemIndex "1" x)
  | otherwise  = findOne xs (idx + 1)

distance :: Num a => (a, a) -> a
distance (x, y) = abs(x - 2) + abs(y - 2)

main = do
    as <- fmap (map (map read . words) . lines) getContents

    let
        (i, j) = head [(i, j) | i <- [0..4], j <- [0..4], as!!i!!j == 1]

    print $ abs (2-i) + abs (2-j)

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

solve xs = abs (2 - y) + abs(2 - x)
    where   (k, _) : _ = filter (\(_,b) -> b == 1) . zip [0..] $ xs
            (x, y) = (mod k 5, div k 5)

import Data.List
f x = abs(a - 2) + abs(b - 2) where
	  Just g = findIndex (=="1") x
	  [a, b] = [div g 5, mod g 5]
main = interact $ show . f . words

import Data.List

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

process contents = let
  mat = contents
    |> lines
    |> map words
    |> map (map read) :: [[Integer]]
  in mat
    |> solve
    |> show

solve mat = solve' mat 0
  |> distance

distance (row, col) = abs (row - 2) + abs (col - 2)

solve' mat row = case findIndex (== 1) (mat !! row) of
  Nothing -> solve' mat (row + 1)
  (Just idx) -> (row, idx)

import Control.Monad
import qualified Data.List as L
import qualified Data.Maybe as M

main :: IO ()
main = do
    l <- (getContents >>= return . map read . words)
    putStrLn $ show $ solve l

solve :: [Int] -> Int
solve = calcMinStep . findPosition

findPosition :: [Int] -> (Int,Int)
findPosition l = (x `div` 5, x `mod` 5)
    where
        x = M.fromMaybe 0 (L.findIndex (==1) l)

calcMinStep :: (Int,Int) -> Int
calcMinStep (x,y) = abs (x-2) + abs(y-2)

{-# LANGUAGE BlockArguments #-}

import Control.Arrow
import Data.List

main = do { x <- solve 0; (show >>> putStrLn) x }

solve :: Int -> IO Int
solve a = do { s <- getLine
             ; let i = (words >>> map read >>> findIndex (==1)) s
               in case i of
                  Nothing -> solve (a+1)
                  Just v -> return $ (abs (2-v)) + (abs (2-a))
             }

import           Control.Applicative
import           Data.List

main = do
  x <- head . elemIndices 1 . tail . (0:) . map read . words <$> getContents
  print (abs (x `mod` 5 - 2) + abs (x `div` 5 - 2))

import Data.List
import Data.Maybe
main = readsolveprint
readsolveprint::IO()
readsolveprint =  interact $ show . solve. map  (map read. words).  take (5) . lines
solve :: [[Int]]->Int
solve xss = abs ((z`div`5)-2)+abs((z`mod`5)-2)
  where z= fromJust $ elemIndex 1 $ concat xss

import Control.Applicative
import Data.List

solve :: Maybe Int -> Int
solve (Just i) =
    let r = quot i 5
        c = rem i 5
    in abs (r - 2) + abs (c - 2)

main = do
    l <- (elemIndex '1'.filter (\x-> x `elem` "01")) <$> getContents
    print $ solve l

{-#LANGUAGE OverloadedStrings#-}
module Main where

import Data.Text (pack, unpack, splitOn, intercalate)

--confirm 5 row and five columns
-- find the position of the number
main :: IO ()
main = do
    strs <- getS
    let p = pos strs
    let ans = abs (2 - fst p) + abs (2 - snd p)
    putStrLn $ show ans

pos :: [String] -> (Int,Int)
pos s = (indexC s, maximum $ map indexR s)
        where
            indexC :: [String] -> Int
            indexC = go2 0
            go2 i [] = -1
            go2 i (c : cs)
                | '1' `elem` c = i
                | otherwise = go2 (i+1) cs
            indexR :: String -> Int
            indexR = go 0
            go i [] = -1
            go i (c : cs)
                | c == '1' = i
                | otherwise = go (i+1) cs

getS :: IO [String]
getS = sequence [getLine >>=
        (pure . unpack . intercalate ""
            . splitOn " " . pack) | _ <- [1..5] ]

import Data.List (findIndices)

solve :: String -> Int
solve  =  solve' . flip divMod 5 . head . findIndices (== "1") . words
  where
    solve' (i, j)  =  abs (i - 2) + abs (j - 2)

main :: IO ()
main  =  getContents >>= print . solve

-- Codeforces 263A

{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -optc-O3 #-}
{-# LANGUAGE BangPatterns #-}

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

main :: IO ()
main = do
    mat <- replicateM 5 ((map read . words) <$> getLine) :: IO [[Int]]
    let Just row = findIndex (any (== 1)) mat
        Just column = findIndex (== 1) (mat !! row)
    print $ abs (row + 1 - 3) + abs (column + 1 - 3)

import Control.Applicative
import Control.Monad
import Data.Array (range)

dim = range ((0,0),(4,4)) :: [(Int,Int)]

parseInts = map read . words

main = do
  xs <- zip dim . concatMap parseInts <$> replicateM 5 getLine :: IO [((Int,Int),Int)]
  let ((i,j),_) = head $ filter ((/=0) . snd) xs
  print $ abs (i-2) + abs (j-2)

import Data.Function

main = findOne >>= putStrLn . show . calculateMoves

indexOf::[Char] -> Char -> Int
indexOf str c = fix (\fn len i res -> case () of
  _ | i >= len -> res
    | str !! i == c -> i
    | otherwise -> fn len (i + 2) res) (length str) 0 (-1) `div` 2

findOne::IO (Int, Int)
findOne = fix (\fn lineIndex -> do
  line <- getLine
  let columnIndex = indexOf line '1'
  if columnIndex == (-1)
  then fn (lineIndex + 1)
  else return (lineIndex, columnIndex)) 0

calculateMoves::(Int, Int) -> Int
calculateMoves coord = calculateDifference (fst coord)
  + calculateDifference (snd coord)

calculateDifference::Int -> Int
calculateDifference pos = abs (pos - 2)

import Text.Printf
import Data.List
import Data.Functor
import Control.Applicative
import Prelude
import Control.Monad
import Data.Maybe
import Data.Function

readInt :: String -> Int
readInt = read

readMatrix :: Int -> Int -> IO [[Int]]
readMatrix n m = forM [1 .. n] (\ _ -> (map readInt . words) <$> getLine)

findPos :: [[Int]] -> Int -> Maybe (Int, Int)
findPos matrix number = (,) <$> iIndex <*> jIndex
    where
        jIndices = map (elemIndex number) matrix
        iIndex = findIndex isJust jIndices
        jIndex = msum jIndices

main :: IO ()
main = do
    matrix <- readMatrix 5 5
    let Just (i, j) = findPos matrix 1
    printf "%d" $ ((+) `on` (\x -> abs (x - 2))) i j

import Control.Monad

getI :: [Char] -> Int -> Int
getI [] i = -1
getI (a:as) i | a == '1' = (i + 1) `quot` 2
              | otherwise = getI as (i + 1)

locate :: [[Char]] -> Int -> (Int, Int)
locate [] j = (-1, -1)
locate (a:as) j | getI (a) (-1) == -1 = locate as (j + 1)
                | otherwise = (getI a (-1), j)

dxdy a = abs (2 - fst a) + abs(2 - snd a)
solve a = putStrLn $ show (dxdy (locate (a) (0)))
main = replicateM 5 getLine >>= solve

import Control.Monad
import Data.Array
import Data.Char
import Data.Maybe
import Data.List
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 arr = abs (a - 2) + abs (b - 2)
    where a    = fromJust $ findIndex (elem 1) arr
          arr0 = fromJust $ find (elem 1) arr
          b    = fromJust $ elemIndex 1 arr0

main :: IO ()
main = replicateM 5 getIntList >>= putStrLn . show . solve

import Data.List
import Data.Maybe

getMatrix :: IO Int
getMatrix = do
  mat <- mapM (\_ -> getLine) [1..5]
  let ind = zip mat [1..]
      (m, row) = fromJust $ find (\(m, _) -> '1' `elem` m) ind
      col = 1 + (fromJust $ findIndex (\a -> "1" == a) $ words m)
  return $ abs (col - 3) + abs (row - 3)

main :: IO ()
main = print =<< getMatrix

import Data.List
import Data.Char
import Control.Applicative
import Data.Array

process a b | a<b = "-1"
            |a>b = "1"
            | otherwise = "0"

main::IO ()
main=do
    a<-getContents
    let a1=concatMap (map read) $ map words $ lines  a::[Int]
    let (b,c)=fst$ head  $ filter (\z-> snd z ==1) $ zip ([(i,j)|i<-[1..5],j<-[1..5]]) a1
    print $ (abs (3-b) )+(abs (3-c))

import Control.Arrow (second)
import Data.List (elemIndex)
import Data.Maybe (fromJust, isJust)

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

solve :: [[Int]] -> Int
solve = distance (2, 2) . getIndex 1

getIndex :: Eq a => a -> [[a]] -> (Int, Int)
getIndex n = second fromJust . head . filter (isJust . snd) . zip [0..] . map (elemIndex n)

distance :: Num a => (a, a) -> (a, a) -> a
distance (xa, ya) (xb, yb) = abs (xa - xb) + abs (ya - yb)

import Prelude hiding (readList, showList)
import Control.Monad
import Control.Applicative
import Data.List

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

readList' :: Read a => a -> IO [a]
readList' _ = readList

readInt :: IO Int
readInt = head <$> readList' (undefined::Int)

showList :: Show a => [a] -> IO ()
showList = putStrLn . unwords . map show

skipLine :: IO ()
skipLine = void $ getLine

count :: (a -> Bool) -> [a] -> Int
count f = length . filter f

divUp :: Integral a => a -> a -> a
divUp x y
  | x `mod` y /= 0 = x `div` y + 1
  | otherwise      = x `div` y

main :: IO ()
main = do
  ls <- replicateM 5 $ readList' (undefined :: Int)
  let ls' = transpose ls
      row = sum $ zipWith (*) (fmap sum ls ) [1..]
      col = sum $ zipWith (*) (fmap sum ls') [1..]
  putStrLn $ show $ abs (3-row) + abs (3-col)

import Data.List

col :: String -> Maybe Int
col line = (elemIndex "1" $ words line)

row :: [String] -> Int -> Int
row (line:lines) rowNum = case inRow of
                               Just colNum -> (abs $ rowNum - 2)
                                 + (abs $ colNum - 2)
                               Nothing -> row lines $ rowNum + 1
  where inRow = col line

main = do
  interact $ show . abs . (flip row) 0 . lines

import Data.List
main = print . solve . parse =<< getContents
parse = (`divMod` 5) . head . elemIndices "1" . words
solve (x,y) = abs(x-2) + abs(y-2)

-- import Debug.Trace
-- import System.IO.Unsafe
-- import Text.Printf
import System.IO
import Control.Monad
import Data.List

glwr = fmap (map read . words) getLine

main = do
  hSetBuffering stdout NoBuffering
  solve

solve :: IO ()
solve = do
  m <- forM [1..5] $ const glwr

  print $ beautifulMatrix m

beautifulMatrix :: [[Int]] -> Int
beautifulMatrix m
  = [ abs (x-2) + abs (y-2)
    | y <- [0..4]
    , x <- [0..4]
    , m!!y!!x == 1
    ] !! 0

main=interact$show.f tbl.map read.words
tbl = map (\x ->abs((div x 5)-2)+abs((mod x 5)-2)) [0..24]
f(x:xs)(0:ys)=f xs ys
f(x:_)_=x

main=interact$show.f g.map read.words
g=map(\x->abs(div x 5-2)+abs(mod x 5-2))[0..]
f(x:xs)(0:ys)=f xs ys
f(x:_)_=x

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

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

-- see https://stackoverflow.com/questions/29186541/why-is-this-haskell-program-so-much-slower-than-an-equivalent-python-one/29186898
import qualified Data.ByteString.Char8 as B

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

solve :: [[Int]] -> Int
solve arr = abs (a - 2) + abs (b - 2)
    where a     = fromJust $ findIndex (elem 1) arr
          arr0  = fromJust $ find (elem 1) arr
          b     = fromJust $ elemIndex 1 arr0

main = replicateM 5 getIntList >>= putStrLn . show . solve

module Main where
import Data.List
import Control.Applicative
import Data.Maybe
findRow :: [String] -> Int
findRow matrix = fromMaybe (-1) $ findIndex (\r -> '1' `elem` r) matrix

findColumn :: String -> Int
findColumn row = fromMaybe (-1) $ elemIndex '1' row

findOne :: [String] -> (Int,Int)
findOne matrix = let rowIndex = findRow matrix in (rowIndex, findColumn $ matrix!!rowIndex)

main = do
  matrix <- mapM (\_ -> filter (/=' ') <$> getLine) [1..5]
  let (row,col) = findOne matrix in print (abs (2 - row) + abs (2 - col))

import Data.Maybe
import Data.List
calcDist (x,y) = (abs (x - 2), (abs (y - 2)))
solve n = let (x,y) = calcDist $ divMod n 5 in x + y
main = interact $ show . solve . fromJust . elemIndex "1" . words

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

removeSpace :: String -> String
removeSpace xs = [ x | x <- xs, not (x `elem` " ") ]

main :: IO ()
main = do
  inputs <- replicateM 5 getLine :: IO [[Char]]
  let ninputs = map removeSpace inputs
  let res = map (\x -> (elemIndex '1' x)) ninputs
  let resm = map (\x -> (fromMaybe (-1) x)) res
  let conc = zip resm [0..(length res)]
  let [(x, y)] = filter (\(a, _) -> a /= -1) conc
  print ((abs (2 - x)) + (abs 2 - y))

main = do
    as <- fmap (map (map read . words) . lines) getContents

    let
        (i, j) = head [(i, j) | i <- [0..4], j <- [0..4], as!!i!!j == 1]

    print $ max (abs (2-i)) (abs (2-j))

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

solve xs = abs (2 - y) + abs(2 - y)
    where   (k, _) : _ = filter (\(_,b) -> b == 1) . zip [0..] $ xs
            (x, y) = (mod k 5, div k 5)

import Data.List
import Data.Char
import Control.Applicative
import Data.Array

process a b | a<b = "-1"
            |a>b = "1"
            | otherwise = "0"

main::IO ()
main=do
    getLine
    a<-getContents
    let a1=concatMap (map read) $ map words $ lines  a::[Int]
    let (b,c)=fst$ head  $ filter (\z-> snd z ==1) $ zip ([(i,j)|i<-[1..5],j<-[1..5]]) a1
    print $ (abs (3-b) )+(abs (3-c))


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

solve :: [Integer] -> Integer
solve (_:m:as) = snd $ foldl f (0, 1) as
  where f (x, y) a | x + a <= m = (x + a, y)
                   | otherwise = (a, y + 1)
solve _ = undefined

main :: IO ()
main = do
  _:m:_ <- fmap (map read . words) getLine
  ls <- fmap (map read . words) getLine
  print $ rush m ls 0

rush :: Int -> [Int] -> Int -> Int
rush _ [] n = n
rush m ls n = rush m (go ls 0) (n + 1)
  where go [] _ = []
        go l@(x:r) a
          | a + x > m = l
          | otherwise = go r (a + x)

main :: IO ()
main = do
	input <- getContents
	ls <- return $ lines input
	nm <- return $ words $ ls!!0
	l2 <- return $ words $ ls!!1
	putStr $ solve (read $ nm!!0) (read $ nm!!1) (map read l2)

solve :: Int -> Int -> [Int] -> String
solve n m as = show $ f m as where
	f :: Int -> [Int] -> Int
	f r [] = if r < m then 1 else 0
	f 0 ls = 1 + (f m ls)
	f r all@(l:ls) = if l <= r then f (r-l) ls else 1+(f m all)

parseInput input = (n, m, xs) where
    ls = lines input
    [n, m] = map read $ words $ head ls :: [Int]
    xs = map read $ words $ last ls :: [Int]

solve _ [] buses _ = buses
solve m xs buses seats  | head xs + seats <= m  = solve m (tail xs) buses (seats + head xs)
                        | otherwise             = solve m (tail xs) (buses + 1) (head xs)

main = do
    input <- getContents
    let (n, m, xs) = parseInput input
    print $ solve m xs 1 0

{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import Text.Printf

readInt = ( readLn :: IO Int )
getInts = map ( read :: String -> Int ) . words <$> getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = do
	[ n, m ] <- getInts
	as <- getInts

	let
		solve _ [] = 0
		solve s (a:as)
			| s + a <= m = solve ( s + a ) as
			| otherwise = 1 + solve a as

	print $ 1 + solve 0 as

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

solve :: [Int] -> Int
solve (m:a) = solve' m a
    where solve' :: Int -> [Int] -> Int
          solve' _ [] = 0
          solve' i (a:x) | a+i > m = 1 + solve' 0 (a:x)
                         | otherwise = solve' (a+i) x

import Control.Monad(liftM)

readi = read :: String -> Int
readL = ((map readi) . words) `liftM` getLine

pc _ x []
    | x /= 0 = 1
    | otherwise = 0
pc m acc (x:xs)
    | acc + x > m = 1 + pc m 0 (x:xs)
    | otherwise = pc m (acc + x) xs

main = do
    [n, m] <- readL
    a <- readL
    putStrLn $ show $ pc m 0 a
    --(sum a + m - 1) `div` m

main = do
    [n,m] <- fmap (map read . words) getLine
    a <- fmap (map read . words) getLine
    print $ busCount m a

busCount :: Integer -> [Integer] -> Integer
busCount _ [] = 0
busCount m a = 1 + busCount m (drop (length taken) a)
    where variants = map (\n -> sum (take n a)) [1..length a]
          taken = takeWhile (<= m) variants

answ [] _ _ r = r
answ (x:xs) k c r
 | x + c <= k = answ xs k (c + x) r
 | otherwise  = answ xs k x (r + 1)

main :: IO()
main = do
    [_, k] <- (map read . words) `fmap` getLine
    xs <- (map read . words) `fmap` getLine
    print $ answ xs k 0 1

solve :: Int -> [Int] -> Int
solve m [_] = 1
solve m (g1:g2:gs)
  | g1 + g2 <= m = solve m (g1+g2:gs)
  | otherwise    = 1 + solve m (g2:gs)

main :: IO ()
main = do
  [_, m] <- fmap (map read . words) getLine :: IO [Int]
  gs <- fmap (map read . words) getLine :: IO [Int]
  print $ solve m gs

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

buses :: Int -> [Int] -> Int
buses m = go 0
	where
		go 0 [] = 0
		go _ [] = 1
		go r (y:ys)
			| r + y <= m = go (r + y) ys
			| otherwise  = 1 + go y ys

main :: IO ()
main = do
	[_, m] <- inputInts
	xs <- inputInts
	print $ buses m xs

import Control.Applicative
import Data.List

process n _ c [] =n + if c>0 then 1 else 0
process n m c (s:ss) | c+s<m = process n m (c+s) ss
                     | c+s==m = process (n+1) m 0 ss
		     | c+s>m = process (n+1) m s ss

main= do
	[n,m]<- map read.words  <$> getLine:: IO [Int]
	s<-map read.words  <$> getLine:: IO [Int]
	print $ process 0 m 0 s

main = do
    let i = fmap (map read . words) getLine :: IO [Int]
    [_, m] <- i
    a <- i
    print $ gao a m m

gao :: [Int] -> Int -> Int -> Int
gao [] _ _ = 1
gao a@(x:xs) rem n
    | x <= rem  = gao xs (rem - x) n
    | otherwise = gao a n n + 1

import Control.Monad(liftM)

readi = read :: String -> Int
readL = ((map readi) . words) `liftM` getLine

main = do
    [n, m] <- readL
    a <- readL
    putStrLn $ show $ (sum a + m - 1) `div` m

main :: IO()
main = do
    [_, k] <- (map read . words) `fmap` getLine
    xs <- (map read . words) `fmap` getLine
    print $ ((sum xs) `quot` k) + if (((sum xs) `rem` k) > 0) then 1 else 0

main :: IO ()
main = do
  [n, m] <- fmap (map read . words) getLine :: IO [Int]
  as <- fmap (map read . words) getLine :: IO [Int]
  print $ toInteger $ ceiling (fromIntegral (sum as) / fromIntegral m)

import Control.Applicative
import Data.List

process n _ _ [] =n
process n m c (s:ss) | c+s<m = process n m (c+s) ss
                     | c+s==m = process (n+1) m 0 ss
		     | c+s>m = process (n+1) m s ss

main= do
	[n,m]<- map read.words  <$> getLine:: IO [Int]
	s<-map read.words  <$> getLine:: IO [Int]
	print $ process 0 m 0 s

main = do
    let i = fmap (map read . words) getLine :: IO [Int]
    [_, m] <- i
    a <- i
    print $ gao a m m

gao :: [Int] -> Int -> Int -> Int
gao [_] _ _ = 1
gao a@(x:xs) rem n
    | x <= rem  = gao xs (rem - x) n
    | otherwise = gao a n n + 1

main = do
    let i = fmap (map read . words) getLine :: IO [Int]
    [n, m] <- i
    a <- i
    print $ gao a n n

gao :: [Int] -> Int -> Int -> Int
gao [_] _ _ = 1
gao a@(x:xs) rem n
    | x <= rem  = gao xs (rem - x) n
    | otherwise = gao a n n + 1