You are given an alphabet consisting of n letters, your task is to make a string of the maximum possible length so that the following conditions are satisfied:   the i-th letter occurs in the string no more than ai times;  the number of occurrences of each letter in the string must be distinct for all the letters that occurred in the string at least once.

The first line of the input contains a single integer n (2  ≤  n  ≤  26) — the number of letters in the alphabet. The next line contains n integers ai (1 ≤ ai ≤ 109) — i-th of these integers gives the limitation on the number of occurrences of the i-th character in the string.

Print a single integer — the maximum length of the string that meets all the requirements.

NoteFor convenience let's consider an alphabet consisting of three letters: "a", "b", "c". In the first sample, some of the optimal strings are: "cccaabbccbb", "aabcbcbcbcb". In the second sample some of the optimal strings are: "acc", "cbc".

import Data.List

toInt x = read x :: Integer

solve :: [Integer] -> [Integer] -> Integer
solve [] ys = sum ys
solve (x:xs) [] = solve xs [x]
solve (x:xs) (y:ys) = solve xs (i:y:ys)
                      where i = if (x `elem` y:ys)
                                then (if y-1 > 0 then y-1 else 0)
                                else x

main = do
    getLine
    s <- getLine
    putStrLn (show (solve (reverse . sort . (map toInt) . words $ s) []))

{-# 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 <- readLn
  ns <- map myread.words <$> getLine
  print $ solve n ns

solve :: Int -> [Integer] -> Integer
solve _ ns = go (group . sort $ ns) where
  go ns = if all ((==1) . length) ns
    then sum . concat $ ns
    else go (group . sort . concat . map stair $ ns) where
      stair [] = []
      stair xs = take (length xs) [maximum xs,maximum xs - 1..0]

{-
instructions go here...
-}

module Main where

solve :: [Integer] -> Integer
solve constraints = sum constraints'
  where constraints' = foldl (\used v ->
                               let v' = closestFree used v
                               in (v':used)
                             )
                             []
                             constraints
        closestFree _  0  = 0
        closestFree [] v = v
        closestFree xs v = if v `elem` xs then closestFree xs (v - 1)
                                          else v

main :: IO ()
main = do
  line1 <- getLine
  let n = read line1 :: Integer

  line2 <- getLine
  let constraints = map read (words line2) :: [Integer]

  putStrLn $ show $ solve constraints

import Data.List

toInt x = read x :: Integer

solve :: [Integer] -> [Integer] -> Integer
solve [] ys = sum ys
solve (x:xs) [] = solve xs [x]
solve (x:xs) (y:ys) = solve xs (i:y:ys)
                      where i = if (x `elem` y:ys) then y-1 else x

main = do
    getLine
    s <- getLine
    putStrLn (show (solve (reverse . sort . (map toInt) . words $ s) []))

import Data.List

toInt x = read x :: Int

solve :: [Int] -> [Int] -> Int
solve [] ys = sum ys
solve (x:xs) [] = solve xs [x]
solve (x:xs) (y:ys) = solve xs (i:y:ys)
                      where i = if (x `elem` y:ys) then y-1 else x

main = do
    getLine
    s <- getLine
    putStrLn (show (solve (reverse . sort . (map toInt) . words $ s) []))

import Data.List

toInt x = read x :: Int

solve :: [Int] -> [Int] -> Int
solve [] x = sum x
solve (x:xs) [] = solve xs [x]
solve (x:xs) (y:ys) = solve xs (i:y:ys)
                      where i = if x == y then x-1 else x

main = do
    getLine
    s <- getLine
    putStrLn (show (solve (reverse . sort . (map toInt) . words $ s) []))

{-# 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 -> Int
main = do
  n <- readLn
  ns <- map myread.words <$> getLine
  print $ solve n ns

solve :: Int -> [Int] -> Int
solve _ ns = go (group . sort $ ns) where
  go ns = if all ((==1) . length) ns
    then sum . concat $ ns
    else go (group . sort . concat . map stair $ ns) where
      stair [] = []
      stair xs = take (length xs) [maximum xs,maximum xs - 1..0]


Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the half-backs and forwards (plays attack).Two teams of company Q decided to battle each other. Let's enumerate players from both teams by integers from 1 to 4. The first and second player play in the first team, the third and the fourth one play in the second team. For each of the four players we know their game skills in defence and attack. The defence skill of the i-th player is ai, the attack skill is bi.Before the game, the teams determine how they will play. First the players of the first team decide who will play in the attack, and who will play in the defence. Then the second team players do the same, based on the choice of their opponents.We will define a team's defence as the defence skill of player of the team who plays defence. Similarly, a team's attack is the attack skill of the player of the team who plays attack. We assume that one team is guaranteed to beat the other one, if its defence is strictly greater than the opponent's attack and its attack is strictly greater than the opponent's defence.The teams of company Q know each other's strengths and therefore arrange their teams optimally. Identify the team that is guaranteed to win (if both teams act optimally) or tell that there is no such team.

The input contain the players' description in four lines. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 100) — the defence and the attack skill of the i-th player, correspondingly.

If the first team can win, print phrase "Team 1" (without the quotes), if the second team can win, print phrase "Team 2" (without the quotes). If no of the teams can definitely win, print "Draw" (without the quotes).

NoteLet consider the first test sample. The first team can definitely win if it will choose the following arrangement: the first player plays attack, the second player plays defence.Consider the second sample. The order of the choosing roles for players makes sense in this sample. As the members of the first team choose first, the members of the second team can beat them (because they know the exact defence value and attack value of the first team).

module Main where

import Control.Monad

numPlayers :: Int
numPlayers = 4

data Player = Player { defence :: Int, attack :: Int }
data Team = Team { defencePlayer :: Player, attackPlayer :: Player }
data Result = Team1 | Draw | Team2 deriving (Eq, Ord)

play :: Team -> Team -> Result
play t1 t2 | teamDefence t1 > teamAttack t2 && teamAttack t1 > teamDefence t2 = Team1
           | teamDefence t1 < teamAttack t2 && teamAttack t1 < teamDefence t2 = Team2
           | otherwise = Draw
  where teamDefence = defence . defencePlayer
        teamAttack = attack . attackPlayer

turn2 :: Team -> [Player] -> Result
turn2 t1 [c, d] = max (play t1 (Team c d)) (play t1 (Team d c))

turn1 :: [Player] -> Result
turn1 (a:b:ps) = min (turn2 (Team a b) ps) (turn2 (Team b a) ps)

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

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

type Tokenizer = State [String]

nextInt :: Tokenizer Int
nextInt = State $ \(s:ss) -> (read s, ss)

nextPlayer :: Tokenizer Player
nextPlayer = liftM2 Player nextInt nextInt

go :: Tokenizer Result
go = do
  players <- replicateM numPlayers nextPlayer
  return $ turn1 players

main :: IO ()
main = do
  content <- liftM words getContents
  let result = fst $ runState go content
  putStrLn $ case result of
    Team1 -> "Team 1"
    Draw  -> "Draw"
    Team2 -> "Team 2"

strToList = (map $ map (read :: (String -> Int))).(map words)

data Player = Player { att :: Int, def :: Int }
data Team = Team { offense :: Player, defense :: Player }

matchResult teamA teamB
            | att_a > def_b && def_a > att_b = "Team 1"
            | att_b > def_a && def_b > att_a = "Team 2"
            | otherwise = "Draw"
            where att_a = att $ offense teamA
                  att_b = att $ offense teamB
                  def_a = def $ defense teamA
                  def_b = def $ defense teamB

f :: (Player, Player) -> (Player, Player) -> String
f (a, b) (c, d)
            | sa == "Team 1" && sc == "Team 1" = "Team 1"
            | sb == "Team 1" && sd == "Team 1" = "Team 1"
            | (sa == "Team 2" || sc == "Team 2") && (sb == "Team 2" || sd == "Team 2") = "Team 2"
            | otherwise = "Draw"
            where sa = matchResult (Team a b) (Team c d)
                  sb = matchResult (Team b a) (Team c d)
                  sc = matchResult (Team a b) (Team d c)
                  sd = matchResult (Team b a) (Team d c)

tuplify2 [a, b] = (a, b)
main = do
    s <- getContents
    let xs = map (\[a, b] -> Player a b) $ strToList (lines s)
    putStrLn $ f (tuplify2 $ take 2 xs) (tuplify2 $ drop 2 xs)

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad
import Control.Monad.ST

import Data.Bits
import Data.Char
import Data.Either
import Data.Function
import Data.IORef
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
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
-- }}}
-- silly utilities {{{
(#) = flip ($)
infixl 0 #

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)

(!>) :: Seq a -> Int -> a
(!>) = Seq.index
-- }}}
-- input and output {{{
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]
-- }}}

inputPair = do
	[a, d] <- inputInts
	return (a, d)

beats ((a1,_), (_,d1)) ((a2,_), (_,d2)) = a1 > d2 && d1 > a2

dominates (p1, p2) (p3, p4) =
	((p1, p2) `beats` (p3, p4)) && ((p1, p2) `beats` (p4, p3))
canBeat (p1, p2) (p3, p4) =
	((p1, p2) `beats` (p3, p4)) || ((p2, p1) `beats` (p3, p4))

main :: IO ()
main = do
	p1 <- inputPair
	p2 <- inputPair
	p3 <- inputPair
	p4 <- inputPair
	putStrLn $ if ((p1, p2) `dominates` (p3, p4)) || ((p2, p1) `dominates` (p3, p4)) then
		"Team 1"
	else if ((p3, p4) `canBeat` (p1, p2)) && ((p3, p4) `canBeat` (p2, p1)) then
		"Team 2"
	else
		"Draw"

module Main where

import Control.Monad

numPlayers :: Int
numPlayers = 4

data Player = Player { defence :: Int, attack :: Int }
data Team = Team { defencePlayer :: Player, attackPlayer :: Player }
data Result = Team1 | Draw | Team2 deriving (Eq, Ord)

play :: Team -> Team -> Result
play t1 t2 | teamAttack t1 > teamAttack t2 && teamDefence t1 > teamDefence t2 = Team1
           | teamAttack t1 < teamAttack t2 && teamDefence t1 < teamDefence t2 = Team2
           | otherwise = Draw
  where teamDefence = defence . defencePlayer
        teamAttack = attack . attackPlayer

turn2 :: Team -> [Player] -> Result
turn2 t1 [c, d] = max (play t1 (Team c d)) (play t1 (Team d c))

turn1 :: [Player] -> Result
turn1 (a:b:ps) = min (turn2 (Team a b) ps) (turn2 (Team b a) ps)

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

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

type Tokenizer = State [String]

nextInt :: Tokenizer Int
nextInt = State $ \(s:ss) -> (read s, ss)

nextPlayer :: Tokenizer Player
nextPlayer = liftM2 Player nextInt nextInt

go :: Tokenizer Result
go = do
  players <- replicateM numPlayers nextPlayer
  return $ turn1 players

main :: IO ()
main = do
  content <- liftM words getContents
  let result = fst $ runState go content
  putStrLn $ case result of
    Team1 -> "Team 1"
    Draw  -> "Draw"
    Team2 -> "Team 2"


Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?Given an integer sequence a1, a2, ..., an of length n. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.A subsegment is a contiguous slice of the whole sequence. For example, {3, 4, 5} and {1} are subsegments of sequence {1, 2, 3, 4, 5, 6}, while {1, 2, 4} and {7} are not.

The first line of input contains a non-negative integer n (1 ≤ n ≤ 100) — the length of the sequence. The second line contains n space-separated non-negative integers a1, a2, ..., an (0 ≤ ai ≤ 100) — the elements of the sequence.

Output "Yes" if it's possible to fulfill the requirements, and "No" otherwise. You can output each letter in any case (upper or lower).

NoteIn the first example, divide the sequence into 1 subsegment: {1, 3, 5} and the requirements will be met.In the second example, divide the sequence into 3 subsegments: {1, 0, 1}, {5}, {1}.In the third example, one of the subsegments must start with 4 which is an even number, thus the requirements cannot be met.In the fourth example, the sequence can be divided into 2 subsegments: {3, 9, 9}, {3}, but this is not a valid solution because 2 is an even number.

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


Imagine a city with n horizontal streets crossing m vertical streets, forming an (n - 1) × (m - 1) grid. In order to increase the traffic flow, mayor of the city has decided to make each street one way. This means in each horizontal street, the traffic moves only from west to east or only from east to west. Also, traffic moves only from north to south or only from south to north in each vertical street. It is possible to enter a horizontal street from a vertical street, or vice versa, at their intersection.  The mayor has received some street direction patterns. Your task is to check whether it is possible to reach any junction from any other junction in the proposed street direction pattern.

The first line of input contains two integers n and m, (2 ≤ n, m ≤ 20), denoting the number of horizontal streets and the number of vertical streets. The second line contains a string of length n, made of characters '<' and '>', denoting direction of each horizontal street. If the i-th character is equal to '<', the street is directed from east to west otherwise, the street is directed from west to east. Streets are listed in order from north to south. The third line contains a string of length m, made of characters '^' and 'v', denoting direction of each vertical street. If the i-th character is equal to '^', the street is directed from south to north, otherwise the street is directed from north to south. Streets are listed in order from west to east.

If the given pattern meets the mayor's criteria, print a single line containing "YES", otherwise print a single line containing "NO".

NoteThe figure above shows street directions in the second sample test case.

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, TupleSections, OverloadedStrings #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import Control.Monad.ST
import Data.Array.Base
import Data.Array.ST (runSTUArray, STArray, runSTArray,range)
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;_->error$"readInt error : bs = "++show bs;}
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 #-}
for :: Monad m => Int -> (Int -> Bool) -> (Int -> Int) -> (Int -> m ()) -> m ()
for !i0 p next f=go i0 where go !i=when(p i)$f i>>go(next i)
{-# INLINE for #-}
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 #-}

type Vertex = Int
type Edge = (Vertex, Vertex)
type Graph = Array Vertex [Vertex]
type Path = [Vertex]

mkGraph :: (Int, Int) -> [Edge] -> Graph
mkGraph bnd edges = unsafeAccumArray (flip (:)) [] bnd edges

vertices :: Graph -> [Vertex]
vertices gr = range $ bounds gr

edges :: Graph -> [Edge]
edges gr = [(from, to) | from <- vertices gr, to <- unsafeAt gr from ]

revGraph :: Graph -> Graph
revGraph gr = mkGraph (bounds gr) . map swap $ edges gr
   where
     swap (x,y) = (y,x)
dfsAll :: Graph -> [Vertex] -> [[Vertex]]
dfsAll gr vs = filter (not.null) $ runST $ do
  vis <- newArray (bounds gr) False :: ST s (STUArray s Vertex Bool)
  mapM (dfsM gr vis) vs

dfsM :: Graph -> STUArray s Vertex Bool -> Vertex -> ST s [Vertex]
dfsM gr vis root = do
  let go res (v:vs) = do
        visited <- unsafeRead vis v
        if visited then go res vs
        else do
          unsafeWrite vis v True
          go (v:res) (unsafeAt gr v ++ vs)
      go res [] = return $ reverse res
  go [] [root]

topSort :: Graph -> [Vertex]
topSort gr = runST $ do
  vis   <- newArray (bounds gr) False :: ST s (STUArray s Vertex Bool)
  stack <- newSTRef []                :: ST s (STRef s [Vertex])
  let visit v = do
        visited <- unsafeRead vis v
        unless visited $ do
          unsafeWrite vis v True
          mapM_ visit $ unsafeAt gr v
          modifySTRef stack (v:)
  mapM_ visit $ vertices gr
  readSTRef stack

scc :: Graph -> [[Vertex]]
scc gr = dfsAll gr . topSort $ revGraph gr

main :: IO ()
main = do
  [n,m] <- map read.words <$> getLine
  hs <- getLine
  vs <- getLine
  let gr = mkGraph' n m hs vs
  case scc gr of
    [_] -> putStrLn "YES"
    _ -> putStrLn "NO"

mkGraph' :: Int -> Int -> String -> String -> Graph
mkGraph' n m hs vs = runSTArray $ do
  gr <- newArray (0,n*m-1) [] :: ST s (STArray s Vertex [Vertex])
  let inGrid (x,y) = 0<=x && x<n && 0<=y && y<m
      toVertex (x,y) = x * m + y
  forM_ (zip[0..n-1]hs) $ \(x,dir) -> do
    case dir of
      '<' -> do
        forM_ [1..m-1] $ \y -> do
          unsafeModify gr (toVertex(x,y)) (toVertex(x,y-1):)
      '>' -> do
        forM_ [0..m-2] $ \y -> do
          unsafeModify gr (toVertex(x,y)) (toVertex(x,y+1):)
  forM_ (zip[0..m-1]vs) $ \(y,dir) -> do
    case dir of
      '^' -> do
        forM_ [1..n-1] $ \x -> do
          unsafeModify gr (toVertex(x,y)) (toVertex(x-1,y):)
      'v' -> do
        forM_ [0..n-2] $ \x -> do
          unsafeModify gr (toVertex(x,y)) (toVertex(x+1,y):)
  return gr


Tonio has a keyboard with only two letters, "V" and "K".One day, he has typed out a string s with only these two letters. He really likes it when the string "VK" appears, so he wishes to change at most one letter in the string (or do no changes) to maximize the number of occurrences of that string. Compute the maximum number of times "VK" can appear as a substring (i. e. a letter "K" right after a letter "V") in the resulting string.

The first line will contain a string s consisting only of uppercase English letters "V" and "K" with length not less than 1 and not greater than 100.

Output a single integer, the maximum number of times "VK" can appear as a substring of the given string after changing at most one character.

NoteFor the first case, we do not change any letters. "VK" appears once, which is the maximum number of times it could appear.For the second case, we can change the second character from a "V" to a "K". This will give us the string "VK". This has one occurrence of the string "VK" as a substring.For the fourth case, we can change the fourth character from a "K" to a "V". This will give us the string "VKKVKKKKKKVVVVVVVVVK". This has three occurrences of the string "VK" as a substring. We can check no other moves can give us strictly more occurrences.

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 [_] = 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

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


Mishka got a six-faced dice. It has integer numbers from $$$2$$$ to $$$7$$$ written on its faces (all numbers on faces are different, so this is an almost usual dice).Mishka wants to get exactly $$$x$$$ points by rolling his dice. The number of points is just a sum of numbers written at the topmost face of the dice for all the rolls Mishka makes.Mishka doesn't really care about the number of rolls, so he just wants to know any number of rolls he can make to be able to get exactly $$$x$$$ points for them. Mishka is very lucky, so if the probability to get $$$x$$$ points with chosen number of rolls is non-zero, he will be able to roll the dice in such a way. Your task is to print this number. It is guaranteed that at least one answer exists.Mishka is also very curious about different number of points to score so you have to answer $$$t$$$ independent queries.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of queries. Each of the next $$$t$$$ lines contains one integer each. The $$$i$$$-th line contains one integer $$$x_i$$$ ($$$2 \le x_i \le 100$$$) — the number of points Mishka wants to get.

Print $$$t$$$ lines. In the $$$i$$$-th line print the answer to the $$$i$$$-th query (i.e. any number of rolls Mishka can make to be able to get exactly $$$x_i$$$ points for them). It is guaranteed that at least one answer exists.

NoteIn the first query Mishka can roll a dice once and get $$$2$$$ points.In the second query Mishka can roll a dice $$$3$$$ times and get points $$$5$$$, $$$5$$$ and $$$3$$$ (for example).In the third query Mishka can roll a dice $$$8$$$ times and get $$$5$$$ points $$$7$$$ times and $$$2$$$ points with the remaining roll.In the fourth query Mishka can roll a dice $$$27$$$ times and get $$$2$$$ points $$$11$$$ times, $$$3$$$ points $$$6$$$ times and $$$6$$$ points $$$10$$$ times.

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

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

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


There is a sequence of colorful stones. The color of each stone is one of red, green, or blue. You are given a string s. The i-th (1-based) character of s represents the color of the i-th stone. If the character is "R", "G", or "B", the color of the corresponding stone is red, green, or blue, respectively.Initially Squirrel Liss is standing on the first stone. You perform instructions one or more times.Each instruction is one of the three types: "RED", "GREEN", or "BLUE". After an instruction c, if Liss is standing on a stone whose colors is c, Liss will move one stone forward, else she will not move.You are given a string t. The number of instructions is equal to the length of t, and the i-th character of t represents the i-th instruction.Calculate the final position of Liss (the number of the stone she is going to stand on in the end) after performing all the instructions, and print its 1-based position. It is guaranteed that Liss don't move out of the sequence.

The input contains two lines. The first line contains the string s (1 ≤ |s| ≤ 50). The second line contains the string t (1 ≤ |t| ≤ 50). The characters of each string will be one of "R", "G", or "B". It is guaranteed that Liss don't move out of the sequence.

Print the final 1-based position of Liss in a single line.

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

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

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

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


Vasya decided to learn to play chess. Classic chess doesn't seem interesting to him, so he plays his own sort of chess.The queen is the piece that captures all squares on its vertical, horizontal and diagonal lines. If the cell is located on the same vertical, horizontal or diagonal line with queen, and the cell contains a piece of the enemy color, the queen is able to move to this square. After that the enemy's piece is removed from the board. The queen cannot move to a cell containing an enemy piece if there is some other piece between it and the queen. There is an n × n chessboard. We'll denote a cell on the intersection of the r-th row and c-th column as (r, c). The square (1, 1) contains the white queen and the square (1, n) contains the black queen. All other squares contain green pawns that don't belong to anyone.The players move in turns. The player that moves first plays for the white queen, his opponent plays for the black queen.On each move the player has to capture some piece with his queen (that is, move to a square that contains either a green pawn or the enemy queen). The player loses if either he cannot capture any piece during his move or the opponent took his queen during the previous move. Help Vasya determine who wins if both players play with an optimal strategy on the board n × n.

The input contains a single number n (2 ≤ n ≤ 109) — the size of the board.

On the first line print the answer to problem — string "white" or string "black", depending on who wins if the both players play optimally.  If the answer is "white", then you should also print two integers r and c representing the cell (r, c), where the first player should make his first move to win. If there are multiple such cells, print the one with the minimum r. If there are still multiple squares, print the one with the minimum c.

NoteIn the first sample test the white queen can capture the black queen at the first move, so the white player wins.In the second test from the statement if the white queen captures the green pawn located on the central vertical line, then it will be captured by the black queen during the next move. So the only move for the white player is to capture the green pawn located at (2, 1). Similarly, the black queen doesn't have any other options but to capture the green pawn located at (2, 3), otherwise if it goes to the middle vertical line, it will be captured by the white queen.During the next move the same thing happens — neither the white, nor the black queen has other options rather than to capture green pawns situated above them. Thus, the white queen ends up on square (3, 1), and the black queen ends up on square (3, 3). In this situation the white queen has to capture any of the green pawns located on the middle vertical line, after that it will be captured by the black queen. Thus, the player who plays for the black queen wins.

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"


Alena has successfully passed the entrance exams to the university and is now looking forward to start studying.One two-hour lesson at the Russian university is traditionally called a pair, it lasts for two academic hours (an academic hour is equal to 45 minutes).The University works in such a way that every day it holds exactly n lessons. Depending on the schedule of a particular group of students, on a given day, some pairs may actually contain classes, but some may be empty (such pairs are called breaks).The official website of the university has already published the schedule for tomorrow for Alena's group. Thus, for each of the n pairs she knows if there will be a class at that time or not.Alena's House is far from the university, so if there are breaks, she doesn't always go home. Alena has time to go home only if the break consists of at least two free pairs in a row, otherwise she waits for the next pair at the university.Of course, Alena does not want to be sleepy during pairs, so she will sleep as long as possible, and will only come to the first pair that is presented in her schedule. Similarly, if there are no more pairs, then Alena immediately goes home.Alena appreciates the time spent at home, so she always goes home when it is possible, and returns to the university only at the beginning of the next pair. Help Alena determine for how many pairs she will stay at the university. Note that during some pairs Alena may be at the university waiting for the upcoming pair.

The first line of the input contains a positive integer n (1 ≤ n ≤ 100) — the number of lessons at the university.  The second line contains n numbers ai (0 ≤ ai ≤ 1). Number ai equals 0, if Alena doesn't have the i-th pairs, otherwise it is equal to 1. Numbers a1, a2, ..., an are separated by spaces.

Print a single number — the number of pairs during which Alena stays at the university.

NoteIn the first sample Alena stays at the university from the second to the fifth pair, inclusive, during the third pair she will be it the university waiting for the next pair. In the last sample Alena doesn't have a single pair, so she spends all the time at home.

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

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

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)


Mr. Bender has a digital table of size n × n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy.We'll consider the table rows numbered from top to bottom from 1 to n, and the columns — numbered from left to right from 1 to n. Initially there is exactly one switched on cell with coordinates (x, y) (x is the row number, y is the column number), and all other cells are switched off. Then each second we switch on the cells that are off but have the side-adjacent cells that are on.For a cell with coordinates (x, y) the side-adjacent cells are cells with coordinates (x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1).In how many seconds will Mr. Bender get happy?

The first line contains four space-separated integers n, x, y, c (1 ≤ n, c ≤ 109; 1 ≤ x, y ≤ n; c ≤ n2).

In a single line print a single integer — the answer to the problem.

NoteInitially the first test has one painted cell, so the answer is 0. In the second test all events will go as is shown on the figure. .

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

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

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


Berland Football Cup starts really soon! Commentators from all over the world come to the event.Organizers have already built $$$n$$$ commentary boxes. $$$m$$$ regional delegations will come to the Cup. Every delegation should get the same number of the commentary boxes. If any box is left unoccupied then the delegations will be upset. So each box should be occupied by exactly one delegation.If $$$n$$$ is not divisible by $$$m$$$, it is impossible to distribute the boxes to the delegations at the moment.Organizers can build a new commentary box paying $$$a$$$ burles and demolish a commentary box paying $$$b$$$ burles. They can both build and demolish boxes arbitrary number of times (each time paying a corresponding fee). It is allowed to demolish all the existing boxes.What is the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $$$m$$$)?

The only line contains four integer numbers $$$n$$$, $$$m$$$, $$$a$$$ and $$$b$$$ ($$$1 \le n, m \le 10^{12}$$$, $$$1 \le a, b \le 100$$$), where $$$n$$$ is the initial number of the commentary boxes, $$$m$$$ is the number of delegations to come, $$$a$$$ is the fee to build a box and $$$b$$$ is the fee to demolish a box.

Output the minimal amount of burles organizers should pay to satisfy all the delegations (i.e. to make the number of the boxes be divisible by $$$m$$$). It is allowed that the final number of the boxes is equal to $$$0$$$.

NoteIn the first example organizers can build $$$5$$$ boxes to make the total of $$$14$$$ paying $$$3$$$ burles for the each of them.In the second example organizers can demolish $$$2$$$ boxes to make the total of $$$0$$$ paying $$$7$$$ burles for the each of them.In the third example organizers are already able to distribute all the boxes equally among the delegations, each one get $$$5$$$ boxes.

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

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)

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

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

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


You are planning to build housing on a street. There are $$$n$$$ spots available on the street on which you can build a house. The spots are labeled from $$$1$$$ to $$$n$$$ from left to right. In each spot, you can build a house with an integer height between $$$0$$$ and $$$h$$$.In each spot, if a house has height $$$a$$$, you will gain $$$a^2$$$ dollars from it.The city has $$$m$$$ zoning restrictions. The $$$i$$$-th restriction says that the tallest house from spots $$$l_i$$$ to $$$r_i$$$ (inclusive) must be at most $$$x_i$$$.You would like to build houses to maximize your profit. Determine the maximum profit possible.

The first line contains three integers $$$n$$$, $$$h$$$, and $$$m$$$ ($$$1 \leq n,h,m \leq 50$$$) — the number of spots, the maximum height, and the number of restrictions. Each of the next $$$m$$$ lines contains three integers $$$l_i$$$, $$$r_i$$$, and $$$x_i$$$ ($$$1 \leq l_i \leq r_i \leq n$$$, $$$0 \leq x_i \leq h$$$) — left and right limits (inclusive) of the $$$i$$$-th restriction and the maximum possible height in that range.

Print a single integer, the maximum profit you can make.

NoteIn the first example, there are $$$3$$$ houses, the maximum height of a house is $$$3$$$, and there are $$$3$$$ restrictions. The first restriction says the tallest house between $$$1$$$ and $$$1$$$ must be at most $$$1$$$. The second restriction says the tallest house between $$$2$$$ and $$$2$$$ must be at most $$$3$$$. The third restriction says the tallest house between $$$3$$$ and $$$3$$$ must be at most $$$2$$$.In this case, it is optimal to build houses with heights $$$[1, 3, 2]$$$. This fits within all the restrictions. The total profit in this case is $$$1^2 + 3^2 + 2^2 = 14$$$.In the second example, there are $$$4$$$ houses, the maximum height of a house is $$$10$$$, and there are $$$2$$$ restrictions. The first restriction says the tallest house from $$$2$$$ to $$$3$$$ must be at most $$$8$$$. The second restriction says the tallest house from $$$3$$$ to $$$4$$$ must be at most $$$7$$$.In this case, it's optimal to build houses with heights $$$[10, 8, 7, 7]$$$. We get a profit of $$$10^2+8^2+7^2+7^2 = 262$$$. Note that there are two restrictions on house $$$3$$$ and both of them must be satisfied. Also, note that even though there isn't any explicit restrictions on house $$$1$$$, we must still limit its height to be at most $$$10$$$ ($$$h=10$$$).

process :: Int -> [(Int,Int,Int)] -> Int
process n xs = sum $ map ((^2).f xs) [1..n]
    where
        f xs i = foldr (\(l,r,x) acc -> if i < l || i > r then acc else min x acc) maxBound xs

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    [n,h,m] <- fmap (map readInt.words) getLine
    xs <- fmap (map (\[l,r,x]->(l,r,x)).map (map readInt.words).lines) getContents
    print $ process n ((1,n,h):xs)


A positive integer is called a 2-3-integer, if it is equal to 2x·3y for some non-negative integers x and y. In other words, these integers are such integers that only have 2 and 3 among their prime divisors. For example, integers 1, 6, 9, 16 and 108 — are 2-3 integers, while 5, 10, 21 and 120 are not.Print the number of 2-3-integers on the given segment [l, r], i. e. the number of sich 2-3-integers t that l ≤ t ≤ r.

The only line contains two integers l and r (1 ≤ l ≤ r ≤ 2·109).

Print a single integer the number of 2-3-integers on the segment [l, r].

NoteIn the first example the 2-3-integers are 1, 2, 3, 4, 6, 8 and 9.In the second example the 2-3-integers are 108, 128, 144, 162 and 192.

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

{-# 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) :: [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


A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....   The Monster will catch them if at any point they scream at the same time, so it wants to know when it will catch them (the first time they scream at the same time) or that they will never scream at the same time.

The first line of input contains two integers a and b (1 ≤ a, b ≤ 100).  The second line contains two integers c and d (1 ≤ c, d ≤ 100).

Print the first time Rick and Morty will scream at the same time, or  - 1 if they will never scream at the same time.

NoteIn the first sample testcase, Rick's 5th scream and Morty's 8th time are at time 82. In the second sample testcase, all Rick's screams will be at odd times and Morty's will be at even times, so they will never scream at the same time.

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

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]

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


Kolya got string s for his birthday, the string consists of small English letters. He immediately added k more characters to the right of the string.Then Borya came and said that the new string contained a tandem repeat of length l as a substring. How large could l be?See notes for definition of a tandem repeat.

The first line contains s (1 ≤ |s| ≤ 200). This string contains only small English letters. The second line contains number k (1 ≤ k ≤ 200) — the number of the added characters.

Print a single number — the maximum length of the tandem repeat that could have occurred in the new string.

NoteA tandem repeat of length 2n is string s, where for any position i (1 ≤ i ≤ n) the following condition fulfills: si = si + n.In the first sample Kolya could obtain a string aabaab, in the second — aaabbbbbb, in the third — abracadabrabracadabra.

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

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

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

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