There is a bus stop near the university. The lessons are over, and n students come to the stop. The i-th student will appear at the bus stop at time ti (all ti's are distinct).We shall assume that the stop is located on the coordinate axis Ox, at point x = 0, and the bus goes along the ray Ox, that is, towards the positive direction of the coordinate axis, and back. The i-th student needs to get to the point with coordinate xi (xi > 0).The bus moves by the following algorithm. Initially it is at point 0. The students consistently come to the stop and get on it. The bus has a seating capacity which is equal to m passengers. At the moment when m students get on the bus, it starts moving in the positive direction of the coordinate axis. Also it starts moving when the last (n-th) student gets on the bus. The bus is moving at a speed of 1 unit of distance per 1 unit of time, i.e. it covers distance y in time y.Every time the bus passes the point at which at least one student needs to get off, it stops and these students get off the bus. The students need 1 + [k / 2] units of time to get off the bus, where k is the number of students who leave at this point. Expression [k / 2] denotes rounded down k / 2. As soon as the last student leaves the bus, the bus turns around and goes back to the point x = 0. It doesn't make any stops until it reaches the point. At the given point the bus fills with students once more, and everything is repeated.If students come to the stop when there's no bus, they form a line (queue) and get on the bus in the order in which they came. Any number of students get on the bus in negligible time, you should assume that it doesn't take any time. Any other actions also take no time. The bus has no other passengers apart from the students.Write a program that will determine for each student the time when he got off the bus. The moment a student got off the bus is the moment the bus stopped at the student's destination stop (despite the fact that the group of students need some time to get off).

The first line contains two space-separated integers n, m (1 ≤ n, m ≤ 105) — the number of students and the number of passengers the bus can transport, correspondingly. Next n lines contain descriptions of the students, one per line. Each line contains a pair of integers ti, xi (1 ≤ ti ≤ 105, 1 ≤ xi ≤ 104). The lines are given in the order of strict increasing of ti. Values of xi can coincide.

Print n numbers w1, w2, ..., wn, wi — the moment of time when the i-th student got off the bus. Print the numbers on one line and separate them with single spaces.

NoteIn the first sample the bus waits for the first student for 3 units of time and drives him to his destination in additional 5 units of time. So the student leaves the bus at the moment of time 3 + 5 = 8.In the second sample the capacity of the bus equals 1, that's why it will drive the first student alone. This student is the same as the student from the first sample. So the bus arrives to his destination at the moment of time 8, spends 1 + [1 / 2] = 1 units of time on getting him off, and returns back to 0 in additional 5 units of time. That is, the bus returns to the bus stop at the moment of time 14. By this moment the second student has already came to the bus stop. So he immediately gets in the bus, and is driven to his destination in additional 5 units of time. He gets there at the moment 14 + 5 = 19. In the third sample the bus waits for the fourth student for 6 units of time, then drives for 5 units of time, then gets the passengers off for 1 + [4 / 2] = 3 units of time, then returns for 5 units of time, and then drives the fifth student for 1 unit of time.

import Data.List
import Control.Arrow
import Data.Function
import Data.Tuple

splitEvery n [] = []
splitEvery n x = uncurry (:) . second (splitEvery n) . splitAt n $ x

go :: Integer -> [(Integer, Integer)] -> (Integer, [Integer])
go arrival students = second (map snd . sort) $ (\(a,b) -> (b,a)) res where
 res = go 0 departure $ groupBy ((==) `on` snd) $ sortBy (compare `on` snd) $ zip [1..] $ map snd students
 go x t [] = ([],t+x)
 go x t (l@((_,y):_):next) = first (map (\(i,_)->(i,t+y-x)) l ++) (go y (t + y - x + 1 + genericLength l `div` 2) next)
 departure = max arrival (fst $ last students)

s::[[Integer]] -> [Integer]
s([_,m]:t)=concat.snd.mapAccumL go 0 . splitEvery (fromIntegral m) . map (\[a,b]->(a,b))$ t
main=interact$unwords.map show.s.map(map read.words).lines

import Data.List
import Control.Arrow
import Data.Function
import Data.Tuple

splitEvery n [] = []
splitEvery n x = uncurry (:) . second (splitEvery n) . splitAt n $ x

go :: Integer -> [(Integer, Integer)] -> (Integer, [Integer])
go arrival students = second (map snd . sort) $ (\(a,b) -> (b,a)) res where
 res = go 0 departure $ groupBy ((==) `on` snd) $ sortBy (compare `on` snd) $ zip [1..] $ map snd students
 go x t [] = ([],t+x)
 go x t (l@((_,y):_):next) = first (map (\(i,_)->(i,t+y)) l ++) (go y (t + y + 1 + genericLength l `div` 2) next)
 departure = max arrival (fst $ last students)

s::[[Integer]] -> [Integer]
s([_,m]:t)=concat.snd.mapAccumL go 0 . splitEvery (fromIntegral m) . map (\[a,b]->(a,b))$ t
main=interact$unwords.map show.s.map(map read.words).lines


You are given a tree consisting of $$$n$$$ vertices. Some of the vertices (at least two) are black, all the other vertices are white.You place a chip on one of the vertices of the tree, and then perform the following operations:  let the current vertex where the chip is located is $$$x$$$. You choose a black vertex $$$y$$$, and then move the chip along the first edge on the simple path from $$$x$$$ to $$$y$$$. You are not allowed to choose the same black vertex $$$y$$$ in two operations in a row (i. e., for every two consecutive operations, the chosen black vertex should be different).You end your operations when the chip moves to the black vertex (if it is initially placed in a black vertex, you don't perform the operations at all), or when the number of performed operations exceeds $$$100^{500}$$$.For every vertex $$$i$$$, you have to determine if there exists a (possibly empty) sequence of operations that moves the chip to some black vertex, if the chip is initially placed on the vertex $$$i$$$.

The first line contains one integer $$$n$$$ ($$$3 \le n \le 3 \cdot 10^5$$$) — the number of vertices in the tree. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$0 \le c_i \le 1$$$), where $$$c_i = 0$$$ means that the $$$i$$$-th vertex is white, and $$$c_i = 1$$$ means that the $$$i$$$-th vertex is black. At least two values of $$$c_i$$$ are equal to $$$1$$$. Then $$$n-1$$$ lines follow, each of them contains two integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \ne v_i$$$) — the endpoints of some edge. These edges form a tree.

Print $$$n$$$ integers. The $$$i$$$-th integer should be equal to $$$1$$$ if there exists a (possibly empty) sequence of operations that moves the chip to some black vertex if it is placed on the vertex $$$i$$$, and $$$0$$$ if no such sequence of operations exists.

import Control.Monad
import Data.Array
import Data.Foldable
import Data.Graph
import Data.Maybe
import qualified Data.ByteString.Char8 as C

data Status = Sure | IsOnlyBlack | HasBlack | Useless deriving Eq
data Gather = GSure | GMaybe { isBlack :: !Bool, total :: !Int }

gather :: Gather -> Status -> Gather
gather x            Useless     = x
gather _            Sure        = GSure
gather GSure        _           = GSure
gather (GMaybe _ t) IsOnlyBlack = GMaybe True (t + 1)
gather (GMaybe b t) HasBlack    = GMaybe b    (t + 1)

status :: Bool -> Gather -> Status
status _ GSure = Sure
status True (GMaybe _ t)
    | t == 0    = IsOnlyBlack
    | otherwise = Sure
status False (GMaybe b t)
    | t == 0      = Useless
    | b && t >= 2 = Sure
    | otherwise   = HasBlack

solve :: IO ()
solve = do
    ~[n] <- readInts
    ca <- listArray (1, n) . map toEnum <$> readInts
    es <- fmap concat $ replicateM (n - 1) $ do
        ~[u, v] <- readInts
        pure [(u, v), (v, u)]
    let g = buildG (1, n) es
        [tree] = dfs g [1]
        dps = rerootDP gather (GMaybe False 0) (status . (ca!)) tree
        ans = [(u, s == Sure || s == IsOnlyBlack || any (ca!) (g!u)) | (u, s) <- dps]
    putStrLn $ unwords $ map (show . fromEnum) $ elems $ array (1, n) ans

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

rerootDP :: (b -> c -> b) -> b -> (Vertex -> b -> c) -> Tree Vertex -> [(Vertex, c)]
rerootDP f b g t = res where
    dfs1 (Node u ts) = r `seq` (r, Node (u, rs) ts') where
        (rs, ts') = unzip $ map dfs1 ts
        r = g u $ foldl' f b rs
    dfs2 (Node (u, rs) ts) up acc = r `seq` (u, r) : acc' where
        bs = foldExclusive f b $ up : rs
        r = g u $ f (head bs) up
        acc' = foldr (uncurry dfs2) acc $ zip ts $ map (g u) $ tail bs
    res = (u, r) : acc where
        (r, Node (u, rs) ts) = dfs1 t
        bs = foldExclusive f b rs
        acc = foldr (uncurry dfs2) [] $ zip ts $ map (g u) bs

foldExclusive :: (b -> a -> b) -> b -> [a] -> [b]
foldExclusive _ _ [] = []
foldExclusive f b as = go b (length as) as [] where
    go b 1 _  acc = b:acc
    go b n as acc = b1 `seq` b2 `seq` go b2 n' as1 $ go b1 (n - n') as2 acc where
        n' = n `div` 2
        (as1, as2) = splitAt n' as
        b1 = foldl' f b as1
        b2 = foldl' f b as2

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

main :: IO ()
main = solve


You are given two strings $$$s$$$ and $$$t$$$. In a single move, you can choose any of two strings and delete the first (that is, the leftmost) character. After a move, the length of the string decreases by $$$1$$$. You can't choose a string if it is empty.For example:  by applying a move to the string "where", the result is the string "here",  by applying a move to the string "a", the result is an empty string "". You are required to make two given strings equal using the fewest number of moves. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the initial strings.Write a program that finds the minimum number of moves to make two given strings $$$s$$$ and $$$t$$$ equal.

The first line of the input contains $$$s$$$. In the second line of the input contains $$$t$$$. Both strings consist only of lowercase Latin letters. The number of letters in each string is between 1 and $$$2\cdot10^5$$$, inclusive.

Output the fewest number of moves required. It is possible that, in the end, both strings will be equal to the empty string, and so, are equal to each other. In this case, the answer is obviously the sum of the lengths of the given strings.

NoteIn the first example, you should apply the move once to the first string and apply the move once to the second string. As a result, both strings will be equal to "est".In the second example, the move should be applied to the string "codeforces" $$$8$$$ times. As a result, the string becomes "codeforces" $$$\to$$$ "es". The move should be applied to the string "yes" once. The result is the same string "yes" $$$\to$$$ "es".In the third example, you can make the strings equal only by completely deleting them. That is, in the end, both strings will be empty.In the fourth example, the first character of the second string should be deleted.

import Data.List

toint s = (read s) :: Integer

doit [] = 0
doit ((x,y):xs) =
	if x == y then
		1 + doit xs
	else
		0

solve::String -> String
solve ss =
	let [s,t] = map reverse (words ss) in
	show (length s + length t - 2 * doit (zip s t)) ++ "\n"

main = do
  interact $ solve

-- Codeforces 1005B
import Data.List

deleteFromRight :: (String, String) -> (String, String)
deleteFromRight ([], s2) = ([], s2)
deleteFromRight (s1, []) = (s1, [])
deleteFromRight (x1:xs1, x2:xs2)
    | x1 == x2 = deleteFromRight (xs1, xs2)
    | otherwise = (x1:xs1, x2:xs2)

rest :: (String, String) -> Int
rest (s1, s2) = (\(a, b) -> (length a) + (length b)) $ deleteFromRight (reverse s1, reverse s2)

main :: IO ()
main = do
    s1 <- getLine
    s2 <- getLine
    print (rest (s1, s2))

f [] a = length a
f a [] = length a
f (a:as) (b:bs) | a==b = f as bs
f as bs = length as + length bs

main = do
    s <- getLine
    t <- getLine
    print $ f (reverse t) (reverse s)

import Data.List

f::String->String->Int
f "" _ =0
f _ ""=0
f (x:xs) (y:ys)
      |x/=y=0
      |otherwise=2 + (f xs ys)

main = do
       e1<-getLine
       e2<-getLine
       let t=(length e1)+(length e2)
       print $ t - (f (reverse e1) (reverse e2))

import Control.Arrow
main = interact $ show . solve . lines
solve [a,b] = go (reverse a) (reverse b) where
  go (a:as) (b:bs) | a == b = go as bs
  go as bs = length as + length bs

main = interact $ pureMain

pureMain :: String -> String
pureMain x = show $ length s + length t - 2 * f (reverse s) (reverse t)
  where
    [s, t] = lines x
    f _ [] = 0
    f [] _ = 0
    f (a:as) (b:bs) | a == b = 1 + f as bs
                    | otherwise = 0

import Control.Arrow
main = interact $ show . solve . lines
solve [a,b] = uncurry (+) $ length *** length $ unzip $ dropWhile (uncurry (==)) $ zip (reverse a) (reverse b)


Gabriella has been instructed to organize a renowned wine tasting event which will be attended by $$$m$$$ critics. On display, there will be $$$n$$$ different varieties of wine, each of which can either be a red wine or a white wine.The wines will come in $$$n$$$ bottles arranged in a line on the table, and, for convenience, each critic will sip from a contiguous interval of bottles: that is, he/she will taste exactly the bottles at position $$$a, \, a + 1, \, \dots, \, b$$$ for some $$$1 \le a \le b \le n$$$. The interval depends on the critic, who will select it on the spot according to their preferences. In fact, the $$$i$$$-th critic ($$$1 \le i \le m$$$) has requested that he/she wants to taste exactly $$$r_i$$$ red wines and $$$w_i$$$ white wines.Gabriella has yet to choose how many bottles of red wine and white wine there will be, and in what order they will appear. Help her find an arrangement (that is, a sequence of $$$n$$$ bottles of either red or white wine) that satisfies the requests of all the critics, or state that no such arrangement exists.

Each test contains multiple test cases. The first line contains an integer $$$t$$$ ($$$1\le t\le 100$$$) — the number of test cases. The descriptions of the $$$t$$$ test cases follow. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$1 \le m \le 100$$$) — the number of bottles of wine and the number of critics. Each of the next $$$m$$$ lines contains two integers $$$r_i$$$ and $$$w_i$$$ ($$$0 \le r_i, \, w_i \le 100$$$, $$$r_i + w_i \ge 1$$$) — the number of red and white wines that the $$$i$$$-th critic wants to taste.

For each test case, if at least one solution exists, print a string of length $$$n$$$ made up of the characters R and W, where the $$$j$$$-th character ($$$1 \le j \le n$$$) denotes the type of the wine in the $$$j$$$-th bottle of the arrangement (R for red and W for white). If there are multiple solutions, print any. If no solution exists, print the string IMPOSSIBLE.

NoteIn the first test case, there are $$$n = 5$$$ bottles of wine to be arranged and $$$m = 3$$$ critics. The arrangement RWRRW satisfies the requests of all three critics. Indeed:   the first critic can choose the interval $$$[3, \, 3]$$$, which contains exactly one bottle of red wine (note that $$$[1, \, 1]$$$ and $$$[4, \, 4]$$$ are other valid choices);  the second critic can choose the interval $$$[1, \, 5]$$$, which contains $$$3$$$ bottles of red wine and $$$2$$$ bottles of white wine;  the third critic can choose the interval $$$[2, \, 5]$$$, which contains $$$2$$$ bottles of red wine and $$$2$$$ bottles of white wine.

main = interact $ unlines . solve . map read . tail . words

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

solve [] = []
solve (n:m:xs) = solve_one n (pairs ps) : solve rest
  where (ps, rest) = splitAt (2 * m) xs

solve_one n ps
  | max_r + max_w > n = "IMPOSSIBLE"
  | otherwise = replicate max_r 'R' ++ replicate (n - max_r) 'W'
  where max_r = maximum $ map fst ps
        max_w = maximum $ map snd ps


Frodo was caught by Saruman. He tore a pouch from Frodo's neck, shook out its contents —there was a pile of different rings: gold and silver..."How am I to tell which is the One?!" the mage howled."Throw them one by one into the Cracks of Doom and watch when Mordor falls!" Somewhere in a parallel Middle-earth, when Saruman caught Frodo, he only found $$$n$$$ rings. And the $$$i$$$-th ring was either gold or silver. For convenience Saruman wrote down a binary string $$$s$$$ of $$$n$$$ characters, where the $$$i$$$-th character was 0 if the $$$i$$$-th ring was gold, and 1 if it was silver.Saruman has a magic function $$$f$$$, which takes a binary string and returns a number obtained by converting the string into a binary number and then converting the binary number into a decimal number. For example, $$$f(001010) = 10, f(111) = 7, f(11011101) = 221$$$.Saruman, however, thinks that the order of the rings plays some important role. He wants to find $$$2$$$ pairs of integers $$$(l_1, r_1), (l_2, r_2)$$$, such that: $$$1 \le l_1 \le n$$$, $$$1 \le r_1 \le n$$$, $$$r_1-l_1+1\ge \lfloor \frac{n}{2} \rfloor$$$  $$$1 \le l_2 \le n$$$, $$$1 \le r_2 \le n$$$, $$$r_2-l_2+1\ge \lfloor \frac{n}{2} \rfloor$$$  Pairs $$$(l_1, r_1)$$$ and $$$(l_2, r_2)$$$ are distinct. That is, at least one of $$$l_1 \neq l_2$$$ and $$$r_1 \neq r_2$$$ must hold. Let $$$t$$$ be the substring $$$s[l_1:r_1]$$$ of $$$s$$$, and $$$w$$$ be the substring $$$s[l_2:r_2]$$$ of $$$s$$$. Then there exists non-negative integer $$$k$$$, such that $$$f(t) = f(w) \cdot k$$$.Here substring $$$s[l:r]$$$ denotes $$$s_ls_{l+1}\ldots s_{r-1}s_r$$$, and $$$\lfloor x \rfloor$$$ denotes rounding the number down to the nearest integer.Help Saruman solve this problem! It is guaranteed that under the constraints of the problem at least one solution exists.

Each test contains multiple test cases. The first line contains one positive integer $$$t$$$ ($$$1 \le t \le 10^3$$$), denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^4$$$) — length of the string. The second line of each test case contains a non-empty binary string of length $$$n$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For every test case print four integers $$$l_1$$$, $$$r_1$$$, $$$l_2$$$, $$$r_2$$$, which denote the beginning of the first substring, the end of the first substring, the beginning of the second substring, and the end of the second substring, respectively. If there are multiple solutions, print any.

import Data.List
import Data.Char (digitToInt)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf x l  = take x l : chunksOf x (drop x l)

toArr :: Read a => String -> [a]
toArr = map read . words

type InType  = String
type OutType = ((Int, Int), (Int, Int))

inpLines :: Int
inpLines = 2

solve :: InType -> OutType
solve n
  | null zeroes = ((1, len - 1), (2, len))
  | i > len `div` 2 = ((1, i), (1, i - 1))
  | otherwise = ((i, len), (i + 1, len))
  where
    zeroes = elemIndices '0' n
    len = length n
    i = last zeroes + 1

receive :: [String] -> InType
receive [_, n] = n
receive _   = error "unexpected input"

main :: IO ()
main = interact $
  unlines . map (showAns . solve . receive) . chunksOf inpLines . tail . lines
    where
      showAns ((l1, r1), (l2, r2)) = unwords (map show [l1,r1,l2,r2])

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

count1 :: String -> Int
count1 = foldr (\a b -> if a == '1' then (b+1) else b) 0

calc :: Int -> String -> (Int,Int,Int,Int)
calc l x =
  let m = (l `div` 2)
      index0 = findIndex (\a -> a == '0') x
  in
    case index0 of
      Just k | k < m -> (k+2,l,k+1,l)
      Just k | otherwise -> (1,k+1,1,k)
      Nothing -> (1,l-1,2,l)

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let l = read line :: Int
    line <- getLine
    let (l1,r1,l2,r2) = calc l line
    putStr $ show l1
    putStr " "
    putStr $ show r1
    putStr " "
    putStr $ show l2
    putStr " "
    putStrLn $ show r2

{-# LANGUAGE LambdaCase #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad (replicateM)
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.List
import Data.Maybe

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines

type Input = (Int, String)

type Output = [Int]

input :: Scanner Input
input = pair int str

output :: Output -> C.ByteString
output = C.pack . unwords . map show

solve :: Input -> Output
solve (n, s)
  | isJust iz = let r = h + fromJust iz in [1, r + 1, 1, r]
  | odd n = [h + 2, n, h + 1, n - 1]
  | s !! (h - 1) == '0' = [h + 1, n, h, n]
  | otherwise = [h + 1, n, h, n - 1]
  where
    h = n `div` 2
    iz = elemIndex '0' (drop h s)

-------------------------- Template ------------------------------------------
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

bstr :: Scanner C.ByteString
bstr = get >>= \case s : ss -> put ss >> return s

str :: Scanner String
str = C.unpack <$> bstr

int :: Scanner Int
int = fst . fromJust . C.readInt <$> bstr

integer :: Scanner Integer
integer = read . C.unpack <$> bstr

double :: Scanner Double
double = read . C.unpack <$> bstr

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t
    then return []
    else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show

import Data.List
import Data.Char (digitToInt)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf x l  = take x l : chunksOf x (drop x l)

toArr :: Read a => String -> [a]
toArr = map read . words

type InType  = String
type OutType = ((Int, Int), (Int, Int))

inpLines :: Int
inpLines = 2

solve :: InType -> OutType
solve n
  | null zeroes = ((1, len - 1), (2, len))
  | i - 1 > len `div` 2 = ((1, i), (1, i - 1))
  | otherwise = ((i, len), (i + 1, len))
  where
    zeroes = elemIndices '0' n
    len = length n
    i = last zeroes + 1

receive :: [String] -> InType
receive [_, n] = n
receive _   = error "unexpected input"

main :: IO ()
main = interact $
  unlines . map (showAns . solve . receive) . chunksOf inpLines . tail . lines
    where
      showAns ((l1, r1), (l2, r2)) = unwords (map show [l1,r1,l2,r2])

import Data.List
import Data.Char (digitToInt)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf x l  = take x l : chunksOf x (drop x l)

toArr :: Read a => String -> [a]
toArr = map read . words

type InType  = String
type OutType = ((Int, Int), (Int, Int))

inpLines :: Int
inpLines = 2

solve :: InType -> OutType
solve n
  | null zeroes = ((1, len - 1), (2, len))
  | i > len `div` 2 = ((1, i), (1, i - 1))
  | otherwise = ((i, len), (i + 1, len))
  where
    zeroes = elemIndices '0' n
    len = length n
    i = last zeroes

receive :: [String] -> InType
receive [_, n] = n
receive _   = error "unexpected input"

main :: IO ()
main = interact $
  unlines . map (showAns . solve . receive) . chunksOf inpLines . tail . lines
    where
      showAns ((l1, r1), (l2, r2)) = unwords (map show [l1,r1,l2,r2])


There are $$$n$$$ points on the plane, $$$(x_1,y_1), (x_2,y_2), \ldots, (x_n,y_n)$$$.You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.

First line contains one integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$). Each of the next $$$n$$$ lines contains two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \leq x_i,y_i \leq 10^9$$$).

Print the minimum length of the shorter side of the triangle. It can be proved that it's always an integer.

NoteIllustration for the first example: Illustration for the second example:

f :: (Integer, Integer) -> Integer
f (a, b) = a + b

convert :: [a] -> [(a,a)]
convert [] = []
convert (x1:x2:xs) = (x1,x2):convert xs

main = interact $   (show.maximum.map f.convert.tail.map read.words)

{-# LANGUAGE Safe #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiWayIf #-}

import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Control.Applicative
import Control.Arrow
import Data.List
import Data.Array
import Data.Array.IO.Safe
import Data.Array.ST.Safe
import Data.IORef
import Data.STRef
import Data.Maybe
import Data.Bits
import Data.Ord
import Data.Ratio
import Data.Int
import Data.Char
import qualified Data.IntMap as IM
import qualified Data.ByteString.Char8 as BS
import qualified Data.Set as Set
import qualified Data.Sequence as Sq
import Data.Tuple
import Data.Function
import Text.Printf
--import Debug.Trace
import Numeric

readIntBS = fst . fromJust . BS.readInt

infixr 1 ?
(?) :: Bool -> (a,a) -> a
(?) b t = (if b then fst else snd) t

main = do
  n <- readLn :: IO Int
  ps <- map (map readIntBS . BS.words) . BS.lines <$> BS.getContents :: IO [[Int]]

  let m = maximum [x+y | [x,y] <- ps]

  print $ m

-- Codeforces 1047 B
main :: IO ()
main = do
    n <- getLine >>= return.read :: IO Int
    number <-getContents >>= return.(take n).lines
                         >>= return.map (sum.(map read).words):: IO [Int]
    putStrLn $ show $ maximum number

import Data.List
import Data.Char

f::String->Int
f x=let (a:b:[])=map read (words x)::[Int]
    in a+b

main = do
       e1<-getLine
       es<-getContents
       let xs=lines es
       putStr $ show $ maximum $ map f xs

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

get = fmap fst . mapMaybe C.readInt . C.words <$> C.getLine

main = sol <$> (flip replicateM get =<< readLn) >>= print

sol :: [[Int]] -> Int
sol = maximum . fmap sum

main = interact $ show . solve . pairs . map read . tail . words
pairs (a:b:xs) = (a,b) : pairs xs
pairs [] = []
solve = maximum . map (uncurry (+))

import           Control.Monad

main :: IO ()
main = do
  n <- (read :: String -> Int) <$> getLine
  print =<< maximum . map (sum . map (read :: String -> Int) . words) <$> replicateM n getLine


There are n lights aligned in a row. These lights are numbered 1 to n from left to right. Initially some of the lights are switched on. Shaass wants to switch all the lights on. At each step he can switch a light on (this light should be switched off at that moment) if there's at least one adjacent light which is already switched on. He knows the initial state of lights and he's wondering how many different ways there exist to switch all the lights on. Please find the required number of ways modulo 1000000007 (109 + 7).

The first line of the input contains two integers n and m where n is the number of lights in the sequence and m is the number of lights which are initially switched on, (1 ≤ n ≤ 1000, 1 ≤ m ≤ n). The second line contains m distinct integers, each between 1 to n inclusive, denoting the indices of lights which are initially switched on.

In the only line of the output print the number of different possible ways to switch on all the lights modulo 1000000007 (109 + 7).

import Control.Applicative
import Data.Int
import Data.List

m :: Int64
m = 1000000007

(+%) :: Int64 -> Int64 -> Int64
a +% b = if c >= m then c - m else c
  where
    c = a + b

(*%) :: Int64 -> Int64 -> Int64
a *% b = a * b `mod` m

main :: IO ()
main = do
  n <- read . head . words <$> getLine
  a <- sort . map read . words <$> getLine
  let b = iterate (\i -> i +% i) 1
      c = iterate (\i -> zipWith (+%) (0:i) $ i ++ [0]) [1]
      d = zipWith (\i j -> j - i - 1) (0:a) $ a ++ [n + 1]
      sb = (b!!) $ sum $ map (max 0 . pred) $ init $ tail d
      sc = zipWith (\i j -> c!!j!!i) d $ scanl1 (+) d
  print $ foldl1 (*%) (sb: sc)


You are given $$$n$$$ numbers $$$a_1, a_2, \ldots, a_n$$$. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors?For example, for the array $$$[1, 4, 5, 6, 7, 8]$$$, the arrangement on the left is valid, while arrangement on the right is not, as $$$5\ge 4 + 1$$$ and $$$8> 1 + 6$$$.

The first line contains a single integer $$$n$$$ ($$$3\le n \le 10^5$$$) — the number of numbers. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \leq a_i \le 10^9$$$) — the numbers. The given numbers are not necessarily distinct (i.e. duplicates are allowed).

If there is no solution, output "NO" in the first line.  If there is a solution, output "YES" in the first line. In the second line output $$$n$$$ numbers — elements of the array in the order they will stay in the circle. The first and the last element you output are considered neighbors in the circle. If there are multiple solutions, output any of them. You can print the circle starting with any element.

NoteOne of the possible arrangements is shown in the first example: $$$4< 2 + 3$$$;$$$2 < 4 + 3$$$;$$$3< 4 + 2$$$.One of the possible arrangements is shown in the second example.No matter how we arrange $$$13, 8, 5$$$ in a circle in the third example, $$$13$$$ will have $$$8$$$ and $$$5$$$ as neighbors, but $$$13\ge 8 + 5$$$. There is no solution in the fourth example.

import Control.Monad
import Data.List

input :: Read a => IO [a]
input = map read <$> words <$> getLine

takeOdd [] = []
takeOdd [x] = [x]
takeOdd (x:_:xs) = x:takeOdd xs

takeEven [] = []
takeEven (_:xs) = takeOdd xs

output = putStrLn <$> unwords <$> map show

main = do
  getLine
  a <- input :: IO [Int]
  let s@(x:y:z:_) = reverse $ sort a
  if x >= y + z then
    putStrLn "NO"
  else do
    putStrLn "YES"
    output $ takeEven s ++ reverse (takeOdd s)

{-# LANGUAGE OverloadedStrings #-}

import Data.List
import Data.Char

main = do
  getLine
  str <- getLine
  let ns = map (\n -> (read n) :: Integer) $ words str
  printResult $ findCircle ns

findCircle :: [Integer] -> Maybe [Integer]
findCircle ns =
  let (n1:n2:n3:ns') = reverse (sort ns) in
  let ns'' = n3 : n1 : n2 : ns' in
  if n1 < (n2+n3) then Just ns'' else Nothing

printResult :: Maybe [Integer] -> IO ()
printResult (Just ns) = putStrLn "YES" >> (putStrLn $ unwords $ map show ns)
printResult Nothing = putStrLn "NO"

import Data.List

printInt::Int->IO()
printInt x=do
    putStr(show x)
    putChar(' ')
printArr t=mapM_ printInt t

main::IO()
main=do
    n<-readLn::IO Int
    s<-getLine
    let t=sort((map read (words s))::[Int])
    let last1=t!!(n-1)
    let last2=t!!(n-2)
    let last3=t!!(n-3)
    if(last1>=last2+last3)
    then putStrLn "NO"
    else do
        putStrLn "YES"
        printArr (fst (splitAt (n-3) t))
        printInt last2
        printInt last1
        printInt last3

import Data.List

solve :: [Int] -> Maybe [Int]
solve l
   | a < b + c = Just $ b:a:c:ls
   | otherwise = Nothing
   where a:b:c:ls = reverse . sort $ l

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

fromIntList :: [Int] -> String
fromIntList = unwords . (map show)

main :: IO ()
main = do
    _ <- getLine
    l <- toIntList <$> getLine
    let res = solve l
        out = case res of
                 Just l -> "YES\n" ++ fromIntList l
                 Nothing -> "NO"
    putStrLn out

{-# LANGUAGE OverloadedStrings #-}

import Data.List
import Data.Char

main = do
  _ <- getLine
  str <- getLine
  let ns = map (\n -> (read n) :: Int) $ words str
  printResult $ findCircle ns

findCircle :: [Int] -> Maybe [Int]
findCircle ns =
  let (n1:n2:n3:ns') = reverse (sort ns) in
  let ns'' = n3 : n1 : n2 : ns' in
  if isGood ns'' then Just ns'' else Nothing

isGood :: [Int] -> Bool
isGood (x1:x2:x3:[]) = (x1 < (x2 + x3)) && (x2 < (x1 + x3)) && (x3 < (x1+x2))
isGood (x1:xs) = isGood' x1 xs
isGood' f (x1:x2:[]) = x2 < (x1 + f)
isGood' f (x1:x2:xs) = x2 < (x1 + (head xs)) && isGood' f (x2 : xs)

printResult :: Maybe [Int] -> IO ()
printResult (Just ns) = putStrLn "YES" >> (putStrLn $ unwords $ map show ns)
printResult Nothing = putStrLn "NO"

{-# LANGUAGE OverloadedStrings #-}

import Data.List
import Data.Char

main = do
  getLine
  str <- getLine
  let ns = map (\n -> (read n) :: Integer) $ words str
  printResult $ findCircle ns

findCircle :: [Integer] -> Maybe [Integer]
findCircle ns =
  let (n1:n2:n3:ns') = reverse (sort ns) in
  let ns'' = n3 : n1 : n2 : ns' in
  if n1 >= (n2+n3) then Just ns'' else Nothing

printResult :: Maybe [Integer] -> IO ()
printResult (Just ns) = putStrLn "YES" >> (putStrLn $ unwords $ map show ns)
printResult Nothing = putStrLn "NO"

{-# LANGUAGE OverloadedStrings #-}

import Data.List
import Data.Char

main = do
  _ <- getLine
  str <- getLine
  let ns = map (digitToInt . head) $ words str
  printResult $ findCircle ns

findCircle :: [Int] -> Maybe [Int]
findCircle ns =
  let (n1:n2:n3:ns') = reverse (sort ns) in
  let ns'' = n3 : n1 : n2 : ns' in
  if isGood ns'' then Just ns'' else Nothing

isGood :: [Int] -> Bool
isGood (x1:xs) = isGood' x1 xs
isGood' f (x1:x2:[]) = x2 < (x1 + f)
isGood' f (x1:x2:xs) = x2 < (x1 + (head xs)) && isGood' f (x2 : xs)

printResult :: Maybe [Int] -> IO ()
printResult (Just ns) = putStrLn "YES" >> (putStrLn $ foldr (\n str -> (intToDigit n) : str) [] ns)
printResult Nothing = putStrLn "NO"

{-# LANGUAGE OverloadedStrings #-}

import Data.List
import Data.Char

main = do
  _ <- getLine
  str <- getLine
  let ns = map (\n -> (read n) :: Int) $ words str
  printResult $ findCircle ns

findCircle :: [Int] -> Maybe [Int]
findCircle ns =
  let (n1:n2:n3:ns') = reverse (sort ns) in
  let ns'' = n3 : n1 : n2 : ns' in
  if isGood ns'' then Just ns'' else Nothing

isGood :: [Int] -> Bool
isGood (x1:xs) = isGood' x1 xs
isGood' f (x1:x2:[]) = x2 < (x1 + f)
isGood' f (x1:x2:xs) = x2 < (x1 + (head xs)) && isGood' f (x2 : xs)

printResult :: Maybe [Int] -> IO ()
printResult (Just ns) = putStrLn "YES" >> (putStrLn $ unwords $ map show ns)
printResult Nothing = putStrLn "NO"

{-# LANGUAGE OverloadedStrings #-}

import Data.List
import Data.Char

main = do
  _ <- getLine
  str <- getLine
  let ns = map (digitToInt . head) $ words str
  printResult $ findCircle ns

findCircle :: [Int] -> Maybe [Int]
findCircle ns =
  let (n1:n2:n3:ns') = reverse (sort ns) in
  let ns'' = n3 : n1 : n2 : ns' in
  if isGood ns'' then Just ns'' else Nothing

isGood :: [Int] -> Bool
isGood (x1:xs) = isGood' x1 xs
isGood' f (x1:x2:[]) = x2 < (x1 + f)
isGood' f (x1:x2:xs) = x2 < (x1 + (head xs)) && isGood' f (x2 : xs)

printResult :: Maybe [Int] -> IO ()
printResult (Just ns) = putStrLn "YES" >> (putStrLn $ foldr (\n str -> (intToDigit n) : ' ' : str) [] ns)
printResult Nothing = putStrLn "NO"


Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan.

The first line of input contains a positive integer n (1 ≤ n ≤ 1 500) — the length of the garland. The second line contains n lowercase English letters s1s2... sn as a string — the initial colours of paper pieces on the garland. The third line contains a positive integer q (1 ≤ q ≤ 200 000) — the number of plans Nadeko has. The next q lines describe one plan each: the i-th among them contains an integer mi (1 ≤ mi ≤ n) — the maximum amount of pieces to repaint, followed by a space, then by a lowercase English letter ci — Koyomi's possible favourite colour.

Output q lines: for each work plan, output one line containing an integer — the largest Koyomity achievable after repainting the garland according to it.

15
yamatonadeshiko
10
1 a
2 a
3 a
4 a
5 a
1 b
2 b
3 b
4 b
5 b

NoteIn the first sample, there are three plans:   In the first plan, at most 1 piece can be repainted. Repainting the "y" piece to become "o" results in "kooomi", whose Koyomity of 3 is the best achievable;  In the second plan, at most 4 pieces can be repainted, and "oooooo" results in a Koyomity of 6;  In the third plan, at most 4 pieces can be repainted, and "mmmmmi" and "kmmmmm" both result in a Koyomity of 5.

{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.Maybe
import Data.List
import Data.Array.Unboxed

readInt = (fromIntegral . fst) . fromJust . B.readInt
readInts = (readInt <$>) . B.words

{-# NOINLINE [1] mscanl' #-}
mscanl' = scanlGo'
  where
    scanlGo' f !q ls    = q : (case ls of
                            []   -> []
                            x:xs -> scanlGo' f (f q x) xs)

build :: Int -> String -> Char -> UArray Int Int
build n s c = listArray (0, n) $ tail $ mscanl' max 0 $ (elems :: UArray Int Int -> [Int])  $ accumArray max 0 (0, n) $ ((flip zip [1..] . tail . mscanl' (\a x -> a + fromEnum (x /= c)) 0) =<<) $ tails s

solve :: Int -> String -> [(Int, Char)] -> [Int]
solve n s = map (\(m, c) -> tbl!c!m)
  where
    bnd = ('a', 'z')
    tbl = listArray bnd $ map (build n s) $ range bnd :: Array Char (UArray Int Int)

main = do
  n <- readInt <$> B.getLine
  s <- getLine
  k <- readInt <$> B.getLine
  qs <- replicateM k ((\(m:c:_) -> (readInt m, B.head c)) . B.words <$> B.getLine)
  mapM_ print $ solve n s qs


You are given a permutation $$$p_1, p_2, \dots, p_n$$$. Then, an undirected graph is constructed in the following way: add an edge between vertices $$$i$$$, $$$j$$$ such that $$$i < j$$$ if and only if $$$p_i > p_j$$$. Your task is to count the number of connected components in this graph.Two vertices $$$u$$$ and $$$v$$$ belong to the same connected component if and only if there is at least one path along edges connecting $$$u$$$ and $$$v$$$.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the elements of the permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print one integer $$$k$$$ — the number of connected components.

NoteEach separate test case is depicted in the image below. The colored squares represent the elements of the permutation. For one permutation, each color represents some connected component. The number of distinct colors is the answer.

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

solve :: IO ()
solve = readInts >> readInts >>=
    print . length . filter id . zipWith (==) [1..] . scanl1 max

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

main :: IO ()
main = flip replicateM_ solve . head =<< readInts

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

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

import qualified Data.Set as Set

mainFun :: SP Builder
mainFun = do
  t <- getInt
  fmap mconcat $ replicateM t $ do
    n <- getInt
    p <- replicateM n getInt
    let
      ss = scanl' (flip Set.insert) (Set.singleton 0) p
      oks = [() | v <- ss, Set.size v == Set.findMax v + 1]
    pure $ putInts [length oks - 1]

type SP = State P.ByteString
type S = StateT P.ByteString

dropSpace :: P.ByteString -> P.ByteString
dropSpace = P.dropWhile (<= ' ') -- not exactly right, but close enough

--getNext :: Monad m => S m P.ByteString
--getNext = state $ P.span (> ' ') . dropSpace

getInt :: Monad m => S m Int
getInt = state $ fromJust . P.readInt . dropSpace

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

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


You are given a set of all integers from $$$l$$$ to $$$r$$$ inclusive, $$$l < r$$$, $$$(r - l + 1) \le 3 \cdot 10^5$$$ and $$$(r - l)$$$ is always odd.You want to split these numbers into exactly $$$\frac{r - l + 1}{2}$$$ pairs in such a way that for each pair $$$(i, j)$$$ the greatest common divisor of $$$i$$$ and $$$j$$$ is equal to $$$1$$$. Each number should appear in exactly one of the pairs.Print the resulting pairs or output that no solution exists. If there are multiple solutions, print any of them.

If any solution exists, print "YES" in the first line. Each of the next $$$\frac{r - l + 1}{2}$$$ lines should contain some pair of integers. GCD of numbers in each pair should be equal to $$$1$$$. All $$$(r - l + 1)$$$ numbers should be pairwise distinct and should have values from $$$l$$$ to $$$r$$$ inclusive. If there are multiple solutions, print any of them. If there exists no solution, print "NO".

{-# LANGUAGE Safe #-}

import Control.Applicative
import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as BS
import Data.Maybe
import Text.Printf

readIntBS = fst . fromJust . BS.readInt

main = do
  [l,r] <- map read . words <$> getLine :: IO [Integer]

  putStrLn "YES"
  forM_ (slice 2 [l..r]) $ \[i,j] -> do
    printf "%d %d\n" i j

slice _ [] = []
slice n xs = take n xs : slice n (drop n xs)

{-# LANGUAGE Safe #-}

import Control.Applicative
import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as BS
import Data.Maybe
import Text.Printf

readIntBS = fst . fromJust . BS.readInt

main = do
  [l,r] <- map read . words <$> getLine :: IO [Int]

  putStrLn "YES"
  forM_ (slice 2 [l..r]) $ \[i,j] -> do
    printf "%d %d\n" i j

slice _ [] = []
slice n xs = take n xs : slice n (drop n xs)


Vasya often uses public transport. The transport in the city is of two types: trolleys and buses. The city has n buses and m trolleys, the buses are numbered by integers from 1 to n, the trolleys are numbered by integers from 1 to m.Public transport is not free. There are 4 types of tickets:   A ticket for one ride on some bus or trolley. It costs c1 burles;  A ticket for an unlimited number of rides on some bus or on some trolley. It costs c2 burles;  A ticket for an unlimited number of rides on all buses or all trolleys. It costs c3 burles;  A ticket for an unlimited number of rides on all buses and trolleys. It costs c4 burles. Vasya knows for sure the number of rides he is going to make and the transport he is going to use. He asked you for help to find the minimum sum of burles he will have to spend on the tickets.

The first line contains four integers c1, c2, c3, c4 (1 ≤ c1, c2, c3, c4 ≤ 1000) — the costs of the tickets. The second line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of buses and trolleys Vasya is going to use. The third line contains n integers ai (0 ≤ ai ≤ 1000) — the number of times Vasya is going to use the bus number i. The fourth line contains m integers bi (0 ≤ bi ≤ 1000) — the number of times Vasya is going to use the trolley number i.

Print a single number — the minimum sum of burles Vasya will have to spend on the tickets.

NoteIn the first sample the profitable strategy is to buy two tickets of the first type (for the first bus), one ticket of the second type (for the second bus) and one ticket of the third type (for all trolleys). It totals to (2·1) + 3 + 7 = 12 burles.In the second sample the profitable strategy is to buy one ticket of the fourth type.In the third sample the profitable strategy is to buy two tickets of the third type: for all buses and for all trolleys.

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

main = do
	[ [ c1, c2, c3, c4 ] , _, as, bs ] <- replicateM 4 $ do
		map read . words <$> getLine

	let
		f a = min ( c1 * a ) c2

	print $ minimum [ c4, c3 * 2, min c3 ( sum ( map f as ) ) + min c3 ( sum ( map f bs ) ) ]

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

main = do
	[ [ c1, c2, c3, c4 ] , _, as, bs ] <- replicateM 4 $ do
		map read . words <$> getLine

	let
		f a = min ( c1 * a ) c2

	print $ minimum [ c4, c3 * 2, c3 + sum ( map f as ) , c3 + sum ( map f bs ), sum ( map f as ) + sum ( map f bs ) ]

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

main = do
	[ [ c1, c2, c3, c4 ] , _, as, bs ] <- replicateM 4 $ do
		map read . words <$> getLine

	let
		f a = min ( c1 * a ) c2

	print $ min c4 $ min c3 ( sum ( map f as ) ) + min c3 ( sum ( map f bs ) )

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

solve :: [Int] -> [Int] -> [Int] -> Int
solve [c1, c2, c3, c4] as ts  =  min c4 (min as' c3 + min ts' c3)
  where
    as'  =  sum $ map (\a -> min (a * c1) c2) as
    ts'  =  sum $ map (\t -> min (t * c1) c2) ts

main :: IO ()
main  =  do
    cs  <-  reads
    getLine
    as  <-  reads
    ts  <-  reads
    print $ solve cs as ts

  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

import Control.Applicative

solve :: [Int] -> Int -> Int -> [Int] -> [Int] -> Int
solve (c1:(c2:(c3:[c4]))) n m a1 a2
  = min c4 (optimal1 + optimal2)
    where
      optimal1 = min c3 ( sum $ map get_better a1 )
      optimal2 = min c3 ( sum $ map get_better a2 )

      get_better x = min (x*c1) c2

main :: IO ()
main = do
  lin1 <- getLine
  let costs = map read (words lin1)

  [n,m] <- map read <$> words <$> getLine

  a1 <- map read <$> words <$> getLine
  a2 <- map read <$> words <$> getLine

  print $ solve costs n m a1 a2

minNum k n
	| n == 0 && k == 1 = 0
	| n == 0 = -1
	| otherwise = (10 ^ (k-1) ) + (n-1)

find x
	| x>=0  = show x
	| otherwise = "No solution"

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

cal :: [Int] -> [Int] -> [Int] -> Int
cal cs bs ts =
	let c4 = cs !! 3
	in
	  min c4 $ (cal1 cs bs) + (cal1 cs ts)

cal1::  [Int] -> [Int] -> Int
cal1 cs bs =
	let c3 = cs !! 2
	in
	  min c3 $ foldl1 (+) $ (cal2 cs bs)

cal2::  [Int] -> [Int] -> [Int]
cal2 cs bs =
	let c1 = cs !! 0
	    c2 = cs !! 1
	in map (\x -> min (c1 * x) c2 ) bs

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

multa :: [Int] -> Int -> [Int]
multa list a = [a * x | x <- list]

minlista :: [Int] -> Int -> [Int]
minlista list a = [min a x | x <- list]

getans :: [Int] -> [Int] -> [Int] -> Int
getans bs tr (c1:c2:c3:c4:_) = min c4 ((min (sum (minlista (multa bs c1) c2)) c3) + min (sum (minlista (multa tr c1) c2)) c3)

main = do
	c14 <- getLine
	nm <- getLine
	buses <- getLine
	trolley <- getLine
	putStr $ show $ getans (map read (words buses)) (map read (words trolley)) (map read (words c14))


Reading books is one of Sasha's passions. Once while he was reading one book, he became acquainted with an unusual character. The character told about himself like that: "Many are my names in many countries. Mithrandir among the Elves, Tharkûn to the Dwarves, Olórin I was in my youth in the West that is forgotten, in the South Incánus, in the North Gandalf; to the East I go not."And at that moment Sasha thought, how would that character be called in the East? In the East all names are palindromes. A string is a palindrome if it reads the same backward as forward. For example, such strings as "kazak", "oo" and "r" are palindromes, but strings "abb" and "ij" are not. Sasha believed that the hero would be named after one of the gods of the East. As long as there couldn't be two equal names, so in the East people did the following: they wrote the original name as a string on a piece of paper, then cut the paper minimum number of times $$$k$$$, so they got $$$k+1$$$ pieces of paper with substrings of the initial string, and then unite those pieces together to get a new string. Pieces couldn't be turned over, they could be shuffled.In this way, it's possible to achive a string abcdefg from the string f|de|abc|g using $$$3$$$ cuts (by swapping papers with substrings f and abc). The string cbadefg can't be received using the same cuts.More formally, Sasha wants for the given palindrome $$$s$$$ find such minimum $$$k$$$, that you can cut this string into $$$k + 1$$$ parts, and then unite them in such a way that the final string will be a palindrome and it won't be equal to the initial string $$$s$$$. It there is no answer, then print "Impossible" (without quotes).

The first line contains one string $$$s$$$ ($$$1 \le |s| \le 5\,000$$$) — the initial name, which consists only of lowercase Latin letters. It is guaranteed that $$$s$$$ is a palindrome.

Print one integer $$$k$$$ — the minimum number of cuts needed to get a new name, or "Impossible" (without quotes).

NoteIn the first example, you can cut the string in those positions: no|l|on, and then unite them as follows on|l|no. It can be shown that there is no solution with one cut.In the second example, you can cut the string right in the middle, and swap peaces, so you get toot.In the third example, you can't make a string, that won't be equal to the initial one.In the fourth example, you can cut the suffix nik and add it to the beginning, so you get nikkinnikkin.

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

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 Data.IntSet (IntSet)
import qualified Data.IntSet as IS
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
import System.IO
import System.Exit
import Data.Char

main :: IO ()
main = do
  s <- BS.takeWhile isLower <$> BS.getLine
  let len = BS.length s
      s0 = BS.head s
  putStrLn
    $ if | BS.all (== s0) (BS.take (shiftR len 1) s) -> "Impossible"
         | isPossibleWith1 (BS.append s s) len -> "1"
         | otherwise -> "2"

isPossibleWith1 :: BS.ByteString -> Int -> Bool
isPossibleWith1 ss len =
  any (\p -> p /= s && all (\i -> BS.index p i == BS.index p (len-i-1))
                         [0..shiftR (len+1) 1]) perms
  where
    s = BS.take len ss
    perms = map (BS.take len) $ takeWhile ((>len).BS.length)
            $ BS.tails $ BS.tail ss

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')

#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read
#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define N(f,g,a,m)\
  f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\
  g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_
#define C(a,m)
N(newIOA,newIOA_,IOArray,IO)
N(newSTA,newSTA_,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,IOUArray,IO)
N(newSTUA,newSTUA_,STUArray s,ST s)
#undef C
#undef N

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

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 Data.IntSet (IntSet)
import qualified Data.IntSet as IS
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
import System.IO
import System.Exit
import Data.Char

main :: IO ()
main = do
  s <- BS.takeWhile isLower <$> BS.getLine
  let len = BS.length s
      s0 = BS.head s
  putStrLn
    $ if | BS.all (== s0) (BS.take (shiftL len 1) s) -> "Impossible"
         | isPossibleWith1 (BS.append s s) len -> "1"
         | otherwise -> "2"

isPossibleWith1 :: BS.ByteString -> Int -> Bool
isPossibleWith1 ss len =
  any (\p -> p /= s && all (\i -> BS.index p i == BS.index p (len-i-1))
                         [0..shiftR (len+1) 1]) perms
  where
    s = BS.take len ss
    perms = map (BS.take len) $ takeWhile ((>len).BS.length)
            $ BS.tails $ BS.tail ss

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')

#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read
#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define N(f,g,a,m)\
  f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\
  g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_
#define C(a,m)
N(newIOA,newIOA_,IOArray,IO)
N(newSTA,newSTA_,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,IOUArray,IO)
N(newSTUA,newSTUA_,STUArray s,ST s)
#undef C
#undef N

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

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 Data.IntSet (IntSet)
import qualified Data.IntSet as IS
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
import System.IO
import System.Exit
import Data.Char

main :: IO ()
main = do
  s <- BS.takeWhile isLower <$> BS.getLine
  putStrLn $ if | BS.all (== BS.head s) s -> "Impossible"
                | isPossibleWith1 (BS.append s s) (BS.length s) -> "1"
                | otherwise -> "2"

isPossibleWith1 :: BS.ByteString -> Int -> Bool
isPossibleWith1 ss len =
  any (\p -> p /= s && all (\i -> BS.index p i == BS.index p (len-i-1))
                         [0..shiftR (len+1) 1]) perms
  where
    s = BS.take len ss
    perms = map (BS.take len) $ takeWhile ((>len).BS.length)
            $ BS.tails $ BS.tail ss

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')

#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read
#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

#define N(f,g,a,m)\
  f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\
  g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_
#define C(a,m)
N(newIOA,newIOA_,IOArray,IO)
N(newSTA,newSTA_,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,IOUArray,IO)
N(newSTUA,newSTUA_,STUArray s,ST s)
#undef C
#undef N


You are given two strings $$$A$$$ and $$$B$$$ representing essays of two students who are suspected cheaters. For any two strings $$$C$$$, $$$D$$$ we define their similarity score $$$S(C,D)$$$ as $$$4\cdot LCS(C,D) - |C| - |D|$$$, where $$$LCS(C,D)$$$ denotes the length of the Longest Common Subsequence of strings $$$C$$$ and $$$D$$$. You believe that only some part of the essays could have been copied, therefore you're interested in their substrings.Calculate the maximal similarity score over all pairs of substrings. More formally, output maximal $$$S(C, D)$$$ over all pairs $$$(C, D)$$$, where $$$C$$$ is some substring of $$$A$$$, and $$$D$$$ is some substring of $$$B$$$. If $$$X$$$ is a string, $$$|X|$$$ denotes its length.A string $$$a$$$ is a substring of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters. Pay attention to the difference between the substring and subsequence, as they both appear in the problem statement. You may wish to read the Wikipedia page about the Longest Common Subsequence problem.

The first line contains two positive integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 5000$$$) — lengths of the two strings $$$A$$$ and $$$B$$$.  The second line contains a string consisting of $$$n$$$ lowercase Latin letters — string $$$A$$$. The third line contains a string consisting of $$$m$$$ lowercase Latin letters — string $$$B$$$.

Output maximal $$$S(C, D)$$$ over all pairs $$$(C, D)$$$, where $$$C$$$ is some substring of $$$A$$$, and $$$D$$$ is some substring of $$$B$$$.

NoteFor the first case:abb from the first string and abab from the second string have LCS equal to abb.The result is $$$S(abb, abab) = (4 \cdot |abb|$$$) - $$$|abb|$$$ - $$$|abab|$$$ = $$$4 \cdot 3 - 3 - 4 = 5$$$.

import Data.List

findMax :: String -> String -> [[Int]]
findMax a b = scanl' byA (replicate (1 + length b) 0) a
  where byA r c = scanl' byB 0 $ zip3 b r $ tail r
          where byB l (d, ul, u) = let mx = max 0 $ max (u-1) (l-1)
                                   in if c == d then max mx (ul+2) else mx

solve :: String -> String
solve input = show $ maximum $ map maximum $ findMax a b
  where (_:a:b:_) = lines input

main = interact solve

findMax :: String -> String -> [[Int]]
findMax a b = scanl byA [0 | _ <- [0..length b]] a
  where byA r c = scanl byB 0 $ zip3 b r $ tail r
          where byB l (d, ul, u) = let mx = max 0 $ max (u-1) (l-1)
                                   in if c == d then max mx (ul+2) else mx

solve :: String -> String
solve input = show $ maximum $ map maximum $ findMax a b
  where (_:a:b:_) = lines input

main = interact solve

findMax :: String -> String -> [[Int]]
findMax a b = scanl byA (replicate (1 + length b) 0) a
  where byA r c = scanl byB 0 $ zip3 b r $ tail r
          where byB l (d, ul, u) = let mx = max 0 $ max (u-1) (l-1)
                                   in if c == d then max mx (ul+2) else mx

solve :: String -> String
solve input = show $ maximum $ map maximum $ findMax a b
  where (_:a:b:_) = lines input

main = interact solve

import Data.List

findMax :: String -> String -> [[Int]]
findMax a b = scanl' byA [0 | _ <- [0..length b]] a
  where byA r c = scanl' byB 0 $ zip3 b r $ tail r
          where byB l (d, ul, u) = let mx = max 0 $ max (u-1) (l-1)
                                   in if c == d then max mx (ul+2) else mx

solve :: String -> String
solve input = show $ maximum $ map maximum $ findMax a b
  where (_:a:b:_) = lines input

main = interact solve

makeS :: String -> String -> [[Int]]
makeS a b = scanl byA [0 | _ <- [0..length b]] a
  where byA r c = scanl byB 0 $ zip3 b r $ init r
          where byB l (d, u, ul) = let mx = maximum [0, l-1, u-1]
                                   in if c == d then max mx (ul+2) else mx

solve :: String -> String
solve input = show $ maximum $ concat $ makeS a b
  where (_:a:b:_) = lines input

main = interact solve

import Data.List

findMax :: String -> String -> [[Int]]
findMax a b = scanl' byA (replicate (1 + length b) 0) a
  where byA r c = scanl' byB 0 $ zip3 b r $ tail r
          where byB l (d, ul, u) = let mx = max 0 $ max (u-10) (l-1)
                                   in if c == d then max mx (ul+2) else mx

solve :: String -> String
solve input = show $ maximum $ map maximum $ findMax a b
  where (_:a:b:_) = lines input

main = interact solve


Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this angle. As you spend lots of time "glued to the screen", your vision is impaired. So you have to write a program that will pass the check for you.

The first line contains a single integer n (1 ≤ n ≤ 105) — the number of mannequins. Next n lines contain two space-separated integers each: xi, yi (|xi|, |yi| ≤ 1000) — the coordinates of the i-th mannequin. It is guaranteed that the origin of the coordinates has no mannequin. It is guaranteed that no two mannequins are located in the same point on the plane.

Print a single real number — the value of the sought angle in degrees. The answer will be considered valid if the relative or absolute error doesn't exceed 10 - 6.

NoteSolution for the first sample test is shown below:   Solution for the second sample test is shown below:   Solution for the third sample test is shown below:   Solution for the fourth sample test is shown below:

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

pairs :: [a] -> [(a, a)]
pairs (x:y:z) = (x, y): pairs z
pairs _ = []

main :: IO ()
main = do
  (n:p) <- fmap (map (fst . fromJust . C.readInt) . C.words) C.getContents
  let a@(h:t) = sort $ map (uncurry atan2) $ take n $ pairs $ map fromIntegral p
      b = maximum $ zipWith (-) (t ++ [h + 2 * pi]) a :: Double
  print $ 360 - 180 / pi * b

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

main = putStrLn . show . solve . tail . map (toEnum . maybe 0 fst . B.readInt) . B.words =<< B.getContents

solve :: [Double] -> Double
solve cs = 360 - maximum (zipWith (-) (ts ++ [360 + t]) (t : ts))
  where
  (t : ts) = sort $ theta cs

theta :: [Double] -> [Double]
theta (x : y : cs) = t : theta cs
  where
  l = sqrt $ x * x + y * y
  t' = acos (x / l) * 180 / pi
  t = if y >= 0 then t' else 360 - t'
theta _ = []

import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as B
import qualified Data.List as L
import qualified Data.Array as A

main :: IO ()
main = do
    n <- B.getLine >>= return . fst . fromMaybe (0,B.empty) . B.readInt
    l <- replicateM n (B.getLine >>= return . fromMaybe (0,0). readXY)
    print $ solve n l
    where
        readXY :: B.ByteString -> Maybe (Int,Int)
        readXY str = do
            (x,s1) <- B.readInt str
            (y,s2) <- B.readInt (B.tail s1)
            return (x,y)

solve :: Int -> [(Int,Int)] -> Double
solve n l = 360 - maxDiffAngle
    where
        ary = A.listArray (0,n) (L.sort . L.map angle $ l)
        maxDiffAngle = loop 0 0
        loop i angle | i == n-1  = max (ary A.! 0 - ary A.! (n-1) + 360) angle
                     | otherwise = loop (i+1) (max (ary A.! (i+1) - ary A.! i) angle)

angle :: (Int,Int) -> Double
angle (0,0) = 0
angle (x,y) =
    case (x'>0,y'>0) of
        (True,True)  -> toDegree (asin (y'/d))
        (False,True) -> toDegree (acos (x'/d))
        (True,False) -> toDegree (asin (y'/d)) + 360
        (False,False) -> toDegree (asin (-y'/d)) + 180
    where
        x' = fromIntegral x
        y' = fromIntegral y
        d  = sqrt ( x' * x' + y' * y')

toDegree :: Double -> Double
toDegree x = x * 180 / pi

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

get_points [] = []
get_points (x:y:remain) = (x,y): get_points remain

main = do
	ct <- C.getContents
	let
		(n:p) = map (fst.fromJust.C.readInt) $ C.words ct
	print $ solve $  get_points $ map fromIntegral p

solve :: (RealFloat a) => [(a,a)] -> a
solve p =
	let
		all@(h:t) = sort $ map (uncurry atan2) p
		res = maximum $ zipWith (-) (t ++ [2*pi+h]) all
	in
		360 - 180/pi*res

import qualified Data.ByteString.Char8 as B

main = putStrLn . show . solve . tail . map (toEnum . maybe 0 fst . B.readInt) . B.words =<< B.getContents

solve :: [Double] -> Double
solve cs = 360 - maximum (zipWith (-) (ts ++ [360 + t]) (t : ts))
  where
  (t : ts) = theta cs

theta :: [Double] -> [Double]
theta (x : y : cs) = t : theta cs
  where
  l = sqrt $ x * x + y * y
  t' = acos (x / l) * 180 / pi
  t = if y >= 0 then t' else 360 - t'
theta _ = []


As you know, all the kids in Berland love playing with cubes. Little Petya has n towers consisting of cubes of the same size. Tower with number i consists of ai cubes stacked one on top of the other. Petya defines the instability of a set of towers as a value equal to the difference between the heights of the highest and the lowest of the towers. For example, if Petya built five cube towers with heights (8, 3, 2, 6, 3), the instability of this set is equal to 6 (the highest tower has height 8, the lowest one has height 2). The boy wants the instability of his set of towers to be as low as possible. All he can do is to perform the following operation several times: take the top cube from some tower and put it on top of some other tower of his set. Please note that Petya would never put the cube on the same tower from which it was removed because he thinks it's a waste of time. Before going to school, the boy will have time to perform no more than k such operations. Petya does not want to be late for class, so you have to help him accomplish this task.

The first line contains two space-separated positive integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 1000) — the number of towers in the given set and the maximum number of operations Petya can perform. The second line contains n space-separated positive integers ai (1 ≤ ai ≤ 104) — the towers' initial heights.

In the first line print two space-separated non-negative integers s and m (m ≤ k). The first number is the value of the minimum possible instability that can be obtained after performing at most k operations, the second number is the number of operations needed for that. In the next m lines print the description of each operation as two positive integers i and j, each of them lies within limits from 1 to n. They represent that Petya took the top cube from the i-th tower and put in on the j-th one (i ≠ j). Note that in the process of performing operations the heights of some towers can become equal to zero. If there are multiple correct sequences at which the minimum possible instability is achieved, you are allowed to print any of them.

NoteIn the first sample you need to move the cubes two times, from the second tower to the third one and from the second one to the first one. Then the heights of the towers are all the same and equal to 6.

import Data.List
import Data.Function
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B

getIntArray :: B.ByteString -> [Int]
getIntArray = map fst . mapMaybe B.readInt . B.words

main = interact $ unlines . map (unwords . map show) . getAns . map read . words

getAns :: [Int] -> [[Int]]
getAns (n:k:xs) = let ans = move (zip xs [1..n]) k
				  in ([head $ last ans, length ans - 1]) : (init ans)

getIsb :: [(Int, Int)] -> Int
getIsb xs = (fst $ maximum xs) - (fst $ minimum xs)

move :: [(Int, Int)] -> Int -> [[Int]]
move xs 0 = [[getIsb xs, 0]]
move xs k
	| isb <= 1 = [[isb, 0]]
	| otherwise = let sx = sort xs;
					  (hi, hv) = head sx;
					  (ti, tv) = last sx;
					  nx = (hi + 1, hv ) : ((tail $ init sx) ++ [(ti - 1, tv)]);
					  pans = move nx (k - 1);
				  in [tv, hv] : pans
	where isb = getIsb xs

import Data.Array

import Data.List
import GHC.Exts
import Data.Set hiding (map)

--type tower = Set (Int,Int)

--next :: tower -> (tower,[Int])
next t = Just ([hi-hj,i,j],t3) where
   ((hi,i),t1) = deleteFindMax t
   ((hj,j),t2) = deleteFindMin t1
   t3 = Data.Set.insert (hi-1,i) $ Data.Set.insert (hj+1,j) t2

solve (1:_) = [[0,0]]
solve (_:k:l) = [s!!n!!0,n]:map tail s' where
  s =  unfoldr next $ fromList $ l `zip` [1..]
  s' =  takeWhile ((>1).(!!0)) $ take k s
  n = length s'

main = interact $ unlines . map (unwords . map show) . solve . map read . words

import Data.List (intercalate)

minimumInstability :: [Float] -> Int
minimumInstability xs = (ceiling d) - (floor d)
    where (s, n) = (sum xs, length xs)
          d = s / (fromIntegral) n

findMs :: [Int] -> ((Int, Int), (Int, Int)) -> Int -> ((Int, Int), (Int, Int))
findMs (x : xs) res@((resmaxn, resmaxv), (resminn, resminv)) k
    | x > resmaxv = findMs xs ((k, x), (resminn, resminv)) (k + 1)
    | x < resminv = findMs xs ((resmaxn, resmaxv), (k, x)) (k + 1)
    | otherwise = findMs xs res (k + 1)
findMs _ res _ = res

move :: [Int] -> Int -> Int -> [Int]
move (x:xs) nmin nmax
    | nmin == 1 && nmax == 1 = x:xs
    | nmin == 1 = (x+1) : (move xs (nmin - 1) (nmax - 1))
    | nmax == 1 = (x-1) : (move xs (nmin - 1) (nmax - 1))
    | nmin < 1 && nmax < 1 = x:xs
    | otherwise = x : (move xs (nmin - 1) (nmax - 1))
move _ _ _ = []

towers :: Int -> Int -> [Int] -> [(Int, Int)]
towers k steps all@(x:xs)
    | k == 0 = [(instability, steps)]
    | minimumInstability (map fromIntegral all) == instability = [(instability, steps)]
    | otherwise = (i, j) : (towers (k-1) (steps + 1) ys)
        where instability = vmax - vmin
              ((nmax, vmax), (nmin, vmin)) = findMs xs ((1,x), (1,x)) 2
              (i, j) = (nmax, nmin)
              ys = move all nmin nmax

output :: [(Int, Int)] -> String
output xs = intercalate "\n" $ map (\(x, y) -> intercalate " " [show x, show y]) (last xs : init xs)

main = do
    [n, k] <- fmap words $ getLine
    getLine >>= putStrLn . output . (towers (read k) 0) . fmap read . words

import Data.Array

import Data.List
import GHC.Exts
import Data.Set hiding (map)

--type tower = Set (Int,Int)

--next :: tower -> (tower,[Int])
next t = Just ([hi-hj,i,j],t3) where
   ((hi,i),t1) = deleteFindMax t
   ((hj,j),t2) = deleteFindMin t1
   t3 = Data.Set.insert (hi-1,i) $ Data.Set.insert (hj+1,j) t2

solve (_:k:l) = [s!!k!!0,k]:map tail (take k s) where s = unfoldr next $ fromList $ l `zip` [1..]

main = interact $ unlines . map (unwords . map show) . solve . map read . words


Ridbit starts with an integer $$$n$$$.In one move, he can perform one of the following operations:   divide $$$n$$$ by one of its proper divisors, or  subtract $$$1$$$ from $$$n$$$ if $$$n$$$ is greater than $$$1$$$. A proper divisor is a divisor of a number, excluding itself. For example, $$$1$$$, $$$2$$$, $$$4$$$, $$$5$$$, and $$$10$$$ are proper divisors of $$$20$$$, but $$$20$$$ itself is not.What is the minimum number of moves Ridbit is required to make to reduce $$$n$$$ to $$$1$$$?

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 1000$$$) — the number of test cases. The only line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^9$$$).

For each test case, output the minimum number of moves required to reduce $$$n$$$ to $$$1$$$.

NoteFor the test cases in the example, $$$n$$$ may be reduced to $$$1$$$ using the following operations in sequence$$$1$$$$$$2 \xrightarrow{} 1$$$$$$3 \xrightarrow{} 2 \xrightarrow{} 1$$$$$$4 \xrightarrow{} 2 \xrightarrow{} 1$$$$$$6 \xrightarrow{} 2 \xrightarrow{} 1$$$$$$9 \xrightarrow{} 3 \xrightarrow{} 2\xrightarrow{} 1$$$

import Control.Arrow ((>>>))

main :: IO ()
main = interact $ words >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines

solve :: Int -> Int
solve n
  | n <= 3 = n - 1
  | even n = 2
  | odd n = 3

{-# LANGUAGE FlexibleInstances, UndecidableInstances, DuplicateRecordFields #-}

module Main where

import Control.Monad
import System.IO

calculate 1 = 0
calculate 2 = 1
calculate 3 = 2
calculate 4 = 2
calculate n
    | (mod n 2) == 1 = 3
    | otherwise = 2

main :: IO()
main = do
    t <- readLn :: IO Int
    forM_ [1..t] $ \t_itr -> do
        nmsTemp <- getLine
        let nms = words nmsTemp
        let n = read (nms !! 0) :: Int
        let result = calculate n
        putStrLn(show result)

{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}

import qualified Data.ByteString.Char8 as B8
import Text.Printf
import Data.Functor ( (<&>) )
import Control.Arrow ((>>>))
import Control.Monad (forM_)
import Data.Maybe (fromJust)
import Data.Traversable (forM)
import qualified Control.Monad.State.Strict as S
import qualified Data.IntMap as IM
import Control.Monad (foldM_)
import Data.Int

readIntB8 :: B8.ByteString -> Maybe Int
readIntB8 = B8.readInt >>> fmap fst

solve :: [Int] -> [Int]
solve = fmap solve'
    where
        solve' n
            | n <= 3    = n - 1
            | even n    = 2
            | otherwise = 3

main :: IO ()
main = do
    Just t <- B8.getLine <&> readIntB8
    ns <- forM [1 .. t] $ \_ -> B8.getLine <&> readIntB8 <&> fromJust
    let answer = solve ns
    forM_ answer $ printf "%d\n"

import Control.Monad
-- input n is an integer
-- get n to 1 with as few operations as possible
-- allowed operations:
-- 1. subtract n by 1
-- 2. divide n by a proper divisor

main = do
  cases <- read <$> getLine
  replicateM_ cases $ do
    n <- read <$> getLine
    putStrLn $ show $ solve n

solve :: Int -> Int
solve 1 = 0
solve 2 = 1
solve 3 = 2
solve n =
  if even n
  then 2
  else 3

import Control.Arrow ((>>>))

main :: IO ()
main = interact $ words >>> drop 1 >>> map (read >>> solve >>> show) >>> unlines

solve :: Int -> Int
solve n
  | n == 1 = 0
  | n == 2 = 1
  | even n = 2
  | odd n = 3

{-# LANGUAGE GADTs, DeriveFunctor, OverloadedStrings #-}

import qualified Data.ByteString.Char8 as B8
import Text.Printf
import Data.Functor ( (<&>) )
import Control.Arrow ((>>>))
import Control.Monad (forM_)
import Data.Maybe (fromJust)
import Data.Traversable (forM)
import qualified Control.Monad.State.Strict as S
import qualified Data.IntMap as IM
import Control.Monad (foldM_)
import Data.Int

readIntB8 :: B8.ByteString -> Maybe Int
readIntB8 = B8.readInt >>> fmap fst

solve :: [Int] -> [Int]
solve = fmap solve'
    where
        solve' n
            | n <= 3    = n - 1
            | even n    = 2
            | otherwise = 3

main :: IO ()
main = do
    Just t <- B8.getLine <&> readIntB8
    ns <- forM [1 .. t] $ \_ -> B8.getLine <&> readIntB8 <&> fromJust
    let answer = solve ns
    forM_ ns $ printf "%d\n"

import Control.Monad
-- input n is an integer
-- get n to 1 with as few operations as possible
-- allowed operations:
-- 1. subtract n by 1
-- 2. divide n by a proper divisor

main = do
  cases <- read <$> getLine
  replicateM_ cases $ do
    n <- read <$> getLine
    putStrLn $ show $ solve n 0

solve :: Int -> Int -> Int
solve 1 counter = counter
solve n counter =
  if ld < n
  then solve (div n (div n ld)) (counter + 1)
  else solve (n - 1) (counter + 1)
  where
    ld = smallestDivisor n

smallestDivisor :: Int -> Int
smallestDivisor n = smallestDivisor' n 2
  where
    smallestDivisor' n 2 =
      if mod n 2 == 0
      then 2
      else smallestDivisor' n 3
    smallestDivisor' n try =
      if mod n try == 0
      then try
      else smallestDivisor' n (try + 2)


Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, or a - b, or a × b.After n - 1 steps there is only one number left. Can you make this number equal to 24?

The first line contains a single integer n (1 ≤ n ≤ 105).

If it's possible, print "YES" in the first line. Otherwise, print "NO" (without the quotes). If there is a way to obtain 24 as the result number, in the following n - 1 lines print the required operations an operation per line. Each operation should be in form: "a op b = c". Where a and b are the numbers you've picked at this operation; op is either "+", or "-", or "*"; c is the result of corresponding operation. Note, that the absolute value of c mustn't be greater than 1018. The result of the last operation must be equal to 24. Separate operator sign and equality sign from numbers with spaces. If there are multiple valid answers, you may print any of them.

import Control.Monad
main = interact $ solve . read
solve n
	| n<4 = "NO"
	| odd n = "YES\n5 * 4 = 20\n3 + 2 = 5\n20 + 5 = 25\n25 - 1 = 24\n" ++ gen 6 n
	| even n = "YES\n1 * 2 = 2\n2 * 3 = 6\n6 * 4 = 24\n\n" ++ gen 5 n
	where gen x y= if x>=y then "" else show (x+1) ++ " - " ++ show x ++ " = 1\n1 * 24 = 24\n" ++ gen (x+2) y

import Data.List

data Opr = Opr Char Integer Integer

applyOpr :: Opr -> Integer
applyOpr (Opr c a b) = case c of
  '+' -> a + b
  '-' -> a - b
  '*' -> a * b

data Answer = No | Yes [Opr]

instance Show Opr where
  show opr@(Opr c a b) = unwords [show a, [c], show b, "=", show $ applyOpr opr]

instance Show Answer where
  show No = "NO"
  show (Yes oprs) = init . unlines $ ["YES"] ++ map show oprs

solve :: Integer -> Answer
solve 1 = No
solve 2 = No
solve 3 = No
solve 4 = Yes [Opr '*' 1 2, Opr '*' 2 3, Opr '*' 6 4]
solve 5 = Yes [Opr '*' 4 5, Opr '+' 2 3, Opr '-' 5 1, Opr '+' 20 4]
solve 6 = Yes [Opr '*' 2 3, Opr '*' 6 4, Opr '+' 1 5, Opr '-' 6 6, Opr '+' 0 24]
-- n > 6
solve n = Yes $ [ Opr '*' 2 3, Opr '*' 6 4, Opr '+' 1 5, Opr '-' 6 6
  ] ++ reverse mid ++ [Opr '*' x 0, Opr '+' 0 24] where
    (x, mid) = foldl' (\(s, oprs) x -> (s + x, (Opr '+' s x):oprs)) (7, []) [8..n]

main = do
  n <- return . read =<< getLine
  print $ solve n

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

get :: State s s
get = State $ id &&& id
put :: s -> State s ()
put = State . const . ((),)
modify :: (s -> s) -> State s ()
modify = State . (.) ((,) ())
evalState :: State s a -> s -> a
evalState = (.) fst . runState
execState :: State s a -> s -> s
execState = (.) snd . runState

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
inf = maxBound `div` 2 :: Int

solve :: [Int] -> Maybe [String]
solve xs = evalState (go xs) M.empty where
    go [s] = return $ if s == 24 then Just [] else Nothing
    go l   = do
        memo <- get
        case M.lookup l memo of
            Just b -> return b
            Nothing -> do
                b <- msum <$> mapM (\(l,s) -> fmap (fmap (s:)) (go l))  (next l)
                pure b <* modify (M.insert l b)

solve1 :: Int -> Maybe [String]
solve1 n | n <= 7 = solve [1..n] | otherwise = fmap (xs++) $ solve [1..if even n then 6 else 7] where
    xs = concat [[pprint i (i-1) ((-),"-"), pprint 1 6 ((*),"*")] | i <- [n,n-2..8]]

pprint :: Int -> Int -> (Int->Int->Int,String) -> String
pprint v w (op,opcode) = unwords $ [show v, opcode, show w, "=", show (op v w)]

next :: [Int] -> [([Int],String)]
next l = M.toList $ M.fromList $ do
    (i,v) <- zip [1..] l
    (j,w) <- zip [1..] l
    guard $ i /= j
    (op,opcode) <- [((+),"+"),((-),"-"),((*),"*")]
    let s = pprint v w (op,opcode)
    return (insert (op v w) (delete v $ delete w l), s)

main = do
    n <- readLn
    case solve1 n of
        Nothing -> putStrLn "NO"
        Just xs -> putStrLn "YES" >> forM_ xs putStrLn

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

main :: IO ()
main = interact $ solve.read

solve :: Int -> String
solve n
  | n <= 3 = "NO"
  | even n = "YES\n" ++ solveEven n
  | otherwise = "YES\n" ++solveOdd n

solveEven n = go n
   where
     go n
       | n > 4 = show n ++ " - " ++ show (n-1) ++ " = 1\n"
               ++ "1 * " ++ show (n-2) ++ " = " ++ show (n-2) ++ "\n"
               ++ go (n-2)
       | n == 4 = unlines [ "1 * 2 = 2"
                          , "3 * 4 = 12"
                          , "2 * 12 = 24"
                          ]

solveOdd n = go n
   where
     go n
       | n > 5 = show n ++ " - " ++ show (n-1) ++ " = 1\n"
               ++ "1 * " ++ show (n-2) ++ " = " ++ show (n-2) ++ "\n"
               ++ go (n-2)
       | n == 5 = unlines [ "5 * 4 = 20"
                          , "2 + 3 = 5"
                          , "5 - 1 = 4"
                          , "20 + 4 = 24"
                          ]

{-# LANGUAGE MagicHash, UnboxedTuples #-}
import qualified Data.ByteString as BS
import Control.Arrow

r1 [] = []
r1 (h : t) = (h, t) : map (second (h:)) (r1 t)

bf :: [(Int, String)] -> [(Int, String)]
bf [x] = [x]
bf l = do
  let (a,as) +++ (b, bs) = (a + b, "(" ++ as ++ "+" ++ bs ++ ")")
  let (a,as) +-- (b, bs) = (a - b, "(" ++ as ++ "-" ++ bs ++ ")")
  let (a,as) +** (b, bs) = (a * b, "(" ++ as ++ "*" ++ bs ++ ")")
  (a, l) <- r1 l
  (b, l) <- r1 l
  concat [bf (a +++ b : l), bf (a +-- b : l), bf (a +** b : l)]

s5 = ["5 * 4 = 20", "3 + 2 = 5", "20 + 5 = 25", "25 - 1 = 24"]
s4 = ["1 * 2 = 2", "2 * 3 = 6", "6 * 4 = 24"]
s :: Int -> Maybe [String]
s 0 = Nothing
s 1 = Nothing
s 2 = Nothing
s 3 = Nothing
s 5 = Just s5
s 4 = Just s4
s n = Just $
  concat [[show (n - i*2) ++ " - " ++ show (n - i*2 - 1) ++ " = 1", "1 * 1 = 1"] |i<-[0..(n-4) `div` 2-1]]
  ++ concat [s5|odd n]
  ++ concat [s4|even n]

pp Nothing = ["NO"]
pp (Just ss) = "YES" : ss

main = interact $ unlines . pp . s . read

import Data.List
import Data.Function
import Data.Char
import Data.Maybe
import qualified Data.ByteString.Lazy.Char8 as B

main = interact $ unlines . reverse . getAns . read

getAns :: Int -> [String]
getAns x
	| x < 4 = ["NO"]
	| x == 4 = ["6 * 4 = 24", "2 * 3 = 6", "1 * 2 = 2", "YES"]
	| x == 5 = ["1 * 24 = 24", "4 * 6 = 24", "5 + 1 = 6", "3 - 2 = 1", "YES"]
	| otherwise = ["1 * 24 = 24", show x ++ " - " ++ show (x - 1) ++ " = 1"] ++ getAns (x - 2)

data Instr = Int :+ Int | Int :* Int | Int :- Int

main = do
  n <- fmap read getLine
  case genAns n of
    [] -> putStrLn "NO"
    is -> putStrLn "YES" >> putStrLn is

genAns :: Int -> String
genAns = unlines . map renderInstr . solve

renderInstr :: Instr -> String
renderInstr (x :+ y) = show x ++ " + " ++ show y ++ " = " ++ show (x+y)
renderInstr (x :- y) = show x ++ " - " ++ show y ++ " = " ++ show (x-y)
renderInstr (x :* y) = show x ++ " * " ++ show y ++ " = " ++ show (x*y)

solve :: Int -> [Instr]
solve n | n < 4 = []
        | n == 4 = genFrom4
        | n == 5 = genFrom5
        | even n = evenInstr n
        | odd n = oddInstr n

oddInstr n = genFrom5 ++ subtractConsecPairs [6,8..n] ++
             multiplyAll1s (length [6,8..n]) ++ mul24And1

genFrom5 = [5 :* 4, 20 :+ 2, 22 :+ 3, 25 :- 1]

evenInstr n = genFrom4 ++ subtractConsecPairs [5,7..n] ++
              multiplyAll1s (length [5,7..n]) ++ mul24And1

genFrom4 = [4 :* 3, 12 :* 2, 24 :* 1]
mul24And1 = [24 :* 1]

multiplyAll1s n = replicate (n-1) mul1s
    where
      mul1s = 1 :* 1
subtractConsecPairs l = l >>= \x -> [(x+1) :- x]

import Control.Monad
main = interact $ solve . read
solve n
	| n<4 = "NO"
	| odd n = "YES\n5 * 4 = 20\n3 + 2 = 5\n20 + 5 = 25\n25 - 1 = 24\n" ++ gen 6 n
	| even n = "YES\n1 * 2 = 2\n2 * 3 = 6\n6 * 4 = 24\n25 - 1 = 24\n" ++ gen 5 n
	where gen x y= if x>=y then "" else show (x+1) ++ " - " ++ show x ++ " = 1\n1 * 24 = 24\n" ++ gen (x+2) y

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

get :: State s s
get = State $ id &&& id
put :: s -> State s ()
put = State . const . ((),)
modify :: (s -> s) -> State s ()
modify = State . (.) ((,) ())
evalState :: State s a -> s -> a
evalState = (.) fst . runState
execState :: State s a -> s -> s
execState = (.) snd . runState

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
inf = maxBound `div` 2 :: Int

solve :: [Int] -> Maybe [String]
solve xs = evalState (go xs) M.empty where
    go [s] = return $ if s == 24 then Just [] else Nothing
    go l   = do
        memo <- get
        case M.lookup l memo of
            Just b -> return b
            Nothing -> do
                b <- msum <$> mapM (\(l,s) -> fmap (fmap (s:)) (go l))  (next l)
                pure b <* modify (M.insert l b)

solve1 :: Int -> Maybe [String]
solve1 n | n <= 7 = solve [1..n] | otherwise = fmap (xs++) $ solve [1..6] where
    xs = concat [[pprint i (i-1) ((-),"-"), pprint 1 6 ((*),"*")] | i <- [n,n-2..8]]

pprint :: Int -> Int -> (Int->Int->Int,String) -> String
pprint v w (op,opcode) = unwords $ [show v, opcode, show w, "=", show (op v w)]

next :: [Int] -> [([Int],String)]
next l = M.toList $ M.fromList $ do
    (i,v) <- zip [1..] l
    (j,w) <- zip [1..] l
    guard $ i /= j
    (op,opcode) <- [((+),"+"),((-),"-"),((*),"*")]
    let s = pprint v w (op,opcode)
    return (insert (op v w) (delete v $ delete w l), s)

main = do
    n <- readLn
    case solve1 n of
        Nothing -> putStrLn "NO"
        Just xs -> putStrLn "YES" >> forM_ xs putStrLn

{-# LANGUAGE MagicHash, UnboxedTuples #-}
import qualified Data.ByteString as BS
import Control.Arrow

r1 [] = []
r1 (h : t) = (h, t) : map (second (h:)) (r1 t)

bf :: [(Int, String)] -> [(Int, String)]
bf [x] = [x]
bf l = do
  let (a,as) +++ (b, bs) = (a + b, "(" ++ as ++ "+" ++ bs ++ ")")
  let (a,as) +-- (b, bs) = (a - b, "(" ++ as ++ "-" ++ bs ++ ")")
  let (a,as) +** (b, bs) = (a * b, "(" ++ as ++ "*" ++ bs ++ ")")
  (a, l) <- r1 l
  (b, l) <- r1 l
  concat [bf (a +++ b : l), bf (a +-- b : l), bf (a +** b : l)]

s5 = ["5 * 4 = 20", "3 + 2 = 5", "20 + 5 = 25", "25 - 1 = 24"]
s4 = ["1 * 2 = 2", "2 * 3 = 6", "6 * 4 = 24"]
s :: Int -> Maybe [String]
s 0 = Nothing
s 1 = Nothing
s 2 = Nothing
s 3 = Nothing
s 5 = Just s5
s 4 = Just s4
s n = Just $
  concat [[show (n - i*2) ++ " - " ++ show (n - i*2 - 1) ++ " = 1", "1 * 1 = 1"] |i<-[1..(n-4) `div` 2]]
  ++ concat [s5|odd n]
  ++ concat [s4|even n]

pp Nothing = ["NO"]
pp (Just ss) = "YES" : ss

main = interact $ unlines . pp . s . read