At the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to m points. We know that c1 schoolchildren got 1 point, c2 children got 2 points, ..., cm children got m points. Now you need to set the passing rate k (integer from 1 to m): all schoolchildren who got less than k points go to the beginner group and those who get at strictly least k points go to the intermediate group. We know that if the size of a group is more than y, then the university won't find a room for them. We also know that if a group has less than x schoolchildren, then it is too small and there's no point in having classes with it. So, you need to split all schoolchildren into two groups so that the size of each group was from x to y, inclusive. Help the university pick the passing rate in a way that meets these requirements.

The first line contains integer m (2 ≤ m ≤ 100). The second line contains m integers c1, c2, ..., cm, separated by single spaces (0 ≤ ci ≤ 100). The third line contains two space-separated integers x and y (1 ≤ x ≤ y ≤ 10000). At least one ci is greater than 0.

If it is impossible to pick a passing rate in a way that makes the size of each resulting groups at least x and at most y, print 0. Otherwise, print an integer from 1 to m — the passing rate you'd like to suggest. If there are multiple possible answers, print any of them.

NoteIn the first sample the beginner group has 7 students, the intermediate group has 6 of them. In the second sample another correct answer is 3.

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

main = do
	getLine
	cs <- map read . words <$> getLine
	[ x, y ] <- map read . words <$> getLine

	let
		ok as = let tot = sum as in x <= tot && tot <= y

		ks = [ k + 1 | k <- [ 1 .. length cs ], ok ( take k cs ), ok ( drop k cs ) ]

	print $ if null ks then 0 else head ks

import Control.Applicative
main :: IO ()
main = do
    getLine
    cs <- map read <$> words <$> getLine
    ls <- map read <$> words <$> getLine
    let x = ls !! 0
        y = ls !! 1
    print . (solve x y) $ cs

solve :: Int -> Int -> [Int] -> Int
solve lb ub cs = helper 1 0 (sum cs) cs
    where
        helper k beginner intermediate left
            | okay beginner && okay intermediate = k
            | null left = 0
            | otherwise = helper (k+1) (beginner + head left) (intermediate - head left) (tail left)
        okay n = lb <= n && n <= ub

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
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.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import System.IO
-- import Debug.Trace

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

main = do
  m <- readLn
  cs <- getInts
  [x, y] <- getInts

  let a = [k | k <- [1..m], let a = sum (take (k-1) cs), let b = sum (drop (k-1) cs), a `elem` [x..y], b `elem` [x..y]]

  print $ if null a then 0 else head a

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

solve :: (Int, Int) -> [Int] -> Int
solve (x, y) as  =  case answers of
    []  ->  0
    as  ->  head as
  where
    answers  =  map fst $ filter (good . snd) $ zip [1..] $ scanl (+) 0 as
    good s1  =  x <= s1 && s1 <= y && x <= s2 && s2 <= y
      where
        s2  =  sum as - s1

main :: IO ()
main  =  do
    getLine
    as  <-  reads
    [x, y]  <-  reads
    print $ solve (x, y) as

  where
    reads :: Num a => IO [a]
    reads  =  liftM (map read . words) getLine
      where
        read ('-':s)  =  (-1) * read s
        read s  =  read' 0 s
        read' a ""  =  a
        read' a (c:s)  =  read' (10 * a + fromIntegral (ord c - ord '0')) s

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

module Main where
import Control.Applicative
import Data.List
main :: IO ()
main = do
  _ <- getLine
  cs <- map read . words <$> getLine :: IO [Int]
  [x,y] <- map read . words <$> getLine :: IO [Int]
  let beginnerSizes = scanl1 (+) cs
      numKids = sum cs
      intermediateSizes = map (numKids -) beginnerSizes
  -- print beginnerSizes
  -- print intermediateSizes
  case find (\(bSize,iSize,_) -> x <= bSize && bSize <= y && x <= iSize && iSize <= y) $
            zip3 beginnerSizes intermediateSizes [1..] of
    Just (_,_,res) -> print (res + 1)
    Nothing -> print (0 :: Int)
  -- correctTimes <- map read . words <$> getLine :: IO [Int]
  -- wrongTimes <- map read . words <$> getLine :: IO [Int]
  -- let minCorrectTime = minimum correctTimes
  --     v = maximum (2*minCorrectTime : correctTimes)
  --     minWrongTime = minimum wrongTimes
  -- print $ if minWrongTime <= v then -1 else v

solve :: [[Int]] -> Int
solve (_:c:[x, y]:_) =
  let cSum = sum c
      partialSums = zip [1..] $ scanl1 (+) c
      inRange :: Int -> Bool
      inRange q = q >= x && q <= y
      matching = filter (\(_, q) -> inRange q && inRange (cSum - q)) partialSums
  in
   if null matching then 0 else 1 + (fst $ head matching)

main :: IO ()
main =
  interact $ show . solve . map (map read . words) . lines

partsum :: [Int] -> [Int]
partsum [] = []
partsum ns = partsum' ns 0
  where partsum' [] _ = []
        partsum' (s:l) c = (c + s) : partsum' l (c + s)

main = do
  n <- read `fmap` getLine :: IO Int
  nums <- (map read . words) `fmap` getLine :: IO [Int]
  [x, y] <- (map read . words) `fmap` getLine :: IO [Int]
  let sum = partsum nums !! (n - 1)
  let fg = take n $ zip (0 : partsum nums) [1..n + 1]
  let res = head $ [snd q | q <- fg, fst q >= x, fst q <= y, sum - fst q >= x, sum - fst q <= y] ++ [0]
  putStrLn $ show res

#!/usr/bin/env runghc
main = do
  c <- getContents
  putStr . unlines . solve . lines $ c

solve::[String]->[String]
solve [] = []
solve (m:ci:xy:cs) = (show . f $ zip3 [2..] (scanl1 (+) c)  (tail . scanr (+) 0 $ c)): solve cs
  where
    c = map read . words $ ci
    [x,y] = map read . words $ xy
    f [] = 0
    f ((i,a,b):ss) = if x<=a && a<=y && x<=b && b<=y then i else f ss

main = do
    input <- getLine
    let m = head (getList input)
    input <- getLine
    let list = getList input
    input <- getLine
    let [x,y] = getList input
    putStr $ show $ getPoint 1 x y list 0 (sum list)

getList :: String -> [Int]
getList x = map read $ words x

inRange :: Int -> Int -> Int -> Bool
inRange v x y = (x <= v && v <= y)

getPoint :: Int -> Int -> Int -> [Int] -> Int -> Int -> Int
getPoint returnVar x y [] l r = 0
getPoint returnVar xLimit yLimit (x:xs) leftSum rightSum =
    if (inRange leftSum xLimit yLimit) && (inRange rightSum xLimit yLimit) then returnVar
    else getPoint (returnVar + 1) xLimit yLimit xs (leftSum + x) (rightSum - x)

solve :: Int -> [Integer] -> Integer -> Integer -> Integer
solve n c l r = find 1 sums
                where
                    parts = map ((flip splitAt) c) [0..n]
                    sums = map (\(x, y) -> (sum x, sum y)) parts
                    find _ [] = 0
                    find pos ((x, y):xs)
                        | all id [x >= l, x <= r, y >= l, y <= r] = pos
                        | otherwise = find (pos + 1) xs

main = do
    n <- getLine
    c <- fmap words getLine
    [x, y] <- fmap words getLine
    print $ solve (read n) (map read c) (read x) (read y)

import Control.Applicative
import Data.List

process _ _ _ _ _ [] = -1
process a b sums cs n (s:ss)  | and [ cs>=a,cs <=b, sums-cs >=a, sums-cs <=b] = n
                              | otherwise = process a b sums (cs+s) (n+1) ss

main= do
	getLine
	s<- map read. words <$> getLine ::IO [Int]
	[a,b]<- map read. words <$> getLine ::IO [Int]
	print $ (+) 1 $  process a b (sum s) 0 0 s

import Control.Applicative

fun :: Int -> Int -> Int -> Int -> Int -> [Int] -> Int
fun llevo total x y v [] = if (llevo>=x && llevo<=y && total-llevo>=x && total-llevo<=y) then v else 0
fun llevo total x y v (l:ls) = if (llevo>=x && llevo<=y && total-llevo>=x && total-llevo<=y) then v else fun (llevo+l) total x y (v+1) ls

main = do
       k <- getLine
       ls <- map read.words <$> getLine
       [x,y] <- map read.words <$> getLine
       let total = sum ls
       putStrLn.show $ fun 0 total x y 1 ls

import Data.List
find x
	| x>=0  = show x
	| otherwise = "No solution"

head' [] = (-1,([],[]))
head' x = head x

parse :: String -> [Int]
parse l = map read $ words l

cal _ students xy =
	let x = xy !! 0
	    y = xy !! 1
	in (+1) $ fst $ head' $filter (chk x y) $ sp students

sp ss =
	let si = [1..(length ss) -1 ]
	in map (\x -> (x , splitAt x ss)) si

chk x y tup = (chkk x y $ sum $ fst $ snd tup) && (chkk x y $  sum $ snd $ snd tup)
chkk x y n = (x <= n) && ( n <= y)

main = do
	l1 <- getLine
	l2 <- getLine
	l3 <- getLine
	putStr $ show $ cal (parse l1) (parse l2) (parse l3)

import Data.List
import Data.Char
import Control.Monad
import Data.Maybe
import Control.Applicative
import Debug.Trace
import qualified Data.ByteString.Char8 as B

debug x = trace (show x) x
(|>) x f = f x; infixl 1 |>
(||>) mx f = mx >>= (return . f); infixl 1 ||>

solve cs total x y =
  solve' cs 0 2

  where
    solve' [] _ _ = 0
    solve' (c:cs) sum r =
      if check sum' then r
        else solve' cs sum' (r+1)
      where
        sum' = sum + c
    check sum =
      x <= sum  && sum <= y && x <= (total-sum) && (total-sum) <= y

main = do
  ls <- getContents ||> lines
  cs <- ls !! 1 |> words |> map read |> return
  [x,y] <- ls !! 2 |> words |> map read |> return
  print $ solve cs (sum cs) x y

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

import Control.Applicative
import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
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.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
-- import Data.Tree
import Data.Tuple
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import System.IO
-- import Debug.Trace

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

main = do
  m <- readLn
  cs <- getInts
  [x, y] <- getInts

  let a = [s | s <- [1..m], let a = sum (take s cs), let b = sum (drop s cs), a `elem` [x..y], b `elem` [x..y]]

  print $ if null a then 0 else head a

import Control.Applicative
import Data.List

process _ _ _ _ _ [] = 0
process a b sums cs n (s:ss)  | and [ cs>=a,cs <=b, sums-cs >=a, sums-cs <=b] = n
                              | otherwise = process a b sums (cs+s) (n+1) ss

main= do
	getLine
	s<- map read. words <$> getLine ::IO [Int]
	[a,b]<- map read. words <$> getLine ::IO [Int]
	print $ process a b (sum s) 0 0 s

import Control.Applicative
import Data.List

process _ _ _ _ _ [] = 0
process a b sums cs n (s:ss)  | and [ cs>=a,cs <=b, sums-cs >=a, sums-cs <=b] = n
                              | otherwise = process a b sums (cs+s) (n+1) ss

main= do
	getLine
	s<- map read. words <$> getLine ::IO [Int]
	[a,b]<- map read. words <$> getLine ::IO [Int]
	print $ (+) 1 $  process a b (sum s) 0 0 s


Lenny is playing a game on a 3 × 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be switched off, if it was switched off then it will be switched on.Lenny has spent some time playing with the grid and by now he has pressed each light a certain number of times. Given the number of times each light is pressed, you have to print the current state of each light.

The input consists of three rows. Each row contains three integers each between 0 to 100 inclusive. The j-th number in the i-th row is the number of times the j-th light of the i-th row of the grid is pressed.

Print three lines, each containing three characters. The j-th character of the i-th line is "1" if and only if the corresponding light is switched on, otherwise it's "0".

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

main = mapM_ (putStrLn . concatMap show) . solve . slice . map (toInteger . maybe 0 fst . B.readInt) . B.words =<< B.getContents

slice :: [Integer] -> [[Integer]]
slice (a : b : c : xs) = [a, b, c] : slice xs
slice xs = []

solve :: [[Integer]] -> [[Integer]]
solve ns = [[(sum [ns!!x'!!y' | [x',y'] <- [[x-1,y], [x,y-1], [x,y], [x,y+1], [x+1,y]], x'>=0, x'<3, y'>=0, y'<3] + 1) `mod` 2 | y <-[0..2]] | x <- [0..2]]

import Data.List
import Data.List.Split

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

solve contents = let
  toggles = contents |> lines |> map words |> map (map read) :: [[Int]]
  states = toggleThem toggles
  in states |> chunksOf 3 |> unlines

toggleThem toggles = [state toggles x y | x <- [0..2], y <- [0..2]]

state toggles x y = let
  count = toggleCount toggles x y
  in if even count then '1' else '0'

toggleCount toggles x y = toggleTimes toggles (x - 1) y
  + toggleTimes toggles x y
  + toggleTimes toggles (x + 1) y
  + toggleTimes toggles x (y - 1)
  + toggleTimes toggles x (y + 1)

toggleTimes toggles x y = if isValid x y then toggles !! x !! y else 0

isValid x y = x >= 0 && x < 3 && y >= 0 && y < 3

import Data.List
import Control.Monad
import qualified Data.Text as T
import Data.Maybe

(f3, x, o, os )  = ((\a b c -> a . b . c), not, id, replicate 9 o)

to01 = map T.unpack . T.chunksOf 3 . T.pack .  map (\x -> if x then '1' else '0')

solve [a,b,c,d,e,f,g,h,i] =
    zipWith ($)
        (zipWith3 f3
            (zipWith3 f3 (if a==1 then [x,x,o,x,o,o,o,o,o] else os)
                         (if b==1 then [x,x,x,o,x,o,o,o,o] else os)
                         (if c==1 then [o,x,x,o,o,x,o,o,o] else os))
            (zipWith3 f3 (if d==1 then [x,o,o,x,x,o,x,o,o] else os)
                         (if e==1 then [o,x,o,x,x,x,o,x,o] else os)
                         (if f==1 then [o,o,x,o,x,x,o,o,x] else os))
            (zipWith3 f3 (if g==1 then [o,o,o,x,o,o,x,x,o] else os)
                         (if h==1 then [o,o,o,o,x,o,x,x,x] else os)
                         (if i==1 then [o,o,o,o,o,x,o,x,x] else os)))
        $ replicate 9 True

main = do
    a <- concat <$> replicateM 3 (map(read :: String -> Int) . words <$>  getLine)
    mapM_ putStrLn $ to01 $ solve $ map (`mod` 2) a

import Control.Monad (liftM)
import Prelude hiding (reads)

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

solve :: [Int] -> [Int]
solve [a11, a12, a13,
       a21, a22, a23,
       a31, a32, a33]
  =  map (\n -> (n - 1) `mod` 2)
      [a11 + a12 + a21, a11 + a12 + a13 + a22, a12 + a13 + a23,
       a11 + a21 + a22 + a31, a12 + a21 + a22 + a23 + a32, a13 + a22 + a23 + a33,
       a21 + a31 + a32, a22 + a31 + a32 + a33, a23 + a32 + a33]

print' :: Show a => [a] -> IO ()
print' [a1, a2, a3, a4, a5, a6, a7, a8, a9]  =  do
    mapM_ (\x -> putStrLn (concatMap show x))
        [[a1, a2, a3], [a4, a5, a6], [a7, a8, a9]]

main :: IO ()
main  =  reads >>= print' . solve

main :: IO ()
main = getContents >>= mapM_ (putStrLn . concatMap show) . solve . map (map read . words) . lines

solve :: [[Int]] -> [[Int]]
solve xs = [ [ 1 - sum [ xs !! i' !! j' | j' <- [0..2], i' <- [0..2], abs (i - i') + abs (j - j') < 2 ] `mod` 2 | j <- [0..2] ] | i <- [0..2] ]
-- solve xs = foldl' f (replicate 3 $ replicate 3 1)
--                   [ (i, j, x) | (j, xs') <- zip [0..2] xs, (i, x) <- zip [0..2] xs' ]
--   where f :: [[Int]] -> (Int, Int, Int) -> [[Int]]
--         f ys (i, j, x) = [ [ if abs (i' - i) + abs (j' - j) < 2 && odd x then 1 - y else y
--                               | (i', y) <- zip [0..] ys' ] | (j', ys') <- zip [0..] ys ]

import Data.List (foldl')

main :: IO ()
main = getContents >>= mapM_ (putStrLn . concatMap show) . solve . map (map read . words) . lines

solve :: [[Int]] -> [[Int]]
solve xs = foldl' f (replicate 3 $ replicate 3 1)
                  [ (i, j, x) | (j, xs') <- zip [0..2] xs, (i, x) <- zip [0..2] xs' ]
  where f :: [[Int]] -> (Int, Int, Int) -> [[Int]]
        f ys (i, j, x) = [ [ if abs (i' - i) + abs (j' - j) < 2 && odd x then 1 - y else y
                              | (i', y) <- zip [0..] ys' ] | (j', ys') <- zip [0..] ys ]

main :: IO ()
main = getContents >>= mapM_ (putStrLn . concatMap show) . solve . map (map read . words) . lines

solve :: [[Int]] -> [[Int]]
solve xs = [ [ (1 + sum [ xs !! i' !! j' | j' <- [0..2], i' <- [0..2], abs (i - i') + abs (j - j') < 2 ]) `mod` 2 | j <- [0..2] ] | i <- [0..2] ]

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

q::[[Int]]
q=[[1,2,4],[1,2,3,5],[2,3,6],[1,4,7,5],[2,4,5,6,8],[3,5,6,9],[7,8,4],[8,7,9,5],[9,8,6]]

process::[Int]->Array Int Int->Int->[Int]
process [] a _ = elems a
process (x:xs) a n | even x = process xs a (n+1)
                   | otherwise = process xs (a//(map (\z->(z,1-a!z)) (q!!n))) (n+1)

chunks n [] = []
chunks n x = (take n x ): (chunks n (drop n x))

main= do
	x<- map read. words <$> getContents::IO [Int]
	let b= listArray (1,9) [1,1,1,1,1,1,1,1,1]
	putStrLn $ unlines $ map concat $  chunks 3 $ map show $ process x  b 0

import Data.List
import Data.List.Split

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

solve contents = let
  toggles = contents |> lines |> map words |> map (map read) :: [[Int]]
  states = toggleThem toggles
  in states |> chunksOf 3 |> unlines |> show

toggleThem toggles = [state toggles x y | x <- [0..2], y <- [0..2]]

state toggles x y = let
  count = toggleCount toggles x y
  in if even count then '1' else '0'

toggleCount toggles x y = toggleTimes toggles (x - 1) y
  + toggleTimes toggles x y
  + toggleTimes toggles (x + 1) y
  + toggleTimes toggles x (y - 1)
  + toggleTimes toggles x (y + 1)

toggleTimes toggles x y = if isValid x y then toggles !! x !! y else 0

isValid x y = x >= 0 && x < 3 && y >= 0 && y < 3

import Data.List
import Control.Monad
import qualified Data.Text as T

(f3, x, o, os )  = ((\a b c -> a . b . c), not, id, replicate 9 o)

to01 = map T.unpack . T.chunksOf 3 . T.pack .  map (\x -> if x then '1' else '0')

solve [a,b,c,d,e,f,g,h,i] =
    zipWith ($)
        (zipWith3 f3
            (zipWith3 f3 (if a==1 then [x,x,o,x,o,o,o,o,o] else os)
                         (if b==1 then [x,x,x,o,x,o,o,o,o] else os)
                         (if c==1 then [o,x,x,o,o,x,o,o,o] else os))
            (zipWith3 f3 (if d==1 then [x,o,o,x,x,o,x,o,o] else os)
                         (if e==1 then [o,x,o,x,x,x,o,x,o] else os)
                         (if f==1 then [o,o,x,o,x,x,o,o,x] else os))
            (zipWith3 f3 (if g==1 then [o,o,o,x,x,o,x,o,o] else os)
                         (if h==1 then [o,o,o,x,x,x,o,x,o] else os)
                         (if i==1 then [o,o,o,o,o,x,o,x,x] else os)))
        $ replicate 9 True

main = do
    a <- concat <$> replicateM 3 (map(read :: String -> Int) . words <$>  getLine)
    mapM_ putStrLn $ to01 $ solve $ map (`mod` 2) a

import Data.List
import Control.Monad
import qualified Data.Text as T
import Data.Maybe

(f3, x, o, os, zeroes )  = ((\a b c -> a . b . c), not, id, replicate 9 o, replicate 9 0)

to01 = map T.unpack . T.chunksOf 3 . T.pack .  map (\x -> if x then '1' else '0')

solve [a,b,c,d,e,f,g,h,i] js =
    zipWith ($)
        (zipWith3 f3
            (zipWith3 f3 (if a==1 then [x,x,o,x,o,o,o,o,o] else os)
                         (if b==1 then [x,x,x,o,x,o,o,o,o] else os)
                         (if c==1 then [o,x,x,o,o,x,o,o,o] else os))
            (zipWith3 f3 (if d==1 then [x,o,o,x,x,o,x,o,o] else os)
                         (if e==1 then [o,x,o,x,x,x,o,x,o] else os)
                         (if f==1 then [o,o,x,o,x,x,o,o,x] else os))
            (zipWith3 f3 (if g==1 then [o,o,o,x,x,o,x,o,o] else os)
                         (if h==1 then [o,o,o,x,x,x,o,x,o] else os)
                         (if i==1 then [o,o,o,o,o,x,o,x,x] else os)))
        js

main = do
    a <- concat <$> replicateM 3 (map(read :: String -> Int) . words <$>  getLine)
    mapM_ putStrLn $ to01 $ fst $ until ((==zeroes).snd) (\(x,y) -> let b = findIndex (/=0) y in if isNothing b then (x,y) else let z = take 9 $ replicate (fromJust b) 0 ++ [1] ++ repeat 0 in (solve z x, zipWith (-) y z)) (replicate 9 True, a)

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

q::[[Int]]
q=[[1,2,4],[1,2,3,5],[2,3,6],[1,4,7,5],[2,4,5,6,8],[3,5,6,9],[7,8,4],[8,7,9,5],[9,8,6]]

process::[Int]->Array Int Int->Int->[Int]
process [] a _ = elems a
process (x:xs) a n | even x = process xs a (n+1)
                   | otherwise = process xs (a//(map (\z->(z,1-a!z)) (q!!n))) (n+1)

chunks n [] = []
chunks n x = (take n x ): (chunks n (drop n x))

main= do
	x<- map read. words <$> getContents::IO [Int]
	let b= listArray (1,9) [1,1,1,1,1,1,1,1,1]
	putStrLn $ unlines $ map unwords $  chunks 3 $ map show $ process x  b 0


The only difference between easy and hard versions is the length of the string.You are given a string $$$s$$$ and a string $$$t$$$, both consisting only of lowercase Latin letters. It is guaranteed that $$$t$$$ can be obtained from $$$s$$$ by removing some (possibly, zero) number of characters (not necessary contiguous) from $$$s$$$ without changing order of remaining characters (in other words, it is guaranteed that $$$t$$$ is a subsequence of $$$s$$$).For example, the strings "test", "tst", "tt", "et" and "" are subsequences of the string "test". But the strings "tset", "se", "contest" are not subsequences of the string "test".You want to remove some substring (contiguous subsequence) from $$$s$$$ of maximum possible length such that after removing this substring $$$t$$$ will remain a subsequence of $$$s$$$.If you want to remove the substring $$$s[l;r]$$$ then the string $$$s$$$ will be transformed to $$$s_1 s_2 \dots s_{l-1} s_{r+1} s_{r+2} \dots s_{|s|-1} s_{|s|}$$$ (where $$$|s|$$$ is the length of $$$s$$$).Your task is to find the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.

The first line of the input contains one string $$$s$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. The second line of the input contains one string $$$t$$$ consisting of at least $$$1$$$ and at most $$$200$$$ lowercase Latin letters. It is guaranteed that $$$t$$$ is a subsequence of $$$s$$$.

Print one integer — the maximum possible length of the substring you can remove so that $$$t$$$ is still a subsequence of $$$s$$$.

main = interact ((++"\n") . show . solve . lines)

solve [s1, s2] =
      let an1 = 0 :(annotate s1 s2)
          an2 = reverse $ annotate (reverse s1) (reverse s2)
          an2' =  an2
      in find_opt an1 an2' (length s2)

annotate s t = (annotate' s t 0)

annotate' [] [] n = []
annotate' s  [] n = n : (annotate' (tail s) [] n)
annotate' (sx:sr) (tx:tr) n
  | sx == tx = (n + 1) : (annotate' sr tr (n + 1))
  | otherwise = n : (annotate' sr (tx:tr) n)

-- find_opt a1 a2 n = a2
find_opt a1 a2 n = find_opt' a1 a2 n 0

find_opt' (ax:_) [] n diff
  | ax >= n = diff
  | otherwise = diff - 1
find_opt' (a1x:a1r) (a2x:a2r) n diff
  | a1x + a2x >= n = max diff $ find_opt' (a1x:a1r) a2r n (diff + 1)
  | otherwise = find_opt' a1r (a2x:a2r) n (diff - 1)

import Control.Monad
import Data.List

readInt :: IO(Int)
readInt = fmap read getLine

readlist :: IO([Integer])
readlist = fmap (map read . words) getLine

loop :: Int -> IO() -> IO()
loop 0 f = do
    f; loop 0 f
loop 1 f = f
loop x f = do
    f; loop (x - 1) f

main = do
	s <- getLine
	t <- getLine
	print (solve s t)

solve :: String -> String -> Int
solve s t = (foldl1 max . zipWith (-) rv $ v) - 1
	where
		v  = (-1):(match (+) s t 0)
		rv = reverse v'
			where v' = (length s):(match (-) (reverse s) (reverse t) $ (length s - 1))

match :: (Int -> Int -> Int) -> String -> String -> Int -> [Int]
match _ _ [] _ = []
match f (x0:xs) y@(y0:ys) pos =
	if x0 == y0 then
		(pos:(match f xs ys (pos `f` 1)))
	else
		match f xs y (pos `f` 1)


In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients strictly less than k, whose remainder is p when divided by (x + k). That is, f(x) = q(x)·(x + k) + p, where q(x) is a polynomial (not necessarily with integer coefficients).

The only line of input contains two space-separated integers p and k (1 ≤ p ≤ 1018, 2 ≤ k ≤ 2 000).

If the polynomial does not exist, print a single integer -1, or output two lines otherwise. In the first line print a non-negative integer d — the number of coefficients in the polynomial. In the second line print d space-separated integers a0, a1, ..., ad - 1, describing a polynomial  fulfilling the given requirements. Your output should satisfy 0 ≤ ai < k for all 0 ≤ i ≤ d - 1, and ad - 1 ≠ 0. If there are many possible solutions, print any of them.

NoteIn the first example, f(x) = x6 + x5 + x4 + x = (x5 - x4 + 3x3 - 6x2 + 12x - 23)·(x + 2) + 46.In the second example, f(x) = x2 + 205x + 92 = (x - 9)·(x + 214) + 2018.

doit :: Integer -> Integer -> [Integer]
doit p k = map snd . takeWhile (/= (0, 0)) . iterate (f . fst) $ (p, 0)
  where f x = let ans = x `mod` k
              in ((x - ans) `div` (-k), ans)

main = do
  [p, k] <- fmap (fmap read . words) getLine
  let ans = drop 1 . doit p $ k
  print . length $ ans
  putStrLn . unwords . map show $ ans

doit :: Integer -> Integer -> [Integer]
doit 0 _ = []
doit p k = tmp : doit ((p - tmp) `div` (-k)) k
  where tmp = p `mod` k

main = do
  [p, k] <- fmap (fmap read . words) getLine
  let ans = doit p k
  print . length $ ans
  putStrLn . unwords . map show $ ans

doit :: [Integer] -> [Integer]
doit [0, _] = []
doit [p, k] = tmp : doit [(p - tmp) `div` (-k), k]
  where tmp = p `mod` k

main = fmap (fmap read . words) getLine >>= return . doit >>= putStrLn . unwords . map show


When Valera was playing football on a stadium, it suddenly began to rain. Valera hid in the corridor under the grandstand not to get wet. However, the desire to play was so great that he decided to train his hitting the ball right in this corridor. Valera went back far enough, put the ball and hit it. The ball bounced off the walls, the ceiling and the floor corridor and finally hit the exit door. As the ball was wet, it left a spot on the door. Now Valera wants to know the coordinates for this spot.Let's describe the event more formally. The ball will be considered a point in space. The door of the corridor will be considered a rectangle located on plane xOz, such that the lower left corner of the door is located at point (0, 0, 0), and the upper right corner is located at point (a, 0, b) . The corridor will be considered as a rectangular parallelepiped, infinite in the direction of increasing coordinates of y. In this corridor the floor will be considered as plane xOy, and the ceiling as plane, parallel to xOy and passing through point (a, 0, b). We will also assume that one of the walls is plane yOz, and the other wall is plane, parallel to yOz and passing through point (a, 0, b).We'll say that the ball hit the door when its coordinate y was equal to 0. Thus the coordinates of the spot are point (x0, 0, z0), where 0 ≤ x0 ≤ a, 0 ≤ z0 ≤ b. To hit the ball, Valera steps away from the door at distance m and puts the ball in the center of the corridor at point . After the hit the ball flies at speed (vx, vy, vz). This means that if the ball has coordinates (x, y, z), then after one second it will have coordinates (x + vx, y + vy, z + vz).See image in notes for clarification.When the ball collides with the ceiling, the floor or a wall of the corridor, it bounces off in accordance with the laws of reflection (the angle of incidence equals the angle of reflection). In the problem we consider the ideal physical model, so we can assume that there is no air resistance, friction force, or any loss of energy.

The first line contains three space-separated integers a, b, m (1 ≤ a, b, m ≤ 100). The first two integers specify point (a, 0, b), through which the ceiling and one of the corridor walls pass. The third integer is the distance at which Valera went away from the door. The second line has three space-separated integers vx, vy, vz (|vx|, |vy|, |vz| ≤ 100, vy < 0, vz ≥ 0) — the speed of the ball after the hit. It is guaranteed that the ball hits the door.

Print two real numbers x0, z0 — the x and z coordinates of point (x0, 0, z0), at which the ball hits the exit door. The answer will be considered correct, if its absolute or relative error does not exceed 10  - 6.

import Monad (liftM)
import Prelude hiding (print)

solve :: (Fractional a, Ord a) => [a] -> (a, a)
solve [a, b, m, vx, vy, vz]  =  solve' (a/2, m, 0) (vx, vy, vz)
  where
    solve' (x, y, z) (vx, vy, vz)
      | ty <= tx && ty <= tz  =  (x + ty * vx, z + ty * vz)
      | tx <  tz   =  solve' (x + tx * vx, y + tx * vy, z + tx * vz) (-vx, vy, vz)
      | tx >  tz   =  solve' (x + tz * vx, y + tz * vy, z + tz * vz) (vx, vy, -vz)
      | otherwise  =  solve' (x + tz * vx, y + tz * vy, z + tz * vz) (-vx, vy, -vz)
      where
        tx  =  if vx >= 0 then (a - x) / vx else -x / vx
        ty  =  -y / vy
        tz  =  if vz >= 0 then (b - z) / vz else -z / vz

print :: Show a => (a, a) -> IO ()
print (a, b)  =  putStrLn (show a ++ " " ++ show b)

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

import Control.Applicative

main = do
  [a,b,m] <- map read.words <$> getLine
  [vx,vy',vz] <- map read.words <$> getLine
  let vy = -vy'
      qx = (2*vx*m+a*vy)`div`(2*vy*a)
      qz = (vz*m)`div`(vy*b)
      x0 = if even qx
              then (fromIntegral $ -2*vy*qx*a+2*vx*m+a*vy)/(fromIntegral $ 2*vy)
              else (fromIntegral $ 2*vy*(qx+1)*a-2*vx*m-a*vy)/(fromIntegral $ 2*vy)
      z0 = if even qz
              then (fromIntegral $ vz*m-qz*b*vy)/(fromIntegral vy)
              else (fromIntegral $ -vz*m+(qz+1)*b*vy)/(fromIntegral vy)
  putStrLn $ unwords $ map show [x0,z0]

import Monad (liftM)
import Prelude hiding (print)

solve :: (Fractional a, Ord a) => [a] -> (a, a)
solve [a, b, m, vx, vy, vz]  =  solve' (a/2, m, 0) (vx, vy, vz)
  where
    solve' (x, y, z) (vx, vy, vz)
      | ty <= tx && ty <= tz  =  (x + ty * vx, z + ty * vz)
      | tx <= tz   =  solve' (0, y + tx * vy, z + tx * vz) (-vx, vy, vz)
      | otherwise  =  solve' (x + tz * vx, y + tz * vy, 0) (vx, vy, -vz)
      where
        tx  =  if vx > 0 then (a - x) / vx else x / vx
        ty  =  -y / vy
        tz  =  if vz > 0 then (b - z) / vz else z / vz

print :: Show a => (a, a) -> IO ()
print (a, b)  =  putStrLn (show a ++ " " ++ show b)

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


Consider the infinite sequence of integers: 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5.... The sequence is built in the following way: at first the number 1 is written out, then the numbers from 1 to 2, then the numbers from 1 to 3, then the numbers from 1 to 4 and so on. Note that the sequence contains numbers, not digits. For example number 10 first appears in the sequence in position 55 (the elements are numerated from one).Find the number on the n-th position of the sequence.

The only line contains integer n (1 ≤ n ≤ 1014) — the position of the number to find. Note that the given number is too large, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

Print the element in the n-th position of the sequence (the elements are numerated from one).

{-# OPTIONS_GHC -O2 #-}

import Data.Int (Int64)

main = do
  a <- readLn :: IO Int64

  let
    b = f a 1
      where
        f a d = if a <= d then a else f (a-d) (d+1)

  print b

main = do
       e<-getLine
       let m=read e::Integer
           n=read e::Double
           r=((-1.0)+sqrt(1+8*n))/2.0
           r2=floor r::Integer
           r3=ceiling r::Integer
           r4=if r3==r2 then (r2-1) else r2
           ans=m - (r4*(r4+1::Integer) `div` 2)
       print ans

main = interact (show . (solve 1) . read)
solve a b
    | b <= a    = b
    | otherwise = solve (a+1) (b-a)

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
import           Control.Applicative
import           Control.Monad
import           Data.List
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function
-- import           Data.ByteString (ByteString)
-- import qualified Data.ByteString.Char8 as C
-- import           Data.ByteString.Char8 ()
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as IntMap
-- import           Data.Sequence ((|>), (<|), (><),ViewR((:>)), ViewL((:<)))
-- import qualified Data.Sequence as S

myread = read :: String -> Integer
main = do
  n <- myread <$> getLine
  print $ solve n

solve :: Integer -> Integer
solve n = n - ((m*(m+1))`div`2) where
  m = ($!) floor ((sqrt (((fromIntegral n -1) * 8)+1) - 1) / 2)
-- solve n = (-) n . last . takeWhile (<n) $ [sum [1..n] | n <- [1..]]

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

main= do
	n<- read <$> getLine::IO Integer
	let x = floor  $ sqrt $ fromIntegral $ n*2
	let y= (div (x*(x+1)) 2)
	let x1 = if (n>y) then   n-y else   n- (div ((x)*(x-1)) 2)
	let x2 = if x1 ==0 then  x else   x1
	print x2

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

sol :: [Integer] -> Integer
sol [n] = f n 1
    where
    f num p
        | num > p = f (num-p) (p+1)
        | otherwise = num


This morning, Roman woke up and opened the browser with $$$n$$$ opened tabs numbered from $$$1$$$ to $$$n$$$. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.He decided to accomplish this by closing every $$$k$$$-th ($$$2 \leq k \leq n - 1$$$) tab. Only then he will decide whether he wants to study for the test or to chat on the social networks. Formally, Roman will choose one tab (let its number be $$$b$$$) and then close all tabs with numbers $$$c = b + i \cdot k$$$ that satisfy the following condition: $$$1 \leq c \leq n$$$ and $$$i$$$ is an integer (it may be positive, negative or zero).For example, if $$$k = 3$$$, $$$n = 14$$$ and Roman chooses $$$b = 8$$$, then he will close tabs with numbers $$$2$$$, $$$5$$$, $$$8$$$, $$$11$$$ and $$$14$$$.After closing the tabs Roman will calculate the amount of remaining tabs with the information for the test (let's denote it $$$e$$$) and the amount of remaining social network tabs ($$$s$$$). Help Roman to calculate the maximal absolute value of the difference of those values $$$|e - s|$$$ so that it would be easy to decide what to do next.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \leq k < n \leq 100$$$) — the amount of tabs opened currently and the distance between the tabs closed. The second line consists of $$$n$$$ integers, each of them equal either to $$$1$$$ or to $$$-1$$$. The $$$i$$$-th integer denotes the type of the $$$i$$$-th tab: if it is equal to $$$1$$$, this tab contains information for the test, and if it is equal to $$$-1$$$, it's a social network tab.

Output a single integer — the maximum absolute difference between the amounts of remaining tabs of different types $$$|e - s|$$$.

NoteIn the first example we can choose $$$b = 1$$$ or $$$b = 3$$$. We will delete then one tab of each type and the remaining tabs are then all contain test information. Thus, $$$e = 2$$$ and $$$s = 0$$$ and $$$|e - s| = 2$$$.In the second example, on the contrary, we can leave opened only tabs that have social networks opened in them.

import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Data.List
import Control.Arrow

int = fst . fromJust . B.readInt
ints = map int . B.words <$> B.getLine
g = (arr length *** arr length) .  partition (<0) .filter (/=0)
sub (a,b) (c,d) = (a-c, b-d)

main = do
    [n,k] <- ints
    bs <- ints
    let gbs = g bs
    print $ maximum $ map (\x -> abs $ uncurry (-) $ sub gbs $ g $ zipWith (*) bs $ take n $ drop x $ cycle $ replicate (k-1) 0 ++ [1]) [0..k-1]

import Data.List

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

-- find maximum |e - s| in groups
solve (k:xs) = maximum $ map (\(e,s) -> abs $ e0 - e - s0 + s) xss
    where xss = map tab $ transpose $ groupK k xs
          (e0,s0) = tab xs

groupK k [] = []
groupK k xs = (\(l,rs) -> l : groupK k rs) $ splitAt k xs

-- (# of tab 1, # of tab -1)
tab xs = let (n,s) = (length xs, sum xs) in ((n + s) `div` 2, (n - s) `div` 2)

-- Codeforces Round #532 (A), Contest 1100, Problem set ?.
-- UNDONE

{-# 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
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function

main :: IO ()
main = do
  [n,k] <- map read . words <$> getLine :: IO [Int]
  ts <- unfoldr (BS.readInt . BS.dropWhile (<'!')) <$> BS.getLine
  let s = sum ts
  print $ maximum $ map abs $ map (s-) $ A.elems
    (A.accumArray (+) 0 (0,k-1) $ zip (cycle [0..k-1]) ts :: UArray Int Int)

import Text.Printf
import Data.List
import Data.Functor
import Control.Applicative
import Prelude
import Control.Monad
import Data.Maybe
import Data.Function
import Data.Array
import qualified Data.ByteString.Char8 as B8
import Data.Foldable (foldr')
import Data.Bits

readInt :: String -> Int
readInt = Prelude.read

readB8Int :: B8.ByteString -> Int
readB8Int = fst . fromJust . B8.readInt

main :: IO ()
main = do
    [n, k] <- (map readInt . words) <$> getLine
    arr <- (map readInt . words) <$> getLine
    let len = length arr
        sm = sum arr
        ss = map (\b -> abs (sm - (sum . map (arr !!) . map (\x -> x - 1) . takeWhile (<= len) . map (\ i -> i * k + b) $ [0 .. ]))) $ [1 .. k]
    printf "%d\n" $ maximum ss


You are given an integer sequence $$$1, 2, \dots, n$$$. You have to divide it into two sets $$$A$$$ and $$$B$$$ in such a way that each element belongs to exactly one set and $$$|sum(A) - sum(B)|$$$ is minimum possible.The value $$$|x|$$$ is the absolute value of $$$x$$$ and $$$sum(S)$$$ is the sum of elements of the set $$$S$$$.

The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^9$$$).

Print one integer — the minimum possible value of $$$|sum(A) - sum(B)|$$$ if you divide the initial sequence $$$1, 2, \dots, n$$$ into two sets $$$A$$$ and $$$B$$$.

NoteSome (not all) possible answers to examples:In the first example you can divide the initial sequence into sets $$$A = \{1, 2\}$$$ and $$$B = \{3\}$$$ so the answer is $$$0$$$.In the second example you can divide the initial sequence into sets $$$A = \{1, 3, 4\}$$$ and $$$B = \{2, 5\}$$$ so the answer is $$$1$$$.In the third example you can divide the initial sequence into sets $$$A = \{1, 4, 5\}$$$ and $$$B = \{2, 3, 6\}$$$ so the answer is $$$1$$$.

-- Haskell Template
solve :: Int -> Int
solve n
  | r == 0 || r == 3 = 0
  | otherwise = 1
  where
  	r = mod n 4

main :: IO ()
main = do
  x <- getLine
  let s = solve (read x)
  putStrLn (show s)

main = readLn >>= print . (`mod` 2) . (`div` 2) . (+1)

-- Codeforces Round #531 (A), Contest 1102, Problem set ?.

{-# 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
import Data.Word

main :: IO ()
main = do
  n <- read <$> getLine :: IO Int
  print $ if mod n 4 `elem` [0,3] then 0 else 1

main = do
    line <- getLine
    let n = read line :: Int
    let m = case n `mod` 4 of 0 -> 0
                              1 -> 1
                              2 -> 1
                              3 -> 0
    print m

main = interact $ show . solve . read
solve n = n * (n+1) `div` 2 `mod` 2

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

main = do
		r<- read <$> getLine ::IO Int
		print $ if odd (div (r *(r+1)) 2) then 1 else 0

main :: IO ()
main = do
  l <- readLn :: IO Int
  putStrLn $ show $ solve l

solve :: Int -> Int
solve 0 = 0
solve 1 = 1
solve 2 = 1
solve 3 = 0
solve n = solve $ n `mod` 4


Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:  on Mondays, Thursdays and Sundays he eats fish food;  on Tuesdays and Saturdays he eats rabbit stew;  on other days of week he eats chicken stake. Polycarp plans to go on a trip and already packed his backpack. His backpack contains:  $$$a$$$ daily rations of fish food;  $$$b$$$ daily rations of rabbit stew;  $$$c$$$ daily rations of chicken stakes. Polycarp has to choose such day of the week to start his trip that his cat can eat without additional food purchases as long as possible. Print the maximum number of days the cat can eat in a trip without additional food purchases, if Polycarp chooses the day of the week to start his trip optimally.

The first line of the input contains three positive integers $$$a$$$, $$$b$$$ and $$$c$$$ ($$$1 \le a, b, c \le 7\cdot10^8$$$) — the number of daily rations of fish food, rabbit stew and chicken stakes in Polycarps backpack correspondingly.

NoteIn the first example the best day for start of the trip is Sunday. In this case, during Sunday and Monday the cat will eat fish food, during Tuesday — rabbit stew and during Wednesday — chicken stake. So, after four days of the trip all food will be eaten.In the second example Polycarp can start his trip in any day of the week. In any case there are food supplies only for one week in Polycarps backpack.In the third example Polycarp can start his trip in any day, excluding Wednesday, Saturday and Sunday. In this case, the cat will eat three different dishes in three days. Nevertheless that after three days of a trip there will be $$$99$$$ portions of rabbit stew in a backpack, can cannot eat anything in fourth day of a trip.

dine a b c week = case (head week) of
  'a' -> if a == 0 then 0 else 1 + (dine (a - 1) b c (tail week))
  'b' -> if b == 0 then 0 else 1 + (dine a (b - 1) c (tail week))
  'c' -> if c == 0 then 0 else 1 + (dine a b (c - 1) (tail week))
process _ _ _ 0 _ = 0
process a b c n week = max (dine a b c week) rec
  where
    rec = process a b c (n - 1) (tail week)
analyze (a:b:c:_) = 7 * n + (process (a - n * 3) (b - n * 2) (c - n * 2) 7 week)
  where
    n = minimum [div a 3, div b 2, div c 2]
    week = cycle ['a', 'b', 'c', 'a', 'c', 'b', 'a']
ans = show . analyze . (map read) . words
main = getLine >>= putStrLn . ans

main :: IO ()
main = do
    inp <- getLine
    let l = map read $ words inp
        a = l!!0
        b = l!!1
        c = l!!2
    putStrLn $ show $ maximum (map (h a b c) [0..6])
    return ()

h :: Int -> Int -> Int -> Int -> Int
h a b c d = dayz $ Just (d,(a,b,c))
dayz :: (Maybe (Int, (Int, Int, Int))) -> Int
dayz Nothing = (-1)
dayz (Just (d,(a,b,c)))
    |a>21000 && b>14000 && c>14000 = 49000+ (dayz $ Just(d,(a-21000,b-14000,c-14000)))
    |otherwise = 1 + (dayz (step (d,(a,b,c))))

step :: (Int,(Int,Int,Int))-> Maybe (Int,(Int,Int,Int))
step (d,(a,b,c))
    |d `elem` [0,3,6] =ok ((d+1) `mod` 7,(a-1,b,c))
    |d `elem` [1,5]   =ok (d+1,(a,b-1,c))
    |otherwise        =ok ((d+1) `mod` 7,(a,b,c-1))
    where ok (a,(b,c,d)) = if -1 `elem` [b,c,d] then Nothing else Just (a,(b,c,d))

{-# LANGUAGE LambdaCase #-}
-- import Control.Arrow
import Data.List
import Data.Ord
import Data.Monoid

main = do
    abc <- map (read :: String -> Int) . words <$> getLine
    let d = take 14 $ cycle "abcacba"
        p s t =  (\case
                    x@[('a':_),('b':_),('c':_)] -> map length x
                    [as@('a':_),bs@('b':_)] -> [length as, length bs, 0]
                    [as@('a':_),cs@('c':_)] -> [length as, 0, length cs]
                    [bs@('b':_),cs@('c':_)] -> [0, length bs, length cs]
                    [as@('a':_)] -> [length as, 0, 0]
                    [bs@('b':_)] -> [0,length bs, 0]
                    [cs@('c':_)] -> [0, 0, length cs]
                ) . group . sort . take t . drop s
        ps = [(t,p s t d) | s <- [0..6], t <- [1..7]]
        zs'@[(ad,ar),(bd,br),(cd,cr)] = zipWith divMod abc [3,2,2]
        wk = minimum $ map fst zs'
        zs = zipWith min [3,2,2] $ zipWith (-) abc $ map (wk*) [3,2,2]
        ys = if zs == [0,0,0]
            then [(7*wk, zs)]
            else filter (all (>=0) . snd) $ map (\x -> (7*wk + fst x, zipWith (-) zs $ snd x)) ps
    print $ fst $ head $  sortBy ((comparing (sum .snd)) `mappend` (flip $ comparing fst)) ys

main :: IO ()
main = do
    inp <- getLine
    let l = map read $ words inp
        a = l!!0
        b = l!!1
        c = l!!2
    putStrLn $ show $ maximum (map (h a b c) [0..7])
    return ()

h :: Int -> Int -> Int -> Int -> Int
h a b c d = dayz $ Just (d,(a,b,c))
--days :: {-Maybe (Int, (Int, Int, Int))-} Maybe a -> Int
dayz Nothing = (-1)
dayz (Just x) = 1 + (dayz (step x))

step :: (Int,(Int,Int,Int))-> Maybe (Int,(Int,Int,Int))
step (d,(a,b,c))
    |d `elem` [0,3,6] =ok (d+1,(a-1,b,c))
    |d `elem` [1,5]   =ok (d+1,(a,b-1,c))
    |otherwise        =ok ((d+1) `mod` 7,(a,b,c-1))
    where ok (a,(b,c,d)) = if -1 `elem` [b,c,d] then Nothing else Just (a,(b,c,d))

main :: IO ()
main = do
    inp <- getLine
    let l = map read $ words inp
        a = l!!0
        b = l!!1
        c = l!!2
    putStrLn $ show $ maximum (map (h a b c) [0..7])
    return ()

h :: Int -> Int -> Int -> Int -> Int
h a b c d = dayz $ Just (d,(a,b,c))
dayz :: (Maybe (Int, (Int, Int, Int))) -> Int
dayz Nothing = (-1)
dayz (Just (d,(a,b,c)))
    |a>21000 && b>14000 && c>14000 = 49000+ (dayz $ Just(d,(a-21000,b-14000,c-14000)))
    |otherwise = 1 + (dayz (step (d,(a,b,c))))

step :: (Int,(Int,Int,Int))-> Maybe (Int,(Int,Int,Int))
step (d,(a,b,c))
    |d `elem` [0,3,6] =ok ((d+1) `mod` 7,(a-1,b,c))
    |d `elem` [1,5]   =ok (d+1,(a,b-1,c))
    |otherwise        =ok ((d+1) `mod` 7,(a,b,c-1))
    where ok (a,(b,c,d)) = if -1 `elem` [b,c,d] then Nothing else Just (a,(b,c,d))

main :: IO ()
main = do
    inp <- getLine
    let l = map read $ words inp
        a = l!!0
        b = l!!1
        c = l!!2
    putStrLn $ show $ {-maximum-} (map (h a b c) [0..7])
    return ()

h :: Int -> Int -> Int -> Int -> Int
h a b c d = dayz $ Just (d,(a,b,c))
--days :: {-Maybe (Int, (Int, Int, Int))-} Maybe a -> Int
dayz Nothing = (-1)
dayz (Just x) = 1 + (dayz (step x))

step :: (Int,(Int,Int,Int))-> Maybe (Int,(Int,Int,Int))
step (d,(a,b,c))
    |d `elem` [0,3,6] =ok (d+1,(a-1,b,c))
    |d `elem` [1,5]   =ok (d+1,(a,b-1,c))
    |otherwise        =ok ((d+1) `mod` 7,(a,b,c-1))
    where ok (a,(b,c,d)) = if -1 `elem` [b,c,d] then Nothing else Just (a,(b,c,d))

main :: IO ()
main = do
    inp <- getLine
    let l = map read $ words inp
        a = l!!0
        b = l!!1
        c = l!!2
    putStrLn $ show $ {-maximum-} (map (h a b c) [0..7])
    return ()

h :: Int -> Int -> Int -> Int -> Int
h a b c d = dayz $ Just (d,(a,b,c))
--days :: {-Maybe (Int, (Int, Int, Int))-} Maybe a -> Int
dayz Nothing = 0
dayz (Just x) = 1 + (dayz (step x))

step :: (Int,(Int,Int,Int))-> Maybe (Int,(Int,Int,Int))
step (d,(a,b,c))
    |d `elem` [0,3,6] =ok (d+1,(a-1,b,c))
    |d `elem` [1,5]   =ok (d+1,(a,b-1,c))
    |otherwise        =ok ((d+1) `mod` 7,(a,b,c-1))
    where ok (a,(b,c,d)) = if 0 `elem` [b,c,d] then Nothing else Just (a,(b,c,d))

main :: IO ()
main = do
    inp <- getLine
    let l = map read $ words inp
        a = l!!0
        b = l!!1
        c = l!!2
    putStrLn $ show $ maximum (map (h a b c) [0..7])
    return ()

h :: Int -> Int -> Int -> Int -> Int
h a b c d = dayz $ Just (d,(a,b,c))
--days :: {-Maybe (Int, (Int, Int, Int))-} Maybe a -> Int
dayz Nothing = 0
dayz (Just x) = 1 + (dayz (step x))

step :: (Int,(Int,Int,Int))-> Maybe (Int,(Int,Int,Int))
step (d,(a,b,c))
    |d `elem` [0,3,6] =ok (d+1,(a-1,b,c))
    |d `elem` [1,5]   =ok (d+1,(a,b-1,c))
    |otherwise        =ok ((d+1) `mod` 7,(a,b,c-1))
    where ok (a,(b,c,d)) = if 0 `elem` [b,c,d] then Nothing else Just (a,(b,c,d))

{-# LANGUAGE LambdaCase #-}
-- import Control.Arrow
import Data.List
import Data.Ord
import Data.Monoid

main = do
    abc <- map (read :: String -> Int) . words <$> getLine
    let d = take 14 $ cycle "abcacba"
        p s t =  (\case
                    x@[('a':_),('b':_),('c':_)] -> map length x
                    [as@('a':_),bs@('b':_)] -> [length as, length bs, 0]
                    [as@('a':_),cs@('c':_)] -> [length as, 0, length cs]
                    [bs@('b':_),cs@('c':_)] -> [0, length bs, length cs]
                    [as@('a':_)] -> [length as, 0, 0]
                    [bs@('b':_)] -> [0,length bs, 0]
                    [cs@('c':_)] -> [0, 0, length cs]
                ) . group . sort . take t . drop s
        ps = [(t,p s t d) | s <- [0..6], t <- [1..7]]
        zs'@[(ad,ar),(bd,br),(cd,cr)] = zipWith divMod abc [3,2,2]
        wk = minimum $ map fst zs'
        zs = zipWith (-) abc $ map (wk*) [3,2,2]
        ys = if zs == [0,0,0]
            then [(7*wk, zs)]
            else map (\x -> (7*wk + fst x, zipWith (\x y -> if x < y then x else x -y) zs $ snd x)) ps
    print $ fst $ head $  sortBy ((flip $ comparing (length . filter (==0) .snd)) `mappend` (flip $ comparing fst)) ys

{-# LANGUAGE LambdaCase #-}
-- import Control.Arrow
import Data.List
import Data.Ord
import Data.Monoid

main = do
    abc <- map (read :: String -> Int) . words <$> getLine
    let d = take 14 $ cycle "abcacba"
        p s t =  (\case
                    x@[('a':_),('b':_),('c':_)] -> map length x
                    [as@('a':_),bs@('b':_)] -> [length as, length bs, 0]
                    [as@('a':_),cs@('c':_)] -> [length as, 0, length cs]
                    [bs@('b':_),cs@('c':_)] -> [0, length bs, length cs]
                    [as@('a':_)] -> [length as, 0, 0]
                    [bs@('b':_)] -> [0,length bs, 0]
                    [cs@('c':_)] -> [0, 0, length cs]
                ) . group . sort . take t . drop s
        ps = [(t,p s t d) | s <- [0..6], t <- [1..7]]
        zs'@[(ad,ar),(bd,br),(cd,cr)] = zipWith divMod abc [3,2,2]
        wk = minimum $ map fst zs'
        zs = zipWith (-) abc $ map (wk*) [3,2,2]
        ys = if zs == [0,0,0]
            then [(7*wk, zs)]
            else map (\x -> (7*wk + fst x, map abs $ zipWith (-) zs $ snd x)) ps
    print $ fst $ head $  sortBy ((flip $ comparing (length . filter (==0) .snd)) `mappend` (flip $ comparing fst)) ys

{-# LANGUAGE LambdaCase #-}
-- import Control.Arrow
import Data.List
import Data.Ord
import Data.Monoid

main = do
   abc <- map (read :: String -> Int) . words <$> getLine
   let  d = take 14 $ cycle "abcacba"
        p s t =  (\case
                    x@[('a':_),('b':_),('c':_)] -> map length x
                    [as@('a':_),bs@('b':_)] -> [length as, length bs, 0]
                    [as@('a':_),cs@('c':_)] -> [length as, 0, length cs]
                    [bs@('b':_),cs@('c':_)] -> [0, length bs, length cs]
                    [as@('a':_)] -> [length as, 0, 0]
                    [bs@('b':_)] -> [0,length bs, 0]
                    [cs@('c':_)] -> [0, 0, length cs]
                ) . group . sort . take t . drop s
        ps = [(t,p s t d) | s <- [0..6], t <- [1..7]]
        zs'@[(ad,ar),(bd,br),(cd,cr)] = zipWith divMod abc [3,2,2]
        wk = minimum $ map fst zs'
        zs = zipWith (-) abc $ map (wk*) [3,2,2]
        ys = map (\x -> (7*wk + fst x, map  abs $ zipWith (-) zs $ snd x)) ps
   print $ fst $ head $ sortBy ((flip $ comparing (length . filter (==0) .snd)) `mappend` (flip $ comparing fst)) ys

{-# LANGUAGE LambdaCase #-}
-- import Control.Arrow
import Data.List
import Data.Ord
import Data.Monoid

main = do
    abc <- map (read :: String -> Int) . words <$> getLine
    let d = take 14 $ cycle "abcacba"
        p s t =  (\case
                    x@[('a':_),('b':_),('c':_)] -> map length x
                    [as@('a':_),bs@('b':_)] -> [length as, length bs, 0]
                    [as@('a':_),cs@('c':_)] -> [length as, 0, length cs]
                    [bs@('b':_),cs@('c':_)] -> [0, length bs, length cs]
                    [as@('a':_)] -> [length as, 0, 0]
                    [bs@('b':_)] -> [0,length bs, 0]
                    [cs@('c':_)] -> [0, 0, length cs]
                ) . group . sort . take t . drop s
        ps = [(t,p s t d) | s <- [0..6], t <- [1..7]]
        zs'@[(ad,ar),(bd,br),(cd,cr)] = zipWith divMod abc [3,2,2]
        wk = minimum $ map fst zs'
        zs = zipWith (-) abc $ map (wk*) [3,2,2]
        ys = if zs == [0,0,0]
            then [(7*wk, zs)]
            else map (\x -> (7*wk + fst x, zipWith (\x y -> if x < y then x else x -y) zs $ snd x)) ps
    print zs
    print $ fst $ head $  sortBy ((flip $ comparing (length . filter (==0) .snd)) `mappend` (flip $ comparing fst)) ys


One day the Codeforces round author sat exams. He had n exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2. The author would need to spend too much time and effort to make the sum of his marks strictly more than k. That could have spoilt the Codeforces round. On the other hand, if the sum of his marks is strictly less than k, the author's mum won't be pleased at all. The Codeforces authors are very smart and they always get the mark they choose themselves. Also, the Codeforces authors just hate re-sitting exams. Help the author and find the minimum number of exams he will have to re-sit if he passes the exams in the way that makes the sum of marks for all n exams equal exactly k.

The single input line contains space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 250) — the number of exams and the required sum of marks. It is guaranteed that there exists a way to pass n exams in the way that makes the sum of marks equal exactly k.

Print the single number — the minimum number of exams that the author will get a 2 for, considering that the sum of marks for all exams must equal k.

NoteIn the first sample the author has to get a 2 for all his exams.In the second sample he should get a 3 for two exams and a 2 for two more.In the third sample he should get a 3 for one exam.

import Data.Char

solve [a,b]
      | b `div` a >= 3 = 0
      | otherwise = a - (b `mod` a)

main = interact $ show . solve . map (read::String->Int) . words

main = getLine >>= putStrLn . func . map read . words
func :: [Int] -> String
func [x,y] = show $ max 0 (3*x - y)

main=interact$show.(\[n,k] -> max (3*n-k) 0).map read.words

s[n,k]=max (3*n-k) 0
main=interact$show.s.map read.words

import Control.Monad (liftM)
import Prelude hiding (reads)

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

solve :: [Int] -> Int
solve [n, k]  =  max 0 (3*n - k)

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

solve :: Int -> Int -> Int
solve n k  =  minimum
  [n - n3 - n4 - n5 |
    n3 <- [0..n], n4 <- [0..n - n3], n5 <- [0..n - n3 - n4],
    n3 + n4 + n5 <= n, 2 * (n - n3 - n4 - n5) + 3 * n3 + 4 * n4 + 5 * n5 == k]

main :: IO ()
main  =  do
    [n, k]  <-  getLine >>= return . map read . words
    print $ solve n k

main = do
  (n:k:_) <- (map read . words) `fmap` getLine
  let rest = k - 2 * n
  print $ max (n - rest) 0

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

solve :: [Int] -> Int
solve [n,k] = max 0 $ 3*n-k

main = getLine >>= print. (\[n, k] -> max 0 (3*n - k)). map read. words

solve n k = n - min (k - 2*n) n
main = do
    line <- getLine
    let [n, k] = map read $ words line :: [Int]
    print $ solve n k


Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).Print -1 if she can't give him k candies during n given days.

The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000). The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).

If it is impossible for Arya to give Bran k candies within n days, print -1. Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.

NoteIn the first sample, Arya can give Bran 3 candies in 2 days.In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.

{-# 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.Trans.State.Lazy
import Control.Monad

main =  mapM_ print . evalState app . B.words =<< B.getContents

app = do
  n <- poi
  k <- poi
  xs <- replicateM n poi
  return [solve n k xs]
  where
    pop = state $ \(x:xs) -> (x, xs)
    poi = fmap int pop
    int = maybe undefined fst . B.readInt

solve n k xs = (\r -> if r > n then -1 else r) $ length $ takeWhile ((< k) . fst) $ scanl (\(t, l) x -> let x' = x + l in (t + min x' 8, max 0 (x' - 8))) (0, 0) xs

f [x] n k s day
	|s+(min 8 x)>=k = day
	|otherwise = (-1)
f (x:y:xs) n k s day
	|s+(min 8 x)>=k = day
	|otherwise = f new_xs n k (s + (min x 8)) (day+1)
	where
		new_xs=(y+x-(min x 8)):xs

main=do
	a<-fmap words (getLine)
	b<-fmap words (getLine)
	let [n,k] = map (\x->read x::Int) a
	let aa = map (\x->read x::Int) b
	print (f aa n k 0 1)

arya _ k _ p | k <= 0 = p
arya _ _ [] p = -1
arya n k [a] p = if k > 8 then -1 else if k > a then -1 else p+1
arya n k (a:b:as) p = arya n (if a > 8 then k - 8 else k - a) (if a > 8 then (a-8+b:as) else  (b:as)) (p+1)

main = do
 [n,k] <- getLine >>= return . map (\x -> read x :: Int) . words
 as <- getLine >>= return . map (\x -> read x :: Int) . words
 print $ arya n k as 0

main = interact $ show . solve . map read . words
solve (n0:k0:as) = go n0 k0 0 as where
  go n k _ _ | k <= 0 = n0 - n
  go 0 _ _ _ = -1
  go _ _ _ [] = -1
  go n k c (a:as) = go (n-1) (k - g) (c' - g) as where
    c' = c + a
    g = min 8 c'

doit :: (Int, Int) -> Int -> (Int, Int)
doit (rem, me) new =
  let menew = me + new
      give = 8 `min` menew
      in (rem - give, menew - give)

main = do
  [n, k] <- fmap (map read . words) getLine
  a <- fmap (map read . words) getLine
  let x = length . takeWhile ((> 0) . fst) . scanl doit (k, 0) $ a
  print $ if x == n + 1 then -1 else x

f [x] n k s day
	|s+(min 8 x)>=k = day
	|otherwise = (-1)
f (x:y:xs) n k s day
	|s>=k = day
	|otherwise = f new_xs n k (s + (min x 8)) (day+1)
	where
		new_xs=(y+x-(min x 8)):xs

main=do
	a<-fmap words (getLine)
	b<-fmap words (getLine)
	let [n,k] = map (\x->read x::Int) a
	let aa = map (\x->read x::Int) b
	print (f aa n k 0 1)

f [] n k s
	|s>=k = n
	|otherwise = (-1)
f (x:xs) n k s
	|s>=k = n
	|otherwise = f xs n k (s + (min x 8))

main=do
	a<-fmap words (getLine)
	b<-fmap words (getLine)
	let [n,k] = map (\x->read x::Int) a
	let aa = map (\x->read x::Int) b
	print (f aa n k 0)

f [] n k s day
	|s>=k = day
	|otherwise = (-1)
f (x:xs) n k s day
	|s>=k = day
	|otherwise = f xs n k (s + (min x 8)) (day+1)

main=do
	a<-fmap words (getLine)
	b<-fmap words (getLine)
	let [n,k] = map (\x->read x::Int) a
	let aa = map (\x->read x::Int) b
	print (f aa n k 0 0)

arya _ k _ p | k <= 0 = p
arya _ _ [] p = -1
arya n k [a] p = -1
arya n k (a:b:as) p = arya n (if a > 8 then k - 8 else k - a) (if a > 8 then (a-8+b:as) else  (b:as)) (p+1)

main = do
 [n,k] <- getLine >>= return . map (\x -> read x :: Int) . words
 as <- getLine >>= return . map (\x -> read x :: Int) . words
 print $ arya n k as 0

arya _ _ [] p = if p == 0 then -1 else p
arya n k [a] p = if k > 8 then -1 else p+1
arya n k (a:b:as) p = arya n (if a > 8 then k - 8 else k - a) (if a > 8 then (a-8+b:as) else  (b:as)) (p+1)

main = do
 [n,k] <- getLine >>= return . map (\x -> read x :: Int) . words
 as <- getLine >>= return . map (\x -> read x :: Int) . words
 print $ arya n k as 0

arya _ k _ p | k <= 0 = p
arya _ _ [] p = -1
arya n k [a] p = if k > 8 then -1 else p+1
arya n k (a:b:as) p = arya n (if a > 8 then k - 8 else k - a) (if a > 8 then (a-8+b:as) else  (b:as)) (p+1)

main = do
 [n,k] <- getLine >>= return . map (\x -> read x :: Int) . words
 as <- getLine >>= return . map (\x -> read x :: Int) . words
 print $ arya n k as 0


Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption.Spinners in Sweetland have the form of V-shaped pieces of caramel. Each spinner can, well, spin around an invisible magic axis. At a specific point in time, a spinner can take 4 positions shown below (each one rotated 90 degrees relative to the previous, with the fourth one followed by the first one):  After the spinner was spun, it starts its rotation, which is described by a following algorithm: the spinner maintains its position for a second then majestically switches to the next position in clockwise or counter-clockwise order, depending on the direction the spinner was spun in.Slastyona managed to have spinner rotating for exactly n seconds. Being fascinated by elegance of the process, she completely forgot the direction the spinner was spun in! Lucky for her, she managed to recall the starting position, and wants to deduct the direction given the information she knows. Help her do this.

There are two characters in the first string – the starting and the ending position of a spinner. The position is encoded with one of the following characters: v (ASCII code 118, lowercase v), < (ASCII code 60), ^ (ASCII code 94) or > (ASCII code 62) (see the picture above for reference). Characters are separated by a single space. In the second strings, a single number n is given (0 ≤ n ≤ 109) – the duration of the rotation. It is guaranteed that the ending position of a spinner is a result of a n second spin in any of the directions, assuming the given starting position.

Output cw, if the direction is clockwise, ccw – if counter-clockwise, and undefined otherwise.

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

main = do
  [b, _, e] <- getLine
  n <- fmap readInt B.getLine
  putStr $ solve b e n

solve b e n
  | not $ x `xor` y = "undefined"
  | x = "cw"
  | y = "ccw"
  where
    x = cs!!(n' + fromJust (elemIndex b cs)) == e
    y = as!!(n' + fromJust (elemIndex b as)) == e
    cs = "v<^>v<^>"
    as = "v>^<v>^<"
    n' = n `mod` 4

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

-- Try Codeforces
-- author: Leonardone @ NEETSDKASU

main = putStrLn . solve . words =<< getContents

solve [_  , _  ,"0"] = "undefined"
solve [s:_, e:_, n ] = ans where
    m = (read n - 1) `mod` 4
    cw  = (!! m) . tail $ dropWhile (/= s) "^>v<^>v<^>v<^>v<"
    ccw = (!! m) . tail $ dropWhile (/= s) "^<v>^<v>^<v>^<v>"
    ans = case (cw == e, ccw == e) of
        (True, False) -> "cw"
        (False, True) -> "ccw"
        otherwise     -> "undefined"

convert '^'=1
convert '>'=2
convert 'v'=3
convert '<'=4
update s f
	|f>=s = (s,f)
	|otherwise=(s,f+4)
func s f time
	|abs (ss - ff )==0 = "undefined"
	|abs (ss - ff )==2 = "undefined"
	|ff-ss==1 && t==1 = "cw"
	|ff-ss==1 && t==3 = "ccw"
	|ff-ss==3 && t==1 = "ccw"
	|ff-ss==3 && t==3 = "cw"
	|otherwise = "undefined"
	where
		t=mod time 4
		(ss,ff)=update (convert s) (convert f)

main=do
	[s,f]<-fmap words getLine
	time<-fmap (\x->read x::Integer) getLine
	putStrLn (func (head s) (head f) time)

convert '^'=1
convert '>'=2
convert 'v'=3
convert '<'=4
func s f time
	|t==0 = "undefined"
	|abs(ff-ss)==2 = "undefined"
	|ff>ss = "cw"
	|ff<ss = "ccw"
	|ff==ss="undefined"
	where
		t=mod time 4
		ff=convert f
		ss=convert s

main=do
	[s,f]<-fmap words getLine
	time<-fmap (\x->read x::Integer) getLine
	putStrLn (func (head s) (head f) time)

convert '^'=1
convert '>'=2
convert 'v'=3
convert '<'=4
updateT 0 = 4
updateT t = t
func s f time
	|t==0 = "undefined"
	|abs(ff-ss)==2 = "undefined"
	|ff>ss = "cw"
	|ff<ss = "ccw"
	|ff==ss="undefined"
	where
		t=updateT (mod time 4)
		ff=convert f
		ss=convert s

main=do
	[s,f]<-fmap words getLine
	time<-fmap (\x->read x::Integer) getLine
	putStrLn (func (head s) (head f) time)

convert '^'=1
convert '>'=2
convert 'v'=3
convert '<'=4
update s f
	|f>=s = (s,f)
	|otherwise=(s,f+4)
func s f time
	|abs (ss - ff )==0 = "undfined"
	|abs (ss - ff )==2 = "undfined"
	|ff-ss==1 && t==1 = "cw"
	|ff-ss==1 && t==3 = "ccw"
	|ff-ss==3 && t==1 = "ccw"
	|ff-ss==3 && t==3 = "cw"
	|otherwise = "undefined"
	where
		t=mod time 4
		(ss,ff)=update (convert s) (convert f)

main=do
	[s,f]<-fmap words getLine
	time<-fmap (\x->read x::Integer) getLine
	putStrLn (func (head s) (head f) time)